From 6332ff0fa979cf3373f5eb1f8e35f63c8387c06d Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Mon, 30 Nov 2026 06:33:28 +0200 Subject: [PATCH] Rebuild the Kanban board after the prototype, with the job editor and quick intake dialog - Toolbar: whose board (own, a person, a service line, all), pipeline views (daily, sales, full), urgent and late filters with a live count, normal and compact density, and the quick intake button. - Columns side by side with horizontal scrolling on desktop, stacked on phones; each user's own column colours and order, the urgent column's threshold menu, and the continuing jobs column. - Cards in customer colours: job cards with their tasks checked off inside the card (the status select is gone), continuing job cards with the next period, PIN and quick add, and pinned task cards. Dragging moves and orders cards; the keyboard opens the job editor from the card title. - Job editor dialog: every job detail, tasks with checklists and templates, quick hours (TimeTracking) and expenses (Expenses), history. - The quick intake form also adds a contact person, initial status and priority, and opens as a dialog on the board. Co-Authored-By: Claude Opus 5.5 --- .../Livewire/⚡job-quick-expense.blade.php | 133 +++ .../Application/Contracts/TaskQueries.php | 7 + .../Repositories/EloquentTaskQueries.php | 10 + .../Livewire/Concerns/DescribesJobHistory.php | 75 ++ .../Livewire/Concerns/EditsJobDetails.php | 187 ++++ .../Livewire/Forms/QuickJobForm.php | 41 +- .../Presentation/Livewire/⚡board.blade.php | 921 +++++++++++++---- .../Presentation/Livewire/⚡form.blade.php | 161 +-- .../Livewire/⚡job-editor.blade.php | 927 ++++++++++++++++++ .../Presentation/Livewire/⚡quick.blade.php | 215 +++- .../Presentation/Livewire/⚡show.blade.php | 54 +- .../Jobs/Presentation/Support/BoardFormat.php | 39 + .../Livewire/⚡job-quick-hours.blade.php | 143 +++ lang/en/expenses.php | 11 + lang/en/jobs.php | 60 ++ lang/en/time.php | 12 + lang/fi/expenses.php | 11 + lang/fi/jobs.php | 60 ++ lang/fi/time.php | 12 + resources/css/app.css | 26 + .../jobs/board/card-header.blade.php | 47 + .../components/jobs/board/job-card.blade.php | 99 ++ .../components/jobs/board/menu.blade.php | 59 ++ .../jobs/board/ongoing-card.blade.php | 105 ++ .../components/jobs/board/person.blade.php | 7 + .../jobs/board/priority-badge.blade.php | 22 + .../components/jobs/board/task-card.blade.php | 69 ++ .../components/jobs/board/task-list.blade.php | 83 ++ tests/Browser/JobsAccessibilityTest.php | 58 +- tests/Fakes/FakeTaskQueries.php | 5 + tests/Feature/Modules/Jobs/JobBoardTest.php | 214 +++- tests/Feature/Modules/Jobs/JobEditorTest.php | 128 +++ .../Modules/Jobs/JobMoneyFieldsTest.php | 6 +- .../Feature/Modules/Jobs/QuickIntakeTest.php | 37 + .../Modules/TimeTracking/ApprovalTest.php | 6 +- 35 files changed, 3556 insertions(+), 494 deletions(-) create mode 100644 app/Modules/Expenses/Presentation/Livewire/⚡job-quick-expense.blade.php create mode 100644 app/Modules/Jobs/Presentation/Livewire/Concerns/DescribesJobHistory.php create mode 100644 app/Modules/Jobs/Presentation/Livewire/Concerns/EditsJobDetails.php create mode 100644 app/Modules/Jobs/Presentation/Livewire/⚡job-editor.blade.php create mode 100644 app/Modules/Jobs/Presentation/Support/BoardFormat.php create mode 100644 app/Modules/TimeTracking/Presentation/Livewire/⚡job-quick-hours.blade.php create mode 100644 resources/views/components/jobs/board/card-header.blade.php create mode 100644 resources/views/components/jobs/board/job-card.blade.php create mode 100644 resources/views/components/jobs/board/menu.blade.php create mode 100644 resources/views/components/jobs/board/ongoing-card.blade.php create mode 100644 resources/views/components/jobs/board/person.blade.php create mode 100644 resources/views/components/jobs/board/priority-badge.blade.php create mode 100644 resources/views/components/jobs/board/task-card.blade.php create mode 100644 resources/views/components/jobs/board/task-list.blade.php create mode 100644 tests/Feature/Modules/Jobs/JobEditorTest.php diff --git a/app/Modules/Expenses/Presentation/Livewire/⚡job-quick-expense.blade.php b/app/Modules/Expenses/Presentation/Livewire/⚡job-quick-expense.blade.php new file mode 100644 index 0000000..ddde84a --- /dev/null +++ b/app/Modules/Expenses/Presentation/Livewire/⚡job-quick-expense.blade.php @@ -0,0 +1,133 @@ +authorize('expenses.use'); + + $this->jobId = $jobId; + } + + /** + * @return list + */ + #[Computed] + public function expenses(): array + { + return app(ExpenseQueries::class)->forJob($this->jobId); + } + + public function isLocked(): bool + { + return app(ExpenseJobs::class)->find($this->jobId)?->isLocked ?? true; + } + + public function save(RecordExpense $record, Clock $clock): void + { + $this->authorize('expenses.record'); + + if (trim($this->description) === '') { + $this->addError('description', __('expenses.errors.description_required')); + + return; + } + + try { + $record->execute($this->jobId, new ExpenseData( + userId: (int) auth()->id(), + category: ExpenseCategory::Materials, + paidBy: ExpensePayer::Company, + spentOn: $clock->today()->format('Y-m-d'), + description: trim($this->description), + cost: $this->cost, + ), (int) auth()->id()); + } catch (ExpenseLocked) { + $this->addError('cost', __('expenses.quick.locked')); + + return; + } catch (ExpenseJobNotFound) { + abort(404); + } catch (DomainException) { + $this->addError('cost', __('expenses.errors.invalid_amount')); + + return; + } + + $this->statusMessage = __('expenses.quick.added', ['description' => trim($this->description)]); + $this->reset('description', 'cost'); + unset($this->expenses); + } +}; +?> + +
+ @if (Gate::allows('expenses.record') && ! $this->isLocked()) +
+
+ +
+
+ +
+
+ +
+
+ @elseif ($this->isLocked()) +

{{ __('expenses.quick.locked') }}

+ @endif + +

{{ $statusMessage }}

+ + @if ($this->expenses === []) +

{{ __('expenses.quick.none') }}

+ @else +
    + @foreach ($this->expenses as $expense) +
  • + {{ $this->summaryText($expense) }} + {{ $this->amount($expense, $expense->costCents) }} +
  • + @endforeach +
+ @endif + + @can('expenses.record') + {{ __('expenses.quick.all') }} + @endcan +
diff --git a/app/Modules/Jobs/Application/Contracts/TaskQueries.php b/app/Modules/Jobs/Application/Contracts/TaskQueries.php index dd7f3f4..b3fad7c 100644 --- a/app/Modules/Jobs/Application/Contracts/TaskQueries.php +++ b/app/Modules/Jobs/Application/Contracts/TaskQueries.php @@ -16,6 +16,13 @@ interface TaskQueries */ public function tasksOf(int $jobId): array; + /** + * Which of the job's tasks are pinned to the Kanban board, by task id. + * + * @return array + */ + public function pinnedTaskIds(int $jobId): array; + /** * Null when the task does not exist or belongs to another job. */ diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index b58af59..92ccc3a 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -36,6 +36,16 @@ class EloquentTaskQueries implements TaskQueries return $this->summaries($models); } + public function pinnedTaskIds(int $jobId): array + { + return TaskModel::query() + ->where('customer_job_id', $jobId) + ->where('is_pinned_to_board', true) + ->pluck('id') + ->mapWithKeys(fn ($id): array => [(int) $id => true]) + ->all(); + } + public function findTask(int $jobId, int $taskId): ?TaskSummary { $model = TaskModel::query()->where('customer_job_id', $jobId)->find($taskId); diff --git a/app/Modules/Jobs/Presentation/Livewire/Concerns/DescribesJobHistory.php b/app/Modules/Jobs/Presentation/Livewire/Concerns/DescribesJobHistory.php new file mode 100644 index 0000000..9fdf754 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/Concerns/DescribesJobHistory.php @@ -0,0 +1,75 @@ + $changes + */ +trait DescribesJobHistory +{ + /** + * @return list + */ + #[Computed] + public function changes(): array + { + $changes = app(CustomerJobQueries::class)->changes($this->jobId); + + return Gate::allows('money.quotes') + ? $changes + : array_values(array_filter($changes, fn (JobChangeEntry $change): bool => ! in_array($change->field, ['quoted_amount', 'monthly_fee'], true))); + } + + public function formatDate(?string $date): string + { + return $date === null ? __('jobs.not_set') : CarbonImmutable::parse($date)->format('j.n.Y'); + } + + /** + * A history value as text: names for ids, labels for enum keys, + * Finnish dates and amounts. + */ + public function historyValue(string $field, ?string $value): string + { + if ($value === null || $value === '') { + return __('jobs.not_set'); + } + + $ids = array_map('intval', explode(',', $value)); + $named = fn (array $names): string => implode(', ', array_map( + fn (int $id): string => $names[$id] ?? __('jobs.history.unknown', ['id' => $id]), + $ids, + )); + + return match ($field) { + 'starts_on', 'due_on', 'planned_from', 'planned_to' => $this->formatDate($value), + 'quoted_amount', 'monthly_fee' => Money::fromCents((int) $value)->format(), + 'kind' => __('jobs.kinds.'.$value), + 'status' => __('jobs.statuses.'.$value), + 'priority' => __('jobs.priorities.'.$value), + 'payment_basis' => __('jobs.payment_bases.'.$value), + 'customer' => $named(app(CustomerQueries::class)->namesByIds($ids)), + 'service_units' => $named(app(CatalogQueries::class)->serviceUnitNames($ids)), + 'responsible_user', 'contact_user', 'biller_user', 'members' => $named(app(UserAccountQueries::class)->namesByIds($ids)), + 'customer_contact' => app(CustomerQueries::class)->findContact($this->job->customer->id, $ids[0])->name ?? __('jobs.history.unknown', ['id' => $ids[0]]), + 'billing_unit' => app(CustomerQueries::class)->findBillingUnit($this->job->customer->id, $ids[0])->name ?? __('jobs.history.unknown', ['id' => $ids[0]]), + default => $value, + }; + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/Concerns/EditsJobDetails.php b/app/Modules/Jobs/Presentation/Livewire/Concerns/EditsJobDetails.php new file mode 100644 index 0000000..b7c2340 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/Concerns/EditsJobDetails.php @@ -0,0 +1,187 @@ + $users + * @property-read list $contacts + * @property-read list $billingUnits + * @property-read list $statusOptions + */ +trait EditsJobDetails +{ + /** + * @return list + */ + #[Computed] + public function serviceUnitOptions(): array + { + $catalog = app(CatalogQueries::class); + $options = []; + + foreach ($catalog->activeServiceUnits() as $unit) { + $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name]; + } + + // Units already on the job stay visible after being taken out of use. + foreach ($this->form->service_unit_ids as $id) { + if (! isset($options[(int) $id]) && ($unit = $catalog->findServiceUnit((int) $id)) !== null) { + $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name, 'note' => __('catalog.inactive')]; + } + } + + return array_values($options); + } + + /** + * @return list + */ + #[Computed] + public function users(): array + { + return app(UserAccountQueries::class)->activeUserOptions(); + } + + /** + * @return list + */ + #[Computed] + public function contacts(): array + { + return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id); + } + + /** + * @return list + */ + #[Computed] + public function billingUnits(): array + { + return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->billingUnitsOf((int) $this->form->customer_id); + } + + /** + * Statuses this user may choose: billing statuses for management and the + * job's biller, archived for management, and always the stored one. + * + * @return list + */ + #[Computed] + public function statusOptions(): array + { + return array_values(array_filter( + JobStatus::cases(), + fn (JobStatus $status): bool => $status->value === $this->storedStatus || $this->maySetStatus($status), + )); + } + + /** + * @return list + */ + #[Computed] + public function tagSuggestions(): array + { + return array_values(array_diff(app(CustomerJobQueries::class)->tagSuggestions($this->newTag), $this->form->tags)); + } + + public function addTag(): void + { + $tag = trim(preg_replace('/\s+/u', ' ', $this->newTag) ?? ''); + + if ($tag === '' || mb_strlen($tag) > 50) { + $this->addError('newTag', __('jobs.errors.invalid_tag')); + + return; + } + + $taken = array_map('mb_strtolower', $this->form->tags); + + if (! in_array(mb_strtolower($tag), $taken, true)) { + $this->form->tags[] = $tag; + } + + $this->newTag = ''; + $this->resetErrorBag('newTag'); + $this->statusMessage = __('jobs.tags.added', ['tag' => $tag]); + } + + public function removeTag(int $index): void + { + $tag = $this->form->tags[$index] ?? null; + + if ($tag === null) { + return; + } + + unset($this->form->tags[$index]); + $this->form->tags = array_values($this->form->tags); + $this->statusMessage = __('jobs.tags.removed', ['tag' => $tag]); + + $this->js("document.getElementById('new-tag')?.focus()"); + } + + public function addLink(): void + { + $this->form->links[] = ['title' => '', 'url' => '']; + $index = count($this->form->links) - 1; + + $this->js("document.getElementById('link-title-{$index}')?.focus()"); + } + + public function removeLink(int $index): void + { + unset($this->form->links[$index]); + $this->form->links = array_values($this->form->links); + + $this->js("document.getElementById('add-link')?.focus()"); + } + + protected function maySetStatus(JobStatus $status): bool + { + $stored = $this->storedStatus === null ? null : JobStatus::tryFrom($this->storedStatus); + + if ($stored !== null && $stored->unlocksTo($status) && ! Gate::allows('jobs.unlock')) { + return false; + } + + if ($status === JobStatus::Archived) { + return Gate::allows('jobs.archive'); + } + + if ($status->isBillingStatus()) { + $details = $this->jobId === null ? null : app(CustomerJobQueries::class)->findDetails($this->jobId); + + return Gate::allows('jobs.set-billing-status', [$details?->biller?->id]); + } + + return true; + } + + /** + * A contact or billing unit of another customer no longer fits. + */ + protected function customerChosen(?int $customerId): void + { + $this->form->customer_contact_id = ''; + $this->form->billing_unit_id = ''; + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/QuickJobForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/QuickJobForm.php index 0302beb..85022d4 100644 --- a/app/Modules/Jobs/Presentation/Livewire/Forms/QuickJobForm.php +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/QuickJobForm.php @@ -14,8 +14,9 @@ use Illuminate\Validation\Rule; use Livewire\Form; /** - * Quick job intake on a phone: only what is needed to open a job (spec 6). - * Everything else gets the defaults and is filled in later. + * Quick job intake on a phone and in the board's dialog: only what is + * needed to open a job (docs/ui-kanban-board.md 6). Everything else gets + * the defaults and is filled in later. */ class QuickJobForm extends Form { @@ -31,6 +32,27 @@ class QuickJobForm extends Form public string $status = JobStatus::Tentative->value; + public string $priority = Priority::Normal->value; + + public string $customer_contact_id = ''; + + /** The intake has a new contact person of the customer to add. */ + public bool $adding_contact = false; + + public string $new_contact_name = ''; + + public string $new_contact_phone = ''; + + /** + * The statuses a job can start in at intake. + * + * @return list + */ + public static function startStatuses(): array + { + return [JobStatus::Prospect, JobStatus::Tentative, JobStatus::QuoteRequest, JobStatus::Order, JobStatus::InProduction]; + } + public function toData(): CustomerJobData { $this->validate(); @@ -42,8 +64,9 @@ class QuickJobForm extends Form responsibleUserId: (int) $this->responsible_user_id, kind: JobKind::OneOff->value, status: $this->status, - priority: Priority::Normal->value, + priority: $this->priority, description: trim($this->description) === '' ? null : $this->description, + customerContactId: $this->customer_contact_id === '' ? null : (int) $this->customer_contact_id, ); } @@ -52,7 +75,7 @@ class QuickJobForm extends Form */ public function clearForNextJob(): void { - $this->reset('customer_id', 'name', 'description', 'service_unit_id'); + $this->reset('customer_id', 'name', 'description', 'service_unit_id', 'priority', 'customer_contact_id', 'adding_contact', 'new_contact_name', 'new_contact_phone'); $this->resetErrorBag(); } @@ -83,7 +106,11 @@ class QuickJobForm extends Form 'description' => ['nullable', 'string', 'max:2000'], 'service_unit_id' => ['required', 'integer'], 'responsible_user_id' => ['required', 'integer'], - 'status' => ['required', Rule::in([JobStatus::Tentative->value, JobStatus::Prospect->value])], + 'status' => ['required', Rule::in(array_map(fn (JobStatus $status): string => $status->value, self::startStatuses()))], + 'priority' => ['required', Rule::enum(Priority::class)], + 'customer_contact_id' => ['nullable', 'integer'], + 'new_contact_name' => [$this->adding_contact ? 'required' : 'nullable', 'string', 'max:255'], + 'new_contact_phone' => ['nullable', 'string', 'max:50'], ]; } @@ -100,6 +127,10 @@ class QuickJobForm extends Form 'service_unit_id.required' => __('jobs.quick.service_unit_required'), 'responsible_user_id.required' => __('jobs.errors.responsible_required'), 'status.in' => __('jobs.errors.status_not_allowed'), + 'priority.*' => __('jobs.errors.status_not_allowed'), + 'new_contact_name.required' => __('jobs.quick.contact_name_required'), + 'new_contact_name.max' => __('jobs.errors.too_long', ['max' => 255]), + 'new_contact_phone.max' => __('jobs.errors.too_long', ['max' => 50]), ]; } } diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php index 07445c1..08fd041 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡board.blade.php @@ -1,40 +1,82 @@ ", "unit-" or "all". */ + #[Url(as: 'taulu', except: 'mine')] + public string $board = 'mine'; - #[Url(except: '')] - public string $priority = ''; + #[Url(as: 'nakyma', except: 'production')] + public string $view = 'production'; - #[Url(as: 'unit', except: '')] - public string $serviceUnit = ''; + #[Url(as: 'kiire', except: false)] + public bool $onlyUrgent = false; + + #[Url(as: 'myohassa', except: false)] + public bool $onlyLate = false; public string $statusMessage = ''; + /** @var array new task titles typed on continuing job cards, by job id */ + public array $newTaskTitles = []; + + /** @var array "lift into the pipeline at once" on those cards, by job id */ + public array $newTaskPins = []; + public function mount(): void { $this->authorize('jobs.view'); + + if (BoardView::tryFrom($this->view) === null) { + $this->view = BoardView::Production->value; + } } public function isSubcontractor(): bool @@ -42,52 +84,407 @@ new class extends Component return auth()->user()?->role === Role::Subcontractor; } + #[Computed] + public function preferences(): BoardPreferences + { + return app(JobBoardQueries::class)->preferencesOf((int) auth()->id()); + } + + public function boardView(): BoardView + { + return BoardView::tryFrom($this->view) ?? BoardView::Production; + } + /** - * @return array> + * @return list */ #[Computed] - public function board(): array + public function cards(): array { $userId = (int) auth()->id(); + $board = $this->isSubcontractor() ? 'all' : $this->board; + $personId = null; + $unitId = null; - return app(CustomerJobQueries::class)->board(new JobListFilter( - priority: Priority::tryFrom($this->priority)?->value, - serviceUnitId: $this->serviceUnit === '' ? null : (int) $this->serviceUnit, - mineForUserId: $this->mine && ! $this->isSubcontractor() ? $userId : null, + if ($board === 'mine') { + $personId = $userId; + } elseif (preg_match('/^person-(\d+)$/', $board, $matches) === 1) { + $personId = (int) $matches[1]; + } elseif (preg_match('/^unit-(\d+)$/', $board, $matches) === 1) { + $unitId = (int) $matches[1]; + } + + return app(JobBoardQueries::class)->cards(new BoardFilter( + personUserId: $personId, + serviceUnitId: $unitId, onlyMemberUserId: $this->isSubcontractor() ? $userId : null, - )); + onlyUrgent: $this->onlyUrgent, + onlyLate: $this->onlyLate, + ), app(Clock::class)->today()->format('Y-m-d')); } /** - * Statuses a card can be moved to by this user. + * @return array> + */ + #[Computed] + public function columns(): array + { + return app(BoardLayout::class)->arrange($this->cards, $this->boardView(), $this->preferences); + } + + public function shownCardCount(): int + { + return array_sum(array_map('count', $this->columns)); + } + + public function quoteCount(): int + { + return count(array_filter($this->cards, fn (BoardCard $card): bool => ! $card->isTaskCard() + && in_array($card->jobStatus, [JobStatus::Prospect, JobStatus::Tentative, JobStatus::QuoteRequest], true))); + } + + /** + * @return array board value => label + */ + #[Computed] + public function boardOptions(): array + { + $options = ['mine' => __('jobs.board.board_mine')]; + + foreach (app(UserAccountQueries::class)->activeUserOptions() as $user) { + if ($user->id !== (int) auth()->id() && $user->role !== Role::Subcontractor) { + $options['person-'.$user->id] = __('jobs.board.board_person', ['name' => $user->name]); + } + } + + foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit) { + $options['unit-'.$unit->id] = __('jobs.board.board_unit', ['name' => $unit->name]); + } + + $options['all'] = __('jobs.board.board_all'); + + return $options; + } + + /** + * Colours of a column: the header and its text, and the body and border + * tinted with the header colour in light and dark mode. * - * @return list + * @return array{header: string, text: string, light: bool, body: string, bodyDark: string, border: string, borderDark: string} */ - public function statusesFor(CustomerJobSummary $job): array + public function columnStyle(BoardColumn $column): array { - return array_values(array_filter( - JobStatus::kanbanStatuses(), - fn (JobStatus $status): bool => $status === $job->status - || ((! $status->isBillingStatus() || Gate::allows('jobs.set-billing-status', [$job->billerUserId])) - && (! $job->status->unlocksTo($status) || Gate::allows('jobs.unlock'))), + $color = $this->preferences->colorOf($column); + + return [ + 'header' => $color->value, + 'text' => $color->textColor(), + 'light' => $color->isLight(), + 'body' => $color->mixedInto(new HexColor('#f6f7f9'), 0.08)->value, + 'bodyDark' => $color->mixedInto(new HexColor('#16160e'), 0.11)->value, + 'border' => $color->mixedInto(new HexColor('#d1d5db'), 0.12)->value, + 'borderDark' => $color->mixedInto(new HexColor('#2a2b23'), 0.15)->value, + ]; + } + + public function openJob(int $jobId): void + { + $this->authorize('jobs.view-job', [$jobId]); + + $this->dispatch('open-job-editor', jobId: $jobId); + } + + /** + * A card was dropped (wire:sort): into another column, or to another + * place in its own column. + */ + public function moveDropped(string $key, int $position, string $columnValue, MoveBoardCard $move): void + { + $this->authorize('jobs.manage'); + + $column = BoardColumn::tryFrom($columnValue); + $card = $this->findCard($key); + + if ($column === null || $card === null || ! in_array($column, $this->boardView()->columns(), true)) { + $this->statusMessage = __('jobs.board.not_moved'); + $this->refreshBoard(); + + return; + } + + $label = $card->number.' '.$card->title; + $columnName = __('jobs.board.column_names.'.$column->value); + + if (! $card->isTaskCard()) { + $status = MoveBoardCard::statusAfterDrop($card->jobStatus, $column); + + if ($status->isBillingStatus() && $status !== $card->jobStatus && ! Gate::allows('jobs.set-billing-status', [$card->billerUserId])) { + $this->statusMessage = __('jobs.board.billing_not_allowed', ['job' => $label, 'status' => __('jobs.statuses.'.$status->value)]); + $this->refreshBoard(); + + return; + } + + if ($card->jobStatus->unlocksTo($status) && ! Gate::allows('jobs.unlock')) { + $this->statusMessage = __('jobs.board.unlock_not_allowed', ['job' => $label, 'status' => __('jobs.statuses.'.$status->value)]); + $this->refreshBoard(); + + return; + } + } elseif (! Gate::allows('jobs.update-task-status', [$card->jobId])) { + abort(403); + } + + $keys = array_values(array_filter( + array_map(fn (BoardCard $other): string => $other->key(), $this->columns[$column->value] ?? []), + fn (string $other): bool => $other !== $key, )); + array_splice($keys, max(0, min($position, count($keys))), 0, [$key]); + + $fromColumn = app(BoardLayout::class)->columnOf($card, $this->boardView(), $this->preferences); + $sortWasByDate = $this->preferences->sortOf($column) === ColumnSort::DueDate; + $threshold = $this->preferences->urgentThreshold; + + try { + $move->execute($card->jobId, $card->taskId, $column, $keys, $threshold, (int) auth()->id()); + } catch (CardCannotMoveThere) { + $this->statusMessage = __('jobs.board.cannot_move', ['column' => $columnName]); + $this->refreshBoard(); + + return; + } catch (CustomerJobNotFound|TaskNotFound) { + $this->statusMessage = __('jobs.board.not_moved'); + $this->refreshBoard(); + + return; + } + + if ($sortWasByDate) { + $this->savePreferences($this->preferences->withColumnSort($column, ColumnSort::Manual)); + } + + $this->refreshBoard(); + $this->statusMessage = match (true) { + $sortWasByDate => __('jobs.board.switched_to_manual', ['column' => $columnName]), + $card->isTaskCard() => __('jobs.board.task_moved', ['task' => $card->title, 'column' => $columnName]), + $fromColumn === $column => __('jobs.board.reordered', ['column' => $columnName]), + $column === BoardColumn::InProductionUrgent && ! $threshold->includes($card->priority) => __('jobs.board.priority_raised', [ + 'job' => $label, + 'priority' => __('jobs.priorities.'.$threshold->lowestPriority()->value), + ]), + $column === BoardColumn::InProduction && $fromColumn === BoardColumn::InProductionUrgent => __('jobs.board.priority_lowered', ['job' => $label]), + default => __('jobs.board.moved', ['job' => $label, 'status' => __('jobs.statuses.'.MoveBoardCard::statusAfterDrop($card->jobStatus, $column)->value)]), + }; } /** - * A card's status select changed. + * A task's checkbox on a card: done, or back to in progress. */ - public function moveJob(int $jobId, string $status, ChangeJobStatus $changeStatus): void + public function setTaskDone(int $jobId, int $taskId, bool $done, ChangeTaskStatus $changeStatus): void { - $this->move($jobId, $status, $changeStatus); + $this->authorize('jobs.update-task-status', [$jobId]); + + $task = $this->findTask($jobId, $taskId); + + if ($task === null) { + $this->statusMessage = __('jobs.board.not_moved'); + + return; + } + + try { + $changeStatus->execute($jobId, $taskId, $done ? TaskStatus::Done : TaskStatus::InProgress); + } catch (TaskNotFound) { + $this->statusMessage = __('jobs.board.not_moved'); + + return; + } + + $this->refreshBoard(); + $this->statusMessage = __($done ? 'jobs.board.task_done' : 'jobs.board.task_reopened', ['task' => $task->title]); + } + + public function pinTask(int $jobId, int $taskId, bool $pinned, PinTaskToBoard $pin): void + { + $this->authorize('jobs.manage-tasks', [$jobId]); + + $task = $this->findTask($jobId, $taskId); + + try { + $pin->execute($jobId, $taskId, $pinned); + } catch (CustomerJobNotFound|TaskNotFound|TaskCannotBePinned) { + $this->statusMessage = __('jobs.board.not_moved'); + + return; + } + + $this->refreshBoard(); + $this->statusMessage = __($pinned ? 'jobs.board.task_pinned' : 'jobs.board.task_unpinned', ['task' => $task->title ?? '']); } /** - * A card was dropped into another column (wire:sort). The position - * inside the column does not matter: cards are ordered by due date. + * Quick add on a continuing job's card: the title only, for the job's + * responsible person, with the first work type of the job's service units. */ - public function moveDropped(int|string $jobId, int $position, string $status, ChangeJobStatus $changeStatus): void + public function addTask(int $jobId, AddTask $addTask, PinTaskToBoard $pin): void { - $this->move((int) $jobId, $status, $changeStatus); + $this->authorize('jobs.manage-tasks', [$jobId]); + + $field = 'newTaskTitles.'.$jobId; + $title = trim((string) ($this->newTaskTitles[$jobId] ?? '')); + + if ($title === '') { + $this->addError($field, __('jobs.board.task_title_required')); + + return; + } + + $details = app(CustomerJobQueries::class)->findDetails($jobId); + + if ($details === null) { + $this->statusMessage = __('jobs.board.not_moved'); + + return; + } + + $workTypeId = $this->firstWorkTypeId(array_map(fn ($unit): int => $unit->id, $details->serviceUnits)); + + if ($workTypeId === null) { + $this->addError($field, __('jobs.board.no_work_type')); + + return; + } + + try { + $taskId = $addTask->execute($jobId, new TaskData($title, $workTypeId, TaskStatus::Waiting->value, assigneeUserId: $details->responsible->id), (int) auth()->id()); + + if ($this->newTaskPins[$jobId] ?? false) { + $pin->execute($jobId, $taskId, true); + } + } catch (DomainException) { + $this->addError($field, __('jobs.board.not_moved')); + + return; + } + + unset($this->newTaskTitles[$jobId], $this->newTaskPins[$jobId]); + $this->refreshBoard(); + $this->statusMessage = __('jobs.board.task_added', ['task' => $title, 'job' => $details->number]); + } + + public function setCustomerColor(int $customerId, ?string $color, ChangeCustomerHeaderColor $changeColor): void + { + $this->authorize('customers.use'); + + $card = collect($this->cards)->first(fn (BoardCard $card): bool => $card->customerId === $customerId); + + try { + $changeColor->execute($customerId, $color); + } catch (InvalidHexColor|CustomerNotFound) { + $this->statusMessage = __('jobs.board.invalid_color'); + + return; + } + + $this->refreshBoard(); + $this->statusMessage = __('jobs.board.customer_color_saved', ['customer' => $card->customerName ?? '']); + } + + public function setColumnColor(string $columnValue, ?string $color): void + { + $column = BoardColumn::tryFrom($columnValue); + + try { + $hex = $color === null ? null : new HexColor($color); + } catch (InvalidHexColor) { + $hex = false; + } + + if ($column === null || $hex === false) { + $this->statusMessage = __('jobs.board.invalid_color'); + + return; + } + + $this->savePreferences($this->preferences->withColumnColor($column, $hex)); + $this->statusMessage = __($hex === null ? 'jobs.board.color_reset' : 'jobs.board.color_saved', ['column' => __('jobs.board.column_names.'.$column->value)]); + } + + public function setColumnSort(string $columnValue, string $sortValue): void + { + $column = BoardColumn::tryFrom($columnValue); + $sort = ColumnSort::tryFrom($sortValue); + + if ($column === null || $sort === null) { + return; + } + + $this->savePreferences($this->preferences->withColumnSort($column, $sort)); + $this->statusMessage = __('jobs.board.sort_saved', ['column' => __('jobs.board.column_names.'.$column->value), 'sort' => __('jobs.board.sorts.'.$sort->value)]); + } + + public function setUrgentThreshold(string $value): void + { + $threshold = UrgentThreshold::tryFrom($value); + + if ($threshold === null) { + return; + } + + $this->savePreferences($this->preferences->withUrgentThreshold($threshold)); + $this->statusMessage = __('jobs.board.threshold_saved', ['threshold' => __('jobs.board.thresholds.'.$threshold->value)]); + } + + public function setDensity(string $value): void + { + $density = BoardDensity::tryFrom($value); + + if ($density === null) { + return; + } + + $this->savePreferences($this->preferences->withDensity($density)); + $this->statusMessage = __('jobs.board.density_saved', ['density' => __('jobs.board.density_'.$density->value)]); + } + + public function setView(string $value): void + { + $this->view = (BoardView::tryFrom($value) ?? BoardView::Production)->value; + $this->refreshBoard(); + } + + public function updated(string $property): void + { + if (in_array($property, ['board', 'onlyUrgent', 'onlyLate'], true)) { + $this->refreshBoard(); + } + } + + #[On('job-saved')] + public function refreshBoard(): void + { + unset($this->cards, $this->columns); + } + + #[On('job-editor-saved')] + public function editorSaved(string $message): void + { + $this->refreshBoard(); + $this->statusMessage = $message; + } + + /** + * A job created in the quick intake dialog: tentative jobs and quote + * requests show up in the sales view. + */ + #[On('quick-job-created')] + public function quickJobCreated(string $status): void + { + if (in_array($status, [JobStatus::Tentative->value, JobStatus::QuoteRequest->value], true) && $this->boardView() === BoardView::Production) { + $this->view = BoardView::Sales->value; + } + + $this->refreshBoard(); } public function render(): mixed @@ -95,53 +492,61 @@ new class extends Component return $this->view()->title(__('jobs.board.title')); } - private function move(int $jobId, string $statusValue, ChangeJobStatus $changeStatus): void + private function savePreferences(BoardPreferences $preferences): void { - $this->authorize('jobs.manage'); - - $status = JobStatus::tryFrom($statusValue); - $job = $this->findCard($jobId); - - if ($status === null || $status === JobStatus::Archived || $job === null) { - $this->statusMessage = __('jobs.board.not_moved'); - - return; - } - - if ($status->isBillingStatus() && $status !== $job->status && ! Gate::allows('jobs.set-billing-status', [$job->billerUserId])) { - $this->statusMessage = __('jobs.board.billing_not_allowed', ['job' => $job->number.' '.$job->name, 'status' => __('jobs.statuses.'.$status->value)]); - unset($this->board); - - return; - } - - if ($job->status->unlocksTo($status) && ! Gate::allows('jobs.unlock')) { - $this->statusMessage = __('jobs.board.unlock_not_allowed', ['job' => $job->number.' '.$job->name, 'status' => __('jobs.statuses.'.$status->value)]); - unset($this->board); - - return; - } - - try { - $changeStatus->execute($jobId, $status, (int) auth()->id()); - } catch (CustomerJobNotFound) { - $this->statusMessage = __('jobs.board.not_moved'); - - return; - } - - unset($this->board); - $this->statusMessage = __('jobs.board.moved', ['job' => $job->number.' '.$job->name, 'status' => __('jobs.statuses.'.$status->value)]); - - $this->js("document.getElementById('job-status-{$jobId}')?.focus()"); + app(SaveBoardPreferences::class)->execute((int) auth()->id(), $preferences); + unset($this->preferences, $this->columns); } - private function findCard(int $jobId): ?CustomerJobSummary + /** + * The first active work type of the job's own service units (their + * services included), else of the shared unit. + * + * @param list $serviceUnitIds + */ + private function firstWorkTypeId(array $serviceUnitIds): ?int { - foreach ($this->board as $jobs) { - foreach ($jobs as $job) { - if ($job->id === $jobId) { - return $job; + $shared = null; + + foreach (app(CatalogQueries::class)->activeWorkTypesFor($serviceUnitIds) as $node) { + $workTypes = [...$node->workTypes, ...array_merge([], ...array_map(fn ($service): array => $service->workTypes, $node->services))]; + $first = $workTypes[0]->id ?? null; + + if ($first === null) { + continue; + } + + if (in_array($node->serviceUnit->id, $serviceUnitIds, true)) { + return $first; + } + + $shared ??= $first; + } + + return $shared; + } + + private function findCard(string $key): ?BoardCard + { + foreach ($this->cards as $card) { + if ($card->key() === $key) { + return $card; + } + } + + return null; + } + + private function findTask(int $jobId, int $taskId): ?BoardTask + { + foreach ($this->cards as $card) { + if ($card->jobId !== $jobId || $card->isTaskCard()) { + continue; + } + + foreach ($card->tasks as $task) { + if ($task->id === $taskId) { + return $task; } } } @@ -151,129 +556,255 @@ new class extends Component }; ?> -@php($canMove = Gate::allows('jobs.manage')) +@php + $canMove = Gate::allows('jobs.manage'); + $canColor = Gate::allows('customers.use'); + $compact = $this->preferences->density === BoardDensity::Compact; + $boardView = $this->boardView(); +@endphp - - - {{ __('jobs.board.show_list') }} - +
+

{{ __('jobs.board.heading') }}

-
- {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} - - - @foreach (Priority::cases() as $option) - - @endforeach - + {{-- Toolbar: whose board, pipeline view, quick filters, density, new job --}} +
+
+
+ @unless ($this->isSubcontractor()) +
+ + +
+ @endunless - - - @foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit) - - @endforeach - +
+ @foreach (BoardView::cases() as $option) + + @endforeach +
- @if ($this->isSubcontractor()) -

{{ __('jobs.list.subcontractor_note') }}

- @else -
- -
- @endif -
- -

{{ $statusMessage }}

- - - -
- @foreach ($this->board as $status => $jobs) -
'border-t-violet-500', - 'order', 'invoiced' => 'border-t-sky-500', - 'in_production' => 'border-t-primary-500', - 'on_hold' => 'border-t-amber-500', - 'done', 'billed' => 'border-t-emerald-500', - 'ongoing' => 'border-t-teal-500', - default => 'border-t-zinc-400', - }]) - > -

- - {{ trans_choice('jobs.board.count', count($jobs), ['count' => count($jobs)]) }} -

- -
    $onlyUrgent, + 'bg-neutral-50 text-neutral-800 hover:bg-neutral-100 dark:bg-[#18191b] dark:text-neutral-100 dark:hover:bg-[#2c2f34]' => ! $onlyUrgent, + ]) > - @forelse ($jobs as $job) -
  • -
    in_array($job->priority->value, ['urgent', 'immediate'], true)]) + + {{ __('jobs.board.only_urgent') }} + + + + + {{ trans_choice('jobs.board.showing', $this->shownCardCount(), ['count' => $this->shownCardCount()]) }} +
+ +
+ {{ __('jobs.board.show_list') }} + +
+ @foreach (BoardDensity::cases() as $option) + + @endforeach +
+ + @can('jobs.manage') + + @endcan +
+
+ +

{{ $statusMessage }}

+
+ + {{-- Columns: side by side from lg up (horizontal scroll), stacked on phones --}} +
+
+ @foreach ($this->columns as $columnValue => $cards) + @php + $column = BoardColumn::from($columnValue); + $style = $this->columnStyle($column); + $sort = $this->preferences->sortOf($column); + $width = $compact ? ($column->isOngoing() ? 'lg:w-[250px]' : 'lg:w-[234px]') : ($column->isOngoing() ? 'lg:w-[268px]' : 'lg:w-[252px]'); + $columnName = __('jobs.board.column_names.'.$columnValue); + @endphp +
+
$style['light'], 'border-white/20' => ! $style['light']]) + > +
+
+ +
+ @if ($column->isUrgentLane()) + + + @endif + + - @if ($canMove) - + + + + $style['light'], 'border-white/30 bg-white/20' => ! $style['light']])> + + {{ trans_choice('jobs.board.card_count', count($cards), ['count' => count($cards)]) }} + +
+
+ +
    $compact, 'gap-2 p-2' => ! $compact]) + > + @foreach ($cards as $card) +
  • + @if ($card->isTaskCard()) + + @elseif ($card->isOngoing()) + + @else + @endif +
  • + @endforeach - {{-- TallStackUI's link is a flex row, so one flex-col span keeps the number above the name. --}} -

    - - - {{ $job->number }} - {{ $job->name }} - - -

    - -

    {{ $job->customerName }}

    - -
    - - -
    - - @if ($canMove) -
    - - @foreach ($this->statusesFor($job) as $option) - - @endforeach - -
    - @endif - - - @empty -
  • {{ __('jobs.board.empty') }}
  • - @endforelse -
-
- @endforeach + @if ($cards === []) +
  • {{ __('jobs.board.empty') }}
  • + @endif + + + @endforeach +
    - + + + + @can('jobs.manage') + + + + @endcan + + +
    diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php index 6c993c6..dde8553 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php @@ -13,6 +13,7 @@ use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\PaymentBasis; use App\Modules\Jobs\Domain\Enums\Priority; use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound; +use App\Modules\Jobs\Presentation\Livewire\Concerns\EditsJobDetails; use App\Modules\Jobs\Presentation\Livewire\Concerns\PicksCustomer; use App\Modules\Jobs\Presentation\Livewire\Forms\JobForm; use App\Modules\Shared\Domain\Exceptions\DomainException; @@ -29,7 +30,9 @@ use Livewire\Component; */ new class extends Component { - use PicksCustomer; + use EditsJobDetails, PicksCustomer { + EditsJobDetails::customerChosen insteadof PicksCustomer; + } #[Locked] public ?int $jobId = null; @@ -69,132 +72,6 @@ new class extends Component $this->form->fillFromDetails($details); } - /** - * @return list - */ - #[Computed] - public function serviceUnitOptions(): array - { - $catalog = app(CatalogQueries::class); - $options = []; - - foreach ($catalog->activeServiceUnits() as $unit) { - $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name]; - } - - // Units already on the job stay visible after being taken out of use. - foreach ($this->form->service_unit_ids as $id) { - if (! isset($options[(int) $id]) && ($unit = $catalog->findServiceUnit((int) $id)) !== null) { - $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name, 'note' => __('catalog.inactive')]; - } - } - - return array_values($options); - } - - /** - * @return list - */ - #[Computed] - public function users(): array - { - return app(UserAccountQueries::class)->activeUserOptions(); - } - - /** - * @return list - */ - #[Computed] - public function contacts(): array - { - return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id); - } - - /** - * @return list - */ - #[Computed] - public function billingUnits(): array - { - return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->billingUnitsOf((int) $this->form->customer_id); - } - - /** - * Statuses this user may choose: billing statuses for management and the - * job's biller, archived for management, and always the stored one. - * - * @return list - */ - #[Computed] - public function statusOptions(): array - { - return array_values(array_filter( - JobStatus::cases(), - fn (JobStatus $status): bool => $status->value === $this->storedStatus || $this->maySetStatus($status), - )); - } - - /** - * @return list - */ - #[Computed] - public function tagSuggestions(): array - { - return array_values(array_diff(app(CustomerJobQueries::class)->tagSuggestions($this->newTag), $this->form->tags)); - } - - public function addTag(): void - { - $tag = trim(preg_replace('/\s+/u', ' ', $this->newTag) ?? ''); - - if ($tag === '' || mb_strlen($tag) > 50) { - $this->addError('newTag', __('jobs.errors.invalid_tag')); - - return; - } - - $taken = array_map('mb_strtolower', $this->form->tags); - - if (! in_array(mb_strtolower($tag), $taken, true)) { - $this->form->tags[] = $tag; - } - - $this->newTag = ''; - $this->resetErrorBag('newTag'); - $this->statusMessage = __('jobs.tags.added', ['tag' => $tag]); - } - - public function removeTag(int $index): void - { - $tag = $this->form->tags[$index] ?? null; - - if ($tag === null) { - return; - } - - unset($this->form->tags[$index]); - $this->form->tags = array_values($this->form->tags); - $this->statusMessage = __('jobs.tags.removed', ['tag' => $tag]); - - $this->js("document.getElementById('new-tag')?.focus()"); - } - - public function addLink(): void - { - $this->form->links[] = ['title' => '', 'url' => '']; - $index = count($this->form->links) - 1; - - $this->js("document.getElementById('link-title-{$index}')?.focus()"); - } - - public function removeLink(int $index): void - { - unset($this->form->links[$index]); - $this->form->links = array_values($this->form->links); - - $this->js("document.getElementById('add-link')?.focus()"); - } - public function save(CreateCustomerJob $createJob, UpdateCustomerJob $updateJob, CustomerJobQueries $jobQueries): void { $this->authorize('jobs.manage'); @@ -239,36 +116,6 @@ new class extends Component { return $this->view()->title($this->heading()); } - - private function maySetStatus(JobStatus $status): bool - { - $stored = $this->storedStatus === null ? null : JobStatus::tryFrom($this->storedStatus); - - if ($stored !== null && $stored->unlocksTo($status) && ! Gate::allows('jobs.unlock')) { - return false; - } - - if ($status === JobStatus::Archived) { - return Gate::allows('jobs.archive'); - } - - if ($status->isBillingStatus()) { - $details = $this->jobId === null ? null : app(CustomerJobQueries::class)->findDetails($this->jobId); - - return Gate::allows('jobs.set-billing-status', [$details?->biller?->id]); - } - - return true; - } - - /** - * A contact or billing unit of another customer no longer fits. - */ - protected function customerChosen(?int $customerId): void - { - $this->form->customer_contact_id = ''; - $this->form->billing_unit_id = ''; - } }; ?> diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡job-editor.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡job-editor.blade.php new file mode 100644 index 0000000..8cc3a06 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡job-editor.blade.php @@ -0,0 +1,927 @@ +authorize('jobs.view-job', [$jobId]); + + $details = app(CustomerJobQueries::class)->findDetails($jobId); + + if ($details === null) { + return; + } + + $this->resetErrorBag(); + $this->reset('newTag', 'newTaskTitle', 'newTaskPin', 'templateId', 'statusMessage', 'customerSearch'); + $this->jobId = $details->id; + $this->loadDetails($details); + $this->newTaskAssignee = (string) $details->responsible->id; + unset($this->job, $this->tasks, $this->changes, $this->contacts, $this->billingUnits, $this->statusOptions); + + $this->js("document.getElementById('".self::DIALOG."').showModal(); document.getElementById('job-editor-name')?.focus()"); + } + + #[Computed] + public function job(): ?CustomerJobDetails + { + return $this->jobId === null ? null : app(CustomerJobQueries::class)->findDetails($this->jobId); + } + + /** + * @return list + */ + #[Computed] + public function tasks(): array + { + return $this->jobId === null ? [] : app(TaskQueries::class)->tasksOf($this->jobId); + } + + /** + * @return list + */ + #[Computed] + public function templates(): array + { + $job = $this->job; + + return $job === null ? [] : app(WorkflowTemplateQueries::class)->activeFor(array_map(fn ($unit): int => $unit->id, $job->serviceUnits)); + } + + /** + * Pinned state of the job's tasks: TaskSummary does not carry it. + * + * @return array + */ + #[Computed] + public function pinnedTasks(): array + { + return $this->jobId === null ? [] : app(TaskQueries::class)->pinnedTaskIds($this->jobId); + } + + public function canEdit(): bool + { + return Gate::allows('jobs.manage'); + } + + public function loggedHours(): string + { + $quarters = $this->jobId === null ? 0 : (app(LoggedJobHours::class)->quartersByJobs([$this->jobId])[$this->jobId] ?? 0); + + return str_replace('.', ',', rtrim(rtrim(number_format($quarters / 4, 2, '.', ''), '0'), '.')); + } + + public function changeStatus(string $value, ChangeJobStatus $changeStatus): void + { + $this->authorize('jobs.manage'); + + $status = JobStatus::tryFrom($value); + $job = $this->job; + + if ($status === null || $job === null) { + return; + } + + if ($status->value !== $this->storedStatus && ! $this->maySetStatus($status)) { + $this->addError('form.status', __('jobs.errors.status_not_allowed')); + $this->form->status = (string) $this->storedStatus; + + return; + } + + try { + $changeStatus->execute($job->id, $status, (int) auth()->id()); + } catch (CustomerJobNotFound) { + return; + } + + $this->resetErrorBag('form.status'); + $this->storedStatus = $status->value; + $this->form->status = $status->value; + unset($this->job, $this->changes, $this->statusOptions); + $this->statusMessage = __('jobs.editor.status_changed', ['number' => $job->number, 'status' => __('jobs.statuses.'.$status->value)]); + $this->dispatch('job-saved'); + } + + public function unlock(ChangeJobStatus $changeStatus): void + { + $this->authorize('jobs.unlock'); + + $this->changeStatus(JobStatus::InProduction->value, $changeStatus); + } + + public function changePriority(string $value, ChangeJobPriority $changePriority): void + { + $this->authorize('jobs.manage'); + + $priority = Priority::tryFrom($value); + $job = $this->job; + + if ($priority === null || $job === null) { + return; + } + + $changePriority->execute($job->id, $priority, (int) auth()->id()); + + $this->form->priority = $priority->value; + unset($this->job, $this->changes); + $this->statusMessage = __('jobs.editor.priority_changed', ['number' => $job->number, 'priority' => __('jobs.priorities.'.$priority->value)]); + $this->dispatch('job-saved'); + } + + public function setTaskDone(int $taskId, bool $done, ChangeTaskStatus $changeStatus): void + { + $this->authorize('jobs.update-task-status', [$this->jobId]); + + $task = $this->findTask($taskId); + + if ($task === null) { + return; + } + + try { + $changeStatus->execute((int) $this->jobId, $taskId, $done ? TaskStatus::Done : TaskStatus::InProgress); + } catch (TaskNotFound) { + return; + } + + unset($this->tasks); + $this->statusMessage = __($done ? 'jobs.board.task_done' : 'jobs.board.task_reopened', ['task' => $task->title]); + $this->dispatch('job-saved'); + } + + /** + * One field of a task row changed: title, status, assignee or due date. + */ + public function updateTaskField(int $taskId, string $field, string $value, UpdateTask $updateTask): void + { + $this->authorize('jobs.manage-tasks', [$this->jobId]); + + $task = $this->findTask($taskId); + + if ($task === null || ! in_array($field, ['title', 'status', 'assignee', 'due_on'], true)) { + return; + } + + $data = new TaskData( + title: $field === 'title' ? $value : $task->title, + workTypeId: $task->workType->id, + status: $field === 'status' ? $value : $task->status->value, + description: $task->description, + dueOn: $field === 'due_on' ? ($value === '' ? null : $value) : $task->dueOn, + estimatedHours: $task->estimatedHours, + assigneeUserId: $field === 'assignee' ? ($value === '' ? null : (int) $value) : $task->assignee?->id, + memberUserIds: array_map(fn ($member): int => $member->id, $task->members), + plannedFrom: $task->plannedFrom, + plannedTo: $task->plannedTo, + ); + + try { + $updateTask->execute((int) $this->jobId, $taskId, $data, (int) auth()->id()); + } catch (DomainException) { + $this->addError('tasks.'.$taskId, __('jobs.board.not_moved')); + unset($this->tasks); + + return; + } + + $this->resetErrorBag('tasks.'.$taskId); + unset($this->tasks); + $this->statusMessage = __('jobs.editor.task_saved', ['task' => $data->title]); + $this->dispatch('job-saved'); + } + + public function pinTask(int $taskId, bool $pinned, PinTaskToBoard $pin): void + { + $this->authorize('jobs.manage-tasks', [$this->jobId]); + + $task = $this->findTask($taskId); + + try { + $pin->execute((int) $this->jobId, $taskId, $pinned); + } catch (DomainException) { + return; + } + + unset($this->pinnedTasks); + $this->statusMessage = __($pinned ? 'jobs.board.task_pinned' : 'jobs.board.task_unpinned', ['task' => $task->title ?? '']); + $this->dispatch('job-saved'); + } + + public function addTask(AddTask $addTask, PinTaskToBoard $pin): void + { + $this->authorize('jobs.manage-tasks', [$this->jobId]); + + $title = trim($this->newTaskTitle); + $workTypeId = $this->firstWorkTypeId(); + + if ($title === '') { + $this->addError('newTaskTitle', __('jobs.board.task_title_required')); + + return; + } + + if ($workTypeId === null) { + $this->addError('newTaskTitle', __('jobs.board.no_work_type')); + + return; + } + + try { + $taskId = $addTask->execute((int) $this->jobId, new TaskData( + $title, + $workTypeId, + TaskStatus::Waiting->value, + assigneeUserId: $this->newTaskAssignee === '' ? null : (int) $this->newTaskAssignee, + ), (int) auth()->id()); + + if ($this->newTaskPin && $this->job?->status === JobStatus::Ongoing) { + $pin->execute((int) $this->jobId, $taskId, true); + } + } catch (DomainException) { + $this->addError('newTaskTitle', __('jobs.board.not_moved')); + + return; + } + + $this->reset('newTaskTitle', 'newTaskPin'); + unset($this->tasks, $this->pinnedTasks); + $this->statusMessage = __('jobs.editor.task_added', ['task' => $title]); + $this->dispatch('job-saved'); + $this->js("document.getElementById('job-editor-new-task')?.focus()"); + } + + public function applyTemplate(AddTasksFromWorkflowTemplate $addFromTemplate): void + { + $this->authorize('jobs.manage-tasks', [$this->jobId]); + + if ($this->templateId === '') { + return; + } + + try { + $result = $addFromTemplate->execute((int) $this->jobId, (int) $this->templateId, (int) auth()->id(), [], true); + } catch (DomainException) { + $this->addError('templateId', __('jobs.board.not_moved')); + + return; + } + + $this->templateId = ''; + unset($this->tasks); + $count = $result->added; + $this->statusMessage = trans_choice('jobs.editor.template_added', $count, ['count' => $count]); + $this->dispatch('job-saved'); + } + + public function save(UpdateCustomerJob $updateJob): void + { + $this->authorize('jobs.manage'); + + $job = $this->job; + + if ($job === null) { + return; + } + + // Status and priority are saved by their own controls in the header. + $this->form->status = $job->status->value; + $this->form->priority = $job->priority->value; + + try { + $updateJob->execute($job->id, $this->form->toData(), (int) auth()->id()); + } catch (CustomerJobNotFound) { + return; + } catch (DomainException $exception) { + $this->form->showDomainError($exception); + + return; + } + + $this->dispatch('job-saved'); + $this->js("document.getElementById('".self::DIALOG."').close()"); + $this->statusMessage = __('jobs.editor.saved', ['number' => $job->number]); + $this->dispatch('job-editor-saved', message: $this->statusMessage); + } + + public function render(): mixed + { + return $this->view(); + } + + private function loadDetails(CustomerJobDetails $details): void + { + $this->storedStatus = $details->status->value; + $this->customerName = $details->customer->name; + $this->form->reset(); + $this->form->fillFromDetails($details); + } + + private function findTask(int $taskId): ?TaskSummary + { + foreach ($this->tasks as $task) { + if ($task->id === $taskId) { + return $task; + } + } + + return null; + } + + private function firstWorkTypeId(): ?int + { + $job = $this->job; + + if ($job === null) { + return null; + } + + $unitIds = array_map(fn ($unit): int => $unit->id, $job->serviceUnits); + $shared = null; + + foreach (app(\App\Modules\Catalog\Application\Contracts\CatalogQueries::class)->activeWorkTypesFor($unitIds) as $node) { + $workTypes = [...$node->workTypes, ...array_merge([], ...array_map(fn ($service): array => $service->workTypes, $node->services))]; + $first = $workTypes[0]->id ?? null; + + if ($first === null) { + continue; + } + + if (in_array($node->serviceUnit->id, $unitIds, true)) { + return $first; + } + + $shared ??= $first; + } + + return $shared; + } +}; +?> + +@php + $job = $this->job; + $canEdit = $this->canEdit(); + $staff = collect($this->users)->reject(fn ($user) => $user->role === Role::Subcontractor); + $headerColor = new HexColor($job?->customer->id !== null ? (app(\App\Modules\Customers\Application\Contracts\CustomerQueries::class)->headerColorsByIds([$job->customer->id])[$job->customer->id] ?? '#23476a') : '#23476a'); + $fieldClass = 'w-full rounded-lg border border-neutral-400 bg-white px-2.5 py-1.5 text-xs text-neutral-900 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-[#6b7079] dark:bg-[#24262a] dark:text-white dark:focus-visible:outline-primary-300'; + $labelClass = 'mb-1 block text-[11px] font-semibold text-neutral-800 dark:text-neutral-100'; + $boxClass = 'space-y-2.5 rounded-xl border border-neutral-200 bg-neutral-100 p-3.5 dark:border-[#36393f] dark:bg-[#18191b]'; + $boxHeading = 'text-[10px] font-extrabold tracking-wider text-neutral-700 uppercase dark:text-neutral-200'; +@endphp + +
    + + +
    +
    + {{ $job?->number }} +

    + {{ __('jobs.editor.heading', ['number' => $job?->number]) }}: {{ $job?->customer->name }} +

    + @if ($job !== null && Gate::allows('customers.use')) + + @endif +
    + +
    + @if ($job !== null) +
    + + +
    +
    + + +
    + @endif + +
    +
    +
    + + @if ($job !== null) + @error('form.status') + + @enderror + + @if (in_array($job->status, [JobStatus::Done, JobStatus::Invoiced, JobStatus::Billed], true)) +
    + + @can('jobs.unlock') + + @endcan +
    + @endif + +

    {{ $statusMessage }}

    + @unless ($canEdit) +

    {{ __('jobs.editor.read_only') }}

    + @endunless + +
    + {{-- Left: content, tasks and records --}} +
    +
    +
    + + + @error('form.name')

    {{ $message }}

    @enderror +
    +
    +
    + + +
    +
    + + +
    +
    +
    + +
    +
    + + @if ($canEdit) + + @endif +
    + @if ($form->links === []) +

    {{ __('jobs.links.none') }}

    + @endif + + @error('form.links')

    {{ $message }}

    @enderror +
    + + {{-- Tasks --}} +
    +
    +
    +

    {{ $job->status === JobStatus::Ongoing ? __('jobs.editor.tasks_ongoing') : __('jobs.editor.tasks') }}

    +

    {{ $job->status === JobStatus::Ongoing ? __('jobs.editor.tasks_hint_ongoing') : __('jobs.editor.tasks_hint') }}

    +
    + @if (Gate::allows('jobs.manage-tasks', [$job->id]) && $this->templates !== [] && $job->status->allowsTasks()) +
    + + + +
    + @endif +
    + + @if ($this->tasks === []) +

    {{ __('jobs.editor.no_tasks') }}

    + @endif + +
      + @foreach ($this->tasks as $task) + @php($canManageTask = Gate::allows('jobs.manage-tasks', [$job->id])) +
    • +
      +
      + status === TaskStatus::Done) + @disabled(! Gate::allows('jobs.update-task-status', [$job->id])) + wire:change="setTaskDone({{ $task->id }}, $event.target.checked)" + aria-label="{{ __('jobs.editor.task_done', ['task' => $task->title]) }}" + class="size-4 rounded border-neutral-500 text-emerald-700 dark:border-neutral-400 dark:bg-[#16171a]" + /> + @if ($canManageTask) + + + @else + {{ $task->title }} + @endif +
      + + @if ($canManageTask) +
      + + + + + + + @if ($job->status === JobStatus::Ongoing) + @php($pinned = $this->pinnedTasks[$task->id] ?? false) + + @endif +
      + @endif +
      + @error('tasks.'.$task->id)

      {{ $message }}

      @enderror + +
      + +
      + +
      +
      +
    • + @endforeach +
    + + @if (Gate::allows('jobs.manage-tasks', [$job->id]) && $job->status->allowsTasks()) +
    +
    + + + + + +
    + @error('newTaskTitle')

    {{ $message }}

    @enderror + @if ($job->status === JobStatus::Ongoing) + + @endif +
    + @endif +
    + + {{-- Records: hours, expenses, history --}} +
    + + + + + + + + + @if ($this->changes === []) +

    {{ __('jobs.history.empty') }}

    + @else +
      + @foreach ($this->changes as $change) +
    1. + + {{ $change->userName }}: + @if ($change->field === 'created') + {{ __('jobs.history.created', ['user' => $change->userName, 'number' => $change->newValue]) }} + @else + {{ __('jobs.history.changed', [ + 'field' => __('jobs.fields.'.$change->field), + 'old' => $this->historyValue($change->field, $change->oldValue), + 'new' => $this->historyValue($change->field, $change->newValue), + ]) }} + @endif + + {{ CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i') }} +
    2. + @endforeach +
    + @endif +
    +
    +
    +
    + + {{-- Right: metadata, schedule, team and money --}} +
    + {{ __('jobs.sections.basics') }} + +
    +

    {{ __('jobs.editor.customer_section') }}

    + +
    + + +
    +
    + + +
    +
    + +
    +

    {{ __('jobs.editor.team_section') }}

    + @foreach (['responsible_user_id' => 'responsible_user', 'contact_user_id' => 'contact_user', 'biller_user_id' => 'biller_user'] as $field => $label) +
    + + + @error('form.'.$field)

    {{ $message }}

    @enderror +
    + @endforeach + +
    + +
    +

    {{ __('jobs.editor.units_section') }}

    + +
    +

    {{ __('jobs.fields.tags') }}

    + @if ($form->tags !== []) +
      + @foreach ($form->tags as $index => $tag) +
    • + {{ $tag }} + @if ($canEdit) + + @endif +
    • + @endforeach +
    + @endif + @if ($canEdit) +
    + + + + @foreach ($this->tagSuggestions as $suggestion) + + @endforeach + + +
    + @error('newTag')

    {{ $message }}

    @enderror + @endif +
    +
    + +
    +

    {{ __('jobs.editor.schedule_section') }}

    +
    + + +
    +
    + @foreach (['starts_on', 'due_on', 'planned_from', 'planned_to'] as $field) +
    + + + @error('form.'.$field)

    {{ $message }}

    @enderror +
    + @endforeach +
    +
    + + + @error('form.estimated_hours')

    {{ $message }}

    @enderror +
    +
    + +
    +

    {{ __('jobs.editor.money_section') }}

    +
    + + +
    + @can('money.quotes') +
    +
    + + + @error('form.quoted_amount')

    {{ $message }}

    @enderror +
    + @if ($form->payment_basis === 'monthly_fee') +
    + + + @error('form.monthly_fee')

    {{ $message }}

    @enderror +
    + @endif +
    + @else +

    {{ __('jobs.editor.money_hidden') }}

    + @endcan +
    + + +
    +
    +
    +
    + @endif + + + {{ __('jobs.editor.footer') }} +
    + @if ($job !== null) + {{ __('jobs.editor.open_page') }} + @endif + @if ($job !== null && $canEdit) + + @endif +
    +
    +
    +
    diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡quick.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡quick.blade.php index 2ca3fe0..74fb6cc 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡quick.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡quick.blade.php @@ -2,9 +2,13 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary; +use App\Modules\Customers\Application\Contracts\CustomerQueries; +use App\Modules\Customers\Application\DTOs\ContactData; +use App\Modules\Customers\Application\DTOs\ContactSummary; +use App\Modules\Customers\Application\UseCases\AddContact; use App\Modules\Jobs\Application\Contracts\CustomerJobQueries; use App\Modules\Jobs\Application\UseCases\CreateCustomerJob; -use App\Modules\Jobs\Domain\Enums\JobStatus; +use App\Modules\Jobs\Domain\Enums\Priority; use App\Modules\Jobs\Presentation\Livewire\Concerns\PicksCustomer; use App\Modules\Jobs\Presentation\Livewire\Forms\QuickJobForm; use App\Modules\Shared\Domain\Exceptions\DomainException; @@ -16,16 +20,25 @@ use Livewire\Attributes\Locked; use Livewire\Component; /** - * Quick job intake (pikavastaanotto), made for phones: customer, name, - * short description, service unit and responsible person. The page stays - * open for the next job and links to the one just created. + * Quick job intake (pikavastaanotto, docs/ui-kanban-board.md 6), made for + * phones and also opened as a dialog on the Kanban board: customer and its + * contact person (with a quick add), name, short description, service + * unit, responsible person, initial status and priority. The page stays + * open for the next job and links to the one just created; the dialog + * closes and the board shows the new card. */ new class extends Component { use PicksCustomer; + public const string DIALOG = 'quick-intake-dialog'; + public QuickJobForm $form; + /** Embedded in the board's dialog instead of being the page. */ + #[Locked] + public bool $inDialog = false; + /** * The job created last on this page, shown with links to it. */ @@ -38,10 +51,11 @@ new class extends Component #[Locked] public string $createdNumber = ''; - public function mount(): void + public function mount(bool $inDialog = false): void { $this->authorize('jobs.manage'); + $this->inDialog = $inDialog; $this->form->responsible_user_id = (string) auth()->id(); } @@ -68,10 +82,40 @@ new class extends Component )); } - public function save(CreateCustomerJob $createJob, CustomerJobQueries $jobQueries): void + /** + * @return list + */ + #[Computed] + public function contacts(): array + { + return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id); + } + + public function save(CreateCustomerJob $createJob, CustomerJobQueries $jobQueries, AddContact $addContact): void { $this->authorize('jobs.manage'); + $this->form->validate(); + + if ($this->form->adding_contact && trim($this->form->new_contact_name) !== '') { + $this->authorize('customers.use'); + + try { + $contactId = $addContact->execute((int) $this->form->customer_id, new ContactData( + name: trim($this->form->new_contact_name), + phone: trim($this->form->new_contact_phone) === '' ? null : trim($this->form->new_contact_phone), + )); + } catch (DomainException) { + $this->addError('form.new_contact_name', __('jobs.quick.contact_name_required')); + + return; + } + + $this->form->customer_contact_id = (string) $contactId; + $this->form->adding_contact = false; + unset($this->contacts); + } + $data = $this->form->toData(); try { @@ -90,6 +134,15 @@ new class extends Component $this->customerName = ''; $this->customerSearch = ''; $this->statusMessage = ''; + unset($this->contacts); + + if ($this->inDialog) { + $this->dispatch('quick-job-created', status: $data->status); + $this->dispatch('job-editor-saved', message: $this->createdMessage); + $this->js("document.getElementById('".self::DIALOG."').close()"); + + return; + } $this->js("document.getElementById('quick-created')?.focus()"); } @@ -98,33 +151,44 @@ new class extends Component { return $this->view()->title(__('jobs.quick.title')); } + + /** + * A contact person of another customer no longer fits. + */ + protected function customerChosen(?int $customerId): void + { + $this->form->customer_contact_id = ''; + unset($this->contacts); + } }; ?> -
    -
    - {{ __('jobs.quick.title') }} -

    {{ __('jobs.quick.intro') }}

    -
    +
    ! $inDialog])> + @unless ($inDialog) +
    + {{ __('jobs.quick.title') }} +

    {{ __('jobs.quick.intro') }}

    +
    -
    - @if ($createdJobId !== null) -
    -

    -

    -

    - {{ __('jobs.quick.open', ['number' => $createdNumber]) }} - {{ __('jobs.quick.complete') }} -

    -
    - @endif -
    +
    + @if ($createdJobId !== null) +
    +

    +

    +

    + {{ __('jobs.quick.open', ['number' => $createdNumber]) }} + {{ __('jobs.quick.complete') }} +

    +
    + @endif +
    + @endunless -

    {{ $statusMessage }}

    +

    $inDialog])>{{ $statusMessage }}

    -
    + ! $inDialog, 'space-y-4 px-5 pb-5' => $inDialog]) novalidate> - +
    +
    +
    + + + @foreach ($this->contacts as $contact) + + @endforeach + +
    + @if ($form->customer_id !== '') + + @endif +
    + @if ($form->adding_contact && $form->customer_id !== '') +
    + + +
    + @endif +
    - + - {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} - - - @foreach ($this->serviceUnits as $unit) - - @endforeach - + - - - @foreach ($this->staff as $user) - - @endforeach - +
    + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach ($this->serviceUnits as $unit) + + @endforeach + - + + + @foreach ($this->staff as $user) + + @endforeach + - + + @foreach (QuickJobForm::startStatuses() as $status) + + @endforeach + + + + @foreach (Priority::cases() as $priority) + + @endforeach + +
    + + @if ($inDialog) +
    + + +
    + @else + + @endif
    diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index cb9114c..b0ce516 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -19,6 +19,7 @@ use App\Modules\Shared\Domain\ValueObjects\Money; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Attributes\On; +use App\Modules\Jobs\Presentation\Livewire\Concerns\DescribesJobHistory; use Livewire\Component; /** @@ -26,6 +27,8 @@ use Livewire\Component; */ new class extends Component { + use DescribesJobHistory; + #[Locked] public int $jobId; @@ -57,20 +60,6 @@ new class extends Component return app(CustomerJobQueries::class)->findDetails($this->jobId) ?? abort(404); } - /** - * @return list - */ - #[Computed] - public function changes(): array - { - $changes = app(CustomerJobQueries::class)->changes($this->jobId); - - // Changes of the quoted amount are shown only to those who may see quotes (spec 5.7). - return Gate::allows('money.quotes') - ? $changes - : array_values(array_filter($changes, fn (JobChangeEntry $change): bool => ! in_array($change->field, ['quoted_amount', 'monthly_fee'], true))); - } - /** * @return list */ @@ -159,43 +148,6 @@ new class extends Component $this->js("document.getElementById('remove-task-dialog').close(); document.getElementById('tasks-heading').focus()"); } - public function formatDate(?string $date): string - { - return $date === null ? __('jobs.not_set') : CarbonImmutable::parse($date)->format('j.n.Y'); - } - - /** - * A history value as text: names for ids, labels for enum keys, - * Finnish dates. - */ - public function historyValue(string $field, ?string $value): string - { - if ($value === null || $value === '') { - return __('jobs.not_set'); - } - - $ids = array_map('intval', explode(',', $value)); - $named = fn (array $names): string => implode(', ', array_map( - fn (int $id): string => $names[$id] ?? __('jobs.history.unknown', ['id' => $id]), - $ids, - )); - - return match ($field) { - 'starts_on', 'due_on', 'planned_from', 'planned_to' => $this->formatDate($value), - 'quoted_amount', 'monthly_fee' => Money::fromCents((int) $value)->format(), - 'kind' => __('jobs.kinds.'.$value), - 'status' => __('jobs.statuses.'.$value), - 'priority' => __('jobs.priorities.'.$value), - 'payment_basis' => __('jobs.payment_bases.'.$value), - 'customer' => $named(app(CustomerQueries::class)->namesByIds($ids)), - 'service_units' => $named(app(CatalogQueries::class)->serviceUnitNames($ids)), - 'responsible_user', 'contact_user', 'biller_user', 'members' => $named(app(UserAccountQueries::class)->namesByIds($ids)), - 'customer_contact' => app(CustomerQueries::class)->findContact($this->job->customer->id, $ids[0])->name ?? __('jobs.history.unknown', ['id' => $ids[0]]), - 'billing_unit' => app(CustomerQueries::class)->findBillingUnit($this->job->customer->id, $ids[0])->name ?? __('jobs.history.unknown', ['id' => $ids[0]]), - default => $value, - }; - } - public function render(): mixed { return $this->view()->title($this->job->number.' '.$this->job->name); diff --git a/app/Modules/Jobs/Presentation/Support/BoardFormat.php b/app/Modules/Jobs/Presentation/Support/BoardFormat.php new file mode 100644 index 0000000..df2f68c --- /dev/null +++ b/app/Modules/Jobs/Presentation/Support/BoardFormat.php @@ -0,0 +1,39 @@ +format('j.n.'); + } + + public static function hours(float|string|null $hours): string + { + if ($hours === null || $hours === '') { + return '0'; + } + + $text = rtrim(rtrim(number_format((float) $hours, 2, '.', ''), '0'), '.'); + + return str_replace('.', ',', $text === '' ? '0' : $text); + } + + /** + * "1,5/4 h": recorded against estimated hours. + */ + public static function cardHours(BoardCard $card): string + { + return __('jobs.board.hours', [ + 'logged' => self::hours($card->loggedHours()), + 'estimated' => self::hours($card->estimatedHours), + ]); + } +} diff --git a/app/Modules/TimeTracking/Presentation/Livewire/⚡job-quick-hours.blade.php b/app/Modules/TimeTracking/Presentation/Livewire/⚡job-quick-hours.blade.php new file mode 100644 index 0000000..b30e820 --- /dev/null +++ b/app/Modules/TimeTracking/Presentation/Livewire/⚡job-quick-hours.blade.php @@ -0,0 +1,143 @@ +authorize('time.use'); + + $this->jobId = $jobId; + $this->taskId = (string) ($this->tasks[0]->id ?? ''); + } + + /** + * @return list + */ + #[Computed] + public function tasks(): array + { + return array_values(array_filter( + app(TaskQueries::class)->tasksOf($this->jobId), + fn (TaskSummary $task): bool => $task->status !== TaskStatus::Done, + )); + } + + public function isLocked(): bool + { + return app(CustomerJobQueries::class)->findDetails($this->jobId)?->status->locksTime() ?? true; + } + + public function loggedHours(): string + { + $quarters = app(TimeEntryQueries::class)->quartersByJobs([$this->jobId])[$this->jobId] ?? 0; + + return str_replace('.', ',', rtrim(rtrim(number_format($quarters / 4, 2, '.', ''), '0'), '.')); + } + + public function estimatedHours(): string + { + $estimate = app(CustomerJobQueries::class)->findDetails($this->jobId)?->estimatedHours; + + return $estimate === null ? '0' : str_replace('.', ',', rtrim(rtrim($estimate, '0'), '.')); + } + + public function save(AddTaskHours $addHours, Clock $clock): void + { + $this->authorize('time.book', $this->jobId); + + $task = collect($this->tasks)->first(fn (TaskSummary $task): bool => (string) $task->id === $this->taskId); + + if ($task === null) { + $this->addError('taskId', __('time.quick_hours.no_tasks')); + + return; + } + + try { + $saved = $addHours->execute((int) auth()->id(), $task->id, $clock->today()->format('Y-m-d'), $this->hours, trim($this->note) === '' ? null : trim($this->note)); + } catch (InvalidWorkedHours) { + $this->addError('hours', __('time.errors.invalid_hours')); + + return; + } catch (DailyHoursExceeded) { + $this->addError('hours', __('time.errors.day_full')); + + return; + } catch (TimeLocked|TimeApproved) { + $this->addError('hours', __('time.quick_hours.locked')); + + return; + } catch (DomainException) { + $this->addError('hours', __('time.quick_hours.not_allowed')); + + return; + } + + $this->reset('hours', 'note'); + $this->statusMessage = __('time.quick_hours.added', ['hours' => $saved, 'task' => $task->title]); + $this->dispatch('job-saved'); + } +}; +?> + +
    + @if ($this->isLocked()) +

    {{ __('time.quick_hours.locked') }}

    + @elseif ($this->tasks === []) +

    {{ __('time.quick_hours.no_tasks') }}

    + @elseif (Gate::allows('time.book', $jobId)) +
    +
    + + @foreach ($this->tasks as $task) + + @endforeach + +
    +
    + +
    +
    + +
    +
    + +
    +
    + @endif + +

    {{ $statusMessage }}

    +

    {{ __('time.quick_hours.total', ['logged' => $this->loggedHours(), 'estimated' => $this->estimatedHours()]) }}

    +
    diff --git a/lang/en/expenses.php b/lang/en/expenses.php index 3f58f33..1f89f5a 100644 --- a/lang/en/expenses.php +++ b/lang/en/expenses.php @@ -110,4 +110,15 @@ return [ 'invalid_markup' => 'Enter the markup as a percentage, e.g. 15 (at most two decimals).', 'text_too_long' => 'The text may be at most 255 characters.', ], + 'quick' => [ + 'description' => 'Expense', + 'description_placeholder' => 'E.g. print media', + 'amount' => 'Amount (€, VAT 0)', + 'add' => 'Add expense', + 'added' => 'Expense :description added.', + 'hidden' => 'Hidden (money permission)', + 'none' => 'The job has no expenses.', + 'all' => 'All expenses of the job', + 'locked' => 'The job\'s expenses are locked.', + ], ]; diff --git a/lang/en/jobs.php b/lang/en/jobs.php index 22dc6c4..e5c1bbe 100644 --- a/lang/en/jobs.php +++ b/lang/en/jobs.php @@ -307,6 +307,58 @@ return [ 'density_saved' => 'Card density: :density.', ], + 'editor' => [ + 'heading' => 'Customer job :number', + 'close' => 'Close the card', + 'color' => 'Colour', + 'color_label' => 'Change the colour of customer :customer', + 'status' => 'Status', + 'priority' => 'Priority', + 'locked' => 'The job is marked done – its hours and expenses are locked for billing.', + 'unlock' => 'Open the lock (management)', + 'read_only' => 'You can mark tasks done, but not change the job\'s details.', + 'links' => 'File links (Drive, Dropbox, materials)', + 'tasks' => 'Tasks of the customer job', + 'tasks_ongoing' => 'Periods and tasks of the continuing job', + 'tasks_hint' => 'Manage work steps, assignees, due dates and checklists.', + 'tasks_hint_ongoing' => 'Mark done or lift a flexible task into the pipeline (PIN).', + 'no_tasks' => 'The job has no tasks yet.', + 'task_done' => 'Done: :task', + 'task_title' => 'Task name', + 'task_status' => 'Status of task :task', + 'task_assignee' => 'Assignee of task :task', + 'task_due' => 'Due date of task :task', + 'no_assignee' => 'No assignee', + 'checklist' => 'Checklist', + 'template' => 'Workflow template', + 'template_choose' => '+ Add from a workflow template…', + 'template_apply' => 'Create', + 'template_added' => '{0} No tasks were added from the template.|{1} :count task was added from the template.|[2,*] :count tasks were added from the template.', + 'new_task' => 'Name of the new task', + 'new_task_placeholder' => 'Add a new task to this customer job…', + 'new_task_assignee' => 'Assignee of the new task', + 'add_task' => 'Add', + 'pin_new' => 'Lift the new task into the pipeline as a card of its own (PIN)', + 'task_added' => 'Task :task added.', + 'task_saved' => 'Task :task saved.', + 'tabs_label' => 'Records', + 'tab_hours' => 'Time entries (:hours h)', + 'tab_expenses' => 'Expenses', + 'tab_history' => 'Change history (:count)', + 'customer_section' => 'Customer and billing unit', + 'team_section' => 'Own team and members', + 'units_section' => 'Service units and tags', + 'schedule_section' => 'Schedule and kind', + 'money_section' => 'Billing and money', + 'money_hidden' => 'Quote and billing amounts are hidden from your role (2.3 Visibility of amounts).', + 'footer' => 'Changes are saved to the customer job and recorded in its change history.', + 'save' => 'Save and close', + 'open_page' => 'Open the job page', + 'saved' => 'Changes to customer job :number saved.', + 'status_changed' => 'Status of job :number: :status.', + 'priority_changed' => 'Priority of job :number: :priority.', + ], + 'calendar' => [ 'title' => 'Task calendar', 'intro' => 'Tasks by assignee according to their schedule. Move a task by dragging its bar, change its length by dragging the bar\'s edge, or open the bar as a button to change the schedule, assignee and status in a form.', @@ -383,6 +435,14 @@ return [ 'open' => 'Open job :number', 'complete' => 'Complete details', 'link' => 'Quick intake', + 'dialog_title' => 'New job / Quick intake', + 'contact' => 'Customer contact person', + 'add_contact' => '+ Quick add new', + 'add_contact_label' => 'Quick add a new contact person', + 'contact_name' => 'Name of the new contact person', + 'contact_phone' => 'Phone', + 'contact_name_required' => 'Enter the name of the new contact person.', + 'start_status' => 'Initial status', ], 'list' => [ diff --git a/lang/en/time.php b/lang/en/time.php index 6f50753..fc09aed 100644 --- a/lang/en/time.php +++ b/lang/en/time.php @@ -103,4 +103,16 @@ return [ 'open_week_of' => 'Open week: :name, :week', 'approver_value' => ':name, :date', ], + 'quick_hours' => [ + 'task' => 'Task', + 'hours' => 'Hours today', + 'note' => 'Description', + 'note_placeholder' => 'E.g. layout and proofs', + 'add' => 'Record hours', + 'added' => ':hours h recorded on task :task for today.', + 'total' => 'Recorded in all: :logged h / estimate: :estimated h.', + 'locked' => 'The job\'s hours are locked, so no hours can be recorded.', + 'no_tasks' => 'The job has no open tasks to record hours on.', + 'not_allowed' => 'You cannot record hours on this job.', + ], ]; diff --git a/lang/fi/expenses.php b/lang/fi/expenses.php index a1a6dfc..55d8872 100644 --- a/lang/fi/expenses.php +++ b/lang/fi/expenses.php @@ -110,4 +110,15 @@ return [ 'invalid_markup' => 'Anna kate prosentteina, esim. 15 (enintään kaksi desimaalia).', 'text_too_long' => 'Teksti voi olla enintään 255 merkkiä.', ], + 'quick' => [ + 'description' => 'Kulu', + 'description_placeholder' => 'Esim. tulostusmedia', + 'amount' => 'Summa (€, ALV 0)', + 'add' => 'Lisää kulu', + 'added' => 'Kulu :description lisätty.', + 'hidden' => 'Piilotettu (rahaoikeus)', + 'none' => 'Työllä ei ole kuluja.', + 'all' => 'Kaikki työn kulut', + 'locked' => 'Työn kulut on lukittu.', + ], ]; diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 3eb1c79..085182c 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -307,6 +307,58 @@ return [ 'density_saved' => 'Korttien tiheys: :density.', ], + 'editor' => [ + 'heading' => 'Asiakastyö :number', + 'close' => 'Sulje kortti', + 'color' => 'Väri', + 'color_label' => 'Vaihda asiakkaan :customer väri', + 'status' => 'Tila', + 'priority' => 'Prioriteetti', + 'locked' => 'Työ on merkitty valmiiksi – tunnit ja kulut on lukittu laskutusta varten.', + 'unlock' => 'Avaa lukitus (johto)', + 'read_only' => 'Voit kuitata tehtäviä, mutta et muuttaa työn tietoja.', + 'links' => 'Tiedostolinkit (Drive, Dropbox, aineistot)', + 'tasks' => 'Asiakastyön tehtävät', + 'tasks_ongoing' => 'Jatkuvan työn jaksot ja tehtävät', + 'tasks_hint' => 'Hallitse työvaiheita, tekijöitä, määräpäiviä ja tarkistuslistoja.', + 'tasks_hint_ongoing' => 'Kuittaa valmiiksi tai nosta joustava tehtävä työputkeen (PIN).', + 'no_tasks' => 'Työllä ei ole vielä tehtäviä.', + 'task_done' => 'Valmis: :task', + 'task_title' => 'Tehtävän nimi', + 'task_status' => 'Tehtävän :task tila', + 'task_assignee' => 'Tehtävän :task tekijä', + 'task_due' => 'Tehtävän :task määräpäivä', + 'no_assignee' => 'Ei tekijää', + 'checklist' => 'Tarkistuslista', + 'template' => 'Työnkulkupohja', + 'template_choose' => '+ Lisää työnkulkupohjasta…', + 'template_apply' => 'Luo', + 'template_added' => '{0} Pohjasta ei lisätty tehtäviä.|{1} Pohjasta lisättiin :count tehtävä.|[2,*] Pohjasta lisättiin :count tehtävää.', + 'new_task' => 'Uuden tehtävän nimi', + 'new_task_placeholder' => 'Lisää uusi tehtävä tälle asiakastyölle…', + 'new_task_assignee' => 'Uuden tehtävän tekijä', + 'add_task' => 'Lisää', + 'pin_new' => 'Nosta uusi tehtävä samalla työputkeen omana korttinaan (PIN)', + 'task_added' => 'Tehtävä :task lisätty.', + 'task_saved' => 'Tehtävä :task tallennettu.', + 'tabs_label' => 'Kirjaukset', + 'tab_hours' => 'Tuntikirjaukset (:hours h)', + 'tab_expenses' => 'Kulut', + 'tab_history' => 'Muutoshistoria (:count)', + 'customer_section' => 'Asiakas ja laskutusyksikkö', + 'team_section' => 'Oma tiimi ja jäsenet', + 'units_section' => 'Palveluyksiköt ja tagit', + 'schedule_section' => 'Aikataulu ja laji', + 'money_section' => 'Laskutus ja raha', + 'money_hidden' => 'Tarjous- ja laskutussummat on piilotettu käyttäjäroolilta (2.3 Rahamäärien näkyvyys).', + 'footer' => 'Muutokset tallentuvat asiakastyölle ja kirjautuvat muutoshistoriaan.', + 'save' => 'Tallenna ja sulje', + 'open_page' => 'Avaa työsivu', + 'saved' => 'Asiakastyön :number muutokset tallennettu.', + 'status_changed' => 'Työn :number tila: :status.', + 'priority_changed' => 'Työn :number prioriteetti: :priority.', + ], + 'calendar' => [ 'title' => 'Tehtäväkalenteri', 'intro' => 'Tehtävät tekijöittäin aikataulun mukaan. Siirrä tehtävää vetämällä palkkia, muuta kestoa vetämällä palkin reunasta tai avaa palkki painikkeena, jolloin aikataulun, tekijän ja tilan voi muuttaa lomakkeella.', @@ -383,6 +435,14 @@ return [ 'open' => 'Avaa työ :number', 'complete' => 'Täydennä tietoja', 'link' => 'Pikavastaanotto', + 'dialog_title' => 'Uusi työ / Pikavastaanotto', + 'contact' => 'Asiakkaan kontaktihenkilö', + 'add_contact' => '+ Pikalisää uusi', + 'add_contact_label' => 'Pikalisää uusi kontaktihenkilö', + 'contact_name' => 'Uuden kontaktihenkilön nimi', + 'contact_phone' => 'Puhelin', + 'contact_name_required' => 'Anna uuden kontaktihenkilön nimi.', + 'start_status' => 'Alkutila', ], 'list' => [ diff --git a/lang/fi/time.php b/lang/fi/time.php index 9a3f175..2e295a3 100644 --- a/lang/fi/time.php +++ b/lang/fi/time.php @@ -103,4 +103,16 @@ return [ 'open_week_of' => 'Avaa viikko: :name, :week', 'approver_value' => ':name, :date', ], + 'quick_hours' => [ + 'task' => 'Tehtävä', + 'hours' => 'Tunnit tänään', + 'note' => 'Selite', + 'note_placeholder' => 'Esim. taitto ja vedostus', + 'add' => 'Kirjaa tunnit', + 'added' => ':hours h kirjattu tehtävälle :task tälle päivälle.', + 'total' => 'Yhteensä kirjattu: :logged h / arvio: :estimated h.', + 'locked' => 'Työn tunnit on lukittu, joten tunteja ei voi kirjata.', + 'no_tasks' => 'Työllä ei ole avoimia tehtäviä, joille kirjata tunteja.', + 'not_allowed' => 'Et voi kirjata tunteja tälle työlle.', + ], ]; diff --git a/resources/css/app.css b/resources/css/app.css index 1f82b12..11f33a0 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -72,3 +72,29 @@ html { @utility card { @apply rounded-xl border border-zinc-200 bg-white p-4 shadow-sm sm:p-5 dark:border-zinc-700 dark:bg-zinc-900; } + +/* The Kanban board's horizontal scrollbar (docs/kanban-prototyyppi.html). */ +.kanban-scroll::-webkit-scrollbar { + height: 10px; + width: 8px; +} + +.kanban-scroll::-webkit-scrollbar-track { + background: rgb(0 0 0 / 0.18); + border-radius: 9999px; +} + +.kanban-scroll::-webkit-scrollbar-thumb { + background: rgb(255 255 255 / 0.4); + border-radius: 9999px; +} + +/* The card being dragged on the board, and the drop place. */ +[wire\:sort\:item].sortable-ghost { + opacity: 0.45; +} + +[wire\:sort\:item].sortable-ghost > article { + outline: 3px solid var(--color-indigo-400); + outline-offset: 1px; +} diff --git a/resources/views/components/jobs/board/card-header.blade.php b/resources/views/components/jobs/board/card-header.blade.php new file mode 100644 index 0000000..927ad54 --- /dev/null +++ b/resources/views/components/jobs/board/card-header.blade.php @@ -0,0 +1,47 @@ +{{-- + The customer-coloured top bar of a job card: the drag handle + (wire:sort:handle) and a click target that opens the job editor. The + keyboard opens the job from the title button below; the palette button + changes the customer's colour for every card and the time sheet. +--}} +@props(['card', 'canMove' => false, 'canColor' => false]) + +@php + $color = new \App\Modules\Shared\Domain\ValueObjects\HexColor($card->customerHeaderColor ?? '#23476a'); + $light = $color->isLight(); +@endphp + +
    $canMove, 'cursor-pointer' => ! $canMove]) +> +
    + @if ($canMove) +
    +
    + $light, 'bg-white/20' => ! $light])>{{ $card->number }} + @if ($canColor) + + @endif +
    +
    diff --git a/resources/views/components/jobs/board/job-card.blade.php b/resources/views/components/jobs/board/job-card.blade.php new file mode 100644 index 0000000..18bad64 --- /dev/null +++ b/resources/views/components/jobs/board/job-card.blade.php @@ -0,0 +1,99 @@ +{{-- + A customer job card (docs/ui-kanban-board.md 4.1): customer bar, title + that opens the job editor, responsible person, service unit, priority, + due date, hours and the job's tasks, which open inside the card and can + be marked done. Compact cards have three rows. +--}} +@props(['card', 'compact' => false, 'canMove' => false, 'canColor' => false, 'canCheck' => false]) + +@use('App\Modules\Jobs\Presentation\Support\BoardFormat') + +@php + $total = count($card->tasks); + $done = $card->doneTaskCount(); +@endphp + +
    + + +
    $compact, 'space-y-2 p-2.5' => ! $compact])> +

    + +

    + + @if ($compact) +
    +
    + + +
    + @if ($total > 0) + + @endif +
    + @else +
    + +
    + @if ($card->serviceUnitName !== null) + {{ $card->serviceUnitName }} + @endif + +
    +
    + +

    + @if ($card->isLate) + + + @else + {{ __('jobs.board.due', ['date' => BoardFormat::shortDate($card->dueOn)]) }} + @endif + + {{ BoardFormat::cardHours($card) }} +

    + + @if ($total > 0) +
    + +
    + @endif + @endif + + @if ($total > 0) +
    $compact, 'mt-1.5' => ! $compact])> + +
    + @endif +
    +
    diff --git a/resources/views/components/jobs/board/menu.blade.php b/resources/views/components/jobs/board/menu.blade.php new file mode 100644 index 0000000..72259ec --- /dev/null +++ b/resources/views/components/jobs/board/menu.blade.php @@ -0,0 +1,59 @@ +{{-- + A small header button that opens a list of choices (menuitemradio): + the urgent threshold and a column's order. Escape and a click outside + close it; focus returns to the button. + + Props: `label` (the button's name), `heading`, `options` (value => text), + `current` (value), `method` and `args` (the Livewire call, with the + chosen value last), `active` (highlights the button). +--}} +@props(['id', 'label', 'heading', 'options', 'current', 'method', 'args' => [], 'active' => false]) + +
    + + + +
    diff --git a/resources/views/components/jobs/board/ongoing-card.blade.php b/resources/views/components/jobs/board/ongoing-card.blade.php new file mode 100644 index 0000000..5bc60d1 --- /dev/null +++ b/resources/views/components/jobs/board/ongoing-card.blade.php @@ -0,0 +1,105 @@ +{{-- + A continuing / season job card (docs/ui-kanban-board.md 4.2): the next + open task with a one-click "mark done", lifting tasks into the pipeline + (PIN), and all periods and tasks with a quick add. +--}} +@props(['card', 'compact' => false, 'canMove' => false, 'canColor' => false, 'canCheck' => false, 'canManage' => false]) + +@php + $total = count($card->tasks); + $done = $card->doneTaskCount(); + $next = $card->nextOpenTask(); +@endphp + +
    + + +
    $compact, 'space-y-2 p-2.5' => ! $compact])> +

    + +

    + +
    +
    + + {{ __('jobs.board.periods', ['done' => $done, 'total' => $total]) }} +
    + @if ($compact) + + @endif +
    + + @if (! $compact && $next !== null) +
    +

    {{ __('jobs.board.next_up') }}

    +

    {{ $next->title }}

    +
    + @if ($canCheck) + + @endif + @if ($canManage) + + @endif +
    +
    + @endif + + @unless ($compact) +
    + +
    + @endunless + +
    + +
    +
    +
    diff --git a/resources/views/components/jobs/board/person.blade.php b/resources/views/components/jobs/board/person.blade.php new file mode 100644 index 0000000..1579997 --- /dev/null +++ b/resources/views/components/jobs/board/person.blade.php @@ -0,0 +1,7 @@ +{{-- A person on a Kanban card: initials in a ball and the first name. --}} +@props(['initials', 'name' => null]) + +class('inline-flex shrink-0 items-center gap-1 rounded bg-neutral-100 px-1.5 py-0.5 font-semibold text-neutral-800 dark:bg-[#1e2023] dark:text-neutral-100') }}> + + {{ $name ?? '–' }} + diff --git a/resources/views/components/jobs/board/priority-badge.blade.php b/resources/views/components/jobs/board/priority-badge.blade.php new file mode 100644 index 0000000..825f774 --- /dev/null +++ b/resources/views/components/jobs/board/priority-badge.blade.php @@ -0,0 +1,22 @@ +{{-- + A Kanban card's priority badge: the text carries the meaning, the + colour only supports it; "Heti" also gets the striped dot. +--}} +@props(['priority']) + +@php + $classes = match ($priority->value) { + 'immediate' => 'bg-orange-100 text-red-950 border-orange-400 dark:bg-orange-950 dark:text-orange-100 dark:border-orange-700', + 'urgent' => 'bg-red-100 text-red-900 border-red-300 dark:bg-red-950 dark:text-red-100 dark:border-red-800', + 'first' => 'bg-amber-100 text-amber-950 border-amber-300 dark:bg-amber-950 dark:text-amber-100 dark:border-amber-800', + 'waiting' => 'bg-blue-100 text-blue-900 border-blue-300 dark:bg-blue-950 dark:text-blue-100 dark:border-blue-800', + default => 'bg-emerald-100 text-emerald-900 border-emerald-300 dark:bg-emerald-950 dark:text-emerald-100 dark:border-emerald-800', + }; +@endphp + +class(['inline-flex shrink-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-bold', $classes]) }}> + @if ($priority->value === 'immediate') + + @endif + {{ __('jobs.priorities.'.$priority->value) }} + diff --git a/resources/views/components/jobs/board/task-card.blade.php b/resources/views/components/jobs/board/task-card.blade.php new file mode 100644 index 0000000..361310f --- /dev/null +++ b/resources/views/components/jobs/board/task-card.blade.php @@ -0,0 +1,69 @@ +{{-- + A task of a continuing job lifted into the pipeline (docs/ui-kanban-board.md + 4.3): dashed border, indigo bar with "Vapauta", link to the parent job. + Its column follows the task's status. +--}} +@props(['card', 'compact' => false, 'canMove' => false, 'canManage' => false]) + +@use('App\Modules\Jobs\Presentation\Support\BoardFormat') + + +
    +
    $canMove, 'cursor-pointer' => ! $canMove]) + > +
    + @if ($canMove) +
    + @if ($canManage) + + @endif +
    + +
    $compact, 'space-y-2 p-2.5' => ! $compact])> +

    +

    + +

    + +

    + +
    + +
    + + @if ($compact) + {{ BoardFormat::shortDate($card->dueOn) }} + @endif +
    +
    + + @unless ($compact) +

    + {{ BoardFormat::shortDate($card->dueOn) }} • {{ BoardFormat::cardHours($card) }} +

    + @endunless +
    +
    diff --git a/resources/views/components/jobs/board/task-list.blade.php b/resources/views/components/jobs/board/task-list.blade.php new file mode 100644 index 0000000..270d00f --- /dev/null +++ b/resources/views/components/jobs/board/task-list.blade.php @@ -0,0 +1,83 @@ +{{-- + A card's tasks inside the card: each with a checkbox that marks it done + (or open again). On a continuing job's card each task can also be lifted + into the pipeline as a card of its own (PIN), and new tasks are added + straight from the card. +--}} +@props(['card', 'canCheck' => false, 'canManage' => false, 'ongoing' => false, 'compact' => false]) + +
      $ongoing && ! $compact])> + @foreach ($card->tasks as $task) +
    • ! $ongoing, + 'space-y-1 p-1.5' => $ongoing, + ])> + + + @if ($ongoing) +
      + @if ($canManage) + + @endif + @if ($task->assigneeFirstName() !== null) + {{ $task->assigneeFirstName() }} + @endif +
      + @elseif ($task->assigneeFirstName() !== null) + {{ $task->assigneeFirstName() }} + @endif +
    • + @endforeach +
    + +@if ($ongoing && $canManage) +
    +
    + + + +
    + @error('newTaskTitles.'.$card->jobId) +

    {{ $message }}

    + @enderror + +
    +@endif diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index a2b3896..2140e4c 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -134,24 +134,62 @@ it('has no accessibility issues on the Kanban board and no sideways scrolling on 'mobile, dark' => ['mobile', 'dark'], ]); -it('moves a card to another column with the keyboard', function () { - $select = '#job-status-'.$this->job->id; - +it('moves a card to another column with the keyboard through the job editor', function () { visit(route('jobs.board')) - ->assertScript('document.querySelector("#column-tentative").textContent.includes("Messuvideo")', true) - ->select($select, 'order') - ->assertSee('Työ '.$this->job->number.' Messuvideo siirretty tilaan Tilaus.') - ->assertScript('document.querySelector("#column-order").textContent.includes("Messuvideo")', true) - ->assertScript('document.activeElement.id', 'job-status-'.$this->job->id) - ->assertNoAccessibilityIssues(level: 2); + ->assertScript('document.querySelector("#column-quotes").textContent.includes("Messuvideo")', true) + ->click('#card-job-'.$this->job->id.'-open') + ->assertScript('document.getElementById("job-editor-dialog").open', true) + ->assertScript('document.activeElement.id', 'job-editor-name') + ->assertNoAccessibilityIssues(level: 2) + ->select('#job-editor-status', 'order') + ->assertSee('Työn '.$this->job->number.' tila: Tilaus.') + ->keys('#job-editor-status', 'Escape') + ->assertScript('document.getElementById("job-editor-dialog").open', false) + ->assertScript('document.querySelector("#column-order").textContent.includes("Messuvideo")', true); expect($this->job->fresh()->status->value)->toBe('order'); }); +it('has no accessibility issues in the job editor and the quick intake dialog', function (string $device, string $colorScheme) { + TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'title' => 'Kuvauspäivä']); + + $visit = visit(route('jobs.board')); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->click('#card-job-'.$this->job->id.'-open') + ->assertScript('document.getElementById("job-editor-dialog").open', true) + ->assertSee('Kuvauspäivä') + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2) + ->keys('#job-editor-name', 'Escape') + ->click('Uusi työ / Pikavastaanotto') + ->assertScript('document.getElementById("quick-intake-dialog").open', true) + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + +it('marks a task done from the task panel of a card', function () { + $this->job->update(['status' => 'in_production']); + $task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'title' => 'Leikkaus', 'status' => 'in_progress']); + + visit(route('jobs.board')) + ->click('[aria-controls="tasks-job-'.$this->job->id.'"]') + ->click('#tasks-job-'.$this->job->id.' input[type=checkbox]') + ->assertSee('Tehtävä Leikkaus kuitattu valmiiksi.') + ->assertNoAccessibilityIssues(level: 2); + + expect($task->fresh()->status->value)->toBe('done'); +}); + it('moves a card by dragging it to another column', function () { visit(route('jobs.board')) ->on()->desktop() - ->drag('[wire\:sort\:item="'.$this->job->id.'"]', '#column-order ul') + ->drag('[wire\:sort\:item="job-'.$this->job->id.'"] [wire\:sort\:handle]', '#column-order ul') ->assertSee('siirretty tilaan Tilaus.'); expect($this->job->fresh()->status->value)->toBe('order'); diff --git a/tests/Fakes/FakeTaskQueries.php b/tests/Fakes/FakeTaskQueries.php index 26a1e80..2a2408f 100644 --- a/tests/Fakes/FakeTaskQueries.php +++ b/tests/Fakes/FakeTaskQueries.php @@ -21,6 +21,11 @@ class FakeTaskQueries implements TaskQueries $this->tasks[$taskId] = new BookableTask($taskId, $jobId, '2026-0001', 'Kampanja', 'Tehtävä '.$taskId, $workTypeId, 'graafinen työ', $jobStatus, TaskStatus::Waiting); } + public function pinnedTaskIds(int $jobId): array + { + return []; + } + public function tasksOf(int $jobId): array { return []; diff --git a/tests/Feature/Modules/Jobs/JobBoardTest.php b/tests/Feature/Modules/Jobs/JobBoardTest.php index c5aac6f..ac22bd8 100644 --- a/tests/Feature/Modules/Jobs/JobBoardTest.php +++ b/tests/Feature/Modules/Jobs/JobBoardTest.php @@ -1,7 +1,11 @@ actingAs($this->employee); }); -it('shows the Kanban columns in order with my jobs, without archived ones', function () { - CustomerJobModel::factory()->create(['name' => 'Tilattu työ', 'status' => 'order', 'responsible_user_id' => $this->employee->id]); +/** + * @return array> card keys by column + */ +function boardColumnKeys(mixed $board): array +{ + return array_map(fn (array $cards): array => array_map(fn ($card): string => $card->key(), $cards), $board->instance()->columns); +} + +it('shows the daily pipeline columns in order with my jobs, without archived ones and the quick-sale job', function () { + $mine = CustomerJobModel::factory()->create(['name' => 'Tilattu työ', 'status' => 'order', 'responsible_user_id' => $this->employee->id]); CustomerJobModel::factory()->create(['name' => 'Arkistoitu työ', 'status' => 'archived', 'responsible_user_id' => $this->employee->id]); + CustomerJobModel::factory()->create(['name' => 'Pikamyynnit', 'status' => 'in_production', 'responsible_user_id' => $this->employee->id, 'quick_sale_year' => 2026]); CustomerJobModel::factory()->create(['name' => 'Muiden työ', 'status' => 'order']); $board = Livewire::test('jobs::board') ->assertSee('Tilattu työ') ->assertDontSee('Arkistoitu työ') + ->assertDontSee('Pikamyynnit') ->assertDontSee('Muiden työ') - ->assertSeeInOrder(['Prospekti', 'Alustava', 'Tarjouspyyntö', 'Tilaus', 'Tuotannossa', 'Keskeytetty', 'Valmis', 'Lasku luotu', 'Laskutettu', 'Jatkuvat / Kausi']) - ->set('mine', false) - ->assertSee('Muiden työ'); + ->assertSeeInOrder(['Tarjoukset', 'Jonossa', 'Työn alla', 'Työn alla • Kiire', 'Odottaa asiakasta', 'Valmis • Laskuta', 'Jatkuvat & Kausi'], false) + ->assertDontSeeHtml('id="job-status-'); - expect(array_keys($board->instance()->board))->not->toContain('archived') - ->and(array_map(fn ($job) => $job->name, $board->instance()->board['order']))->toContain('Tilattu työ', 'Muiden työ'); + expect(array_keys($board->instance()->columns))->toBe(['quotes', 'order', 'in_production', 'in_production_urgent', 'on_hold', 'done', 'ongoing']) + ->and(boardColumnKeys($board)['order'])->toBe(['job-'.$mine->id]); + + $board->set('board', 'all')->assertSee('Muiden työ'); $this->get(route('jobs.board'))->assertOk()->assertSee('Kanban'); }); -it('moves a job with the select or by dropping it, and records the change', function () { +it('shows the sales and full pipelines with their own columns', function () { + $board = Livewire::test('jobs::board')->call('setView', 'sales'); + expect(array_keys($board->instance()->columns))->toBe(['prospect', 'tentative', 'quote_request']); + + $board->call('setView', 'full'); + expect(array_keys($board->instance()->columns))->toContain('invoiced', 'billed', 'ongoing')->not->toContain('quotes'); +}); + +it('filters by person, service line, urgency and lateness', function () { + $colleague = User::factory()->create(['name' => 'Anna Korhonen']); + $urgent = CustomerJobModel::factory()->create(['name' => 'Kiiretyö', 'status' => 'in_production', 'priority' => 'urgent', 'responsible_user_id' => $colleague->id]); + $late = CustomerJobModel::factory()->create(['name' => 'Myöhässä oleva', 'status' => 'order', 'due_on' => now()->subDays(3), 'responsible_user_id' => $colleague->id]); + + $board = Livewire::test('jobs::board') + ->assertSee('Henkilö: Anna Korhonen') + ->set('board', 'person-'.$colleague->id) + ->assertSee('Kiiretyö') + ->assertSee('Myöhässä oleva') + ->toggle('onlyUrgent') + ->assertSee('Kiiretyö') + ->assertDontSee('Myöhässä oleva') + ->assertSee('Näytetään 1 kortti'); + + $board->toggle('onlyUrgent')->toggle('onlyLate') + ->assertSee('Myöhässä oleva') + ->assertDontSee('Kiiretyö'); + + expect($urgent->id)->not->toBe($late->id); +}); + +it('moves a job to another column by dropping it, and records the change', function () { $job = CustomerJobModel::factory()->create(['name' => 'Messuvideo', 'status' => 'tentative', 'responsible_user_id' => $this->employee->id]); Livewire::test('jobs::board') - ->call('moveJob', $job->id, 'order') + ->call('moveDropped', 'job-'.$job->id, 0, 'order') ->assertSee('Työ '.$job->number.' Messuvideo siirretty tilaan Tilaus.') - ->call('moveDropped', (string) $job->id, 0, 'in_production') + ->call('moveDropped', 'job-'.$job->id, 0, 'in_production') ->assertSee('siirretty tilaan Tuotannossa.'); expect($job->fresh()->status->value)->toBe('in_production') ->and(DB::table('customer_job_changes')->where('customer_job_id', $job->id)->where('field', 'status')->count())->toBe(2); }); +it('raises the priority when a job is dropped into the urgent column, by the user\'s threshold', function () { + $job = CustomerJobModel::factory()->create(['name' => 'Juliste', 'status' => 'in_production', 'priority' => 'normal', 'responsible_user_id' => $this->employee->id]); + + $board = Livewire::test('jobs::board') + ->call('setUrgentThreshold', 'first') + ->call('moveDropped', 'job-'.$job->id, 0, 'in_production_urgent') + ->assertSee('siirretty Kiire-listaan (prioriteetti nostettu: Ensin)'); + + expect($job->fresh()->priority->value)->toBe('first') + ->and(boardColumnKeys($board)['in_production_urgent'])->toBe(['job-'.$job->id]); + + $board->call('moveDropped', 'job-'.$job->id, 0, 'in_production'); + expect($job->fresh()->priority->value)->toBe('normal'); +}); + +it('stores the drop order inside a column and switches a due-date column to own order', function () { + $first = CustomerJobModel::factory()->create(['status' => 'order', 'due_on' => now()->addDays(2), 'responsible_user_id' => $this->employee->id]); + $second = CustomerJobModel::factory()->create(['status' => 'order', 'due_on' => now()->addDay(), 'responsible_user_id' => $this->employee->id]); + + $board = Livewire::test('jobs::board')->call('setColumnSort', 'order', 'due_date'); + expect(boardColumnKeys($board)['order'])->toBe(['job-'.$second->id, 'job-'.$first->id]); + + $board->call('moveDropped', 'job-'.$second->id, 1, 'order') + ->assertSee('järjestys: oma järjestys'); + + expect(boardColumnKeys($board)['order'])->toBe(['job-'.$first->id, 'job-'.$second->id]) + ->and(DB::table('job_board_preferences')->where('user_id', $this->employee->id)->value('column_sorts'))->toBe('{"order":"manual"}'); +}); + it('lets only management and the biller move a job to a billing status', function () { $job = CustomerJobModel::factory()->create(['status' => 'done', 'responsible_user_id' => $this->employee->id]); Livewire::test('jobs::board') - ->call('moveJob', $job->id, 'invoiced') + ->call('setView', 'full') + ->call('moveDropped', 'job-'.$job->id, 0, 'invoiced') ->assertSee('voi asettaa vain johto tai työn laskuttaja'); expect($job->fresh()->status->value)->toBe('done'); $job->update(['biller_user_id' => $this->employee->id]); - Livewire::test('jobs::board')->call('moveJob', $job->id, 'invoiced'); + Livewire::test('jobs::board')->call('setView', 'full')->call('moveDropped', 'job-'.$job->id, 0, 'invoiced'); expect($job->fresh()->status->value)->toBe('invoiced'); }); -it('ignores unknown statuses, archiving and jobs not on the board', function () { +it('keeps continuing jobs in their own column', function () { + $ongoing = CustomerJobModel::factory()->create(['name' => 'Futsal LIVE', 'status' => 'ongoing', 'responsible_user_id' => $this->employee->id]); + $order = CustomerJobModel::factory()->create(['status' => 'order', 'responsible_user_id' => $this->employee->id]); + + $board = Livewire::test('jobs::board') + ->call('moveDropped', 'job-'.$ongoing->id, 0, 'in_production') + ->assertSee('Korttia ei voi siirtää listaan Työn alla.') + ->call('moveDropped', 'job-'.$order->id, 0, 'ongoing') + ->assertSee('Korttia ei voi siirtää listaan Jatkuvat & Kausi.', false); + + expect($ongoing->fresh()->status->value)->toBe('ongoing') + ->and($order->fresh()->status->value)->toBe('order') + ->and(boardColumnKeys($board)['ongoing'])->toBe(['job-'.$ongoing->id]); +}); + +it('ignores unknown columns and cards not on the board', function () { $job = CustomerJobModel::factory()->create(['status' => 'order', 'responsible_user_id' => $this->employee->id]); $other = CustomerJobModel::factory()->create(['status' => 'order']); Livewire::test('jobs::board') - ->call('moveJob', $job->id, 'nonsense') + ->call('moveDropped', 'job-'.$job->id, 0, 'nonsense') ->assertSee('Työtä ei siirretty.') - ->call('moveJob', $job->id, 'archived') - ->call('moveJob', $other->id, 'done') - ->call('moveJob', 999, 'done'); + ->call('moveDropped', 'job-'.$job->id, 0, 'archived') + ->call('moveDropped', 'job-'.$job->id, 0, 'invoiced') + ->call('moveDropped', 'job-'.$other->id, 0, 'done') + ->call('moveDropped', 'job-999', 0, 'done'); expect($job->fresh()->status->value)->toBe('order') ->and($other->fresh()->status->value)->toBe('order'); }); -it('shows a subcontractor only their cards, without moving', function () { +it('marks a task done from the card and opens it again', function () { + $job = CustomerJobModel::factory()->create(['status' => 'in_production', 'responsible_user_id' => $this->employee->id]); + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'title' => 'Vedos asiakkaalle', 'status' => 'in_progress']); + + $board = Livewire::test('jobs::board') + ->assertSee('Tehtävät (0/1)') + ->call('setTaskDone', $job->id, $task->id, true) + ->assertSee('Tehtävä Vedos asiakkaalle kuitattu valmiiksi.') + ->assertSee('Tehtävät (1/1)'); + + expect($task->fresh()->status->value)->toBe('done'); + + $board->call('setTaskDone', $job->id, $task->id, false); + expect($task->fresh()->status->value)->toBe('in_progress'); +}); + +it('lifts a continuing job\'s task into the pipeline and releases it', function () { + $job = CustomerJobModel::factory()->create(['name' => 'Somemarkkinointi', 'status' => 'ongoing', 'responsible_user_id' => $this->employee->id]); + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'title' => 'Joulukampanja', 'status' => 'waiting']); + + $board = Livewire::test('jobs::board') + ->assertSee('Seuraava vuorossa:') + ->call('pinTask', $job->id, $task->id, true) + ->assertSee('Tehtävä Joulukampanja nostettu työputkeen.') + ->assertSee('Tehtävä • PIN'); + + expect(boardColumnKeys($board)['order'])->toBe(['task-'.$task->id]); + + $board->call('moveDropped', 'task-'.$task->id, 0, 'in_production'); + expect($task->fresh()->status->value)->toBe('in_progress'); + + $board->call('pinTask', $job->id, $task->id, false); + expect((bool) $task->fresh()->is_pinned_to_board)->toBeFalse(); +}); + +it('adds a task to a continuing job straight from its card', function () { + $job = CustomerJobModel::factory()->create(['status' => 'ongoing', 'responsible_user_id' => $this->employee->id]); + $unitId = DB::table('customer_job_service_unit')->where('customer_job_id', $job->id)->value('service_unit_id'); + + Livewire::test('jobs::board') + ->call('addTask', $job->id) + ->assertSee('Anna tehtävän nimi.') + ->set('newTaskTitles.'.$job->id, 'Ottelu 12.12.') + ->set('newTaskPins.'.$job->id, true) + ->call('addTask', $job->id) + ->assertSee('Tehtävä Ottelu 12.12. lisätty'); + + $task = TaskModel::query()->where('customer_job_id', $job->id)->sole(); + expect($task->title)->toBe('Ottelu 12.12.') + ->and((bool) $task->is_pinned_to_board)->toBeTrue() + ->and($task->assignee_user_id)->toBe($this->employee->id) + ->and($unitId)->not->toBeNull(); +}); + +it('keeps each user\'s column colours and density their own and saves the customer colour for everyone', function () { + $customer = CustomerModel::factory()->create(['name' => 'Ässä KP Oy']); + CustomerJobModel::factory()->create(['customer_id' => $customer->id, 'status' => 'order', 'responsible_user_id' => $this->employee->id]); + + $board = Livewire::test('jobs::board') + ->call('setColumnColor', 'order', '#B91C1C') + ->assertSee('Listan Jonossa otsikkoväri tallennettu.') + ->call('setDensity', 'compact') + ->call('setCustomerColor', $customer->id, '#991b1b') + ->assertSee('Asiakkaan Ässä KP Oy väri tallennettu.') + ->assertSeeHtml('background-color: #991b1b; color: #ffffff') + ->call('setColumnColor', 'order', 'javascript:alert(1)') + ->assertSee('Väri ei kelpaa.'); + + expect($board->instance()->columnStyle(BoardColumn::Order)['header'])->toBe('#b91c1c') + ->and($board->instance()->preferences->density)->toBe(BoardDensity::Compact); + + expect($customer->fresh()->header_color)->toBe('#991b1b'); + + $this->actingAs(User::factory()->create()); + $otherBoard = Livewire::test('jobs::board'); + expect($otherBoard->instance()->columnStyle(BoardColumn::Order)['header'])->toBe('#23476a') + ->and($otherBoard->instance()->preferences->density)->toBe(BoardDensity::Normal); + + $this->actingAs($this->employee); + Livewire::test('jobs::board')->call('setColumnColor', 'order', null)->assertSee('palautettu oletukseksi'); +}); + +it('shows a subcontractor only their cards, without moving or changing colours', function () { $subcontractor = User::factory()->subcontractor()->create(); $theirs = CustomerJobModel::factory()->withMembers([$subcontractor->id])->create(['name' => 'Alihankintatyö', 'status' => 'order']); CustomerJobModel::factory()->create(['name' => 'Muu työ', 'status' => 'order']); @@ -85,8 +258,11 @@ it('shows a subcontractor only their cards, without moving', function () { ->assertSee('Alihankintatyö') ->assertDontSee('Muu työ') ->assertDontSeeHtml('wire:sort=') - ->call('moveJob', $theirs->id, 'done') + ->assertDontSeeHtml('id="board-select"') + ->call('moveDropped', 'job-'.$theirs->id, 0, 'done') ->assertForbidden(); + Livewire::test('jobs::board')->call('setCustomerColor', $theirs->customer_id, '#000000')->assertForbidden(); + expect($theirs->fresh()->status->value)->toBe('order'); }); diff --git a/tests/Feature/Modules/Jobs/JobEditorTest.php b/tests/Feature/Modules/Jobs/JobEditorTest.php new file mode 100644 index 0000000..6531824 --- /dev/null +++ b/tests/Feature/Modules/Jobs/JobEditorTest.php @@ -0,0 +1,128 @@ +employee = User::factory()->create(); + $this->actingAs($this->employee); + $this->job = CustomerJobModel::factory()->create(['name' => 'Kylkiteippaukset', 'status' => 'order', 'responsible_user_id' => $this->employee->id]); +}); + +it('opens a job from the board and saves its details without leaving the board', function () { + Livewire::test('jobs::board') + ->call('openJob', $this->job->id) + ->assertDispatched('open-job-editor', jobId: $this->job->id); + + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->assertSet('form.name', 'Kylkiteippaukset') + ->assertSee($this->job->number) + ->set('form.name', 'Pakettiauton kylkiteippaukset') + ->set('form.instructions', 'Asiakkaan logo vektorina') + ->call('save') + ->assertHasNoErrors() + ->assertDispatched('job-saved') + ->assertDispatched('job-editor-saved'); + + expect($this->job->fresh()->name)->toBe('Pakettiauton kylkiteippaukset') + ->and($this->job->fresh()->instructions)->toBe('Asiakkaan logo vektorina'); +}); + +it('changes the status and priority at once and records them', function () { + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->call('changeStatus', 'in_production') + ->assertSee('tila: Tuotannossa') + ->call('changePriority', 'urgent') + ->assertSee('prioriteetti: Kiire'); + + expect($this->job->fresh()->status->value)->toBe('in_production') + ->and($this->job->fresh()->priority->value)->toBe('urgent') + ->and(DB::table('customer_job_changes')->where('customer_job_id', $this->job->id)->whereIn('field', ['status', 'priority'])->count())->toBe(2); +}); + +it('keeps an employee from billing statuses and from opening the lock', function () { + $this->job->update(['status' => 'done']); + + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->assertSee('tunnit ja kulut on lukittu') + ->assertDontSee('Avaa lukitus (johto)') + ->call('changeStatus', 'invoiced') + ->assertHasErrors('form.status') + ->call('changeStatus', 'in_production') + ->assertHasErrors('form.status'); + + expect($this->job->fresh()->status->value)->toBe('done'); + + $this->actingAs(User::factory()->management()->create()); + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->call('unlock'); + + expect($this->job->fresh()->status->value)->toBe('in_production'); +}); + +it('edits, adds and marks tasks done in the editor', function () { + $task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'title' => 'Vedos', 'status' => 'waiting']); + + $editor = Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->call('updateTaskField', $task->id, 'title', 'Vedos asiakkaalle') + ->call('updateTaskField', $task->id, 'due_on', '2026-12-16') + ->call('setTaskDone', $task->id, true) + ->set('newTaskTitle', 'Asennus') + ->call('addTask') + ->assertHasNoErrors() + ->assertSee('Tehtävä Asennus lisätty.'); + + expect($task->fresh()->title)->toBe('Vedos asiakkaalle') + ->and($task->fresh()->due_on?->format('Y-m-d'))->toBe('2026-12-16') + ->and($task->fresh()->status->value)->toBe('done') + ->and(TaskModel::query()->where('customer_job_id', $this->job->id)->where('title', 'Asennus')->value('assignee_user_id'))->toBe($this->employee->id); + + $editor->call('updateTaskField', $task->id, 'nonsense', 'x'); + expect($task->fresh()->title)->toBe('Vedos asiakkaalle'); +}); + +it('hides quote amounts without the quotes permission', function () { + $this->job->update(['quoted_amount_cents' => 123400]); + + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->assertSee('Tarjous- ja laskutussummat on piilotettu') + ->assertDontSeeHtml('id="job-editor-quoted"'); + + $this->actingAs(User::factory()->management()->create()); + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->assertSeeHtml('id="job-editor-quoted"'); +}); + +it('lets a subcontractor only look at their own job and tick its tasks', function () { + $subcontractor = User::factory()->subcontractor()->create(); + $theirs = CustomerJobModel::factory()->withMembers([$subcontractor->id])->create(['status' => 'in_production']); + $task = TaskModel::factory()->create(['customer_job_id' => $theirs->id, 'status' => 'in_progress']); + + $this->actingAs($subcontractor); + + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $this->job->id) + ->assertForbidden(); + + Livewire::test('jobs::job-editor') + ->dispatch('open-job-editor', jobId: $theirs->id) + ->assertSee('Voit kuitata tehtäviä') + ->call('setTaskDone', $task->id, true) + ->call('save') + ->assertForbidden(); + + expect($task->fresh()->status->value)->toBe('done'); +}); diff --git a/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php b/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php index 0d96fd2..ad7b93e 100644 --- a/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php +++ b/tests/Feature/Modules/Jobs/JobMoneyFieldsTest.php @@ -78,17 +78,17 @@ it('shows the quoted amount to an employee with the quotes permission', function it('records when a job is done and clears it when management opens the lock', function () { $this->actingAs(User::factory()->management()->create()); - Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'done'); + Livewire::test('jobs::board')->set('board', 'all')->call('setView', 'full')->call('moveDropped', 'job-'.$this->job->id, 0, 'done'); $completedAt = $this->job->refresh()->completed_at; expect($completedAt)->not->toBeNull(); - Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'invoiced'); + Livewire::test('jobs::board')->set('board', 'all')->call('setView', 'full')->call('moveDropped', 'job-'.$this->job->id, 0, 'invoiced'); expect($this->job->refresh()->completed_at?->equalTo($completedAt))->toBeTrue(); $this->get(route('jobs.show', $this->job->id))->assertSee('Valmistunut'); - Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'in_production'); + Livewire::test('jobs::board')->set('board', 'all')->call('setView', 'full')->call('moveDropped', 'job-'.$this->job->id, 0, 'in_production'); expect($this->job->refresh()->completed_at)->toBeNull(); }); diff --git a/tests/Feature/Modules/Jobs/QuickIntakeTest.php b/tests/Feature/Modules/Jobs/QuickIntakeTest.php index b036217..b2613a7 100644 --- a/tests/Feature/Modules/Jobs/QuickIntakeTest.php +++ b/tests/Feature/Modules/Jobs/QuickIntakeTest.php @@ -88,3 +88,40 @@ it('keeps subcontractors out and shows the menu link only to those who may open $this->get(route('jobs.quick'))->assertForbidden(); $this->get(route('jobs.index'))->assertDontSee('Pikavastaanotto'); }); + +it('opens a job from the board\'s dialog with a new contact person, status and priority', function () { + Livewire::test('jobs::quick', ['inDialog' => true]) + ->call('selectCustomer', $this->customer->id) + ->set('form.adding_contact', true) + ->set('form.name', 'Pakettiauton kylkiteippaukset') + ->set('form.service_unit_id', (string) $this->unit->id) + ->call('save') + ->assertHasErrors('form.new_contact_name') + ->set('form.new_contact_name', 'Ville Virtanen') + ->set('form.new_contact_phone', '040 123 4567') + ->set('form.status', 'in_production') + ->set('form.priority', 'urgent') + ->call('save') + ->assertHasNoErrors() + ->assertDispatched('quick-job-created', status: 'in_production') + ->assertDispatched('job-editor-saved'); + + $job = CustomerJobModel::query()->sole(); + $contactId = DB::table('customer_contacts')->where('customer_id', $this->customer->id)->where('name', 'Ville Virtanen')->value('id'); + + expect($job->status->value)->toBe('in_production') + ->and($job->priority->value)->toBe('urgent') + ->and($job->customer_contact_id)->toBe($contactId); +}); + +it('refuses initial statuses past production', function () { + Livewire::test('jobs::quick') + ->call('selectCustomer', $this->customer->id) + ->set('form.name', 'Valmis jo') + ->set('form.service_unit_id', (string) $this->unit->id) + ->set('form.status', 'done') + ->call('save') + ->assertHasErrors('form.status'); + + expect(CustomerJobModel::query()->count())->toBe(0); +}); diff --git a/tests/Feature/Modules/TimeTracking/ApprovalTest.php b/tests/Feature/Modules/TimeTracking/ApprovalTest.php index 3c8213b..8692cdc 100644 --- a/tests/Feature/Modules/TimeTracking/ApprovalTest.php +++ b/tests/Feature/Modules/TimeTracking/ApprovalTest.php @@ -110,15 +110,15 @@ it('lets only management move a done job back, which opens its lock', function ( $this->actingAs($this->employee); Livewire::test('jobs::board') - ->set('mine', false) - ->call('moveJob', $job->id, 'in_production') + ->set('board', 'all')->call('setView', 'full') + ->call('moveDropped', 'job-'.$job->id, 0, 'in_production') ->assertSet('statusMessage', fn (string $message) => str_contains($message, 'lukituksen voi avata vain johto')); expect($job->refresh()->status)->toBe(JobStatus::Done); $this->actingAs(User::factory()->management()->create()); - Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $job->id, 'in_production'); + Livewire::test('jobs::board')->set('board', 'all')->call('setView', 'full')->call('moveDropped', 'job-'.$job->id, 0, 'in_production'); expect($job->refresh()->status)->toBe(JobStatus::InProduction);