17 Commits
Author SHA1 Message Date
petriandClaude Opus 5.5 8be732ada8 Pass the choice to the Kanban column menus (they called the action without it)
Collection::join() plucks from objects, so joining the Js arguments gave an
empty string and the sort and urgent threshold menus called
setColumnSort() / setUrgentThreshold() with no arguments (500).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:59:14 +02:00
petriandClaude Opus 5.5 9eac4c4d4e Remember for each user which Kanban cards have their task list open
The open cards are kept in the user's board preferences (expanded_cards,
at most 500), saved without redrawing the board and restored on return.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:25:58 +02:00
petriandClaude Opus 5.5 e274a8d2b1 Scroll only the body of work dialogs, so there is one scrollbar
The native dialog scrolled too once its content outgrew the browser's
default max-height. It now clips to the viewport and only the body scrolls.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:13:38 +02:00
petriandClaude Opus 5.5 f3d2b3e39e Give the editor's task checklist its own toggle, comments and images their tabs
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:05:44 +02:00
petriandClaude Opus 5.5 1d9bcefb41 Fix editor colour refresh, task row layout, dark date icons and time cell width
- The job editor redraws its customer-coloured header when the board saves
  a customer colour (customer-color-changed).
- Service units and members in the editor's sidebar are in two columns.
- Native controls follow the dark theme (color-scheme), so the date
  picker's calendar icon is light.
- Task status, assignee and due date sit side by side in the editor.
- Each task in the editor has its checklist, comments and images.
- The time sheet's time field shows five characters (00:00).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 11:00:53 +02:00
petriandClaude Opus 5.5 38c5b43018 Include the last day of a date range in expense and time entry queries
SQLite stores date casts as "Y-m-d 00:00:00", so a between ending at
"Y-m-d" left out the month's last day and the week's Sunday (the own
expenses test failed on the 30th). Ranges now end before the next day.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:47:01 +02:00
petriandClaude Opus 5.5 f24bd3cc35 Document the board, time sheet and colour pieces in CLAUDE.md
Also drops a redundant array_values() that Larastan flagged in MoveBoardCard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 10:32:15 +02:00
petri a4dbe8ce09 Kanban / timesheet update 2026-11-30 06:56:14 +02:00
petriandClaude Opus 5.5 6332ff0fa9 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 <[email protected]>
2026-11-30 06:33:28 +02:00
petriandClaude Opus 5.5 f4b58f6b1d Darken the dark canvas, add customer colours, the ongoing status and the board model
- Dark theme page background is #5a5e60; text on it is lifted to zinc-200 /
  primary-100 and TallStackUI's dark labels, hints and checkbox labels are
  lightened so everything stays at 4.5:1.
- Shared HexColor picks white or black text by the higher WCAG contrast; a
  native-dialog colour picker and a large work dialog component.
- Customers get a header colour (customers.header_color), set on the
  customer page.
- New job status Jatkuvat / Kausi (ongoing): open, never late, billed
  monthly like running jobs.
- Kanban model: board columns and views, urgent threshold, per-user board
  preferences (density, column colours and sort), card positions, tasks of
  continuing jobs pinned to the board, MoveBoardCard and board queries with
  logged hours from TimeTracking.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-30 06:11:49 +02:00
petriandClaude Opus 5.5 de168619b3 Card the remaining form pages in the new look
The tasks-from-template, expense, stock item, workflow template and task
hour forms sat inside @if blocks, so the earlier pass left them as bare
fields on the page background. They are now cards; the template table has
the indigo header row and primary focus rings, the expense billing fieldset
and workflow steps get an inner surface instead of a nested card, locked-job
notices are amber, and the item image picker button uses the primary colour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 11:15:09 +02:00
petriandClaude Opus 5.5 51b40b24fe Give the UI an indigo look with cards, status badges and empty states
- Dark indigo header and tinted page background; the mobile main menu gets
  its own row, in the same order as the keyboard reaches it.
- Page titles with an icon chip (x-page-title, x-page, x-page-header) and
  card sections (x-panel, the card utility); x-table styled as a card with
  an indigo header row in AppServiceProvider::styleTables().
- Job and task statuses, late work, unapproved hours and stock states as
  badges with icon and text (x-status-badge, x-jobs.status,
  x-jobs.task-status), never colour alone.
- Empty lists as x-empty-state; dashboard quick link tiles, week hour bars
  and trend arrows; Kanban columns and task cards edged by status; calendar
  today column and bar accents; quick sale, reports and machine console
  restyled; signed-out pages show the app name.
- Focus rings use the primary colour in both themes (white in the header).
- Document the components in CLAUDE.md; test the status badges.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 10:53:10 +02:00
petriandClaude Sonnet 5.5 ef400054b0 Return stock of cancelled maintenance, throttle the PIN page's password
Cancelling a maintenance record now reverses the stock it used, through
Inventory's new ReverseMaintenanceStockUse behind the MaintenanceMaterials
port, in the same transaction as the cancellation.

The PIN page allows 5 wrong current passwords a minute per user, as the
login form does, so a signed-in session cannot be used to guess the
password.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 10:10:18 +02:00
petriandClaude Sonnet 5.5 6692396a63 Fix console hours, sign-in landing and counter usage races
- Hours the counter reading cannot parse (",5") no longer fail after
  they are saved; they just get no hour counter suggestion.
- The console's sign-in falls back to a console machine list
  (machines::console-picker at /console/machines) instead of /machines,
  so it stays in the console's own session.
- Recording counter usage locks the counter first, so usage saved at
  the same time from two devices is not lost.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 10:05:02 +02:00
petriandClaude Sonnet 5.5 32c33e2a64 Give the machine console its own session with PIN sign-in, make counters cumulative
The console under console/ has its own session cookie and console guard
(UseConsoleSession), so signing out or changing user there leaves the
normal interface alone. Links open it in a new window through a one-time
handoff key; a signed-out console asks for a PIN code or password on its
own login page. Users set their 4-6 digit PIN on the profile's PIN page,
and the console's change user dialog takes it on a keypad; five wrong
PINs lock PIN sign-in for 15 minutes.

Machine counters are cumulative: users record how much a job used and it
is added to the latest reading. A maintenance record restarts the whole
counter interval from the reading at the record.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:58:11 +02:00
petriandClaude Sonnet 5.5 87e38260dc Show a task card's actions above tabs for notes, images and materials
The opened task card keeps its details and description at the top, then
the status, book hours, edit and remove actions, and below them tabs:
checklist and comments, images, and materials and machines. The tabs are
a project component (x-tabs) after the WAI-ARIA pattern, because
TallStackUI's tab ties its panels to missing ids and has no arrow keys.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:58:04 +02:00
petriandClaude Sonnet 5.5 701f05780f Change a quick sale order before making starts
An unpaid order whose lines have no completed step can be reopened in the
cart from the open orders list; saving replaces its lines with current
prices and processes, moves the machine work list rows and keeps the
pickup number. Keyboard browser tests cover changing and cancelling an
order and moving production steps.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-29 09:11:36 +02:00
293 changed files with 17926 additions and 1552 deletions
+3 -1
View File
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -33,7 +33,7 @@ use Illuminate\Support\Carbon;
* @property-read UserMoneyPermissionsModel|null $moneyPermissions
*/
#[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id', 'locale'])]
#[Hidden(['password', 'remember_token'])]
#[Hidden(['password', 'remember_token', 'pin_hash'])]
class User extends Authenticatable implements HasLocalePreference
{
/** @use HasFactory<UserFactory> */
@@ -21,8 +21,8 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis;
*/
class JobsForBilling implements BillingJobs
{
/** Statuses in which a monthly fee job is billed: running or done. */
private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done];
/** Statuses in which a monthly fee job is billed: running, ongoing or done. */
private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done, JobStatus::Ongoing];
public function __construct(
private CustomerJobQueries $jobs,
@@ -318,7 +318,7 @@ new class extends Component
<div class="space-y-2">
<p><x-link :href="route('billing.index')" navigate>{{ __('billing.export.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="document-arrow-down">{{ $this->heading() }}</x-page-title>
<p class="flex items-center gap-2 text-sm">
@if ($export->isDraft())
<x-icon name="pencil-square" class="size-5 shrink-0" aria-hidden="true" />
@@ -353,16 +353,16 @@ new class extends Component
wire:change="savePeriod($event.target.value)"
aria-describedby="billing-period-help @error('period') billing-period-error @enderror"
@error('period') aria-invalid="true" @enderror
class="w-full rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400 dark:[color-scheme:dark]"
class="w-full rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400 dark:[color-scheme:dark]"
/>
<p id="billing-period-help" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.export.period_help') }}</p>
<p id="billing-period-help" class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('billing.export.period_help') }}</p>
@error('period')
<p id="billing-period-error" class="text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</div>
@if ($export->hasProblems())
<p class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
<p class="flex items-start gap-2 rounded-lg border border-amber-700 bg-amber-50 p-4 text-sm text-amber-950 dark:border-amber-400 dark:bg-amber-400/10 dark:text-amber-100">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
{{ __('billing.export.problems') }}
</p>
@@ -380,11 +380,11 @@ new class extends Component
<h2 id="invoices-heading" class="text-xl font-semibold">{{ __('billing.invoices.title') }}</h2>
@if ($export->invoices === [])
<p class="text-sm">{{ __('billing.invoices.none') }}</p>
<x-empty-state icon="banknotes">{{ __('billing.invoices.none') }}</x-empty-state>
@endif
@foreach ($export->invoices as $invoiceNumber => $invoice)
<section wire:key="invoice-{{ $invoice->key }}" aria-labelledby="invoice-{{ $invoice->key }}-heading" class="space-y-4 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<section wire:key="invoice-{{ $invoice->key }}" aria-labelledby="invoice-{{ $invoice->key }}-heading" class="card space-y-4">
<div class="space-y-1">
<h3 id="invoice-{{ $invoice->key }}-heading" class="text-lg font-semibold">{{ __('billing.invoices.heading', ['number' => $invoiceNumber + 1, 'customer' => $invoice->customerName]) }}</h3>
<dl class="grid gap-x-4 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
@@ -428,7 +428,7 @@ new class extends Component
<table class="w-full text-sm">
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.months_caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.month') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
</tr>
@@ -463,7 +463,7 @@ new class extends Component
<table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.jobs.hours_caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.work_type') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.jobs.approved_hours') }}</th>
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.billable_hours') }}</th>
@@ -488,7 +488,7 @@ new class extends Component
aria-label="{{ __('billing.jobs.billable_label', ['work_type' => $row->name]) }}"
aria-describedby="hours-help-{{ $job->jobId }}"
@error('hours.'.$job->jobId.'.'.$row->workTypeId) aria-invalid="true" aria-errormessage="{{ $fieldId }}-error" @enderror
class="w-20 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
class="w-20 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/>
@if ($row->isAdjusted)
<span class="ml-1 text-xs">({{ __('billing.jobs.adjusted') }})</span>
@@ -504,7 +504,7 @@ new class extends Component
</tbody>
</table>
</div>
<p id="hours-help-{{ $job->jobId }}" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.jobs.billable_help') }}</p>
<p id="hours-help-{{ $job->jobId }}" class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('billing.jobs.billable_help') }}</p>
@endif
@php($expenseLines = $this->linesOfKind($job, LineKind::Expense))
@@ -512,7 +512,7 @@ new class extends Component
<table class="w-full text-sm">
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.expenses_caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.expense') }}</th>
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
</tr>
@@ -557,7 +557,7 @@ new class extends Component
<table class="w-full text-sm">
<caption class="sr-only">{{ __('billing.lines.caption', ['job' => $job->label()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<tr class="border-b-2 border-primary-200 text-left text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-3">{{ __('billing.lines.description') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.recorded') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('billing.lines.quantity') }}</th>
@@ -630,7 +630,7 @@ new class extends Component
<p class="text-sm">{{ __('billing.available.intro') }}</p>
@if ($export->availableJobs === [])
<p class="text-sm">{{ __('billing.available.none') }}</p>
<x-empty-state icon="banknotes">{{ __('billing.available.none') }}</x-empty-state>
@else
<x-table :headers="$this->availableHeaders()" :rows="$export->availableJobs">
@interact('column_job', $available)
@@ -87,7 +87,7 @@ new class extends Component
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('billing.index.title') }}</h1>
<x-page-title icon="banknotes">{{ __('billing.index.title') }}</x-page-title>
<p class="max-w-3xl text-sm">{{ __('billing.index.intro') }}</p>
</div>
@@ -102,7 +102,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $statusMessage }}</p>
@if ($this->exports === [])
<p class="text-sm">{{ __('billing.index.none') }}</p>
<x-empty-state icon="banknotes">{{ __('billing.index.none') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->exports">
@interact('column_number', $export)
@@ -78,11 +78,11 @@ new class extends Component
<div class="mx-auto max-w-4xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<p><x-link :href="route('jobs.show', $job->id)" navigate>{{ __('billing.job_months.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="calendar">{{ $this->heading() }}</x-page-title>
<p class="max-w-3xl text-sm">{{ __('billing.job_months.intro') }}</p>
</div>
<section aria-labelledby="summary-heading" class="space-y-2">
<section aria-labelledby="summary-heading" class="card space-y-2">
<h2 id="summary-heading" class="sr-only">{{ __('billing.job_months.summary') }}</h2>
<dl class="grid grid-cols-1 gap-x-6 gap-y-1 text-sm sm:grid-cols-[auto_1fr]">
<dt class="font-medium">{{ __('billing.job_months.customer') }}</dt>
@@ -113,7 +113,7 @@ new class extends Component
<h2 id="billed-heading" class="text-xl font-semibold">{{ __('billing.job_months.billed_title', ['count' => count($billing->billed)]) }}</h2>
@if ($billing->billed === [])
<p class="text-sm">{{ __('billing.job_months.none_billed') }}</p>
<x-empty-state icon="banknotes">{{ __('billing.job_months.none_billed') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$billing->billed">
@interact('column_month', $month)
@@ -137,7 +137,7 @@ new class extends Component
@endif
</section>
<section aria-labelledby="unbilled-heading" class="space-y-3">
<section aria-labelledby="unbilled-heading" class="card space-y-3">
<h2 id="unbilled-heading" class="text-xl font-semibold">{{ __('billing.job_months.unbilled_title', ['month' => $this->monthLabel($billing->currentMonth)]) }}</h2>
@if ($billing->unbilled === [])
@@ -114,13 +114,13 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.title') }}</h1>
<x-page-title icon="squares-plus">{{ __('catalog.title') }}</x-page-title>
<x-button :href="route('catalog.service-units.create')" wire:navigate icon="plus" :text="__('catalog.actions.add_service_unit')" />
</div>
<div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.intro') }}</p>
<p class="text-zinc-600 dark:text-zinc-200">{{ __('catalog.intro') }}</p>
<p><x-link :href="route('catalog.prices')" navigate>{{ __('catalog.prices_link') }}</x-link></p>
<p><x-link :href="route('catalog.workflow-templates')" navigate>{{ __('catalog.workflows_link') }}</x-link></p>
</div>
@@ -139,7 +139,7 @@ new class extends Component
<section
wire:key="service-unit-{{ $unit->id }}"
aria-labelledby="service-unit-{{ $unit->id }}-heading"
class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700"
class="card space-y-4"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 id="service-unit-{{ $unit->id }}-heading" class="text-xl font-semibold break-words">
@@ -159,11 +159,11 @@ new class extends Component
</div>
@if ($unit->isShared)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.shared') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.shared') }}</p>
@endif
@if ($unit->usesStock)
<p class="flex items-center gap-1 text-sm text-zinc-600 dark:text-zinc-300">
<p class="flex items-center gap-1 text-sm text-zinc-600 dark:text-zinc-200">
<x-icon name="archive-box" class="size-4" aria-hidden="true" />
{{ __('catalog.service_units.uses_stock_on') }}
</p>
@@ -121,16 +121,16 @@ new class extends Component
?>
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1>
<x-page-title icon="tag">{{ __('catalog.prices.title') }}</x-page-title>
<section aria-labelledby="consumer-products-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="consumer-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.consumer_products') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.consumer_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.consumer_help') }}</p>
</div>
@if ($this->consumerProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
<x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else
<x-table :headers="$this->consumerHeaders()" :rows="$this->consumerProducts">
@interact('column_name', $product)
@@ -156,7 +156,7 @@ new class extends Component
<section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.hourly_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.hourly_help') }}</p>
</div>
@foreach ($this->hourlyRates as $group)
@@ -173,7 +173,7 @@ new class extends Component
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span>
<span class="text-zinc-600 dark:text-zinc-200">{{ $row->serviceName }}:</span>
@endif
{{ $row->name }}
</th>
@@ -191,7 +191,7 @@ new class extends Component
<h2 id="other-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.other_products') }}</h2>
@if ($this->otherProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
<x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else
<x-table :headers="$this->otherHeaders()" :rows="$this->otherProducts">
@interact('column_name', $product)
@@ -217,7 +217,7 @@ new class extends Component
@endif
</section>
<section aria-labelledby="mileage-heading" class="space-y-2">
<section aria-labelledby="mileage-heading" class="card space-y-2">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
<p>
{{ $this->mileageRateCents === null
@@ -226,6 +226,6 @@ new class extends Component
</p>
</section>
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.no_permission') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.price_list.no_permission') }}</p>
@endif
</div>
@@ -346,8 +346,8 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.intro') }}</p>
<x-page-title icon="tag">{{ __('catalog.prices.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.prices.intro') }}</p>
</div>
@if (session('status'))
@@ -364,7 +364,7 @@ new class extends Component
<section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.prices.hourly_rates_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.prices.hourly_rates_help') }}</p>
</div>
@foreach ($this->hourlyRates as $group)
@@ -388,7 +388,7 @@ new class extends Component
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span>
<span class="text-zinc-600 dark:text-zinc-200">{{ $row->serviceName }}:</span>
@endif
{{ $row->name }}
@unless ($row->isActive)
@@ -405,7 +405,7 @@ new class extends Component
wire:change="saveRate({{ $row->workTypeId }}, $event.target.value)"
aria-label="{{ __('catalog.prices.rate_label', ['name' => ($row->serviceName !== null ? $row->serviceName.': ' : '').$row->name, 'unit' => $group->serviceUnitName]) }}"
@error('rates.'.$row->workTypeId) aria-invalid="true" aria-describedby="rate-{{ $row->workTypeId }}-error" @enderror
class="w-24 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
class="w-24 rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400"
/>
@error('rates.'.$row->workTypeId)
<p id="rate-{{ $row->workTypeId }}-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -424,10 +424,10 @@ new class extends Component
<h2 id="products-heading" class="text-xl font-semibold">{{ __('catalog.products.title') }}</h2>
<x-button :href="route('catalog.products.create')" wire:navigate icon="plus" :text="__('catalog.products.add')" />
</div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.help') }}</p>
@if ($this->products === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
<x-empty-state icon="tag">{{ __('catalog.products.none') }}</x-empty-state>
@else
<x-table :headers="$this->productHeaders()" :rows="$this->products">
@interact('column_name', $product)
@@ -444,14 +444,14 @@ new class extends Component
@interact('column_net', $product)
<span class="whitespace-nowrap">{{ $this->money($product->netCents) }}</span>
@unless ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.entered') }}</span>
@endunless
@endinteract
@interact('column_gross', $product)
<span class="whitespace-nowrap">{{ $this->money($product->grossCents) }}</span>
@if ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.entered') }}</span>
@endif
@endinteract
@@ -467,7 +467,7 @@ new class extends Component
@if ($product->durationQuarters > 0)
{{ __('catalog.products.duration_value', ['hours' => $this->duration($product->durationQuarters)]) }}
@if ($product->workTypeName !== null)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $product->workTypeName }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ $product->workTypeName }}</span>
@endif
@else
{{ __('catalog.products.no_duration') }}
@@ -492,7 +492,7 @@ new class extends Component
<h2 id="vat-rates-heading" class="text-xl font-semibold">{{ __('catalog.vat_rates.title') }}</h2>
<x-button :href="route('catalog.vat-rates.create')" wire:navigate icon="plus" :text="__('catalog.vat_rates.add')" />
</div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.help') }}</p>
<x-table :headers="$this->vatRateHeaders()" :rows="$this->vatRates">
@interact('column_name', $vatRate)
@@ -522,7 +522,7 @@ new class extends Component
</x-table>
</section>
<section aria-labelledby="mileage-heading" class="space-y-4">
<section aria-labelledby="mileage-heading" class="card space-y-4">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.expense_markup.section') }}</h2>
<form wire:submit="saveMileageRate" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
@@ -552,7 +552,7 @@ new class extends Component
</form>
</section>
<section aria-labelledby="internal-cost-heading" class="space-y-4">
<section aria-labelledby="internal-cost-heading" class="card space-y-4">
<h2 id="internal-cost-heading" class="text-xl font-semibold">{{ __('catalog.internal_cost.section') }}</h2>
<form wire:submit="saveInternalHourlyCost" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
@@ -179,9 +179,9 @@ new class extends Component
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="cube">{{ $this->heading() }}</x-page-title>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
@@ -193,7 +193,7 @@ new class extends Component
<div class="space-y-1">
<x-checkbox id="product-consumer" wire:model.live="form.is_consumer_product" :label="__('catalog.products.consumer')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.consumer_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.products.consumer_help') }}</p>
</div>
<x-select.native wire:model.live="form.vat_rate_id" :label="__('catalog.products.vat_rate')" :aria-label="__('catalog.products.vat_rate')">
@@ -87,13 +87,13 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="rectangle-stack">{{ $this->heading() }}</x-page-title>
@if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
<div class="flex flex-wrap gap-3">
@@ -89,17 +89,17 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="building-office">{{ $this->heading() }}</x-page-title>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@unless ($isShared)
<div class="space-y-1">
<x-checkbox id="uses-stock" wire:model="usesStock" :label="__('catalog.service_units.uses_stock')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.service_units.uses_stock_hint') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.service_units.uses_stock_hint') }}</p>
</div>
@endunless
@@ -103,13 +103,13 @@ new class extends Component
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="receipt-percent">{{ $this->heading() }}</x-page-title>
@if ($vatRateId !== null)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.change_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.change_help') }}</p>
@endif
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="name" :label="__('catalog.fields.name')" :hint="__('catalog.vat_rates.name_help')" autocomplete="off" required />
<x-input
@@ -126,7 +126,7 @@ new class extends Component
@else
<div class="space-y-1">
<x-checkbox id="vat-rate-default" wire:model="makeDefault" :label="__('catalog.vat_rates.make_default')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.make_default_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.vat_rates.make_default_help') }}</p>
</div>
@endif
@@ -106,13 +106,13 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="wrench-screwdriver">{{ $this->heading() }}</x-page-title>
@if ($unitName !== '')
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.fields.service_unit') }}: {{ $unitName }}</p>
@endif
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" autocomplete="off" required />
@if ($this->services !== [])
@@ -311,9 +311,9 @@ new class extends Component
?>
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="queue-list">{{ $this->heading() }}</x-page-title>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" :hint="__('catalog.workflows.name_help')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
@@ -334,10 +334,10 @@ new class extends Component
@endforeach
</x-select.native>
<section aria-labelledby="steps-heading" class="space-y-4">
<section aria-labelledby="steps-heading" class="space-y-4 rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-800/50">
<div class="space-y-1">
<h2 id="steps-heading" class="text-xl font-semibold">{{ __('catalog.workflows.steps') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.steps_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.steps_help') }}</p>
</div>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
@@ -350,7 +350,7 @@ new class extends Component
@foreach ($form->steps as $index => $step)
{{-- The index is part of the key: a moved step is rendered anew, so its fields bind to their new position. --}}
<li wire:key="step-{{ $step['key'] }}-{{ $index }}">
<fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-white p-4 dark:border-zinc-700 dark:bg-black">
<fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-white p-4 dark:border-zinc-700 dark:bg-zinc-900">
<legend class="px-1 font-medium">{{ __('catalog.workflows.step_legend', ['number' => $index + 1]) }}</legend>
<x-input
@@ -388,7 +388,7 @@ new class extends Component
@if ($this->stepUsesStock($index) || ($step['materials'] ?? []) !== [])
<fieldset class="space-y-3">
<legend class="text-sm font-semibold">{{ __('catalog.workflows.materials') }}</legend>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.materials_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.materials_help') }}</p>
@foreach ($step['materials'] ?? [] as $materialIndex => $material)
<div wire:key="material-{{ $material['key'] }}-{{ $materialIndex }}" class="flex flex-wrap items-end gap-2">
@@ -82,13 +82,13 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.workflows.title') }}</h1>
<x-page-title icon="queue-list">{{ __('catalog.workflows.title') }}</x-page-title>
<x-button :href="route('catalog.workflow-templates.create')" wire:navigate icon="plus" :text="__('catalog.workflows.add')" />
</div>
<div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.intro') }}</p>
<p class="text-zinc-600 dark:text-zinc-200">{{ __('catalog.workflows.intro') }}</p>
<p><x-link :href="route('catalog.index')" navigate>{{ __('catalog.workflows.back_to_catalog') }}</x-link></p>
</div>
@@ -138,7 +138,7 @@ new class extends Component
wire:click="toggleActive({{ $template->id }})"
@checked($template->isActive)
aria-label="{{ __('catalog.actions.active_named', ['name' => $template->name]) }}"
class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800"
class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:border-zinc-500 dark:bg-zinc-800"
/>
<span aria-hidden="true">{{ __('catalog.actions.active') }}</span>
</label>
@@ -147,6 +147,6 @@ new class extends Component
</x-table>
</section>
@empty
<p>{{ __('catalog.workflows.none') }}</p>
<x-empty-state icon="tag">{{ __('catalog.workflows.none') }}</x-empty-state>
@endforelse
</div>
@@ -25,6 +25,14 @@ interface CustomerQueries
*/
public function namesByIds(array $ids): array;
/**
* Card header colours (#rrggbb, null = default colour) by customer id.
*
* @param list<int> $ids
* @return array<int, string|null>
*/
public function headerColorsByIds(array $ids): array;
/**
* The company's own internal customer, whose jobs hold internal work
* and the yearly quick sale job.
@@ -22,6 +22,7 @@ final readonly class CustomerSummary
public ?string $businessId,
public ?string $personalIdentityCodeMasked = null,
public bool $isInternal = false,
public ?string $headerColor = null,
) {}
public function hasPersonalIdentityCode(): bool
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidHexColor;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
/**
* Sets the customer's colour, shared by its Kanban cards and its time sheet
* rows. Null returns to the default colour.
*/
final class ChangeCustomerHeaderColor
{
public function __construct(
private CustomerRepository $customers,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerNotFound
* @throws InvalidHexColor
*/
public function execute(int $customerId, ?string $color): void
{
$headerColor = $color === null || trim($color) === '' ? null : new HexColor($color);
$this->transactions->run(function () use ($customerId, $headerColor): void {
$customer = $this->customers->findById($customerId) ?? throw new CustomerNotFound($customerId);
$customer->changeHeaderColor($headerColor);
$this->customers->save($customer);
});
}
}
@@ -11,6 +11,7 @@ use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
/**
* A customer of the company: a business or a private consumer.
@@ -27,6 +28,7 @@ final class Customer
private ?BusinessId $businessId,
private ?PersonalIdentityCode $personalIdentityCode,
private bool $internal = false,
private ?HexColor $headerColor = null,
) {
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
self::ensureInternalIsCompany($internal, $type);
@@ -54,8 +56,9 @@ final class Customer
?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode = null,
bool $internal = false,
?HexColor $headerColor = null,
): self {
return new self($id, $name, $type, $businessId, $personalIdentityCode, $internal);
return new self($id, $name, $type, $businessId, $personalIdentityCode, $internal, $headerColor);
}
/**
@@ -81,6 +84,20 @@ final class Customer
$this->personalIdentityCode = $personalIdentityCode;
}
/**
* The colour of the customer's card headers on the Kanban board and of
* its rows on the time sheet. Null uses the default colour.
*/
public function changeHeaderColor(?HexColor $color): void
{
$this->headerColor = $color;
}
public function headerColor(): ?HexColor
{
return $this->headerColor;
}
public function removePersonalIdentityCode(): void
{
$this->personalIdentityCode = null;
@@ -23,9 +23,10 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $personal_identity_code Decrypted by the cast; sensitive.
* @property string|null $personal_identity_code_hash
* @property bool $is_internal
* @property string|null $header_color #rrggbb
*/
#[Table('customers')]
#[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash'])]
#[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash', 'header_color'])]
#[Hidden(['personal_identity_code', 'personal_identity_code_hash'])]
#[UseFactory(CustomerFactory::class)]
class CustomerModel extends Model
@@ -27,6 +27,11 @@ class EloquentCustomerQueries implements CustomerQueries
return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
}
public function headerColorsByIds(array $ids): array
{
return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('header_color', 'id')->all();
}
public function internalCustomerId(): ?int
{
$id = CustomerModel::query()->where('is_internal', true)->orderBy('id')->value('id');
@@ -118,7 +123,7 @@ class EloquentCustomerQueries implements CustomerQueries
? null
: (new PersonalIdentityCode($model->personal_identity_code))->masked();
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal);
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal, $model->header_color);
}
private function toContactSummary(CustomerContactModel $model): ContactSummary
@@ -10,6 +10,7 @@ use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
use Illuminate\Database\QueryException;
class EloquentCustomerRepository implements CustomerRepository
@@ -35,6 +36,7 @@ class EloquentCustomerRepository implements CustomerRepository
'business_id' => $customer->businessId()?->value,
'personal_identity_code' => $customer->personalIdentityCode()?->value,
'personal_identity_code_hash' => $customer->personalIdentityCode() === null ? null : $this->hasher->hash($customer->personalIdentityCode()),
'header_color' => $customer->headerColor()?->value,
])->save();
return $this->toEntity($model);
@@ -83,6 +85,7 @@ class EloquentCustomerRepository implements CustomerRepository
$model->business_id === null ? null : new BusinessId($model->business_id),
$model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code),
(bool) $model->is_internal,
$model->header_color === null ? null : new HexColor($model->header_color),
);
}
}
@@ -91,14 +91,14 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<x-page-title icon="building-office-2">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.billing_units.fields.name')" :hint="__('customers.billing_units.fields.name_description')" autocomplete="off" required />
<x-textarea wire:model="form.billing_address" :label="__('customers.billing_units.fields.billing_address')" :hint="__('customers.billing_units.fields.billing_address_description')" resize-auto />
@@ -88,14 +88,14 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<x-page-title icon="user">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('customers.customer_label') }}:
<x-link :href="route('customers.show', $customerId)" navigate>{{ $customerName }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('customers.contacts.fields.name')" autocomplete="off" required />
<x-input wire:model="form.title" :label="__('customers.contacts.fields.title')" :hint="__('customers.contacts.fields.title_description')" autocomplete="off" />
@@ -120,11 +120,11 @@ new class extends Component
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">
<x-page-title icon="user-group">
{{ __($customerId === null ? 'customers.create_title' : 'customers.edit_title') }}
</h1>
</x-page-title>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input
wire:model="form.name"
:label="__('customers.fields.name')"
@@ -63,7 +63,7 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('customers.title') }}</h1>
<x-page-title icon="user-group">{{ __('customers.title') }}</x-page-title>
<x-button :href="route('customers.create')" wire:navigate icon="plus" :text="__('customers.new')" />
</div>
@@ -80,12 +80,12 @@ new class extends Component
:hint="__('customers.search_description')"
/>
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-300">
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-100">
{{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }}
</p>
@if ($this->customers->total() === 0)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.empty') }}</p>
<x-empty-state icon="user-group">{{ __('customers.empty') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->customers" paginate>
@interact('column_name', $customer)
@@ -5,6 +5,7 @@ use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\Services\CustomerRemoval;
use App\Modules\Customers\Application\UseCases\ChangeCustomerHeaderColor;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Application\UseCases\RemoveCustomer;
@@ -16,6 +17,7 @@ use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Shared\Domain\Exceptions\InvalidHexColor;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
@@ -71,6 +73,27 @@ new class extends Component
return $this->customerQueries->findSummary($this->customerId) ?? abort(404);
}
/**
* The colour picker's "Use colour", or "Restore default colour" with null.
*/
public function setHeaderColor(?string $color, ChangeCustomerHeaderColor $changeColor): void
{
$this->authorize('customers.use');
try {
$changeColor->execute($this->customerId, $color);
} catch (InvalidHexColor) {
$this->statusMessage = __('customers.errors.invalid_header_color');
return;
} catch (CustomerNotFound) {
abort(404);
}
unset($this->customer);
$this->statusMessage = __('customers.header_color_saved');
}
/**
* The personal identity code as this user may see it: in full for admins
* and management, masked for others. Computed, so the full code is never
@@ -211,8 +234,11 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-4">
<a href="{{ route('customers.index') }}" wire:navigate class="inline-flex min-h-6 items-center gap-1 rounded-md text-sm font-medium text-primary-700 underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:text-primary-100 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-left" class="size-4" aria-hidden="true" />{{ __('customers.title') }}
</a>
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 id="customer-heading" tabindex="-1" class="text-2xl font-semibold break-words focus:outline-none">{{ $this->customer->name }}</h1>
<x-page-title icon="user-group" id="customer-heading" tabindex="-1" class="focus:outline-none">{{ $this->customer->name }}</x-page-title>
<div class="flex flex-wrap gap-2">
<x-button
@@ -224,6 +250,14 @@ new class extends Component
:text="__('customers.edit_details')"
/>
<x-button
subtle
color="black"
icon="swatch"
:text="__('customers.fields.header_color')"
x-on:click="$dispatch('color-picker:open', {{ Js::from(['id' => 'colour-picker', 'title' => __('customers.header_color_title', ['name' => $this->customer->name]), 'color' => $this->customer->headerColor ?? '#23476a', 'method' => 'setHeaderColor', 'args' => [], 'resettable' => $this->customer->headerColor !== null]) }})"
/>
@if ($this->canBeRemoved)
<x-button
wire:click="confirmRemoval('customer', {{ $customerId }})"
@@ -240,7 +274,7 @@ new class extends Component
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
<dl class="card grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('customers.fields.type') }}</dt>
<dd>
{{ __('customers.types.'.$this->customer->type->value) }}
@@ -272,7 +306,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
</div>
<section aria-labelledby="contacts-heading" class="space-y-4">
<section aria-labelledby="contacts-heading" class="card space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="contacts-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.contacts.title') }}
@@ -287,7 +321,7 @@ new class extends Component
</div>
@if ($this->contacts === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.contacts.empty') }}</p>
<x-empty-state icon="user-group">{{ __('customers.contacts.empty') }}</x-empty-state>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->contacts as $contact)
@@ -314,7 +348,7 @@ new class extends Component
@endif
@if ($contact->note !== null)
<p class="whitespace-pre-line text-zinc-600 dark:text-zinc-300">{{ $contact->note }}</p>
<p class="whitespace-pre-line text-zinc-600 dark:text-zinc-200">{{ $contact->note }}</p>
@endif
</div>
@@ -345,7 +379,7 @@ new class extends Component
@endif
</section>
<section aria-labelledby="billing-units-heading" class="space-y-4">
<section aria-labelledby="billing-units-heading" class="card space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="billing-units-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">
{{ __('customers.billing_units.title') }}
@@ -360,7 +394,7 @@ new class extends Component
</div>
@if ($this->billingUnits === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('customers.billing_units.empty') }}</p>
<x-empty-state icon="user-group">{{ __('customers.billing_units.empty') }}</x-empty-state>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-200 dark:divide-zinc-700 dark:border-zinc-700">
@foreach ($this->billingUnits as $billingUnit)
@@ -427,4 +461,6 @@ new class extends Component
<x-button wire:click="remove" color="red" icon="trash" :text="__('customers.remove')" />
</x-slot:actions>
</x-confirm-dialog>
<x-color-picker />
</div>
@@ -54,33 +54,42 @@ new class extends Component
};
?>
<div class="mx-auto max-w-7xl space-y-8 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('dashboard.greeting', ['name' => auth()->user()->name]) }}</h1>
<x-page width="wide">
<x-page-header :title="__('dashboard.greeting', ['name' => auth()->user()->name])" />
@php($overview = $this->overview)
<nav aria-label="{{ __('dashboard.links.title') }}">
<ul class="flex flex-wrap gap-2">
<ul class="grid grid-cols-1 gap-3 min-[400px]:grid-cols-2 sm:grid-cols-3 lg:grid-cols-5">
@foreach ($this->quickLinks() as $link)
<li><x-button :href="route($link['route'])" wire:navigate :icon="$link['icon']" :text="$link['label']" /></li>
<li>
<a
href="{{ route($link['route']) }}"
wire:navigate
class="group flex h-full min-h-16 items-center gap-3 rounded-xl border border-zinc-200 bg-white p-3 text-sm font-medium shadow-sm transition hover:border-primary-400 hover:shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:border-zinc-700 dark:bg-zinc-900 dark:hover:border-primary-300 dark:focus-visible:outline-primary-300"
>
<span class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary-600 text-white group-hover:bg-primary-700 dark:bg-primary-500" aria-hidden="true">
<x-icon :name="$link['icon']" class="size-5" />
</span>
<span class="min-w-0 break-words">{{ $link['label'] }}</span>
</a>
</li>
@endforeach
</ul>
</nav>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="tasks-heading" class="space-y-4 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="tasks-heading" class="text-xl font-semibold">{{ __('dashboard.tasks.title') }}</h2>
<x-panel :title="__('dashboard.tasks.title')" icon="clipboard-document-list" heading-id="tasks-heading">
@if (! $overview->hasTasks())
<p class="text-sm">{{ __('dashboard.tasks.none') }}</p>
<x-empty-state icon="check-badge">{{ __('dashboard.tasks.none') }}</x-empty-state>
@endif
@foreach (['overdue' => $overview->overdue, 'soon' => $overview->soon, 'this_week' => $overview->thisWeek] as $group => $tasks)
@if ($tasks !== [])
<div class="space-y-2">
<h3 class="flex items-center gap-2 font-semibold">
<div @class(['space-y-2', 'rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-400/30 dark:bg-red-400/10' => $group === 'overdue'])>
<h3 @class(['flex items-center gap-2 font-semibold', 'text-red-800 dark:text-red-200' => $group === 'overdue'])>
@if ($group === 'overdue')
<x-icon name="exclamation-triangle" class="size-5 text-red-700 dark:text-red-400" aria-hidden="true" />
<x-icon name="exclamation-triangle" class="size-5" aria-hidden="true" />
@endif
{{ __('dashboard.tasks.groups.'.$group, ['count' => count($tasks)]) }}
</h3>
@@ -88,9 +97,9 @@ new class extends Component
@foreach ($tasks as $task)
<li wire:key="task-{{ $task->taskId }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="flex flex-wrap gap-x-3 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.tasks.statuses.'.$task->status) }}</span>
<span class="block text-zinc-600 dark:text-zinc-200">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-zinc-700 dark:text-zinc-200">
<x-jobs.task-status :status="$task->status" />
@if ($task->dueOn !== null)
<span>{{ __('dashboard.tasks.due', ['date' => $this->dateLabel($task->dueOn)]) }}</span>
@endif
@@ -98,9 +107,7 @@ new class extends Component
<span>{{ __('dashboard.tasks.starts', ['date' => $this->dateLabel($task->plannedFrom)]) }}</span>
@endif
@if ($task->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
<x-status-badge tone="danger" icon="exclamation-triangle">{{ __('jobs.late') }}</x-status-badge>
@endif
</span>
</li>
@@ -114,12 +121,12 @@ new class extends Component
<p class="text-sm">{{ trans_choice('dashboard.tasks.later', $overview->laterCount, ['count' => $overview->laterCount]) }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.tasks.to_calendar') }}</x-link></p>
@endif
</section>
</x-panel>
<div class="space-y-6">
<section aria-labelledby="week-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="week-heading" class="text-xl font-semibold">{{ __('dashboard.week.title') }}</h2>
<x-panel :title="__('dashboard.week.title')" icon="clock" heading-id="week-heading">
{{-- The bars are decoration; the hours are the table's text. A full day (7.5 h) or the week's longest day fills a bar. --}}
@php($dayMax = max(30, ...array_values($overview->week->days)))
<table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.week.caption', ['from' => $this->dateLabel($overview->week->monday)]) }}</caption>
<thead>
@@ -127,7 +134,7 @@ new class extends Component
@foreach (array_keys($overview->week->days) as $day)
<th scope="col" class="py-1 text-center font-medium">
{{ $this->dayName($day) }}
<span class="block text-xs font-normal text-zinc-600 dark:text-zinc-300">{{ (new DateTimeImmutable($day))->format('j.n.') }}</span>
<span class="block text-xs font-normal text-zinc-600 dark:text-zinc-200">{{ (new DateTimeImmutable($day))->format('j.n.') }}</span>
</th>
@endforeach
</tr>
@@ -135,45 +142,43 @@ new class extends Component
<tbody>
<tr>
@foreach ($overview->week->days as $quarters)
<td class="py-1 text-center">{{ $this->hours($quarters) }}</td>
<td class="px-0.5 pt-2 text-center align-bottom">
<span class="mx-auto flex h-14 w-full max-w-8 items-end overflow-hidden rounded-md bg-zinc-100 dark:bg-zinc-800" aria-hidden="true">
<span class="block w-full bg-primary-500 dark:bg-primary-400" style="height: {{ round(min(1, $quarters / $dayMax) * 100) }}%"></span>
</span>
<span class="mt-1 block tabular-nums">{{ $this->hours($quarters) }}</span>
</td>
@endforeach
</tr>
</tbody>
</table>
<p class="text-sm">
{{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }}
<p class="flex flex-wrap items-center gap-2 text-sm">
<span class="font-semibold">{{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }}</span>
@if ($overview->week->unapprovedQuarters > 0)
<span class="inline-flex items-center gap-1">
<x-icon name="exclamation-circle" class="size-4" aria-hidden="true" />
{{ __('dashboard.week.unapproved', ['hours' => $this->hours($overview->week->unapprovedQuarters)]) }}
</span>
<x-status-badge tone="warning" icon="exclamation-circle">{{ __('dashboard.week.unapproved', ['hours' => $this->hours($overview->week->unapprovedQuarters)]) }}</x-status-badge>
@endif
</p>
<p class="text-sm"><x-link :href="route('time.week')" navigate>{{ __('dashboard.week.open') }}</x-link></p>
</section>
<section aria-labelledby="jobs-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h2 id="jobs-heading" class="text-xl font-semibold">{{ __('dashboard.jobs.title') }}</h2>
</x-panel>
<x-panel :title="__('dashboard.jobs.title')" icon="briefcase" heading-id="jobs-heading">
@if ($overview->jobs === [])
<p class="text-sm">{{ __('dashboard.jobs.none') }}</p>
<x-empty-state icon="briefcase">{{ __('dashboard.jobs.none') }}</x-empty-state>
@else
<ul class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobs as $job)
<li wire:key="job-{{ $job->id }}" class="py-2 text-sm">
<x-link :href="route('jobs.show', $job->id)" navigate class="font-medium">{{ $job->number }} {{ $job->name }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">{{ $job->customerName }}</span>
<span class="flex flex-wrap items-center gap-x-3 text-zinc-700 dark:text-zinc-200">
<span>{{ __('jobs.statuses.'.$job->status) }}</span>
<span class="block text-zinc-600 dark:text-zinc-200">{{ $job->customerName }}</span>
<span class="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-zinc-700 dark:text-zinc-200">
<x-jobs.status :status="$job->status" />
<x-jobs.priority :priority="\App\Modules\Jobs\Domain\Enums\Priority::from($job->priority)" />
@if ($job->dueOn !== null)
<span>{{ __('dashboard.jobs.due', ['date' => $this->dateLabel($job->dueOn)]) }}</span>
@endif
@if ($job->isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
<x-status-badge tone="danger" icon="exclamation-triangle">{{ __('jobs.late') }}</x-status-badge>
@endif
</span>
</li>
@@ -184,7 +189,7 @@ new class extends Component
<p class="text-sm">
<x-link :href="route('jobs.index')" navigate>{{ trans_choice('dashboard.jobs.all', $overview->jobCount, ['count' => $overview->jobCount]) }}</x-link>
</p>
</section>
</x-panel>
</div>
</div>
@@ -192,4 +197,4 @@ new class extends Component
{{-- Loaded right after the page, not only when scrolled to. --}}
<livewire:dashboard::management lazy="on-load" />
@endcan
</div>
</x-page>
@@ -32,7 +32,7 @@ new class extends Component
public function placeholder(): string
{
return '<section class="rounded-lg border border-zinc-300 p-4 dark:border-zinc-600"><p role="status" class="text-sm">'.e(__('dashboard.management.loading')).'</p></section>';
return '<section class="rounded-xl border border-zinc-200 bg-white p-4 shadow-sm dark:border-zinc-700 dark:bg-zinc-900"><p role="status" class="text-sm">'.e(__('dashboard.management.loading')).'</p></section>';
}
/**
@@ -66,12 +66,13 @@ new class extends Component
<section aria-labelledby="management-heading" class="space-y-6">
@php($overview = $this->overview)
<h2 id="management-heading" class="text-xl font-semibold">{{ __('dashboard.management.title') }}</h2>
<h2 id="management-heading" class="flex items-center gap-2 border-t border-zinc-200 pt-6 text-xl font-semibold dark:border-zinc-700">
<x-icon name="presentation-chart-line" class="size-6 text-primary-700 dark:text-primary-300" aria-hidden="true" />
{{ __('dashboard.management.title') }}
</h2>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="todo-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="todo-heading" class="text-lg font-semibold">{{ __('dashboard.todo.title') }}</h3>
<x-panel :title="__('dashboard.todo.title')" icon="inbox-stack" :level="3" heading-id="todo-heading">
<ul class="space-y-2 text-sm">
@can('time.approve-others')
<li>
@@ -133,12 +134,11 @@ new class extends Component
</li>
@endcan
</ul>
</section>
</x-panel>
@can('reports.view')
<section aria-labelledby="month-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="month-heading" class="text-lg font-semibold">{{ __('dashboard.month.title') }}</h3>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<x-panel :title="__('dashboard.month.title')" icon="chart-bar" :level="3" heading-id="month-heading">
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('dashboard.month.period', [
'from' => $this->dateLabel($overview->monthFrom), 'to' => $this->dateLabel($overview->monthTo),
'previous_from' => $this->dateLabel($overview->previousFrom), 'previous_to' => $this->dateLabel($overview->previousTo),
@@ -155,25 +155,32 @@ new class extends Component
['label' => 'margin', 'value' => $month->marginCents === null ? __('dashboard.month.no_cost') : $this->money($month->marginCents), 'current' => $month->marginCents, 'previous' => $previous->marginCents, 'route' => 'reports.profitability'],
['label' => 'sales', 'value' => $this->money($month->salesCents), 'current' => $month->salesCents, 'previous' => $previous->salesCents, 'route' => 'reports.sales'],
] as $figure)
<div class="rounded border border-zinc-200 p-3 dark:border-zinc-700">
@php($ratio = $figure['current'] !== null && $figure['previous'] !== null ? (new \App\Modules\Dashboard\Domain\ValueObjects\Change($figure['current'], $figure['previous']))->ratio() : null)
<div class="rounded-lg border border-zinc-200 bg-zinc-50 p-3 dark:border-zinc-700 dark:bg-zinc-800/60">
<dt class="text-sm">
<x-link :href="route($figure['route'])" navigate>{{ __('dashboard.month.'.$figure['label']) }}</x-link>
</dt>
<dd class="text-lg font-semibold">{{ $figure['value'] }}</dd>
<dd class="text-xl font-semibold tabular-nums">{{ $figure['value'] }}</dd>
@if ($figure['current'] !== null && $figure['previous'] !== null)
<dd class="text-sm text-zinc-700 dark:text-zinc-200">{{ $this->change($figure['current'], $figure['previous']) }}</dd>
<dd class="flex items-center gap-1 text-sm text-zinc-700 dark:text-zinc-200">
@if ($ratio !== null && $ratio > 0)
<x-icon name="arrow-trending-up" class="size-4 text-emerald-700 dark:text-emerald-300" aria-hidden="true" />
@elseif ($ratio !== null && $ratio < 0)
<x-icon name="arrow-trending-down" class="size-4 text-red-700 dark:text-red-300" aria-hidden="true" />
@endif
{{ $this->change($figure['current'], $figure['previous']) }}
</dd>
@endif
</div>
@endforeach
</dl>
<p class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('dashboard.month.billing_note') }}</p>
</section>
<p class="text-xs text-zinc-600 dark:text-zinc-200">{{ __('dashboard.month.billing_note') }}</p>
</x-panel>
@endcan
</div>
<div class="grid gap-6 lg:grid-cols-2">
<section aria-labelledby="jobs-overview-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="jobs-overview-heading" class="text-lg font-semibold">{{ __('dashboard.stock.title') }}</h3>
<x-panel :title="__('dashboard.stock.title')" icon="briefcase" :level="3" heading-id="jobs-overview-heading">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('dashboard.stock.caption') }}</caption>
@@ -186,10 +193,12 @@ new class extends Component
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($overview->jobCounts as $status => $count)
<tr wire:key="status-{{ $status }}">
<th scope="row" class="py-1 text-left font-normal">
<x-link :href="route('jobs.index', ['status' => $status, 'mine' => 0])" navigate>{{ __('jobs.statuses.'.$status) }}</x-link>
<th scope="row" class="py-1.5 text-left font-normal">
<a href="{{ route('jobs.index', ['status' => $status, 'mine' => 0]) }}" wire:navigate class="rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-jobs.status :status="$status" class="underline-offset-2 hover:underline" />
</a>
</th>
<td class="py-1 text-right">{{ $count }}</td>
<td class="py-1.5 text-right font-semibold tabular-nums">{{ $count }}</td>
</tr>
@endforeach
</tbody>
@@ -214,7 +223,7 @@ new class extends Component
@foreach ($overview->oldestOverdueTasks as $task)
<li wire:key="late-{{ $task->taskId }}" class="py-2">
<x-link :href="route('jobs.show', $task->jobId).'#task-'.$task->taskId" navigate class="font-medium">{{ $task->title }}</x-link>
<span class="block text-zinc-600 dark:text-zinc-300">
<span class="block text-zinc-600 dark:text-zinc-200">
{{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->assigneeName ?? __('dashboard.stock.no_assignee') }}
· {{ __('dashboard.tasks.due', ['date' => $this->dateLabel((string) $task->dueOn)]) }}
</span>
@@ -222,13 +231,11 @@ new class extends Component
@endforeach
</ul>
@endif
</section>
<section aria-labelledby="load-heading" class="space-y-3 rounded-lg border border-zinc-300 bg-white p-4 dark:border-zinc-600 dark:bg-zinc-900">
<h3 id="load-heading" class="text-lg font-semibold">{{ __('dashboard.load.title') }}</h3>
</x-panel>
<x-panel :title="__('dashboard.load.title')" icon="users" :level="3" heading-id="load-heading">
@if ($overview->workloads === [])
<p class="text-sm">{{ __('dashboard.load.none') }}</p>
<x-empty-state icon="users">{{ __('dashboard.load.none') }}</x-empty-state>
@else
<div class="overflow-x-auto rounded focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600" tabindex="0" role="region" aria-label="{{ __('dashboard.load.caption') }}">
<table class="w-full text-sm">
@@ -262,6 +269,6 @@ new class extends Component
<p class="text-sm">{{ __('dashboard.load.note') }}</p>
<p class="text-sm"><x-link :href="route('jobs.calendar')" navigate>{{ __('dashboard.load.to_calendar') }}</x-link></p>
@endif
</section>
</x-panel>
</div>
</section>
@@ -34,7 +34,10 @@ class EloquentExpenseQueries implements ExpenseQueries
return $this->summaries(ExpenseModel::query()
->where('user_id', $userId)
->whereBetween('spent_on', [$start->toDateString(), $start->copy()->endOfMonth()->toDateString()]));
// An upper bound before the next month: SQLite keeps date casts as "Y-m-d 00:00:00",
// which a between ending at the month's last "Y-m-d" would leave out.
->where('spent_on', '>=', $start->toDateString())
->where('spent_on', '<', $start->copy()->addMonth()->toDateString()));
}
public function find(int $id): ?ExpenseSummary
@@ -227,17 +227,17 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.fields.job') }}: {{ $job->label() }}</p>
<x-page-title icon="receipt-refund">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('expenses.fields.job') }}: {{ $job->label() }}</p>
</div>
@if ($job->isLocked)
<p class="flex items-start gap-2 rounded-lg border border-zinc-300 p-3 text-sm dark:border-zinc-600">
<p class="flex items-start gap-2 rounded-lg border border-amber-700 bg-amber-50 p-3 text-sm text-amber-950 dark:border-amber-400 dark:bg-amber-400/10 dark:text-amber-100">
<x-icon name="lock-closed" class="size-5 shrink-0" aria-hidden="true" />
{{ __('expenses.locked') }}
</p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="form.category" :label="__('expenses.fields.category')" :aria-label="__('expenses.fields.category')">
@foreach (ExpenseCategory::cases() as $category)
@@ -281,7 +281,7 @@ new class extends Component
<x-input wire:model.live.blur="form.cost" inputmode="decimal" :label="__('expenses.fields.cost')" :hint="__('expenses.form.cost_help')" autocomplete="off" required />
@endif
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
<fieldset class="space-y-4 rounded-lg border border-zinc-200 bg-zinc-50 p-4 dark:border-zinc-700 dark:bg-zinc-800/50">
<legend class="px-1 font-medium">{{ __('expenses.form.billing') }}</legend>
<x-checkbox id="expense-billable" wire:model.live="form.is_billable" :label="__('expenses.fields.is_billable')" />
@@ -0,0 +1,133 @@
<?php
use App\Modules\Expenses\Application\Contracts\ExpenseJobs;
use App\Modules\Expenses\Application\Contracts\ExpenseQueries;
use App\Modules\Expenses\Application\DTOs\ExpenseData;
use App\Modules\Expenses\Application\DTOs\ExpenseSummary;
use App\Modules\Expenses\Application\UseCases\RecordExpense;
use App\Modules\Expenses\Domain\Enums\ExpenseCategory;
use App\Modules\Expenses\Domain\Enums\ExpensePayer;
use App\Modules\Expenses\Domain\Exceptions\ExpenseJobNotFound;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
use App\Modules\Expenses\Presentation\Livewire\Concerns\ShowsExpenses;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\Clock;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Quick expenses of a job in the board's job editor: a description and an
* amount without VAT, paid by the company, dated today. The list shows
* amounts only to those who may see them; the full form is on the job's
* expense page.
*/
new class extends Component
{
use ShowsExpenses;
#[Locked]
public int $jobId;
public string $description = '';
public string $cost = '';
public string $statusMessage = '';
public function mount(int $jobId): void
{
$this->authorize('expenses.use');
$this->jobId = $jobId;
}
/**
* @return list<ExpenseSummary>
*/
#[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);
}
};
?>
<div class="space-y-2.5 text-xs">
@if (Gate::allows('expenses.record') && ! $this->isLocked())
<form wire:submit="save" class="grid gap-3 sm:grid-cols-12 sm:items-start">
<div class="sm:col-span-6">
<x-input id="quick-expense-description-{{ $jobId }}" wire:model="description" maxlength="255" :label="__('expenses.quick.description')" :placeholder="__('expenses.quick.description_placeholder')" autocomplete="off" />
</div>
<div class="sm:col-span-3">
<x-input id="quick-expense-cost-{{ $jobId }}" wire:model="cost" inputmode="decimal" :label="__('expenses.quick.amount')" placeholder="0,00" autocomplete="off" />
</div>
<div class="sm:col-span-3 sm:pt-6">
<x-button submit sm class="w-full" :text="__('expenses.quick.add')" />
</div>
</form>
@elseif ($this->isLocked())
<p class="font-semibold">{{ __('expenses.quick.locked') }}</p>
@endif
<p role="status" aria-live="polite" class="min-h-4 font-medium">{{ $statusMessage }}</p>
@if ($this->expenses === [])
<p>{{ __('expenses.quick.none') }}</p>
@else
<ul class="space-y-1">
@foreach ($this->expenses as $expense)
<li wire:key="quick-expense-{{ $expense->id }}" class="flex justify-between gap-2 rounded border border-neutral-200 bg-white px-2.5 py-1.5 dark:border-[#36393f] dark:bg-[#25272b]">
<span class="min-w-0 break-words">{{ $this->summaryText($expense) }}</span>
<span class="shrink-0 font-bold">{{ $this->amount($expense, $expense->costCents) }}</span>
</li>
@endforeach
</ul>
@endif
@can('expenses.record')
<x-link :href="route('expenses.job', $jobId)" navigate class="text-xs">{{ __('expenses.quick.all') }}</x-link>
@endcan
</div>
@@ -138,7 +138,7 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold break-words">{{ __('expenses.job_page.title', ['job' => $job->label()]) }}</h1>
<x-page-title icon="receipt-refund">{{ __('expenses.job_page.title', ['job' => $job->label()]) }}</x-page-title>
<x-link :href="route('jobs.show', $job->id)" navigate class="text-sm">{{ __('expenses.job_page.back_to_job') }}</x-link>
</div>
@@ -161,11 +161,11 @@ new class extends Component
<h2 id="expenses-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('expenses.job_page.list') }}</h2>
@unless ($this->canSeeTotals)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('expenses.amounts_hidden_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('expenses.amounts_hidden_help') }}</p>
@endunless
@if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p>
<x-empty-state icon="receipt-refund">{{ __('expenses.none') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense)
@@ -174,7 +174,7 @@ new class extends Component
@interact('column_what', $expense)
<span class="block font-medium break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
<span class="block text-xs text-zinc-600 dark:text-zinc-200">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span>
@endinteract
@@ -101,8 +101,8 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('expenses.mine.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<x-page-title icon="receipt-refund">{{ __('expenses.mine.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __(auth()->user()?->can('expenses.record') ? 'expenses.mine.help' : 'expenses.mine.help_subcontractor') }}
</p>
</div>
@@ -117,7 +117,7 @@ new class extends Component
<h2 id="month-heading" class="text-xl font-semibold" aria-live="polite">{{ $this->monthLabel() }}</h2>
@if ($this->expenses === [])
<p class="text-sm">{{ __('expenses.none') }}</p>
<x-empty-state icon="receipt-refund">{{ __('expenses.none') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->expenses">
@interact('column_spentOn', $expense)
@@ -139,7 +139,7 @@ new class extends Component
@interact('column_what', $expense)
<span class="block break-words whitespace-normal">{{ $this->summaryText($expense) }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
<span class="block text-xs text-zinc-600 dark:text-zinc-200">
{{ __('expenses.categories.'.$expense->category->value) }}, {{ __('expenses.payers.'.$expense->paidBy->value) }}
</span>
@endinteract
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Returns the stock a cancelled maintenance record used (spec 19.5): each
* of its use movements not yet reversed gets a reversal, recorded today.
*/
final class ReverseMaintenanceStockUse
{
public function __construct(
private StockMovementRepository $movements,
private ReverseStockMovement $reverse,
private TransactionManager $transactions,
) {}
/**
* @return int How many movements were reversed.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $maintenanceRecordId, int $actorUserId): int
{
return $this->transactions->run(function () use ($maintenanceRecordId, $actorUserId): int {
$movementIds = $this->movements->unreversedUseOfMaintenance($maintenanceRecordId);
foreach ($movementIds as $movementId) {
$this->reverse->execute($movementId, $actorUserId, true);
}
return count($movementIds);
});
}
}
@@ -14,6 +14,13 @@ interface StockMovementRepository
public function isReversed(int $movementId): bool;
/**
* The ids of a maintenance record's use movements that are not reversed.
*
* @return list<int>
*/
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array;
/**
* The item's balance in thousandths: the sum of its movements.
*/
@@ -4,6 +4,7 @@ namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use DateTimeImmutable;
@@ -50,6 +51,19 @@ class EloquentStockMovementRepository implements StockMovementRepository
return StockMovementModel::query()->where('reverses_movement_id', $movementId)->exists();
}
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array
{
return StockMovementModel::query()
->where('maintenance_record_id', $maintenanceRecordId)
->where('kind', StockMovementKind::Consumption)
->whereNotIn('id', StockMovementModel::query()->whereNotNull('reverses_movement_id')->select('reverses_movement_id'))
->orderBy('id')
->pluck('id')
->map(fn (mixed $id): int => (int) $id)
->values()
->all();
}
public function balanceOf(int $itemId): int
{
return (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
@@ -171,7 +171,7 @@ new class extends Component
<div class="space-y-2">
<p class="text-sm"><x-link :href="route('inventory.counts')" navigate>{{ __('inventory.counts.back') }}</x-link></p>
<h1 class="text-2xl font-semibold">{{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }}</h1>
<x-page-title icon="clipboard-document-check">{{ __('inventory.counts.name', ['date' => $this->dateLabel($count->countedOn)]) }}</x-page-title>
<p class="text-sm">
{{ $count->groupNames === [] ? __('inventory.counts.whole_stock') : implode(', ', $count->groupNames) }}
· {{ __('inventory.counts.started_by', ['name' => $count->startedByName]) }}
@@ -185,7 +185,7 @@ new class extends Component
<p class="text-sm">{{ __('inventory.counts.values', ['before' => $this->money((int) $count->valueBeforeCents), 'after' => $this->money((int) $count->valueAfterCents)]) }}</p>
@endcan
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.counts.count_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.counts.count_help') }}</p>
@endif
</div>
@@ -202,7 +202,7 @@ new class extends Component
@endcan
@else
@can('inventory.manage-counts')
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 text-sm font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 text-sm font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-down-tray" class="size-4" aria-hidden="true" />
{{ __('inventory.counts.download_csv') }}
</a>
@@ -211,7 +211,7 @@ new class extends Component
</div>
@forelse ($this->groupedLines() as $groupName => $lines)
<section wire:key="count-group-{{ md5($groupName) }}" aria-label="{{ $groupName }}" class="space-y-2">
<section wire:key="count-group-{{ md5($groupName) }}" aria-label="{{ $groupName }}" class="card space-y-2">
<h2 class="text-lg font-semibold">{{ $groupName }}</h2>
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
@foreach ($lines as $line)
@@ -219,7 +219,7 @@ new class extends Component
<li wire:key="count-line-{{ $line->itemId }}" class="flex flex-wrap items-end justify-between gap-3 p-3">
<div class="min-w-0 flex-1 space-y-1">
<p class="font-medium break-words">{{ $line->itemName }}</p>
<p class="text-sm text-zinc-700 dark:text-zinc-300">
<p class="text-sm text-zinc-700 dark:text-zinc-200">
@if ($line->isCounted())
{{ __('inventory.counts.book', ['book' => $this->quantity((int) $line->bookMilli, $line->unit)]) }}
· <span class="font-medium">{{ __('inventory.counts.difference', ['difference' => $this->signed((int) $difference, $line->unit)]) }}</span>
@@ -240,7 +240,7 @@ new class extends Component
<p class="text-sm font-medium">{{ $line->isCounted() ? $this->quantity((int) $line->countedMilli, $line->unit) : '–' }}</p>
@else
<div class="w-36">
<label for="counted-{{ $line->itemId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">
<label for="counted-{{ $line->itemId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-200">
{{ __('inventory.counts.counted', ['unit' => __('inventory.units.'.$line->unit->value)]) }}
<span class="sr-only">: {{ $line->itemName }}</span>
</label>
@@ -252,7 +252,7 @@ new class extends Component
value="{{ $line->isCounted() ? StockQuantity::inputValue((int) $line->countedMilli) : '' }}"
wire:change="saveCounted({{ $line->itemId }}, $event.target.value)"
@error('counted.'.$line->itemId) aria-invalid="true" aria-describedby="counted-{{ $line->itemId }}-error" @enderror
class="mt-1 h-10 w-full rounded-md border border-zinc-500 bg-white px-2 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100"
class="mt-1 h-10 w-full rounded-md border border-zinc-500 bg-white px-2 text-right text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:border-zinc-400 dark:bg-zinc-900 dark:text-zinc-100"
/>
@error('counted.'.$line->itemId)
<p id="counted-{{ $line->itemId }}-error" class="mt-1 text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -73,12 +73,12 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.counts.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.counts.intro') }}</p>
<x-page-title icon="clipboard-document-check">{{ __('inventory.counts.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.counts.intro') }}</p>
</div>
@can('inventory.manage-counts')
<section aria-labelledby="start-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<section aria-labelledby="start-heading" class="card space-y-3">
<h2 id="start-heading" class="text-lg font-semibold">{{ __('inventory.counts.start_title') }}</h2>
<form wire:submit="start" class="space-y-4" novalidate>
@if ($this->groupOptions !== [])
@@ -97,11 +97,11 @@ new class extends Component
</section>
@endcan
<section aria-labelledby="counts-heading" class="space-y-3">
<section aria-labelledby="counts-heading" class="card space-y-3">
<h2 id="counts-heading" class="text-lg font-semibold">{{ __('inventory.counts.list') }}</h2>
@if ($this->counts === [])
<p class="text-sm">{{ __('inventory.counts.none') }}</p>
<x-empty-state icon="archive-box">{{ __('inventory.counts.none') }}</x-empty-state>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
@foreach ($this->counts as $count)
@@ -124,7 +124,7 @@ new class extends Component
{{ __('inventory.counts.confirmed_by', ['name' => $count->confirmedByName, 'at' => $this->dateLabel((string) $count->confirmedAt)]) }}
</span>
@can('inventory.manage-counts')
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700">
<a href="{{ route('inventory.counts.csv', $count->id) }}" class="inline-flex items-center gap-1 font-medium underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-down-tray" class="size-4" aria-hidden="true" />
{{ __('inventory.counts.csv_named', ['date' => $this->dateLabel($count->countedOn)]) }}
</a>
@@ -152,14 +152,14 @@ new class extends Component
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.groups.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.groups.intro') }}</p>
<x-page-title icon="folder">{{ __('inventory.groups.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.groups.intro') }}</p>
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
</div>
<p role="status" aria-live="polite" class="text-sm font-medium">{{ $message }}</p>
<form wire:submit="add" class="flex flex-wrap items-end gap-3" novalidate>
<form wire:submit="add" class="card flex flex-wrap items-end gap-3" novalidate>
<div class="min-w-0 flex-1">
<x-input id="new-group-name" wire:model="newName" :label="__('inventory.groups.name')" autocomplete="off" maxlength="150" />
</div>
@@ -167,7 +167,7 @@ new class extends Component
</form>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.groups.none') }}</p>
<x-empty-state icon="archive-box">{{ __('inventory.groups.none') }}</x-empty-state>
@else
<ul class="divide-y divide-zinc-200 rounded-lg border border-zinc-300 dark:divide-zinc-700 dark:border-zinc-600">
@foreach ($this->groups as $group)
@@ -183,7 +183,7 @@ new class extends Component
@else
<div class="min-w-0 flex-1">
<p class="font-medium break-words">{{ $group->name }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ trans_choice('inventory.groups.items', $group->itemCount, ['count' => $group->itemCount]) }}
@unless ($group->isActive)
· {{ __('inventory.status.inactive') }}
@@ -93,8 +93,8 @@ new class extends Component
<div class="mx-auto max-w-6xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('inventory.index.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.index.intro') }}</p>
<x-page-title icon="archive-box">{{ __('inventory.index.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.index.intro') }}</p>
@can('inventory.manage')
<div class="flex flex-wrap gap-3">
<x-button :href="route('inventory.items.create')" wire:navigate icon="plus" :text="__('inventory.index.new_item')" />
@@ -127,13 +127,13 @@ new class extends Component
</p>
@if ($this->items === [])
<p class="text-sm">{{ __('inventory.index.none') }}</p>
<x-empty-state icon="archive-box">{{ __('inventory.index.none') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->items">
@interact('column_name', $item)
<x-link :href="route('inventory.items.show', $item->id)" navigate class="whitespace-normal">{{ $item->name }}</x-link>
@if ($item->code !== null)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $item->code }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ $item->code }}</span>
@endif
@endinteract
@@ -170,12 +170,12 @@ new class extends Component
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="archive-box">{{ $this->heading() }}</x-page-title>
@if ($this->groups === [])
<p class="text-sm">{{ __('inventory.form.no_groups') }} <x-link :href="route('inventory.groups')" navigate>{{ __('inventory.index.groups') }}</x-link></p>
@else
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native id="item-group" wire:model="groupId" :label="__('inventory.form.group')" :aria-label="__('inventory.form.group')">
@foreach ($this->groups as $group)
@@ -198,8 +198,8 @@ new class extends Component
<x-input id="item-reorder" wire:model="reorderLevel" inputmode="decimal" :label="__('inventory.form.reorder_level')" :hint="__('inventory.form.reorder_level_hint')" autocomplete="off" />
<div class="space-y-2">
<label for="item-image" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('inventory.form.image') }}</label>
<p id="item-image-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
<label for="item-image" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-200">{{ __('inventory.form.image') }}</label>
<p id="item-image-hint" class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.form.image_hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
@if ($hasImage && $itemId !== null)
<img src="{{ route('inventory.items.image', [$itemId, 'thumbnail']) }}" alt="{{ __('inventory.form.current_image') }}" class="size-24 rounded-md border border-zinc-300 object-cover dark:border-zinc-600" />
<x-checkbox id="remove-image" wire:model="removeImage" :label="__('inventory.form.remove_image')" />
@@ -211,7 +211,7 @@ new class extends Component
accept="image/jpeg,image/png,image/webp,image/gif"
aria-describedby="item-image-hint @error('image') item-image-error @enderror"
@error('image') aria-invalid="true" @enderror
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-primary-50 file:px-3 file:py-2 file:font-medium file:text-primary-800 hover:file:bg-primary-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:text-zinc-100 dark:file:bg-primary-950 dark:file:text-primary-100 dark:hover:file:bg-primary-900"
/>
@error('image')
<p id="item-image-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -347,7 +347,7 @@ new class extends Component
@endif
<div class="min-w-0 flex-1 space-y-2">
<p class="text-sm"><x-link :href="route('inventory.index')" navigate>{{ __('inventory.groups.back') }}</x-link></p>
<h1 class="text-2xl font-semibold break-words">{{ $item->name }}</h1>
<x-page-title icon="archive-box">{{ $item->name }}</x-page-title>
<x-inventory.stock-status :item="$item" />
@can('inventory.manage')
<div class="flex flex-wrap gap-2">
@@ -360,7 +360,7 @@ new class extends Component
<p id="item-status" tabindex="-1" role="status" aria-live="polite" class="text-sm font-medium focus:outline-none">{{ $message }}</p>
<section aria-labelledby="details-heading" class="space-y-3">
<section aria-labelledby="details-heading" class="card space-y-3">
<h2 id="details-heading" class="text-lg font-semibold">{{ __('inventory.item.details') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-2 lg:grid-cols-3">
<div>
@@ -406,9 +406,9 @@ new class extends Component
<div class="grid gap-6 lg:grid-cols-2">
@can('inventory.manage')
<section aria-labelledby="purchase-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<section aria-labelledby="purchase-heading" class="card space-y-3">
<h2 id="purchase-heading" class="text-lg font-semibold">{{ __('inventory.purchase.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.purchase.intro') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.purchase.intro') }}</p>
<form wire:submit="recordPurchase" class="space-y-4" novalidate>
<x-input id="purchase-day" wire:model="purchaseDay" type="date" :label="__('inventory.purchase.day')" required />
<x-input id="purchase-quantity" wire:model="purchaseQuantity" inputmode="decimal" :label="__('inventory.purchase.quantity', ['unit' => $unitLabel])" autocomplete="off" />
@@ -420,7 +420,7 @@ new class extends Component
</form>
</section>
<section aria-labelledby="write-off-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<section aria-labelledby="write-off-heading" class="card space-y-3">
<h2 id="write-off-heading" class="text-lg font-semibold">{{ __('inventory.write_off.title') }}</h2>
<form wire:submit="recordWriteOff" class="space-y-4" novalidate>
<x-input id="write-off-quantity" wire:model="writeOffQuantity" inputmode="decimal" :label="__('inventory.write_off.quantity', ['unit' => $unitLabel])" autocomplete="off" />
@@ -432,9 +432,9 @@ new class extends Component
@if ($item->isActive)
@can('inventory.record-use')
<section aria-labelledby="use-heading" class="space-y-3 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<section aria-labelledby="use-heading" class="card space-y-3">
<h2 id="use-heading" class="text-lg font-semibold">{{ __('inventory.use.title') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.use.intro') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.use.intro') }}</p>
<form wire:submit="recordUse" class="space-y-4" novalidate>
<x-input id="use-quantity" wire:model="useQuantity" inputmode="decimal" :label="__('inventory.use.quantity', ['unit' => $unitLabel])" autocomplete="off" />
<x-input id="use-reason" wire:model="useReason" :label="__('inventory.use.reason')" autocomplete="off" maxlength="255" />
@@ -451,10 +451,10 @@ new class extends Component
<h2 id="history-heading" class="text-lg font-semibold">{{ __('inventory.item.history') }}</h2>
@if ($this->movements === [])
<p class="text-sm">{{ __('inventory.item.history_none') }}</p>
<x-empty-state icon="archive-box">{{ __('inventory.item.history_none') }}</x-empty-state>
@else
@if (count($this->movements) >= $this::HISTORY_LIMIT)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.item.history_limit', ['count' => $this::HISTORY_LIMIT]) }}</p>
@endif
<x-table :headers="$this->headers()" :rows="$this->movements">
@@ -272,7 +272,7 @@ new class extends Component
<div>
@if (($this->context?->usesStock ?? false) || $this->movements !== [])
<section aria-label="{{ __('inventory.task.list_of', ['title' => $taskTitle]) }}" class="space-y-3">
<section data-task-section aria-label="{{ __('inventory.task.list_of', ['title' => $taskTitle]) }}" class="space-y-3">
<h4 class="font-medium">{{ __('inventory.task.title') }}</h4>
<p id="task-{{ $taskId }}-materials-status" tabindex="-1" role="status" aria-live="polite" class="text-sm focus:outline-none">{{ $message }}</p>
@@ -332,7 +332,7 @@ new class extends Component
/>
@if (mb_strlen(trim($search)) >= 2)
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-200">
{{ trans_choice('inventory.task.results', count($this->results), ['count' => count($this->results)]) }}
</p>
<ul class="space-y-1">
@@ -341,11 +341,11 @@ new class extends Component
<button
type="button"
wire:click="selectItem({{ $result->id }})"
class="flex min-h-11 w-full flex-wrap items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:hover:bg-zinc-700"
class="flex min-h-11 w-full flex-wrap items-center justify-between gap-2 rounded-md px-3 py-2 text-left text-sm hover:bg-zinc-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:hover:bg-zinc-700"
aria-label="{{ __('inventory.task.choose', ['item' => $result->name, 'balance' => $this->quantity($result->balanceMilli, $result->unit)]) }}"
>
<span class="font-medium">{{ $result->name }}</span>
<span class="text-zinc-700 dark:text-zinc-300">{{ $this->quantity($result->balanceMilli, $result->unit) }}</span>
<span class="text-zinc-700 dark:text-zinc-200">{{ $this->quantity($result->balanceMilli, $result->unit) }}</span>
</button>
</li>
@endforeach
@@ -356,7 +356,7 @@ new class extends Component
@endif
@if ($this->movements === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('inventory.task.none') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('inventory.task.none') }}</p>
@else
<ul class="divide-y divide-zinc-200 text-sm dark:divide-zinc-700">
@foreach ($this->movements as $movement)
@@ -364,7 +364,7 @@ new class extends Component
<span>
<span class="font-medium">{{ $movement->itemName }}</span>
{{ $this->quantity(-$movement->quantityMilli, $movement->unit) }}
<span class="text-zinc-600 dark:text-zinc-300">
<span class="text-zinc-600 dark:text-zinc-200">
· {{ __('inventory.kinds.'.$movement->kind->value) }} · {{ $movement->userName }}, {{ $this->dateLabel($movement->recordedAt) }}
@if ($movement->reversedByMovementId !== null)
· {{ __('inventory.task.undone_mark') }}
@@ -4,6 +4,13 @@ use App\Modules\Inventory\Presentation\Http\Controllers\DownloadInventoryCount;
use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage;
use Illuminate\Support\Facades\Route;
// Pictures on the machine console, which has its own session (paths under console/).
Route::middleware(['web', 'auth', 'can:inventory.view'])
->get('/console/inventory/items/{item}/image/{size}', ShowStockItemImage::class)
->whereNumber('item')
->whereIn('size', ['full', 'thumbnail'])
->name('inventory.items.console-image');
Route::middleware(['web', 'auth', 'can:inventory.view'])
->prefix('inventory')
->name('inventory.')
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\BoardCard;
use App\Modules\Jobs\Application\DTOs\BoardFilter;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
/**
* Read side of the Kanban board.
*/
interface JobBoardQueries
{
/**
* Every card the filter lets through: open and done jobs (not archived,
* not the yearly quick-sale job) with their tasks, and tasks of
* continuing jobs pinned to the board as cards of their own.
*
* @param string $today Y-m-d, for late jobs
* @return list<BoardCard>
*/
public function cards(BoardFilter $filter, string $today): array;
/**
* The user's board settings, or the defaults.
*/
public function preferencesOf(int $userId): BoardPreferences;
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
/**
* Hours recorded on jobs and tasks, for the Kanban cards. The TimeTracking
* module provides it; Jobs knows nothing about time entries.
*/
interface LoggedJobHours
{
/**
* Recorded quarter-hours by job id (jobs without hours are left out).
*
* @param list<int> $jobIds
* @return array<int, int>
*/
public function quartersByJobs(array $jobIds): array;
/**
* Recorded quarter-hours by task id (tasks without hours are left out).
*
* @param list<int> $taskIds
* @return array<int, int>
*/
public function quartersByTasks(array $taskIds): array;
}
@@ -16,6 +16,23 @@ 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<int, bool>
*/
public function pinnedTaskIds(int $jobId): array;
/**
* Tasks scheduled for the user between the dates (Y-m-d): booked on
* their task calendar row, or open tasks they are the assignee or a
* member of whose planned period overlaps the dates or that have no
* planned period at all (so unscheduled own work is never hidden).
*
* @return list<int>
*/
public function scheduledTaskIdsFor(int $userId, string $from, string $to): array;
/**
* Null when the task does not exist or belongs to another job.
*/
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobKind;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A card on the Kanban board: a customer job, or a task of a continuing
* job that is pinned to the board as its own card ($taskId set).
*/
final readonly class BoardCard
{
/**
* @param list<BoardTask> $tasks the job's tasks (empty on a task card)
*/
public function __construct(
public int $jobId,
public ?int $taskId,
public string $number,
public string $title,
public string $jobName,
public int $customerId,
public string $customerName,
public ?string $customerHeaderColor,
public JobStatus $jobStatus,
public ?TaskStatus $taskStatus,
public Priority $priority,
public JobKind $kind,
public ?string $dueOn,
public bool $isLate,
public ?string $responsibleName,
public ?string $serviceUnitName,
public ?string $estimatedHours,
public int $loggedQuarters,
public int $boardPosition,
public ?int $billerUserId,
public array $tasks = [],
) {}
public function isTaskCard(): bool
{
return $this->taskId !== null;
}
/**
* Stable key for wire:key and wire:sort:item: "job-12" or "task-34".
*/
public function key(): string
{
return $this->isTaskCard() ? 'task-'.$this->taskId : 'job-'.$this->jobId;
}
public function isOngoing(): bool
{
return $this->jobStatus === JobStatus::Ongoing && ! $this->isTaskCard();
}
public function doneTaskCount(): int
{
return count(array_filter($this->tasks, fn (BoardTask $task): bool => $task->isDone()));
}
/**
* The first open task of a continuing job ("Seuraava vuorossa").
*/
public function nextOpenTask(): ?BoardTask
{
foreach ($this->tasks as $task) {
if (! $task->isDone()) {
return $task;
}
}
return null;
}
public function responsibleInitials(): string
{
if ($this->responsibleName === null || trim($this->responsibleName) === '') {
return '?';
}
$parts = preg_split('/\s+/', trim($this->responsibleName)) ?: [];
$initials = '';
foreach (array_slice($parts, 0, 2) as $part) {
$initials .= mb_strtoupper(mb_substr($part, 0, 1));
}
return $initials;
}
public function responsibleFirstName(): ?string
{
return $this->responsibleName === null ? null : explode(' ', trim($this->responsibleName))[0];
}
public function loggedHours(): float
{
return $this->loggedQuarters / 4;
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Whose cards the Kanban board shows (docs/ui-kanban-board.md 2): one
* person's jobs (their own board or another person's), one service line,
* or the whole company. Subcontractors are always limited to their jobs.
*/
final readonly class BoardFilter
{
public function __construct(
/** Jobs this user is responsible for, a member of or does a task of. */
public ?int $personUserId = null,
public ?int $serviceUnitId = null,
/** Restricts everything to jobs the user is a member of (subcontractors). */
public ?int $onlyMemberUserId = null,
public bool $onlyUrgent = false,
public bool $onlyLate = false,
) {}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task row in a Kanban card's task list.
*/
final readonly class BoardTask
{
public function __construct(
public int $id,
public string $title,
public TaskStatus $status,
public ?string $assigneeName,
public bool $pinnedToBoard,
public ?string $dueOn = null,
) {}
public function isDone(): bool
{
return $this->status === TaskStatus::Done;
}
public function assigneeFirstName(): ?string
{
return $this->assigneeName === null ? null : explode(' ', trim($this->assigneeName))[0];
}
}
@@ -8,8 +8,9 @@ use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task as time is recorded on it: which job and work type it belongs to,
* and whether the job is locked for time entries.
* A task as time is recorded on it: which job, customer and work type it
* belongs to, the job's payment basis (a PaymentBasis value) and whether
* the job is locked for time entries.
*/
final readonly class BookableTask
{
@@ -23,6 +24,10 @@ final readonly class BookableTask
public string $workTypeName,
public JobStatus $jobStatus,
public TaskStatus $taskStatus,
public int $customerId = 0,
public string $customerName = '',
public ?string $customerHeaderColor = null,
public ?string $paymentBasis = null,
) {}
public function isLocked(): bool
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Jobs\Application\DTOs\BoardCard;
use App\Modules\Jobs\Domain\Enums\BoardColumn;
use App\Modules\Jobs\Domain\Enums\BoardView;
use App\Modules\Jobs\Domain\Enums\ColumnSort;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
/**
* Places Kanban cards in the columns of a view and orders each column
* (docs/ui-kanban-board.md 3–4):
*
* - jobs in production go to the urgent column when their priority meets
* the user's threshold, to the normal one otherwise;
* - continuing jobs only ever stand in "Jatkuvat & Kausi";
* - a pinned task stands in Jonossa, Työn alla or Valmis by its status;
* - a manual column is in drag order, a due-date column has the earliest
* due date on top and cards without one last.
*/
final class BoardLayout
{
/**
* @param list<BoardCard> $cards
* @return array<string, list<BoardCard>> by BoardColumn value, in the view's column order
*/
public function arrange(array $cards, BoardView $view, BoardPreferences $preferences): array
{
$columns = [];
foreach ($view->columns() as $column) {
$columns[$column->value] = [];
}
foreach ($cards as $card) {
$column = $this->columnOf($card, $view, $preferences);
if ($column !== null && array_key_exists($column->value, $columns)) {
$columns[$column->value][] = $card;
}
}
foreach ($columns as $value => $columnCards) {
$columns[$value] = $this->sorted($columnCards, $preferences->sortOf(BoardColumn::from($value)));
}
return $columns;
}
public function columnOf(BoardCard $card, BoardView $view, BoardPreferences $preferences): ?BoardColumn
{
if ($card->isTaskCard()) {
return $card->taskStatus === null ? null : BoardColumn::forTask($card->taskStatus);
}
if ($card->jobStatus === JobStatus::Ongoing) {
return BoardColumn::Ongoing;
}
return BoardColumn::forJob($card->jobStatus, $card->priority, $preferences->urgentThreshold, $view->gathersQuotes());
}
/**
* @param list<BoardCard> $cards
* @return list<BoardCard>
*/
private function sorted(array $cards, ColumnSort $sort): array
{
usort($cards, function (BoardCard $a, BoardCard $b) use ($sort): int {
if ($sort === ColumnSort::DueDate) {
$byDue = ($a->dueOn ?? '9999-12-31') <=> ($b->dueOn ?? '9999-12-31');
if ($byDue !== 0) {
return $byDue;
}
}
return [$a->boardPosition, $a->isTaskCard() ? 1 : 0, $a->taskId ?? $a->jobId]
<=> [$b->boardPosition, $b->isTaskCard() ? 1 : 0, $b->taskId ?? $b->jobId];
});
return $cards;
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a job's priority (e.g. in the board's job editor) and records it.
*/
final class ChangeJobPriority
{
public function __construct(
private CustomerJobRepository $jobs,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
*/
public function execute(int $jobId, Priority $priority, int $actorUserId): void
{
$this->transactions->run(function () use ($jobId, $priority, $actorUserId): void {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$changes = $job->changePriority($priority);
if ($changes === []) {
return;
}
$this->jobs->save($job);
$this->jobs->recordChanges($jobId, $actorUserId, $changes);
});
}
}
@@ -0,0 +1,145 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Enums\BoardColumn;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Enums\UrgentThreshold;
use App\Modules\Jobs\Domain\Events\TaskCompleted;
use App\Modules\Jobs\Domain\Exceptions\CardCannotMoveThere;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* A Kanban card dropped into a column (docs/ui-kanban-board.md 3):
*
* - a job dropped into another status's column gets that status;
* - a job dropped into "Työn alla • Kiire" gets at least the threshold's
* priority, and one dropped into the normal "Työn alla" with an urgent
* priority gets the normal priority;
* - a pinned task card gets the status of its new column;
* - the column's cards get positions in the dropped order.
*
* Who may set a billing status or open a lock is checked by the caller.
*/
final class MoveBoardCard
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private BoardRepository $board,
private TransactionManager $transactions,
private EventDispatcher $events,
private Clock $clock,
) {}
/**
* @param list<string> $orderedKeys the target column's card keys ("job-12", "task-34") in their new order
*
* @throws CustomerJobNotFound
* @throws TaskNotFound
* @throws CardCannotMoveThere
*/
public function execute(int $jobId, ?int $taskId, BoardColumn $target, array $orderedKeys, UrgentThreshold $threshold, int $actorUserId): void
{
$this->transactions->run(function () use ($jobId, $taskId, $target, $orderedKeys, $threshold, $actorUserId): void {
if ($taskId === null) {
$this->moveJob($jobId, $target, $threshold, $actorUserId);
} else {
$this->moveTask($jobId, $taskId, $target);
}
$this->reorder($orderedKeys);
});
}
/**
* The status a job gets when dropped into the column: its own when the
* column already holds it (e.g. moving between the quote statuses in
* "Tarjoukset"), the column's otherwise.
*/
public static function statusAfterDrop(JobStatus $current, BoardColumn $target): JobStatus
{
return in_array($current, $target->statuses(), true) ? $current : $target->targetStatus();
}
private function moveJob(int $jobId, BoardColumn $target, UrgentThreshold $threshold, int $actorUserId): void
{
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$current = $job->details()->status;
if (($current === JobStatus::Ongoing) !== $target->isOngoing()) {
throw new CardCannotMoveThere;
}
$changes = $job->changeStatus(self::statusAfterDrop($current, $target));
$priority = $job->details()->priority;
if ($target->isUrgentLane() && ! $threshold->includes($priority)) {
$changes = [...$changes, ...$job->changePriority($threshold->lowestPriority())];
} elseif ($target->isNormalProductionLane() && $threshold->includes($priority)) {
$changes = [...$changes, ...$job->changePriority(Priority::Normal)];
}
$job->recordCompletion($this->clock->now());
if ($changes !== []) {
$this->jobs->save($job);
$this->jobs->recordChanges($jobId, $actorUserId, $changes);
}
}
private function moveTask(int $jobId, int $taskId, BoardColumn $target): void
{
$status = $target->taskStatus() ?? throw new CardCannotMoveThere;
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$wasDone = $task->status() === TaskStatus::Done;
if ($task->status() === $status || ($status === TaskStatus::InProgress && $task->status() === TaskStatus::InReview)) {
return;
}
$task->changeStatus($status);
$this->tasks->save($task);
if (! $wasDone && $status === TaskStatus::Done) {
$this->events->dispatch(new TaskCompleted($taskId, $jobId));
}
}
/**
* @param list<string> $orderedKeys
*/
private function reorder(array $orderedKeys): void
{
$jobPositions = [];
$taskPositions = [];
foreach ($orderedKeys as $index => $key) {
if (preg_match('/^(job|task)-(\d+)$/', $key, $matches) !== 1) {
continue;
}
$position = ($index + 1) * 10;
if ($matches[1] === 'job') {
$jobPositions[(int) $matches[2]] = $position;
} else {
$taskPositions[(int) $matches[2]] = $position;
}
}
$this->board->setJobPositions($jobPositions);
$this->board->setTaskPositions($taskPositions);
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskCannotBePinned;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Lifts a task of a continuing job onto the Kanban board as a card of its
* own ("Nosta putkeen"), or releases it back under the job's card.
*/
final class PinTaskToBoard
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private BoardRepository $board,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
* @throws TaskNotFound
* @throws TaskCannotBePinned
*/
public function execute(int $jobId, int $taskId, bool $pinned): void
{
$this->transactions->run(function () use ($jobId, $taskId, $pinned): void {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
if ($pinned && $job->details()->status !== JobStatus::Ongoing) {
throw new TaskCannotBePinned;
}
$this->board->setTaskPinned($taskId, $pinned);
});
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Stores one user's Kanban settings. They never change anyone else's board.
*/
final class SaveBoardPreferences
{
public function __construct(
private BoardRepository $board,
private TransactionManager $transactions,
) {}
public function execute(int $userId, BoardPreferences $preferences): void
{
$this->transactions->run(fn () => $this->board->savePreferences($userId, $preferences));
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
/**
* Kanban board state that is not part of a job's details: card order,
* tasks pinned to the board and each user's board settings. None of it is
* recorded in a job's change history.
*/
interface BoardRepository
{
/**
* @param array<int, int> $positions board position by job id
*/
public function setJobPositions(array $positions): void;
/**
* @param array<int, int> $positions board position by task id
*/
public function setTaskPositions(array $positions): void;
public function setTaskPinned(int $taskId, bool $pinned): void;
public function preferencesOf(int $userId): BoardPreferences;
public function savePreferences(int $userId, BoardPreferences $preferences): void;
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Entities;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
@@ -87,6 +88,14 @@ final class CustomerJob
return $this->changeDetails($this->details->withStatus($status));
}
/**
* @return list<FieldChange>
*/
public function changePriority(Priority $priority): array
{
return $this->changeDetails($this->details->withPriority($priority));
}
public function id(): ?int
{
return $this->id;
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* A column of the Kanban board (docs/ui-kanban-board.md 2–3). Most columns
* are one job status; "Tarjoukset" gathers the three sales statuses, and
* jobs in production are split into a normal and an urgent column by the
* user's urgent threshold. Continuing jobs have a column of their own.
*/
enum BoardColumn: string
{
case Quotes = 'quotes';
case Prospect = 'prospect';
case Tentative = 'tentative';
case QuoteRequest = 'quote_request';
case Order = 'order';
case InProduction = 'in_production';
case InProductionUrgent = 'in_production_urgent';
case OnHold = 'on_hold';
case Done = 'done';
case Invoiced = 'invoiced';
case Billed = 'billed';
case Ongoing = 'ongoing';
/**
* @return list<JobStatus>
*/
public function statuses(): array
{
return match ($this) {
self::Quotes => [JobStatus::Prospect, JobStatus::Tentative, JobStatus::QuoteRequest],
self::InProduction, self::InProductionUrgent => [JobStatus::InProduction],
default => [JobStatus::from($this->value)],
};
}
/**
* The status a card gets when it is dropped into this column from
* another one.
*/
public function targetStatus(): JobStatus
{
return match ($this) {
self::Quotes => JobStatus::QuoteRequest,
self::InProduction, self::InProductionUrgent => JobStatus::InProduction,
default => JobStatus::from($this->value),
};
}
public function isOngoing(): bool
{
return $this === self::Ongoing;
}
public function isUrgentLane(): bool
{
return $this === self::InProductionUrgent;
}
public function isNormalProductionLane(): bool
{
return $this === self::InProduction;
}
/**
* Whether a promoted (pinned) task card may be in or dropped into this
* column: its column follows the task's status.
*/
public function acceptsTasks(): bool
{
return in_array($this, [self::Order, self::InProduction, self::Done], true);
}
/**
* The column header colour before the user picks one (the design's
* default palette).
*/
public function defaultColor(): string
{
return match ($this) {
self::Quotes, self::Tentative => '#4338ca',
self::Prospect => '#374151',
self::QuoteRequest => '#6d28d9',
self::Order => '#23476a',
self::InProduction, self::InProductionUrgent => '#1d4ed8',
self::OnHold => '#78350f',
self::Done => '#14532d',
self::Invoiced => '#0f5c63',
self::Billed => '#065f46',
self::Ongoing => '#3b2d5e',
};
}
/**
* A Heroicon name for the column header.
*/
public function icon(): string
{
return match ($this) {
self::Quotes, self::QuoteRequest => 'document-text',
self::Prospect => 'light-bulb',
self::Tentative => 'pencil-square',
self::Order => 'inbox-stack',
self::InProduction => 'play-circle',
self::InProductionUrgent => 'fire',
self::OnHold => 'clock',
self::Done => 'check-circle',
self::Invoiced => 'credit-card',
self::Billed => 'check-badge',
self::Ongoing => 'arrow-path',
};
}
/**
* The column a job card stands in. A sales status is in "Tarjoukset" in
* views that gather them, in its own column otherwise.
*/
public static function forJob(JobStatus $status, Priority $priority, UrgentThreshold $threshold, bool $gatherQuotes): ?self
{
return match ($status) {
JobStatus::Prospect, JobStatus::Tentative, JobStatus::QuoteRequest => $gatherQuotes ? self::Quotes : self::from($status->value),
JobStatus::InProduction => $threshold->includes($priority) ? self::InProductionUrgent : self::InProduction,
JobStatus::Archived => null,
default => self::from($status->value),
};
}
/**
* The column a promoted task card stands in, by the task's status.
*/
public static function forTask(TaskStatus $status): self
{
return match ($status) {
TaskStatus::Waiting => self::Order,
TaskStatus::InProgress, TaskStatus::InReview => self::InProduction,
TaskStatus::Done => self::Done,
};
}
/**
* The task status a promoted task card gets when dropped here.
*/
public function taskStatus(): ?TaskStatus
{
return match ($this) {
self::Order => TaskStatus::Waiting,
self::InProduction => TaskStatus::InProgress,
self::Done => TaskStatus::Done,
default => null,
};
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Card density of a user's Kanban board: normal cards or three-row
* compact cards (docs/ui-kanban-board.md 1.1).
*/
enum BoardDensity: string
{
case Normal = 'normal';
case Compact = 'compact';
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Näkymäputki of the Kanban board (docs/ui-kanban-board.md 2.2).
*/
enum BoardView: string
{
/** Päivittäinen työputki: quotes gathered, production, continuing jobs. */
case Production = 'production';
/** Myynti & Tarjoukset: the three sales statuses apart. */
case Sales = 'sales';
/** Täysi tilaputki: every status from prospect to billed, plus continuing jobs. */
case Full = 'full';
/**
* @return list<BoardColumn>
*/
public function columns(): array
{
return match ($this) {
self::Production => [
BoardColumn::Quotes, BoardColumn::Order, BoardColumn::InProduction, BoardColumn::InProductionUrgent,
BoardColumn::OnHold, BoardColumn::Done, BoardColumn::Ongoing,
],
self::Sales => [BoardColumn::Prospect, BoardColumn::Tentative, BoardColumn::QuoteRequest],
self::Full => [
BoardColumn::Prospect, BoardColumn::Tentative, BoardColumn::QuoteRequest, BoardColumn::Order,
BoardColumn::InProduction, BoardColumn::InProductionUrgent, BoardColumn::OnHold, BoardColumn::Done,
BoardColumn::Invoiced, BoardColumn::Billed, BoardColumn::Ongoing,
],
};
}
public function gathersQuotes(): bool
{
return $this === self::Production;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Order of cards in one Kanban column: the user's own drag order, or by due
* date with the earliest (most overdue) on top and cards without one last.
*/
enum ColumnSort: string
{
case Manual = 'manual';
case DueDate = 'due_date';
}
@@ -19,6 +19,7 @@ enum JobStatus: string
case Done = 'done';
case Invoiced = 'invoiced';
case Billed = 'billed';
case Ongoing = 'ongoing';
case Archived = 'archived';
/**
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Which priorities lift a job in production into the "Työn alla • Kiire"
* column of the Kanban board (docs/ui-kanban-board.md 3.1). Each user
* chooses it for their own board.
*/
enum UrgentThreshold: string
{
case Immediate = 'immediate';
case Urgent = 'urgent';
case First = 'first';
/**
* The lowest priority that is urgent at this threshold.
*/
public function lowestPriority(): Priority
{
return match ($this) {
self::Immediate => Priority::Immediate,
self::Urgent => Priority::Urgent,
self::First => Priority::First,
};
}
public function includes(Priority $priority): bool
{
return self::rank($priority) >= self::rank($this->lowestPriority());
}
/**
* Waiting 1, Normal 2, First 3, Urgent 4, Immediate 5.
*/
public static function rank(Priority $priority): int
{
return match ($priority) {
Priority::Waiting => 1,
Priority::Normal => 2,
Priority::First => 3,
Priority::Urgent => 4,
Priority::Immediate => 5,
};
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A Kanban card was dropped into a column it cannot stand in: a continuing
* job outside "Jatkuvat & Kausi", another job into it, or a pinned task
* outside Jonossa, Työn alla and Valmis.
*/
final class CardCannotMoveThere extends DomainException
{
public function __construct()
{
parent::__construct('The card cannot be moved to that column.');
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Only tasks of continuing jobs (status "Jatkuvat / Kausi") can be lifted
* onto the Kanban board as cards of their own.
*/
final class TaskCannotBePinned extends DomainException
{
public function __construct()
{
parent::__construct('Only tasks of continuing jobs can be pinned to the board.');
}
}
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Enums\BoardColumn;
use App\Modules\Jobs\Domain\Enums\BoardDensity;
use App\Modules\Jobs\Domain\Enums\ColumnSort;
use App\Modules\Jobs\Domain\Enums\UrgentThreshold;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
/**
* One user's Kanban board settings: card density, the urgent threshold,
* their own colour and order for each column, and which cards they keep
* open (task list shown). A column without a colour of its own uses the
* design's default colour.
*/
final readonly class BoardPreferences
{
/** At most this many open cards are remembered, the latest kept. */
public const int MAX_EXPANDED_CARDS = 500;
/**
* @param array<string, HexColor> $columnColors by BoardColumn value
* @param array<string, ColumnSort> $columnSorts by BoardColumn value
* @param list<string> $expandedCards card keys ("job-12", "task-34"), oldest first
*/
public function __construct(
public BoardDensity $density = BoardDensity::Normal,
public UrgentThreshold $urgentThreshold = UrgentThreshold::Urgent,
public array $columnColors = [],
public array $columnSorts = [],
public array $expandedCards = [],
) {}
public static function defaults(): self
{
return new self;
}
public static function isCardKey(string $key): bool
{
return preg_match('/^(job|task)-\d+$/', $key) === 1;
}
/**
* Rebuilds stored settings, dropping unknown columns and invalid values
* so a bad stored value never breaks the board.
*
* @param array<array-key, mixed> $colors
* @param array<array-key, mixed> $sorts
* @param array<array-key, mixed> $expanded
*/
public static function fromStored(?string $density, ?string $threshold, array $colors, array $sorts, array $expanded = []): self
{
$columnColors = [];
foreach ($colors as $column => $color) {
if (BoardColumn::tryFrom((string) $column) !== null && is_string($color) && preg_match('/^#[0-9a-f]{6}$/i', $color) === 1) {
$columnColors[(string) $column] = new HexColor($color);
}
}
$columnSorts = [];
foreach ($sorts as $column => $sort) {
$parsed = is_string($sort) ? ColumnSort::tryFrom($sort) : null;
if (BoardColumn::tryFrom((string) $column) !== null && $parsed !== null) {
$columnSorts[(string) $column] = $parsed;
}
}
$expandedCards = array_values(array_unique(array_filter($expanded, fn ($key): bool => is_string($key) && self::isCardKey($key))));
return new self(
BoardDensity::tryFrom((string) $density) ?? BoardDensity::Normal,
UrgentThreshold::tryFrom((string) $threshold) ?? UrgentThreshold::Urgent,
$columnColors,
$columnSorts,
array_slice($expandedCards, -self::MAX_EXPANDED_CARDS),
);
}
public function colorOf(BoardColumn $column): HexColor
{
return $this->columnColors[$column->value] ?? new HexColor($column->defaultColor());
}
public function hasOwnColor(BoardColumn $column): bool
{
return isset($this->columnColors[$column->value]);
}
public function sortOf(BoardColumn $column): ColumnSort
{
return $this->columnSorts[$column->value] ?? ColumnSort::Manual;
}
public function isCardExpanded(string $key): bool
{
return in_array($key, $this->expandedCards, true);
}
public function withDensity(BoardDensity $density): self
{
return new self($density, $this->urgentThreshold, $this->columnColors, $this->columnSorts, $this->expandedCards);
}
public function withUrgentThreshold(UrgentThreshold $threshold): self
{
return new self($this->density, $threshold, $this->columnColors, $this->columnSorts, $this->expandedCards);
}
/**
* Null returns the column to its default colour.
*/
public function withColumnColor(BoardColumn $column, ?HexColor $color): self
{
$colors = $this->columnColors;
if ($color === null) {
unset($colors[$column->value]);
} else {
$colors[$column->value] = $color;
}
return new self($this->density, $this->urgentThreshold, $colors, $this->columnSorts, $this->expandedCards);
}
public function withColumnSort(BoardColumn $column, ColumnSort $sort): self
{
$sorts = $this->columnSorts;
$sorts[$column->value] = $sort;
return new self($this->density, $this->urgentThreshold, $this->columnColors, $sorts, $this->expandedCards);
}
/**
* Opens or closes a card's task list for this user. A card key that is
* not one ("job-12" / "task-34") changes nothing.
*/
public function withCardExpanded(string $key, bool $expanded): self
{
if (! self::isCardKey($key)) {
return $this;
}
$cards = array_values(array_diff($this->expandedCards, [$key]));
if ($expanded) {
$cards[] = $key;
}
return new self($this->density, $this->urgentThreshold, $this->columnColors, $this->columnSorts, array_slice($cards, -self::MAX_EXPANDED_CARDS));
}
/**
* @return array<string, string>
*/
public function colorValues(): array
{
return array_map(fn (HexColor $color): string => $color->value, $this->columnColors);
}
/**
* @return array<string, string>
*/
public function sortValues(): array
{
return array_map(fn (ColumnSort $sort): string => $sort->value, $this->columnSorts);
}
}
@@ -102,6 +102,18 @@ final readonly class JobDetails
);
}
public function withPriority(Priority $priority): self
{
return new self(
$this->name, $this->description, $this->customerId, $this->serviceUnitIds,
$this->startsOn, $this->dueOn, $this->plannedFrom, $this->plannedTo,
$this->kind, $this->status, $priority, $this->paymentBasis, $this->estimatedHours,
$this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId,
$this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds,
$this->tags, $this->links, $this->quotedAmount, $this->monthlyFee,
);
}
public function withServiceUnit(int $serviceUnitId): self
{
return new self(
@@ -0,0 +1,21 @@
<?php
namespace App\Modules\Jobs\Infrastructure;
use App\Modules\Jobs\Application\Contracts\LoggedJobHours;
/**
* Default when no module records hours.
*/
class NoLoggedJobHours implements LoggedJobHours
{
public function quartersByJobs(array $jobIds): array
{
return [];
}
public function quartersByTasks(array $taskIds): array
{
return [];
}
}
@@ -31,6 +31,7 @@ use Illuminate\Database\Eloquent\Model;
* @property JobKind $kind
* @property JobStatus $status
* @property Priority $priority
* @property int $board_position
* @property PaymentBasis|null $payment_basis
* @property string|null $estimated_hours
* @property string|null $customer_reference
@@ -0,0 +1,36 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* One user's Kanban board settings.
*
* @property int $id
* @property int $user_id
* @property string $density
* @property string $urgent_threshold
* @property array<string, string>|null $column_colors
* @property array<string, string>|null $column_sorts
* @property list<string>|null $expanded_cards
*/
#[Table('job_board_preferences')]
#[Fillable(['user_id', 'density', 'urgent_threshold', 'column_colors', 'column_sorts', 'expanded_cards'])]
class JobBoardPreferenceModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_id' => 'integer',
'column_colors' => 'array',
'column_sorts' => 'array',
'expanded_cards' => 'array',
];
}
}
@@ -27,6 +27,8 @@ use Illuminate\Database\Eloquent\Model;
* @property CarbonImmutable|null $planned_to
* @property string|null $estimated_hours
* @property int|null $assignee_user_id
* @property bool $is_pinned_to_board
* @property int $board_position
* @property int $created_by
*/
#[Table('tasks')]
@@ -50,6 +52,8 @@ class TaskModel extends Model
'planned_from' => 'immutable_date',
'planned_to' => 'immutable_date',
'assignee_user_id' => 'integer',
'is_pinned_to_board' => 'boolean',
'board_position' => 'integer',
'created_by' => 'integer',
];
}
@@ -0,0 +1,54 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\JobBoardPreferenceModel;
use Illuminate\Support\Facades\DB;
/**
* Card order and pins are plain column updates: they are board state, not
* job details, so they bypass the job entity and its change history.
*/
class EloquentBoardRepository implements BoardRepository
{
public function setJobPositions(array $positions): void
{
foreach ($positions as $jobId => $position) {
DB::table('customer_jobs')->where('id', $jobId)->update(['board_position' => $position]);
}
}
public function setTaskPositions(array $positions): void
{
foreach ($positions as $taskId => $position) {
DB::table('tasks')->where('id', $taskId)->update(['board_position' => $position]);
}
}
public function setTaskPinned(int $taskId, bool $pinned): void
{
DB::table('tasks')->where('id', $taskId)->update(['is_pinned_to_board' => $pinned]);
}
public function preferencesOf(int $userId): BoardPreferences
{
$model = JobBoardPreferenceModel::query()->where('user_id', $userId)->first();
return $model === null
? BoardPreferences::defaults()
: BoardPreferences::fromStored($model->density, $model->urgent_threshold, $model->column_colors ?? [], $model->column_sorts ?? [], $model->expanded_cards ?? []);
}
public function savePreferences(int $userId, BoardPreferences $preferences): void
{
JobBoardPreferenceModel::query()->updateOrCreate(['user_id' => $userId], [
'density' => $preferences->density->value,
'urgent_threshold' => $preferences->urgentThreshold->value,
'column_colors' => $preferences->colorValues(),
'column_sorts' => $preferences->sortValues(),
'expanded_cards' => $preferences->expandedCards,
]);
}
}
@@ -197,7 +197,7 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
{
return array_values($this->billingInfo(CustomerJobModel::query()
->where('payment_basis', PaymentBasis::MonthlyFee)
->whereIn('status', [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done])
->whereIn('status', [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done, JobStatus::Ongoing])
->orderBy('number')
->get()));
}
@@ -0,0 +1,220 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\JobBoardQueries;
use App\Modules\Jobs\Application\Contracts\LoggedJobHours;
use App\Modules\Jobs\Application\DTOs\BoardCard;
use App\Modules\Jobs\Application\DTOs\BoardFilter;
use App\Modules\Jobs\Application\DTOs\BoardTask;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\ValueObjects\BoardPreferences;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Customer, user and service unit names and customer colours come from
* those modules' query contracts; recorded hours from LoggedJobHours.
*/
class EloquentJobBoardQueries implements JobBoardQueries
{
public function __construct(
private CustomerQueries $customers,
private UserAccountQueries $users,
private CatalogQueries $catalog,
private LoggedJobHours $hours,
private BoardRepository $board,
) {}
public function cards(BoardFilter $filter, string $today): array
{
$jobs = $this->filteredJobs($filter, $today)->get();
if ($jobs->isEmpty()) {
return [];
}
$jobIds = $jobs->pluck('id')->map(fn ($id): int => (int) $id)->all();
$tasks = TaskModel::query()
->whereIn('customer_job_id', $jobIds)
->orderByRaw('status = ?', [TaskStatus::Done->value])
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderBy('board_position')
->orderBy('id')
->get();
$customerIds = $jobs->pluck('customer_id')->unique()->values()->all();
$customerNames = $this->customers->namesByIds($customerIds);
$customerColors = $this->customers->headerColorsByIds($customerIds);
$userNames = $this->users->namesByIds($jobs->pluck('responsible_user_id')
->merge($tasks->pluck('assignee_user_id')->filter())
->map(fn ($id): int => (int) $id)->unique()->values()->all());
$jobQuarters = $this->hours->quartersByJobs($jobIds);
$pinnedTasks = $tasks->filter(fn (TaskModel $task): bool => (bool) $task->is_pinned_to_board);
$taskQuarters = $this->hours->quartersByTasks($pinnedTasks->pluck('id')->map(fn ($id): int => (int) $id)->values()->all());
$serviceUnitNames = $this->firstServiceUnitNames($jobIds);
$tasksByJob = $tasks->groupBy('customer_job_id');
$cards = [];
foreach ($jobs as $job) {
$jobTasks = $tasksByJob->get($job->id) ?? collect();
$common = [
'customerName' => $customerNames[$job->customer_id] ?? '',
'customerColor' => $customerColors[$job->customer_id] ?? null,
'serviceUnit' => $serviceUnitNames[$job->id] ?? null,
];
$cards[] = new BoardCard(
jobId: $job->id,
taskId: null,
number: $job->number,
title: $job->name,
jobName: $job->name,
customerId: $job->customer_id,
customerName: $common['customerName'],
customerHeaderColor: $common['customerColor'],
jobStatus: $job->status,
taskStatus: null,
priority: $job->priority,
kind: $job->kind,
dueOn: $job->due_on?->format('Y-m-d'),
isLate: $this->isLate($job->status, $job->due_on?->format('Y-m-d'), $today),
responsibleName: $userNames[$job->responsible_user_id] ?? null,
serviceUnitName: $common['serviceUnit'],
estimatedHours: $this->hoursText($job->estimated_hours),
loggedQuarters: $jobQuarters[$job->id] ?? 0,
boardPosition: (int) $job->board_position,
billerUserId: $job->biller_user_id,
tasks: $jobTasks->map(fn (TaskModel $task): BoardTask => new BoardTask(
$task->id,
$task->title,
$task->status,
$task->assignee_user_id === null ? null : ($userNames[$task->assignee_user_id] ?? null),
(bool) $task->is_pinned_to_board,
$task->due_on?->format('Y-m-d'),
))->values()->all(),
);
if ($job->status !== JobStatus::Ongoing) {
continue;
}
foreach ($jobTasks as $task) {
if (! $task->is_pinned_to_board) {
continue;
}
$cards[] = new BoardCard(
jobId: $job->id,
taskId: $task->id,
number: $job->number,
title: $task->title,
jobName: $job->name,
customerId: $job->customer_id,
customerName: $common['customerName'],
customerHeaderColor: $common['customerColor'],
jobStatus: $job->status,
taskStatus: $task->status,
priority: Priority::Normal,
kind: $job->kind,
dueOn: $task->due_on?->format('Y-m-d'),
isLate: $task->status !== TaskStatus::Done && $task->due_on !== null && $task->due_on->format('Y-m-d') < $today,
responsibleName: $task->assignee_user_id === null ? null : ($userNames[$task->assignee_user_id] ?? null),
serviceUnitName: $common['serviceUnit'],
estimatedHours: $this->hoursText($task->estimated_hours),
loggedQuarters: $taskQuarters[$task->id] ?? 0,
boardPosition: (int) $task->board_position,
billerUserId: $job->biller_user_id,
);
}
}
return $cards;
}
public function preferencesOf(int $userId): BoardPreferences
{
return $this->board->preferencesOf($userId);
}
/**
* @return Builder<CustomerJobModel>
*/
private function filteredJobs(BoardFilter $filter, string $today): Builder
{
$query = CustomerJobModel::query()
->where('status', '!=', JobStatus::Archived->value)
->whereNull('quick_sale_year');
foreach (array_filter([$filter->personUserId, $filter->onlyMemberUserId]) as $userId) {
JobInvolvement::restrict($query, $userId);
}
if ($filter->serviceUnitId !== null) {
$query->whereIn('id', DB::table('customer_job_service_unit')->select('customer_job_id')->where('service_unit_id', $filter->serviceUnitId));
}
if ($filter->onlyUrgent) {
$query->whereIn('priority', [Priority::Urgent->value, Priority::Immediate->value]);
}
if ($filter->onlyLate) {
$query->whereNotNull('due_on')
->where('due_on', '<', $today)
->whereIn('status', array_map(
fn (JobStatus $status): string => $status->value,
array_values(array_filter(JobStatus::openStatuses(), fn (JobStatus $status): bool => $status !== JobStatus::Ongoing)),
));
}
return $query->orderBy('board_position')->orderBy('id');
}
/**
* A continuing job runs past its due date by nature, so it is never late.
*/
private function isLate(JobStatus $status, ?string $dueOn, string $today): bool
{
return $dueOn !== null && $dueOn < $today && $status->isOpen() && $status !== JobStatus::Ongoing;
}
private function hoursText(?string $hours): ?string
{
return $hours === null ? null : rtrim(rtrim($hours, '0'), '.');
}
/**
* The first service unit's name of each job.
*
* @param list<int> $jobIds
* @return array<int, string>
*/
private function firstServiceUnitNames(array $jobIds): array
{
/** @var Collection<int, object{customer_job_id: int, service_unit_id: int}> $rows */
$rows = DB::table('customer_job_service_unit')
->whereIn('customer_job_id', $jobIds)
->orderBy('service_unit_id')
->get(['customer_job_id', 'service_unit_id']);
$names = $this->catalog->serviceUnitNames($rows->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->unique()->values()->all());
$first = [];
foreach ($rows as $row) {
$first[(int) $row->customer_job_id] ??= $names[(int) $row->service_unit_id] ?? null;
}
return array_filter($first, fn (?string $name): bool => $name !== null);
}
}
@@ -3,6 +3,7 @@
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\BookableTask;
use App\Modules\Jobs\Application\DTOs\NamedId;
@@ -21,8 +22,31 @@ class EloquentTaskQueries implements TaskQueries
public function __construct(
private CatalogQueries $catalog,
private UserAccountQueries $users,
private CustomerQueries $customers,
) {}
public function scheduledTaskIdsFor(int $userId, string $from, string $to): array
{
$booked = DB::table('task_bookings')
->where('user_id', $userId)
->whereBetween('day', [$from, $to])
->pluck('task_id');
$planned = DB::table('tasks')
->where('status', '!=', TaskStatus::Done->value)
->where(fn ($query) => $query
->whereNull('planned_from')
->orWhere(fn ($query) => $query
->where('planned_from', '<=', $to)
->where(fn ($query) => $query->whereNull('planned_to')->orWhere('planned_to', '>=', $from))))
->where(fn ($query) => $query
->where('assignee_user_id', $userId)
->orWhereIn('id', DB::table('task_members')->select('task_id')->where('user_id', $userId)))
->pluck('id');
return $booked->merge($planned)->map(fn ($id): int => (int) $id)->unique()->values()->all();
}
public function tasksOf(int $jobId): array
{
$models = TaskModel::query()
@@ -36,6 +60,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);
@@ -106,7 +140,11 @@ class EloquentTaskQueries implements TaskQueries
->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id')
->orderBy('customer_jobs.number')
->orderBy('tasks.id')
->get(['tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.work_type_id', 'tasks.status', 'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.status as job_status']);
->get(['tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.work_type_id', 'tasks.status', 'customer_jobs.number', 'customer_jobs.name', 'customer_jobs.status as job_status', 'customer_jobs.customer_id', 'customer_jobs.payment_basis']);
$customerIds = $rows->pluck('customer_id')->map(fn ($id): int => (int) $id)->unique()->values()->all();
$customerNames = $this->customers->namesByIds($customerIds);
$customerColors = $this->customers->headerColorsByIds($customerIds);
$workTypeNames = [];
foreach ($rows->pluck('work_type_id')->unique() as $workTypeId) {
@@ -123,6 +161,10 @@ class EloquentTaskQueries implements TaskQueries
$workTypeNames[(int) $row->work_type_id] ?? '',
JobStatus::from((string) $row->job_status),
TaskStatus::from((string) $row->status),
(int) $row->customer_id,
$customerNames[(int) $row->customer_id] ?? '',
$customerColors[(int) $row->customer_id] ?? null,
$row->payment_basis === null ? null : (string) $row->payment_basis,
))->values()->all();
}
@@ -7,7 +7,9 @@ use App\Modules\Customers\Application\Contracts\CustomerReferences;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\ChecklistQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\JobBoardQueries;
use App\Modules\Jobs\Application\Contracts\JobOverviewQueries;
use App\Modules\Jobs\Application\Contracts\LoggedJobHours;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\Contracts\TaskCommentQueries;
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
@@ -15,6 +17,7 @@ use App\Modules\Jobs\Application\Contracts\TaskImageQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\Jobs\Application\Contracts\UpcomingTasks;
use App\Modules\Jobs\Domain\Contracts\BoardRepository;
use App\Modules\Jobs\Domain\Contracts\ChecklistItemRepository;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
@@ -25,12 +28,15 @@ use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Infrastructure\CustomerReferencesFromJobs;
use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs;
use App\Modules\Jobs\Infrastructure\Files\GdTaskImageFiles;
use App\Modules\Jobs\Infrastructure\NoLoggedJobHours;
use App\Modules\Jobs\Infrastructure\NothingUsesTasks;
use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentBoardRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistItemRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentJobBoardQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentJobOverviewQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBookingRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries;
@@ -75,6 +81,10 @@ class JobsServiceProvider extends ServiceProvider
UpcomingTasks::class => EloquentUpcomingTasks::class,
// Replaced by the TimeTracking module, which knows which tasks have time entries.
TaskUsage::class => NothingUsesTasks::class,
BoardRepository::class => EloquentBoardRepository::class,
JobBoardQueries::class => EloquentJobBoardQueries::class,
// Replaced by the TimeTracking module, which records the hours.
LoggedJobHours::class => NoLoggedJobHours::class,
];
public function register(): void
@@ -0,0 +1,75 @@
<?php
namespace App\Modules\Jobs\Presentation\Livewire\Concerns;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
/**
* A job's change history as text, shared by the job page and the board's
* job editor. Quote and monthly fee changes are shown only to those who may
* see quotes (spec 5.7). The page has `$jobId` and a computed `job`.
*
* @property-read CustomerJobDetails $job
* @property-read list<JobChangeEntry> $changes
*/
trait DescribesJobHistory
{
/**
* @return list<JobChangeEntry>
*/
#[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,
};
}
}
@@ -0,0 +1,187 @@
<?php
namespace App\Modules\Jobs\Presentation\Livewire\Concerns;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Presentation\Livewire\Forms\JobForm;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
/**
* The choices and list editing of a job's details, shared by the job form
* page and the board's job editor: service units, people, the customer's
* contacts and billing units, the statuses this user may set, tags and
* links. The page has a JobForm `$form`, `$jobId`, `$storedStatus`,
* `$newTag` and (from PicksCustomer) `$statusMessage`.
*
* @property JobForm $form
* @property-read list<UserOption> $users
* @property-read list<ContactSummary> $contacts
* @property-read list<BillingUnitSummary> $billingUnits
* @property-read list<JobStatus> $statusOptions
*/
trait EditsJobDetails
{
/**
* @return list<array{value: int, label: string}>
*/
#[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<UserOption>
*/
#[Computed]
public function users(): array
{
return app(UserAccountQueries::class)->activeUserOptions();
}
/**
* @return list<ContactSummary>
*/
#[Computed]
public function contacts(): array
{
return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id);
}
/**
* @return list<BillingUnitSummary>
*/
#[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<JobStatus>
*/
#[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<string>
*/
#[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 = '';
}
}
@@ -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<JobStatus>
*/
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]),
];
}
}
File diff suppressed because it is too large Load Diff
@@ -508,11 +508,11 @@ new class extends Component
<div class="mx-auto max-w-[120rem] space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.calendar.title') }}</h1>
<p class="max-w-3xl text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.intro') }}</p>
<x-page-title icon="calendar-days">{{ __('jobs.calendar.title') }}</x-page-title>
<p class="max-w-3xl text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.calendar.intro') }}</p>
</div>
<div class="flex flex-wrap items-end gap-4">
<div class="card flex flex-wrap items-end gap-4">
<div class="flex flex-wrap gap-2">
<x-button subtle color="black" icon="chevron-left" wire:click="showPrevious" :text="__('jobs.calendar.previous')" />
<x-button subtle color="black" wire:click="showToday" :text="__('jobs.calendar.today')" />
@@ -530,7 +530,7 @@ new class extends Component
</div>
@if ($this->isSubcontractor())
<p class="pb-2 text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.subcontractor_note') }}</p>
<p class="pb-2 text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.calendar.subcontractor_note') }}</p>
@else
<div class="pb-2">
<x-checkbox id="calendar-only-mine" wire:model.live="mine" :label="__('jobs.calendar.only_mine')" />
@@ -540,7 +540,7 @@ new class extends Component
<p role="status" aria-live="polite" class="min-h-5 text-sm font-medium">{{ $statusMessage }}</p>
<section aria-labelledby="calendar-range-heading" class="space-y-3">
<section aria-labelledby="calendar-range-heading" class="card space-y-3">
<h2 id="calendar-range-heading" class="text-lg font-semibold">
{{ __('jobs.calendar.range', ['from' => $this->shortDate($days[0]), 'to' => $this->shortDate($days[count($days) - 1])]) }}
</h2>
@@ -563,6 +563,7 @@ new class extends Component
@class([
'border-l border-zinc-200 px-1 py-2 text-center dark:border-zinc-700',
'bg-zinc-200 dark:bg-zinc-950' => $this->isDayOff($day),
'border-b-4 border-b-primary-600 bg-primary-50 text-primary-900 dark:border-b-primary-300 dark:bg-primary-950 dark:text-primary-100' => $day === now()->format('Y-m-d'),
])
>
<div @class(['font-semibold' => $day === now()->format('Y-m-d')])>{{ $this->dayLabel($day) }}</div>
@@ -606,7 +607,7 @@ new class extends Component
wire:key="cell-{{ $rowKey }}-{{ $day }}"
data-calendar-day="{{ $day }}"
data-calendar-user="{{ $row->userId ?? '' }}"
x-bind:class="isTarget('{{ $day }}', '{{ $row->userId ?? '' }}') && 'outline-2 -outline-offset-2 outline-blue-700 dark:outline-blue-300'"
x-bind:class="isTarget('{{ $day }}', '{{ $row->userId ?? '' }}') && 'outline-2 -outline-offset-2 outline-primary-600 dark:outline-primary-300'"
@class([
'min-h-12 border-l border-zinc-200 dark:border-zinc-700',
'bg-amber-100 dark:bg-amber-950' => $overloaded,
@@ -622,7 +623,7 @@ new class extends Component
@class([
'pointer-events-none px-1 pt-1 text-right text-xs whitespace-nowrap',
'font-semibold text-amber-900 dark:text-amber-200' => $booked > $this->capacityMinutes,
'text-zinc-600 dark:text-zinc-300' => $booked === 0,
'text-zinc-600 dark:text-zinc-200' => $booked === 0,
])
style="grid-column: {{ $index + 2 }}; grid-row: 1;"
>
@@ -651,10 +652,10 @@ new class extends Component
x-on:pointerdown="begin($event, 'move', @js(['task' => $bar->task->taskId, 'job' => $bar->task->jobId, 'user' => $bar->userId, 'from' => $bar->from, 'to' => $bar->to]))"
x-on:click="clickBar($el, 'bar-info-{{ $bar->key() }}', () => $wire.openDialog({{ $bar->task->taskId }}, {{ $bar->userId ?? 'null' }}))"
@class([
'relative z-10 mx-0.5 my-1 flex min-w-0 touch-none flex-col justify-center overflow-hidden border px-2 text-left text-xs leading-tight select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-300',
'relative z-10 mx-0.5 my-1 flex min-w-0 touch-none flex-col justify-center overflow-hidden border px-2 text-left text-xs leading-tight select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300',
'cursor-grab' => $canManage,
'border-primary-300 bg-primary-100 text-primary-950 dark:border-primary-600 dark:bg-primary-900 dark:text-white' => $bar->task->status !== TaskStatus::Done && ! $bar->late,
'border-red-600 bg-red-100 text-red-950 dark:border-red-400 dark:bg-red-950 dark:text-white' => $bar->late,
'border-primary-300 border-l-4 border-l-primary-600 bg-primary-100 text-primary-950 shadow-sm dark:border-primary-600 dark:border-l-primary-300 dark:bg-primary-900 dark:text-white' => $bar->task->status !== TaskStatus::Done && ! $bar->late,
'border-red-600 border-l-4 bg-red-100 text-red-950 shadow-sm dark:border-red-400 dark:bg-red-950 dark:text-white' => $bar->late,
'border-zinc-300 bg-zinc-100 text-zinc-800 dark:border-zinc-600 dark:bg-zinc-700 dark:text-zinc-100' => $bar->task->status === TaskStatus::Done,
'rounded-l-md' => $bar->from >= $days[0],
'rounded-r-md' => $bar->to <= $days[count($days) - 1],
@@ -750,7 +751,7 @@ new class extends Component
<h3 id="agenda-{{ $rowKey }}-name" class="font-semibold break-words">{{ $row->name }}</h3>
@if ($row->bars === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.no_tasks') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.calendar.no_tasks') }}</p>
@else
<ul class="space-y-2">
@foreach ($row->bars as $bar)
@@ -760,7 +761,7 @@ new class extends Component
id="agenda-bar-{{ $bar->key() }}"
wire:click="openDialog({{ $bar->task->taskId }}, {{ $bar->userId ?? 'null' }})"
@class([
'flex w-full flex-col gap-1 rounded-md border p-2 text-left text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-300',
'flex w-full flex-col gap-1 rounded-md border p-2 text-left text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300',
'border-zinc-300 dark:border-zinc-600' => ! $bar->late,
'border-red-600 border-l-4 bg-red-50 dark:border-red-400 dark:bg-red-950' => $bar->late,
])
@@ -786,13 +787,13 @@ new class extends Component
</div>
</section>
<section aria-labelledby="unscheduled-heading" class="space-y-3" x-data>
<section aria-labelledby="unscheduled-heading" class="card space-y-3" x-data>
<h2 id="unscheduled-heading" class="text-lg font-semibold">{{ __('jobs.calendar.unscheduled') }}</h2>
@if ($this->unscheduled === [])
<p class="text-sm">{{ __('jobs.calendar.unscheduled_none') }}</p>
<x-empty-state icon="calendar-days">{{ __('jobs.calendar.unscheduled_none') }}</x-empty-state>
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.unscheduled_intro') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.calendar.unscheduled_intro') }}</p>
<ul class="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
@foreach ($this->unscheduled as $task)
@@ -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<array{value: int, label: string}>
*/
#[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<UserOption>
*/
#[Computed]
public function users(): array
{
return app(UserAccountQueries::class)->activeUserOptions();
}
/**
* @return list<ContactSummary>
*/
#[Computed]
public function contacts(): array
{
return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id);
}
/**
* @return list<BillingUnitSummary>
*/
#[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<JobStatus>
*/
#[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<string>
*/
#[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 = '';
}
};
?>
@@ -282,11 +129,11 @@ new class extends Component
@endphp
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<x-page-title icon="briefcase">{{ $this->heading() }}</x-page-title>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
<form wire:submit="save" class="space-y-8" novalidate>
<form wire:submit="save" class="card space-y-8" novalidate>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.basics') }}</legend>
@@ -470,7 +317,7 @@ new class extends Component
<p id="tags-label" class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ __('jobs.fields.tags') }}</p>
@if ($form->tags === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tags.none') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tags.none') }}</p>
@else
<ul aria-labelledby="tags-label" class="flex flex-wrap gap-2">
@foreach ($form->tags as $index => $tag)
@@ -498,7 +345,7 @@ new class extends Component
<p class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ __('jobs.fields.links') }}</p>
@if ($form->links === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.links.none') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.links.none') }}</p>
@endif
@foreach ($form->links as $index => $link)
@@ -97,30 +97,27 @@ new class extends Component
};
?>
<div class="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex flex-wrap items-baseline gap-x-4 gap-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.title') }}</h1>
<x-link :href="route('jobs.board')" navigate>{{ __('jobs.board.link') }}</x-link>
</div>
<x-page width="wide">
<x-page-header :title="__('jobs.title')" icon="briefcase">
<x-link :href="route('jobs.board')" navigate class="text-sm">{{ __('jobs.board.link') }}</x-link>
@can('jobs.manage')
<div class="flex flex-wrap gap-2">
<x-slot:actions>
<x-button :href="route('jobs.quick')" wire:navigate subtle color="black" icon="bolt" :text="__('jobs.quick.link')" />
<x-button :href="route('jobs.create')" wire:navigate icon="plus" :text="__('jobs.new')" />
</div>
</x-slot:actions>
@endcan
</div>
</x-page-header>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
@if ($this->isSubcontractor())
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.list.subcontractor_note') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.list.subcontractor_note') }}</p>
@endif
<div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<div class="grid gap-4 rounded-xl border border-zinc-200 bg-white p-4 shadow-sm md:grid-cols-2 xl:grid-cols-4 dark:border-zinc-700 dark:bg-zinc-900">
<div class="md:col-span-2 xl:col-span-4">
<x-input
wire:model.live.debounce.300ms="search"
@@ -161,7 +158,7 @@ new class extends Component
</div>
</div>
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-300">
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-100">
{{ trans_choice('jobs.list.result_count', $this->jobs->total(), ['count' => $this->jobs->total()]) }}
@if ($mine && ! $this->isSubcontractor())
– {{ __('jobs.list.only_mine_description') }}
@@ -169,7 +166,7 @@ new class extends Component
</p>
@if ($this->jobs->total() === 0)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.list.empty') }}</p>
<x-empty-state icon="briefcase">{{ __('jobs.list.empty') }}</x-empty-state>
@else
<x-table :headers="$this->headers()" :rows="$this->jobs" paginate>
@interact('column_number', $job)
@@ -181,7 +178,7 @@ new class extends Component
@endinteract
@interact('column_status', $job)
{{ __('jobs.statuses.'.$job->status->value) }}
<x-jobs.status :status="$job->status" />
@endinteract
@interact('column_priority', $job)
@@ -193,4 +190,4 @@ new class extends Component
@endinteract
</x-table>
@endif
</div>
</x-page>
@@ -0,0 +1,975 @@
<?php
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\LoggedJobHours;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\DTOs\TaskSummary;
use App\Modules\Jobs\Application\UseCases\AddTask;
use App\Modules\Jobs\Application\UseCases\AddTasksFromWorkflowTemplate;
use App\Modules\Jobs\Application\UseCases\ChangeJobPriority;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus;
use App\Modules\Jobs\Application\UseCases\PinTaskToBoard;
use App\Modules\Jobs\Application\UseCases\UpdateCustomerJob;
use App\Modules\Jobs\Application\UseCases\UpdateTask;
use App\Modules\Jobs\Domain\Enums\JobKind;
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\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Presentation\Livewire\Concerns\DescribesJobHistory;
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;
use App\Modules\Shared\Domain\ValueObjects\HexColor;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Component;
/**
* The board's full job editor (docs/ui-kanban-board.md 5): a two-column
* work area in a dialog where every detail of a job can be seen and changed
* without leaving the board. Status and priority change at once, task rows
* save as they change, and "Tallenna ja sulje" saves the job's details.
* Without jobs.manage the editor only shows the job and lets tasks be
* marked done.
*/
new class extends Component
{
use DescribesJobHistory;
use EditsJobDetails, PicksCustomer {
EditsJobDetails::customerChosen insteadof PicksCustomer;
}
public const string DIALOG = 'job-editor-dialog';
#[Locked]
public ?int $jobId = null;
#[Locked]
public ?string $storedStatus = null;
public JobForm $form;
public string $newTag = '';
public string $newTaskTitle = '';
public string $newTaskAssignee = '';
public bool $newTaskPin = false;
public string $templateId = '';
#[On('open-job-editor')]
public function open(int $jobId): void
{
$this->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<TaskSummary>
*/
#[Computed]
public function tasks(): array
{
return $this->jobId === null ? [] : app(TaskQueries::class)->tasksOf($this->jobId);
}
/**
* @return list<WorkflowTemplateDetails>
*/
#[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<int, bool>
*/
#[Computed]
public function pinnedTasks(): array
{
return $this->jobId === null ? [] : app(TaskQueries::class)->pinnedTaskIds($this->jobId);
}
/**
* The colour picker lives on the board, so the board tells the editor
* when a customer's colour changed; the header colour is read on render.
*/
#[On('customer-color-changed')]
public function customerColorChanged(): void
{
unset($this->job);
}
#[On('task-comments-changed')]
#[On('task-images-changed')]
public function refreshTasks(): void
{
unset($this->tasks);
}
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';
$controlClass = 'w-auto max-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
<div>
<x-work-dialog id="job-editor-dialog" width="max-w-5xl">
<x-slot:header>
<div
style="background-color: {{ $headerColor->value }}; color: {{ $headerColor->textColor() }}"
class="flex shrink-0 flex-wrap items-center justify-between gap-3 rounded-t-2xl border-b border-black/15 px-5 py-3"
>
<div class="flex min-w-0 flex-1 flex-wrap items-center gap-2.5">
<span class="shrink-0 rounded bg-black/25 px-2 py-0.5 text-xs font-extrabold tracking-wider text-white uppercase">{{ $job?->number }}</span>
<h2 id="job-editor-dialog-title" class="min-w-0 truncate text-sm font-extrabold">
<span class="sr-only">{{ __('jobs.editor.heading', ['number' => $job?->number]) }}: </span>{{ $job?->customer->name }}
</h2>
@if ($job !== null && Gate::allows('customers.use'))
<button
type="button"
x-on:click="$dispatch('color-picker:open', {{ Js::from([
'id' => 'colour-picker',
'title' => __('jobs.board.customer_color_title', ['customer' => $job->customer->name]),
'color' => $headerColor->value,
'method' => 'setCustomerColor',
'args' => [$job->customer->id],
'resettable' => true,
]) }})"
aria-label="{{ __('jobs.editor.color_label', ['customer' => $job->customer->name]) }}"
class="inline-flex min-h-6 items-center gap-1 rounded bg-black/20 px-2 text-[11px] font-semibold transition hover:bg-black/30 focus-visible:outline-2 focus-visible:outline-current"
>
<x-icon name="swatch" class="size-3.5" aria-hidden="true" />
<span>{{ __('jobs.editor.color') }}</span>
</button>
@endif
</div>
<div class="flex shrink-0 flex-wrap items-center gap-2">
@if ($job !== null)
<div class="flex items-center gap-1 rounded-lg bg-black/20 px-2 py-1">
<label for="job-editor-status" class="text-[11px] font-bold">{{ __('jobs.editor.status') }}:</label>
<select
id="job-editor-status"
wire:model="form.status"
wire:change="changeStatus($event.target.value)"
@disabled(! $canEdit)
class="rounded border-0 bg-transparent py-0 pr-7 pl-1 text-xs font-extrabold focus-visible:outline-2 focus-visible:outline-current"
>
@foreach ($this->statusOptions as $status)
<option value="{{ $status->value }}" class="bg-white text-neutral-900 dark:bg-[#282a2e] dark:text-white">{{ __('jobs.statuses.'.$status->value) }}</option>
@endforeach
</select>
</div>
<div class="flex items-center gap-1 rounded-lg bg-black/20 px-2 py-1">
<label for="job-editor-priority" class="text-[11px] font-bold">{{ __('jobs.editor.priority') }}:</label>
<select
id="job-editor-priority"
wire:model="form.priority"
wire:change="changePriority($event.target.value)"
@disabled(! $canEdit)
class="rounded border-0 bg-transparent py-0 pr-7 pl-1 text-xs font-extrabold focus-visible:outline-2 focus-visible:outline-current"
>
@foreach (Priority::cases() as $priority)
<option value="{{ $priority->value }}" class="bg-white text-neutral-900 dark:bg-[#282a2e] dark:text-white">{{ __('jobs.priorities.'.$priority->value) }}</option>
@endforeach
</select>
</div>
@endif
<button
type="button"
x-on:click="$el.closest('dialog').close()"
aria-label="{{ __('jobs.editor.close') }}"
class="inline-flex size-8 items-center justify-center rounded-lg bg-black/20 transition hover:bg-black/35 focus-visible:outline-2 focus-visible:outline-current"
>
<x-icon name="x-mark" class="size-4" aria-hidden="true" />
</button>
</div>
</div>
</x-slot:header>
@if ($job !== null)
@error('form.status')
<p role="alert" class="border-b border-red-300 bg-red-50 px-5 py-2 text-xs font-semibold text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-100">{{ $message }}</p>
@enderror
@if (in_array($job->status, [JobStatus::Done, JobStatus::Invoiced, JobStatus::Billed], true))
<div role="status" class="flex flex-wrap items-center justify-between gap-2 border-b border-amber-300 bg-amber-100 px-5 py-2 text-xs font-semibold text-amber-950 dark:border-amber-800 dark:bg-amber-950/90 dark:text-amber-100">
<span class="inline-flex items-center gap-1.5"><x-icon name="lock-closed" class="size-4" aria-hidden="true" />{{ __('jobs.editor.locked') }}</span>
@can('jobs.unlock')
<button type="button" wire:click="unlock" class="min-h-6 rounded bg-amber-800 px-2.5 text-[11px] font-bold text-white hover:bg-amber-900 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-amber-900 dark:focus-visible:outline-amber-200">{{ __('jobs.editor.unlock') }}</button>
@endcan
</div>
@endif
<p role="status" aria-live="polite" class="min-h-4 px-5 pt-2 text-xs font-medium">{{ $statusMessage }}</p>
@unless ($canEdit)
<p class="px-5 text-xs">{{ __('jobs.editor.read_only') }}</p>
@endunless
<div class="grid grid-cols-1 gap-5 p-5 lg:grid-cols-12">
{{-- Left: content, tasks and records --}}
<div class="space-y-5 lg:col-span-8">
<fieldset @disabled(! $canEdit) class="space-y-3">
<div>
<label for="job-editor-name" class="{{ $labelClass }}">{{ __('jobs.fields.name') }}</label>
<input id="job-editor-name" type="text" wire:model="form.name" maxlength="255" autocomplete="off" class="w-full rounded-xl border border-neutral-300 bg-neutral-100/70 px-3 py-2 text-base font-extrabold text-neutral-900 focus-visible:outline-2 focus-visible:outline-primary-600 dark:border-[#4b5058] dark:bg-[#18191b] dark:text-white dark:focus-visible:outline-primary-300" />
@error('form.name') <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<div>
<label for="job-editor-description" class="{{ $labelClass }}">{{ __('jobs.fields.description') }}</label>
<textarea id="job-editor-description" rows="3" wire:model="form.description" class="{{ $fieldClass }} bg-neutral-50 p-2.5 dark:bg-[#18191b]"></textarea>
</div>
<div>
<label for="job-editor-instructions" class="{{ $labelClass }}">{{ __('jobs.fields.instructions') }}</label>
<textarea id="job-editor-instructions" rows="3" wire:model="form.instructions" class="{{ $fieldClass }} bg-amber-50/40 p-2.5 dark:bg-[#1e1d19]"></textarea>
</div>
</div>
</fieldset>
<section aria-labelledby="job-editor-links-heading" class="{{ $boxClass }} bg-neutral-50">
<div class="flex items-center justify-between">
<h3 id="job-editor-links-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.links') }}</h3>
@if ($canEdit)
<button type="button" id="add-link" wire:click="addLink" class="min-h-6 text-xs font-bold text-primary-700 hover:underline focus-visible:outline-2 focus-visible:outline-primary-600 dark:text-primary-100 dark:focus-visible:outline-primary-300">+ {{ __('jobs.links.add') }}</button>
@endif
</div>
@if ($form->links === [])
<p class="text-[11px]">{{ __('jobs.links.none') }}</p>
@endif
<ul class="space-y-1.5">
@foreach ($form->links as $index => $link)
<li wire:key="editor-link-{{ $index }}" class="grid grid-cols-1 gap-2 rounded-lg border border-neutral-200 bg-white p-2 sm:grid-cols-12 dark:border-[#36393f] dark:bg-[#25272b]">
@if ($canEdit)
<div class="sm:col-span-5">
<label for="link-title-{{ $index }}" class="sr-only">{{ __('jobs.links.title') }}</label>
<input id="link-title-{{ $index }}" wire:model="form.links.{{ $index }}.title" placeholder="{{ __('jobs.links.title') }}" class="{{ $fieldClass }}" />
</div>
<div class="sm:col-span-5">
<label for="link-url-{{ $index }}" class="sr-only">{{ __('jobs.links.url') }}</label>
<input id="link-url-{{ $index }}" type="url" wire:model="form.links.{{ $index }}.url" placeholder="https://…" class="{{ $fieldClass }}" />
</div>
<button type="button" wire:click="removeLink({{ $index }})" aria-label="{{ __('jobs.links.remove', ['number' => $index + 1]) }}" class="min-h-6 rounded text-xs font-bold text-red-700 hover:underline focus-visible:outline-2 focus-visible:outline-primary-600 sm:col-span-2 dark:text-red-200 dark:focus-visible:outline-primary-300">✕</button>
@else
<a href="{{ $link['url'] }}" target="_blank" rel="noopener" class="font-semibold text-primary-700 hover:underline sm:col-span-12 dark:text-primary-100">{{ $link['title'] }} <span class="sr-only">({{ __('layout.opens_in_new_window') }})</span></a>
@endif
</li>
@endforeach
</ul>
@error('form.links') <p class="text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</section>
{{-- Tasks --}}
<section aria-labelledby="job-editor-tasks-heading" class="{{ $boxClass }} bg-neutral-50">
<div class="flex flex-wrap items-center justify-between gap-2">
<div>
<h3 id="job-editor-tasks-heading" class="{{ $boxHeading }}">{{ $job->status === JobStatus::Ongoing ? __('jobs.editor.tasks_ongoing') : __('jobs.editor.tasks') }}</h3>
<p class="text-[11px]">{{ $job->status === JobStatus::Ongoing ? __('jobs.editor.tasks_hint_ongoing') : __('jobs.editor.tasks_hint') }}</p>
</div>
@if (Gate::allows('jobs.manage-tasks', [$job->id]) && $this->templates !== [] && $job->status->allowsTasks())
<form wire:submit="applyTemplate" class="flex items-center gap-1.5">
<label for="job-editor-template" class="sr-only">{{ __('jobs.editor.template') }}</label>
<select id="job-editor-template" wire:model="templateId" class="{{ $controlClass }} py-1 text-[11px]">
<option value="">{{ __('jobs.editor.template_choose') }}</option>
@foreach ($this->templates as $template)
<option value="{{ $template->id }}">{{ $template->name }}</option>
@endforeach
</select>
<button type="submit" class="min-h-6 rounded-lg bg-indigo-700 px-2.5 text-[11px] font-bold text-white hover:bg-indigo-800 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">{{ __('jobs.editor.template_apply') }}</button>
</form>
@endif
</div>
@if ($this->tasks === [])
<p class="text-[11px]">{{ __('jobs.editor.no_tasks') }}</p>
@endif
<ul class="space-y-2">
@foreach ($this->tasks as $task)
@php($canManageTask = Gate::allows('jobs.manage-tasks', [$job->id]))
<li wire:key="editor-task-{{ $task->id }}" x-data="{ checklist: false, extras: false }" class="space-y-2 rounded-xl border border-neutral-200 bg-white p-2.5 text-xs dark:border-[#36393f] dark:bg-[#25272b]">
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="flex min-w-0 flex-1 items-center gap-2">
<input
type="checkbox"
id="editor-task-done-{{ $task->id }}"
@checked($task->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)
<label for="editor-task-title-{{ $task->id }}" class="sr-only">{{ __('jobs.editor.task_title') }}</label>
<input
id="editor-task-title-{{ $task->id }}"
type="text"
value="{{ $task->title }}"
maxlength="255"
wire:change="updateTaskField({{ $task->id }}, 'title', $event.target.value)"
class="min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 font-bold text-neutral-900 hover:border-neutral-300 focus-visible:outline-2 focus-visible:outline-primary-600 dark:text-white dark:hover:border-[#4b5058] dark:focus-visible:outline-primary-300"
/>
@else
<span class="font-bold">{{ $task->title }}</span>
@endif
</div>
@if ($canManageTask)
<div class="flex flex-wrap items-center gap-1.5">
<label for="editor-task-status-{{ $task->id }}" class="sr-only">{{ __('jobs.editor.task_status', ['task' => $task->title]) }}</label>
<select id="editor-task-status-{{ $task->id }}" wire:change="updateTaskField({{ $task->id }}, 'status', $event.target.value)" class="{{ $controlClass }} py-0.5 text-[11px]">
@foreach (TaskStatus::cases() as $taskStatus)
<option value="{{ $taskStatus->value }}" @selected($taskStatus === $task->status)>{{ __('jobs.tasks.statuses.'.$taskStatus->value) }}</option>
@endforeach
</select>
<label for="editor-task-assignee-{{ $task->id }}" class="sr-only">{{ __('jobs.editor.task_assignee', ['task' => $task->title]) }}</label>
<select id="editor-task-assignee-{{ $task->id }}" wire:change="updateTaskField({{ $task->id }}, 'assignee', $event.target.value)" class="{{ $controlClass }} py-0.5 text-[11px]">
<option value="">{{ __('jobs.editor.no_assignee') }}</option>
@foreach ($this->users as $user)
<option value="{{ $user->id }}" @selected($user->id === $task->assignee?->id)>{{ $user->name }}</option>
@endforeach
</select>
<label for="editor-task-due-{{ $task->id }}" class="sr-only">{{ __('jobs.editor.task_due', ['task' => $task->title]) }}</label>
<input id="editor-task-due-{{ $task->id }}" type="date" value="{{ $task->dueOn }}" wire:change="updateTaskField({{ $task->id }}, 'due_on', $event.target.value)" class="{{ $controlClass }} py-0.5 text-[11px]" />
@if ($job->status === JobStatus::Ongoing)
@php($pinned = $this->pinnedTasks[$task->id] ?? false)
<button
type="button"
wire:click="pinTask({{ $task->id }}, {{ $pinned ? 'false' : 'true' }})"
aria-label="{{ $pinned ? __('jobs.board.unpin_label', ['task' => $task->title]) : __('jobs.board.pin_label', ['task' => $task->title]) }}"
@class(['min-h-6 rounded px-2.5 text-[11px] font-bold text-white transition focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300', 'bg-amber-700 hover:bg-amber-800' => $pinned, 'bg-indigo-600 hover:bg-indigo-700' => ! $pinned])
>{{ $pinned ? __('jobs.board.unpin') : __('jobs.board.pin') }}</button>
@endif
</div>
@endif
</div>
@error('tasks.'.$task->id) <p class="text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
<div class="space-y-1 pl-6">
<div class="flex flex-wrap gap-3">
<button
type="button"
x-on:click="checklist = ! checklist"
x-bind:aria-expanded="checklist.toString()"
aria-controls="editor-checklist-{{ $task->id }}"
class="inline-flex min-h-6 items-center gap-1 rounded text-[11px] font-semibold text-indigo-800 hover:underline focus-visible:outline-2 focus-visible:outline-primary-600 dark:text-indigo-100 dark:focus-visible:outline-primary-300"
>
<x-icon name="chevron-right" class="size-3 transition" x-bind:class="checklist && 'rotate-90'" aria-hidden="true" />
{{ __('jobs.editor.checklist') }}
</button>
<button
type="button"
x-on:click="extras = ! extras"
x-bind:aria-expanded="extras.toString()"
aria-controls="editor-extras-{{ $task->id }}"
class="inline-flex min-h-6 items-center gap-1 rounded text-[11px] font-semibold text-indigo-800 hover:underline focus-visible:outline-2 focus-visible:outline-primary-600 dark:text-indigo-100 dark:focus-visible:outline-primary-300"
>
<x-icon name="chevron-right" class="size-3 transition" x-bind:class="extras && 'rotate-90'" aria-hidden="true" />
{{ __('jobs.editor.extras', ['comments' => $task->commentCount, 'images' => $task->imageCount]) }}
</button>
</div>
<div id="editor-checklist-{{ $task->id }}" x-show="checklist" x-cloak class="pt-1">
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'editor-checklist-'.$task->id" />
</div>
<div id="editor-extras-{{ $task->id }}" x-show="extras" x-cloak class="pt-1">
<x-tabs
id="editor-task-{{ $task->id }}-tabs"
:label="__('jobs.tasks.tabs.label', ['title' => $task->title])"
:tabs="[
'comments' => __('jobs.editor.tab_comments', ['count' => $task->commentCount]),
'images' => __('jobs.editor.tab_images', ['count' => $task->imageCount]),
]"
>
<x-tabs.panel tabs-id="editor-task-{{ $task->id }}-tabs" name="comments">
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'editor-comments-'.$task->id" />
</x-tabs.panel>
<x-tabs.panel tabs-id="editor-task-{{ $task->id }}-tabs" name="images">
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'editor-images-'.$task->id" />
</x-tabs.panel>
</x-tabs>
</div>
</div>
</li>
@endforeach
</ul>
@if (Gate::allows('jobs.manage-tasks', [$job->id]) && $job->status->allowsTasks())
<form wire:submit="addTask" class="space-y-2 border-t border-neutral-200 pt-2 dark:border-[#36393f]">
<div class="flex flex-wrap gap-2">
<label for="job-editor-new-task" class="sr-only">{{ __('jobs.editor.new_task') }}</label>
<input id="job-editor-new-task" type="text" wire:model="newTaskTitle" maxlength="255" placeholder="{{ __('jobs.editor.new_task_placeholder') }}" class="{{ $fieldClass }} min-w-[200px] flex-1 placeholder:text-neutral-600 dark:placeholder:text-neutral-300" />
<label for="job-editor-new-task-assignee" class="sr-only">{{ __('jobs.editor.new_task_assignee') }}</label>
<select id="job-editor-new-task-assignee" wire:model="newTaskAssignee" class="{{ $controlClass }}">
<option value="">{{ __('jobs.editor.no_assignee') }}</option>
@foreach ($this->users as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</select>
<button type="submit" class="min-h-6 rounded-lg bg-primary-600 px-3.5 text-xs font-bold text-white hover:bg-primary-700 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">+ {{ __('jobs.editor.add_task') }}</button>
</div>
@error('newTaskTitle') <p class="text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
@if ($job->status === JobStatus::Ongoing)
<label class="flex cursor-pointer items-center gap-2 text-xs">
<input type="checkbox" wire:model="newTaskPin" class="size-4 rounded border-neutral-500 text-indigo-600 dark:border-neutral-400 dark:bg-[#16171a]" />
<span>{{ __('jobs.editor.pin_new') }}</span>
</label>
@endif
</form>
@endif
</section>
{{-- Records: hours, expenses, history --}}
<div class="rounded-xl border border-neutral-200 bg-neutral-50 p-3.5 dark:border-[#36393f] dark:bg-[#1b1c1f]">
<x-tabs
id="job-editor-tabs-{{ $job->id }}"
wire:key="job-editor-tabs-{{ $job->id }}"
:label="__('jobs.editor.tabs_label')"
:tabs="[
'hours' => __('jobs.editor.tab_hours', ['hours' => $this->loggedHours()]),
'expenses' => __('jobs.editor.tab_expenses'),
'history' => __('jobs.editor.tab_history', ['count' => count($this->changes)]),
]"
>
<x-tabs.panel tabs-id="job-editor-tabs-{{ $job->id }}" name="hours">
<livewire:time::job-quick-hours :job-id="$job->id" :wire:key="'editor-hours-'.$job->id" />
</x-tabs.panel>
<x-tabs.panel tabs-id="job-editor-tabs-{{ $job->id }}" name="expenses">
<livewire:expenses::job-quick-expense :job-id="$job->id" :wire:key="'editor-expenses-'.$job->id" />
</x-tabs.panel>
<x-tabs.panel tabs-id="job-editor-tabs-{{ $job->id }}" name="history">
@if ($this->changes === [])
<p class="text-xs">{{ __('jobs.history.empty') }}</p>
@else
<ol class="max-h-48 space-y-1.5 overflow-y-auto text-[11px]" tabindex="0" aria-label="{{ __('jobs.sections.history') }}">
@foreach ($this->changes as $change)
<li class="flex flex-wrap items-center justify-between gap-2 border-b border-neutral-200 py-1 dark:border-[#2e3137]">
<span>
<strong>{{ $change->userName }}</strong>:
@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
</span>
<span class="shrink-0">{{ CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i') }}</span>
</li>
@endforeach
</ol>
@endif
</x-tabs.panel>
</x-tabs>
</div>
</div>
{{-- Right: metadata, schedule, team and money --}}
<fieldset @disabled(! $canEdit) class="space-y-4 text-xs lg:col-span-4">
<legend class="sr-only">{{ __('jobs.sections.basics') }}</legend>
<section aria-labelledby="job-editor-customer-heading" class="{{ $boxClass }}">
<h3 id="job-editor-customer-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.customer_section') }}</h3>
<x-jobs.customer-picker :customer-id="$form->customer_id" :customer-name="$customerName" :search="$customerSearch" :results="$this->customerResults" />
<div>
<label for="job-editor-contact" class="{{ $labelClass }}">{{ __('jobs.fields.customer_contact') }}</label>
<select id="job-editor-contact" wire:model="form.customer_contact_id" class="{{ $fieldClass }}">
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->contacts as $contact)
<option wire:key="editor-contact-{{ $contact->id }}" value="{{ $contact->id }}">{{ $contact->name }}</option>
@endforeach
</select>
</div>
<div>
<label for="job-editor-billing-unit" class="{{ $labelClass }}">{{ __('jobs.fields.billing_unit') }}</label>
<select id="job-editor-billing-unit" wire:model="form.billing_unit_id" class="{{ $fieldClass }}">
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->billingUnits as $unit)
<option wire:key="editor-billing-unit-{{ $unit->id }}" value="{{ $unit->id }}">{{ $unit->name }}</option>
@endforeach
</select>
</div>
</section>
<section aria-labelledby="job-editor-team-heading" class="{{ $boxClass }}">
<h3 id="job-editor-team-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.team_section') }}</h3>
@foreach (['responsible_user_id' => 'responsible_user', 'contact_user_id' => 'contact_user', 'biller_user_id' => 'biller_user'] as $field => $label)
<div>
<label for="job-editor-{{ $field }}" class="{{ $labelClass }}">{{ __('jobs.fields.'.$label) }}</label>
<select id="job-editor-{{ $field }}" wire:model="form.{{ $field }}" class="{{ $fieldClass }}">
@if ($field !== 'responsible_user_id')
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@endif
@foreach ($staff as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</select>
@error('form.'.$field) <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
@endforeach
<x-checkbox-group
:columns="2"
:legend="__('jobs.fields.members')"
model="form.member_user_ids"
:options="collect($this->users)->map(fn ($user) => ['value' => $user->id, 'label' => $user->name, 'note' => $user->role === Role::Subcontractor ? __('users.roles.subcontractor') : null])->all()"
/>
</section>
<section aria-labelledby="job-editor-units-heading" class="{{ $boxClass }}">
<h3 id="job-editor-units-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.units_section') }}</h3>
<x-checkbox-group :columns="2" :legend="__('jobs.fields.service_units')" model="form.service_unit_ids" :options="$this->serviceUnitOptions" />
<div class="space-y-1.5">
<p id="editor-tags-label" class="{{ $labelClass }}">{{ __('jobs.fields.tags') }}</p>
@if ($form->tags !== [])
<ul aria-labelledby="editor-tags-label" class="flex flex-wrap gap-1">
@foreach ($form->tags as $index => $tag)
<li wire:key="editor-tag-{{ $tag }}" class="inline-flex items-center gap-1 rounded-full border border-indigo-300 bg-indigo-100 px-2 py-0.5 text-[11px] font-bold text-indigo-900 dark:border-indigo-700 dark:bg-indigo-950 dark:text-indigo-100">
{{ $tag }}
@if ($canEdit)
<button type="button" wire:click="removeTag({{ $index }})" aria-label="{{ __('jobs.tags.remove', ['tag' => $tag]) }}" class="inline-flex size-5 items-center justify-center rounded-full hover:bg-indigo-200 focus-visible:outline-2 focus-visible:outline-primary-600 dark:hover:bg-indigo-900 dark:focus-visible:outline-primary-300">×</button>
@endif
</li>
@endforeach
</ul>
@endif
@if ($canEdit)
<div class="flex gap-1">
<label for="new-tag" class="sr-only">{{ __('jobs.tags.new') }}</label>
<input id="new-tag" type="text" list="editor-tag-suggestions" wire:model.live.debounce.300ms="newTag" wire:keydown.enter.prevent="addTag" autocomplete="off" placeholder="{{ __('jobs.tags.new') }}" class="{{ $fieldClass }} placeholder:text-neutral-600 dark:placeholder:text-neutral-300" />
<datalist id="editor-tag-suggestions">
@foreach ($this->tagSuggestions as $suggestion)
<option value="{{ $suggestion }}"></option>
@endforeach
</datalist>
<button type="button" wire:click="addTag" class="min-h-6 rounded-lg bg-neutral-700 px-2 text-[11px] font-bold text-white hover:bg-neutral-800 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300">{{ __('jobs.tags.add') }}</button>
</div>
@error('newTag') <p class="text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
@endif
</div>
</section>
<section aria-labelledby="job-editor-schedule-heading" class="{{ $boxClass }}">
<h3 id="job-editor-schedule-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.schedule_section') }}</h3>
<div>
<label for="job-editor-kind" class="{{ $labelClass }}">{{ __('jobs.fields.kind') }}</label>
<select id="job-editor-kind" wire:model="form.kind" class="{{ $fieldClass }}">
@foreach (JobKind::cases() as $kind)
<option value="{{ $kind->value }}">{{ __('jobs.kinds.'.$kind->value) }}</option>
@endforeach
</select>
</div>
<div class="grid grid-cols-2 gap-2">
@foreach (['starts_on', 'due_on', 'planned_from', 'planned_to'] as $field)
<div>
<label for="job-editor-{{ $field }}" class="{{ $labelClass }}">{{ __('jobs.fields.'.$field) }}</label>
<input id="job-editor-{{ $field }}" type="date" wire:model="form.{{ $field }}" class="{{ $fieldClass }}" />
@error('form.'.$field) <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
@endforeach
</div>
<div>
<label for="job-editor-estimated-hours" class="{{ $labelClass }}">{{ __('jobs.fields.estimated_hours') }}</label>
<input id="job-editor-estimated-hours" type="number" step="0.25" min="0" inputmode="decimal" wire:model="form.estimated_hours" class="{{ $fieldClass }}" />
@error('form.estimated_hours') <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
</section>
<section aria-labelledby="job-editor-money-heading" class="{{ $boxClass }}">
<h3 id="job-editor-money-heading" class="{{ $boxHeading }}">{{ __('jobs.editor.money_section') }}</h3>
<div>
<label for="job-editor-payment-basis" class="{{ $labelClass }}">{{ __('jobs.fields.payment_basis') }}</label>
<select id="job-editor-payment-basis" wire:model.live="form.payment_basis" class="{{ $fieldClass }}">
<option value="">{{ __('jobs.fields.no_payment_basis') }}</option>
@foreach (PaymentBasis::cases() as $basis)
<option value="{{ $basis->value }}">{{ __('jobs.payment_bases.'.$basis->value) }}</option>
@endforeach
</select>
</div>
@can('money.quotes')
<div class="grid grid-cols-2 gap-2">
<div>
<label for="job-editor-quoted" class="{{ $labelClass }}">{{ __('jobs.fields.quoted_amount_input') }}</label>
<input id="job-editor-quoted" inputmode="decimal" autocomplete="off" wire:model="form.quoted_amount" class="{{ $fieldClass }}" />
@error('form.quoted_amount') <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
@if ($form->payment_basis === 'monthly_fee')
<div>
<label for="job-editor-monthly-fee" class="{{ $labelClass }}">{{ __('jobs.fields.monthly_fee_input') }}</label>
<input id="job-editor-monthly-fee" inputmode="decimal" autocomplete="off" wire:model="form.monthly_fee" class="{{ $fieldClass }}" />
@error('form.monthly_fee') <p class="mt-1 text-xs font-semibold text-red-700 dark:text-red-200">{{ $message }}</p> @enderror
</div>
@endif
</div>
@else
<p class="rounded bg-neutral-200/70 p-2 text-[11px] dark:bg-[#24262a]">{{ __('jobs.editor.money_hidden') }}</p>
@endcan
<div>
<label for="job-editor-reference" class="{{ $labelClass }}">{{ __('jobs.fields.customer_reference') }}</label>
<input id="job-editor-reference" autocomplete="off" wire:model="form.customer_reference" class="{{ $fieldClass }}" />
</div>
</section>
</fieldset>
</div>
@endif
<x-slot:footer>
<span class="text-[11px]">{{ __('jobs.editor.footer') }}</span>
<div class="flex flex-wrap items-center gap-3">
@if ($job !== null)
<x-link :href="route('jobs.show', $job->id)" navigate class="text-xs">{{ __('jobs.editor.open_page') }}</x-link>
@endif
@if ($job !== null && $canEdit)
<x-button wire:click="save" sm :text="__('jobs.editor.save')" />
@endif
</div>
</x-slot:footer>
</x-work-dialog>
</div>
@@ -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<ContactSummary>
*/
#[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,13 +151,23 @@ 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);
}
};
?>
<div class="mx-auto max-w-lg space-y-6 p-4 sm:p-6">
<div @class(['mx-auto max-w-lg space-y-6 p-4 sm:p-6' => ! $inDialog])>
@unless ($inDialog)
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.quick.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.quick.intro') }}</p>
<x-page-title icon="bolt">{{ __('jobs.quick.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.quick.intro') }}</p>
</div>
<div id="quick-created" tabindex="-1" role="status" aria-live="polite" class="focus:outline-none">
@@ -121,10 +184,11 @@ new class extends Component
</div>
@endif
</div>
@endunless
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
<p role="status" aria-live="polite" @class(['text-sm', 'px-5 pt-3' => $inDialog])>{{ $statusMessage }}</p>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" @class(['card space-y-6' => ! $inDialog, 'space-y-4 px-5 pb-5' => $inDialog]) novalidate>
<x-jobs.customer-picker
:customer-id="$form->customer_id"
:customer-name="$customerName"
@@ -132,34 +196,83 @@ new class extends Component
:results="$this->customerResults"
/>
<x-input wire:model="form.name" :label="__('jobs.fields.name')" autocomplete="off" required />
<div class="space-y-2">
<div class="flex flex-wrap items-end justify-between gap-2">
<div class="min-w-0 flex-1">
<x-select.native
id="{{ $inDialog ? 'dialog-' : '' }}quick-contact"
wire:model="form.customer_contact_id"
:label="__('jobs.quick.contact')"
:aria-label="__('jobs.quick.contact')"
:disabled="$form->customer_id === ''"
:hint="$form->customer_id === '' ? __('jobs.customer_picker.choose_customer_first') : null"
>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->contacts as $contact)
<option wire:key="quick-contact-{{ $contact->id }}" value="{{ $contact->id }}">{{ $contact->name }}</option>
@endforeach
</x-select.native>
</div>
@if ($form->customer_id !== '')
<x-button
wire:click="$toggle('form.adding_contact')"
subtle
color="black"
sm
:text="__('jobs.quick.add_contact')"
:aria-label="__('jobs.quick.add_contact_label')"
x-bind:aria-expanded="$wire.form.adding_contact.toString()"
/>
@endif
</div>
@if ($form->adding_contact && $form->customer_id !== '')
<div class="grid gap-3 rounded-lg border border-indigo-400 bg-indigo-50/40 p-3 sm:grid-cols-2 dark:border-indigo-500 dark:bg-[#1e2026]">
<x-input id="{{ $inDialog ? 'dialog-' : '' }}quick-contact-name" wire:model="form.new_contact_name" :label="__('jobs.quick.contact_name')" autocomplete="off" required />
<x-input id="{{ $inDialog ? 'dialog-' : '' }}quick-contact-phone" wire:model="form.new_contact_phone" type="tel" :label="__('jobs.quick.contact_phone')" autocomplete="off" />
</div>
@endif
</div>
<x-textarea wire:model="form.description" :label="__('jobs.quick.description')" rows="3" />
<x-input id="{{ $inDialog ? 'dialog-' : '' }}quick-name" wire:model="form.name" :label="__('jobs.fields.name')" autocomplete="off" required />
<x-textarea id="{{ $inDialog ? 'dialog-' : '' }}quick-description" wire:model="form.description" :label="__('jobs.quick.description')" rows="3" />
<div class="grid gap-4 sm:grid-cols-2">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model="form.service_unit_id" :label="__('jobs.quick.service_unit')" :aria-label="__('jobs.quick.service_unit')" required>
<x-select.native id="{{ $inDialog ? 'dialog-' : '' }}quick-service-unit" wire:model="form.service_unit_id" :label="__('jobs.quick.service_unit')" :aria-label="__('jobs.quick.service_unit')" required>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->serviceUnits as $unit)
<option value="{{ $unit->id }}">{{ $unit->name }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model="form.responsible_user_id" :label="__('jobs.fields.responsible_user')" :aria-label="__('jobs.fields.responsible_user')" required>
<x-select.native id="{{ $inDialog ? 'dialog-' : '' }}quick-responsible" wire:model="form.responsible_user_id" :label="__('jobs.fields.responsible_user')" :aria-label="__('jobs.fields.responsible_user')" required>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->staff as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</x-select.native>
<x-radio.group
wire:model="form.status"
:label="__('jobs.fields.status')"
:options="[
['label' => __('jobs.statuses.'.JobStatus::Tentative->value), 'value' => JobStatus::Tentative->value],
['label' => __('jobs.statuses.'.JobStatus::Prospect->value), 'value' => JobStatus::Prospect->value],
]"
/>
<x-select.native id="{{ $inDialog ? 'dialog-' : '' }}quick-status" wire:model="form.status" :label="__('jobs.quick.start_status')" :aria-label="__('jobs.quick.start_status')">
@foreach (QuickJobForm::startStatuses() as $status)
<option value="{{ $status->value }}">{{ __('jobs.statuses.'.$status->value) }}</option>
@endforeach
</x-select.native>
<x-select.native id="{{ $inDialog ? 'dialog-' : '' }}quick-priority" wire:model="form.priority" :label="__('jobs.fields.priority')" :aria-label="__('jobs.fields.priority')">
@foreach (Priority::cases() as $priority)
<option value="{{ $priority->value }}">{{ __('jobs.priorities.'.$priority->value) }}</option>
@endforeach
</x-select.native>
</div>
@if ($inDialog)
<div class="flex justify-end gap-2 border-t border-neutral-200 pt-3 dark:border-[#36393f]">
<x-button subtle color="black" :text="__('layout.cancel')" x-on:click="$el.closest('dialog').close()" />
<x-button submit :text="__('jobs.quick.save')" />
</div>
@else
<x-button submit lg class="w-full" :text="__('jobs.quick.save')" />
@endif
</form>
</div>
@@ -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<JobChangeEntry>
*/
#[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<TaskSummary>
*/
@@ -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);
@@ -205,15 +157,20 @@ new class extends Component
@php($job = $this->job)
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<x-page>
<div class="space-y-4">
<div class="flex flex-wrap items-start justify-between gap-4">
<div class="min-w-0 flex-1 space-y-1">
<a href="{{ route('jobs.index') }}" wire:navigate class="inline-flex min-h-6 items-center gap-1 rounded-md text-sm font-medium text-primary-700 underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:text-primary-100 dark:focus-visible:outline-primary-300">
<x-icon name="arrow-left" class="size-4" aria-hidden="true" />{{ __('jobs.title') }}
</a>
<h1 class="text-2xl font-semibold break-words">
<span class="whitespace-nowrap">{{ $job->number }}</span> {{ $job->name }}
<span class="whitespace-nowrap text-primary-700 dark:text-primary-100">{{ $job->number }}</span> {{ $job->name }}
</h1>
</div>
@can('jobs.manage')
<x-button :href="route('jobs.edit', $job->id)" wire:navigate subtle color="black" icon="pencil" :text="__('jobs.edit')" />
<x-button :href="route('jobs.edit', $job->id)" wire:navigate icon="pencil" :text="__('jobs.edit')" />
@endcan
</div>
@@ -221,14 +178,14 @@ new class extends Component
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
<dl class="flex flex-wrap gap-x-8 gap-y-2 text-sm">
<div class="flex gap-2"><dt class="font-medium">{{ __('jobs.fields.status') }}:</dt><dd>{{ __('jobs.statuses.'.$job->status->value) }}</dd></div>
<dl class="card flex flex-wrap items-center gap-x-8 gap-y-2 py-3 text-sm sm:py-3">
<div class="flex items-center gap-2"><dt class="font-medium">{{ __('jobs.fields.status') }}:</dt><dd><x-jobs.status :status="$job->status" class="text-sm" /></dd></div>
<div class="flex gap-2"><dt class="font-medium">{{ __('jobs.fields.priority') }}:</dt><dd><x-jobs.priority :priority="$job->priority" /></dd></div>
<div class="flex gap-2"><dt class="font-medium">{{ __('jobs.fields.due_on') }}:</dt><dd><x-jobs.due-date :date="$job->dueOn" :status="$job->status" /></dd></div>
</dl>
</div>
<section aria-labelledby="basics-heading" class="space-y-3">
<section aria-labelledby="basics-heading" class="card space-y-3">
<h2 id="basics-heading" class="text-xl font-semibold">{{ __('jobs.sections.basics') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
@@ -291,7 +248,8 @@ new class extends Component
@endif
</section>
<section aria-labelledby="schedule-heading" class="space-y-3">
<div class="grid gap-6 md:grid-cols-2">
<section aria-labelledby="schedule-heading" class="card space-y-3">
<h2 id="schedule-heading" class="text-xl font-semibold">{{ __('jobs.sections.schedule') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
@@ -306,7 +264,7 @@ new class extends Component
</dl>
</section>
<section aria-labelledby="members-heading" class="space-y-3">
<section aria-labelledby="members-heading" class="card space-y-3">
<h2 id="members-heading" class="text-xl font-semibold">{{ __('jobs.sections.members') }}</h2>
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
@@ -325,6 +283,8 @@ new class extends Component
</dl>
</section>
</div>
<section id="tasks" aria-labelledby="tasks-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="tasks-heading" tabindex="-1" class="text-xl font-semibold focus:outline-none">{{ __('jobs.tasks.title') }}</h2>
@@ -341,14 +301,14 @@ new class extends Component
@can('jobs.manage-tasks', $job->id)
@unless ($job->status->allowsTasks())
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.not_allowed_yet') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.not_allowed_yet') }}</p>
@endunless
@endcan
<p role="status" aria-live="polite" class="text-sm">{{ $taskStatusMessage }}</p>
@if ($this->tasks === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.empty') }}</p>
<x-empty-state icon="clipboard-document-list">{{ __('jobs.tasks.empty') }}</x-empty-state>
@else
@php($canChangeStatus = Gate::allows('jobs.update-task-status', $job->id))
@php($canManageTasks = Gate::allows('jobs.manage-tasks', $job->id))
@@ -395,7 +355,7 @@ new class extends Component
x-on:tasks-expand.window="open = $event.detail"
x-on:focusin="if ($event.target.closest('[data-task-details]')) open = true"
>
<article aria-labelledby="task-{{ $task->id }}-title" class="rounded-lg border border-zinc-200 bg-white text-sm dark:border-zinc-700 dark:bg-zinc-900">
<article aria-labelledby="task-{{ $task->id }}-title" @class(['rounded-xl border border-l-4 border-zinc-200 bg-white text-sm shadow-sm dark:border-zinc-700 dark:bg-zinc-900', match ($task->status->value) { 'in_progress' => 'border-l-primary-500', 'in_review' => 'border-l-amber-500', 'done' => 'border-l-emerald-500', default => 'border-l-zinc-400' }])>
<div class="flex flex-col gap-2 p-3 sm:flex-row sm:flex-wrap sm:items-center sm:gap-x-6">
<h3 id="task-{{ $task->id }}-title" class="min-w-0 text-base font-medium sm:flex-1">
<button
@@ -405,7 +365,7 @@ new class extends Component
x-bind:aria-expanded="open.toString()"
aria-expanded="false"
aria-controls="task-{{ $task->id }}-details"
class="flex min-h-6 w-full items-start gap-2 rounded-md text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400"
class="flex min-h-6 w-full items-start gap-2 rounded-md text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
>
<x-icon name="chevron-right" class="mt-0.5 size-5 shrink-0 transition-transform" x-bind:class="{ 'rotate-90': open }" aria-hidden="true" />
<span class="min-w-0 break-words">{{ $task->title }}</span>
@@ -423,7 +383,7 @@ new class extends Component
</div>
<div class="flex flex-wrap gap-x-1">
<dt class="font-medium">{{ __('jobs.tasks.fields.status') }}:</dt>
<dd>{{ __('jobs.tasks.statuses.'.$task->status->value) }}</dd>
<dd><x-jobs.task-status :status="$task->status" /></dd>
</div>
@if ($task->commentCount > 0)
<div class="flex flex-wrap gap-x-1">
@@ -470,14 +430,6 @@ new class extends Component
<p class="whitespace-pre-line">{{ $task->description }}</p>
@endif
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'checklist-'.$task->id" />
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
<livewire:inventory::task-materials :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'materials-'.$task->id" />
<livewire:machines::task-machine :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'machine-'.$task->id" />
<div class="flex flex-wrap items-end gap-3">
@if ($canChangeStatus)
<div class="w-full sm:w-56">
@@ -530,6 +482,33 @@ new class extends Component
/>
@endif
</div>
<x-tabs
id="task-{{ $task->id }}-tabs"
:label="__('jobs.tasks.tabs.label', ['title' => $task->title])"
:tabs="[
'notes' => __('jobs.tasks.tabs.notes'),
'images' => __('jobs.tasks.tabs.images'),
'materials' => __('jobs.tasks.tabs.materials'),
]"
class="pt-2"
>
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="notes" class="space-y-3">
<livewire:jobs::task-checklist :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'checklist-'.$task->id" />
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
</x-tabs.panel>
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="images">
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
</x-tabs.panel>
{{-- The sections mark themselves data-task-section when they have something to show. --}}
<x-tabs.panel tabs-id="task-{{ $task->id }}-tabs" name="materials" class="group space-y-3">
<livewire:inventory::task-materials :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'materials-'.$task->id" />
<livewire:machines::task-machine :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'machine-'.$task->id" />
<p class="group-has-[[data-task-section]]:hidden">{{ __('jobs.tasks.tabs.no_materials') }}</p>
</x-tabs.panel>
</x-tabs>
</div>
</article>
</li>
@@ -551,17 +530,17 @@ new class extends Component
</section>
@can('expenses.record')
<section aria-labelledby="expenses-heading" class="space-y-3">
<section aria-labelledby="expenses-heading" class="card space-y-3">
<h2 id="expenses-heading" class="text-xl font-semibold">{{ __('jobs.sections.expenses') }}</h2>
<x-link :href="route('expenses.job', $job->id)" navigate>{{ __('expenses.job_page.link') }}</x-link>
</section>
@endcan
<section aria-labelledby="links-heading" class="space-y-3">
<section aria-labelledby="links-heading" class="card space-y-3">
<h2 id="links-heading" class="text-xl font-semibold">{{ __('jobs.sections.links') }}</h2>
@if ($job->links === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.links.none') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.links.none') }}</p>
@else
<ul class="list-disc space-y-1 pl-5 text-sm">
@foreach ($job->links as $link)
@@ -575,12 +554,12 @@ new class extends Component
@endif
</section>
<section aria-labelledby="instructions-heading" class="space-y-3">
<section aria-labelledby="instructions-heading" class="card space-y-3">
<h2 id="instructions-heading" class="text-xl font-semibold">{{ __('jobs.sections.instructions') }}</h2>
<p class="whitespace-pre-line text-sm">{{ $job->instructions ?? __('jobs.not_set') }}</p>
</section>
<section aria-labelledby="history-heading" class="space-y-3" x-data="{ open: false }">
<section aria-labelledby="history-heading" class="card space-y-3" x-data="{ open: false }">
<h2 id="history-heading" class="text-xl font-semibold">
<button
type="button"
@@ -589,7 +568,7 @@ new class extends Component
x-bind:aria-expanded="open.toString()"
aria-expanded="false"
aria-controls="history-panel"
class="flex min-h-6 items-center gap-2 rounded-md text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400"
class="flex min-h-6 items-center gap-2 rounded-md text-left focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
>
<x-icon name="chevron-right" class="size-5 shrink-0 transition-transform" x-bind:class="{ 'rotate-90': open }" aria-hidden="true" />
{{ __('jobs.sections.history') }}
@@ -599,7 +578,7 @@ new class extends Component
<div id="history-panel" x-show="open" x-cloak>
@if ($this->changes === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.history.empty') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.history.empty') }}</p>
@else
<ol class="space-y-2 text-sm">
@foreach ($this->changes as $change)
@@ -616,7 +595,7 @@ new class extends Component
<span class="font-medium">{{ __('jobs.history.unlocked') }}</span>
@endif
@endif
<span class="block text-zinc-600 dark:text-zinc-300">
<span class="block text-zinc-600 dark:text-zinc-200">
{{ __('jobs.history.by', ['user' => $change->userName, 'time' => CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i')]) }}
</span>
</li>
@@ -625,4 +604,4 @@ new class extends Component
@endif
</div>
</section>
</div>
</x-page>
@@ -276,7 +276,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm">{{ $message }}</p>
@if ($this->items === [])
<p class="text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.checklist.empty') }}</p>
<p class="text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.checklist.empty') }}</p>
@else
<ul class="space-y-2" aria-label="{{ __('jobs.tasks.checklist.list_of', ['title' => $taskTitle]) }}">
@foreach ($this->items as $item)
@@ -297,14 +297,14 @@ new class extends Component
id="checklist-item-{{ $item->id }}"
wire:change="check({{ $item->id }}, $event.target.checked)"
@checked($item->done)
class="mt-0.5 size-4 shrink-0 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800"
class="mt-0.5 size-4 shrink-0 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:border-zinc-500 dark:bg-zinc-800"
/>
<span @class(['line-through' => $item->done])>{{ $item->text }}</span>
</label>
@else
<span class="min-w-0 grow break-words">
<span @class(['line-through' => $item->done])>{{ $item->text }}</span>
<span class="text-zinc-600 dark:text-zinc-300">({{ $item->done ? __('jobs.tasks.checklist.done') : __('jobs.tasks.checklist.not_done') }})</span>
<span class="text-zinc-600 dark:text-zinc-200">({{ $item->done ? __('jobs.tasks.checklist.done') : __('jobs.tasks.checklist.not_done') }})</span>
</span>
@endif
@@ -289,7 +289,7 @@ new class extends Component
<p role="status" aria-live="polite" class="text-sm">{{ $message }}</p>
@if ($this->comments === [])
<p class="text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.comments.empty') }}</p>
<p class="text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.comments.empty') }}</p>
@else
<ol class="space-y-3">
@foreach ($this->comments as $comment)
@@ -298,7 +298,7 @@ new class extends Component
<li wire:key="task-comment-{{ $comment->id }}" class="space-y-1 rounded-md bg-zinc-50 p-3 dark:bg-zinc-800">
<p class="flex flex-wrap gap-x-2">
<span class="font-medium">{{ $this->authorName($comment) }}</span>
<span class="text-zinc-600 dark:text-zinc-300">
<span class="text-zinc-600 dark:text-zinc-200">
<time datetime="{{ str_replace(' ', 'T', $comment->createdAt) }}">{{ $at }}</time>
@if ($comment->editedAt !== null)
({{ __('jobs.tasks.comments.edited', ['at' => $this->formatTime($comment->editedAt)]) }})
@@ -171,14 +171,14 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">
<x-page-title icon="clipboard-document-list">{{ $this->heading() }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">
{{ __('jobs.tasks.job_label') }}:
<x-link :href="route('jobs.show', $jobId)" navigate>{{ $jobTitle }}</x-link>
</p>
</div>
<form wire:submit="save" class="space-y-6" novalidate>
<form wire:submit="save" class="card space-y-6" novalidate>
<x-input wire:model="form.title" :label="__('jobs.tasks.fields.title')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
@@ -228,7 +228,7 @@ new class extends Component
<fieldset class="space-y-2">
<legend class="text-sm font-semibold">{{ __('jobs.tasks.schedule') }}</legend>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.fields.planned_hint') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.fields.planned_hint') }}</p>
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model="form.planned_from" type="date" :label="__('jobs.tasks.fields.planned_from')" />
<x-input wire:model="form.planned_to" type="date" :label="__('jobs.tasks.fields.planned_to')" />
@@ -338,7 +338,7 @@ new class extends Component
</p>
@if ($this->images === [])
<p class="text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.images.empty') }}</p>
<p class="text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.images.empty') }}</p>
@else
<ul class="grid grid-cols-1 gap-4 min-[360px]:grid-cols-2 lg:grid-cols-3">
@foreach ($this->images as $index => $image)
@@ -351,7 +351,7 @@ new class extends Component
href="{{ $fullUrl }}"
target="_blank"
rel="noopener"
class="block rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400"
class="block rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
>
<img
src="{{ route('jobs.tasks.images.show', [$jobId, $taskId, $image->id, 'thumbnail']) }}"
@@ -367,7 +367,7 @@ new class extends Component
@if ($image->caption !== null)
<span class="block">{{ $image->caption }}</span>
@endif
<span class="block text-zinc-600 dark:text-zinc-300">
<span class="block text-zinc-600 dark:text-zinc-200">
{{ $this->uploaderName($image) }}, <time datetime="{{ str_replace(' ', 'T', $image->uploadedAt) }}">{{ $this->formatTime($image->uploadedAt) }}</time>
</span>
</figcaption>
@@ -386,7 +386,7 @@ new class extends Component
<a
href="{{ $fullUrl }}?download=1"
aria-label="{{ __('jobs.tasks.images.download_named', ['image' => $alt]) }}"
class="inline-flex min-h-6 items-center rounded-md px-2 py-1 text-sm font-medium text-zinc-900 underline hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:focus-visible:outline-blue-400"
class="inline-flex min-h-6 items-center rounded-md px-2 py-1 text-sm font-medium text-zinc-900 underline hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:text-zinc-100"
>{{ __('jobs.tasks.images.download') }}</a>
@if ($canUpload && $this->isOwn($image))
@@ -422,8 +422,8 @@ new class extends Component
@if ($canUpload)
<form wire:submit="add" class="space-y-3">
<div class="space-y-1">
<label for="image-new-{{ $taskId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('jobs.tasks.images.new') }}</label>
<p id="image-new-{{ $taskId }}-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.images.hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
<label for="image-new-{{ $taskId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-200">{{ __('jobs.tasks.images.new') }}</label>
<p id="image-new-{{ $taskId }}-hint" class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.images.hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
<input
type="file"
id="image-new-{{ $taskId }}"
@@ -431,7 +431,7 @@ new class extends Component
accept="image/jpeg,image/png,image/webp,image/gif"
aria-describedby="image-new-{{ $taskId }}-hint @error('photo') image-new-{{ $taskId }}-error @enderror"
@error('photo') aria-invalid="true" @enderror
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600"
/>
@error('photo')
<p id="image-new-{{ $taskId }}-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -214,8 +214,8 @@ new class extends Component
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.tasks.from_template.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.job_label') }}: {{ $jobTitle }}</p>
<x-page-title icon="queue-list">{{ __('jobs.tasks.from_template.title') }}</x-page-title>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.job_label') }}: {{ $jobTitle }}</p>
</div>
<p class="text-sm">{{ __('jobs.tasks.from_template.intro') }}</p>
@@ -225,11 +225,11 @@ new class extends Component
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
<p>{{ __('jobs.tasks.from_template.none') }}</p>
<x-empty-state icon="queue-list">{{ __('jobs.tasks.from_template.none') }}</x-empty-state>
<x-button :href="route('jobs.show', $jobId)" wire:navigate subtle color="black" :text="__('jobs.tasks.from_template.back')" />
@else
<form wire:submit="add" class="space-y-6" novalidate>
<form wire:submit="add" class="card space-y-6" novalidate>
<x-radio.group
id="template"
wire:model.live="templateId"
@@ -241,13 +241,13 @@ new class extends Component
@if (($template = $this->selectedTemplate) !== null)
{{-- An input grid is a form, so a native table rather than <x-table>. --}}
<div class="space-y-2">
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.from_template.schedule_help') }}</p>
<p class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.from_template.schedule_help') }}</p>
{{-- Below sm the rows stack (each cell on its own line, with its own visible label) so that the page reflows at 320 px. --}}
<table class="w-full border-collapse text-sm">
<caption class="mb-2 text-left font-medium">{{ __('jobs.tasks.from_template.table_caption', ['name' => $template->name]) }}</caption>
<thead class="max-sm:hidden">
<tr class="border-b border-zinc-200 dark:border-zinc-700">
<tr class="border-b-2 border-primary-200 text-primary-900 dark:border-primary-800 dark:text-primary-100">
<th scope="col" class="py-2 pr-2 text-left font-semibold">{{ __('jobs.tasks.from_template.task') }}</th>
<th scope="col" class="px-1 py-2 text-left font-semibold">{{ __('jobs.tasks.fields.due_on') }}</th>
<th scope="col" class="px-1 py-2 text-left font-semibold">{{ __('jobs.tasks.fields.estimated_hours') }}</th>
@@ -259,7 +259,7 @@ new class extends Component
<tr wire:key="row-{{ $template->id }}-{{ $index }}" class="border-b border-zinc-200 align-top max-sm:block max-sm:py-2 dark:border-zinc-700">
<th scope="row" class="py-2 pr-2 text-left font-normal break-words max-sm:block max-sm:py-0">
<span class="font-medium">{{ $step->title }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $step->workTypeName }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-200">{{ $step->workTypeName }}</span>
</th>
<td class="px-1 py-2 max-sm:block max-sm:px-0 max-sm:py-1">
<span class="block text-xs font-medium sm:hidden" aria-hidden="true">{{ __('jobs.tasks.fields.due_on') }}</span>
@@ -269,7 +269,7 @@ new class extends Component
wire:model="rows.{{ $index }}.due_on"
aria-label="{{ __('jobs.tasks.from_template.due_on_of', ['title' => $step->title]) }}"
@error('rows.'.$index.'.due_on') aria-invalid="true" aria-describedby="row-{{ $index }}-due-on-error" @enderror
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800 dark:[color-scheme:dark]"
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800 dark:[color-scheme:dark] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
/>
@error('rows.'.$index.'.due_on')
<p id="row-{{ $index }}-due-on-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -285,7 +285,7 @@ new class extends Component
wire:model="rows.{{ $index }}.estimated_hours"
aria-label="{{ __('jobs.tasks.from_template.hours_of', ['title' => $step->title]) }}"
@error('rows.'.$index.'.estimated_hours') aria-invalid="true" aria-describedby="row-{{ $index }}-hours-error" @enderror
class="w-16 rounded-md border max-sm:w-full border-zinc-500 bg-white px-2 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
class="w-16 rounded-md border max-sm:w-full border-zinc-500 bg-white px-2 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
/>
@error('rows.'.$index.'.estimated_hours')
<p id="row-{{ $index }}-hours-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@@ -297,7 +297,7 @@ new class extends Component
id="row-{{ $index }}-assignee"
wire:model="rows.{{ $index }}.assignee_user_id"
aria-label="{{ __('jobs.tasks.from_template.assignee_of', ['title' => $step->title]) }}"
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary-600 dark:focus-visible:outline-primary-300"
>
<option value="">{{ __('jobs.calendar.no_assignee') }}</option>
@foreach ($this->userOptions as $user)
@@ -317,7 +317,7 @@ new class extends Component
aria-describedby="schedule-to-due-dates-hint"
:label="__('jobs.tasks.from_template.schedule_to_due')"
/>
<p id="schedule-to-due-dates-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.from_template.schedule_to_due_hint') }}</p>
<p id="schedule-to-due-dates-hint" class="text-sm text-zinc-600 dark:text-zinc-200">{{ __('jobs.tasks.from_template.schedule_to_due_hint') }}</p>
</div>
</div>
@endif
@@ -0,0 +1,39 @@
<?php
namespace App\Modules\Jobs\Presentation\Support;
use App\Modules\Jobs\Application\DTOs\BoardCard;
use Carbon\CarbonImmutable;
/**
* Finnish short formats on Kanban cards: "16.12." and "1,5".
*/
final class BoardFormat
{
public static function shortDate(?string $date): string
{
return $date === null ? '–' : CarbonImmutable::parse($date)->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),
]);
}
}
@@ -13,4 +13,9 @@ interface MaintenanceMaterials
* @return bool False when the stock could not be recorded (e.g. the item is out of use).
*/
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool;
/**
* Returns the stock a cancelled maintenance record used.
*/
public function returnUseOf(int $maintenanceRecordId, int $userId): void;
}
@@ -24,10 +24,10 @@ use App\Modules\Users\Application\Contracts\Clock;
/**
* Machine maintenance (spec 19.5): maintenance items are kept by
* management; counter readings and maintenance done are recorded by
* management; counter usage and maintenance done are recorded by
* anyone using the machine. A maintenance record starts the item's
* intervals again and uses up its stock item; a mistaken record is
* cancelled by management, never deleted.
* cancelled by management, never deleted, and its stock use reversed.
*/
final class MachineMaintenance
{
@@ -98,50 +98,55 @@ final class MachineMaintenance
}
/**
* Records a counter's reading, e.g. the machine's own total counter.
* Records how much of a counter one job used (spec 19.5): counters are
* cumulative, so the usage is added to the counter's latest reading.
*
* @return int The counter's new reading.
*
* @throws CounterNotFound
* @throws InvalidReading
*/
public function recordReading(int $counterId, string $reading, int $actorUserId): int
public function recordUsage(int $counterId, string $usage, int $actorUserId): int
{
$milli = Reading::parse($reading) ?? throw new InvalidReading;
$usageMilli = Reading::parse($usage);
$this->transactions->run(function () use ($counterId, $milli, $actorUserId): void {
$this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound;
$this->maintenance->addReading($counterId, $milli, $actorUserId, $this->clock->now());
if ($usageMilli === null || $usageMilli <= 0) {
throw new InvalidReading;
}
return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int {
if (! $this->maintenance->lockCounter($counterId)) {
throw new CounterNotFound;
}
$reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli;
$this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now());
return $reading;
});
return $milli;
}
/**
* Records maintenance done (Huolto tehty) with the counter's reading
* (the latest one when not given) and uses up the item's stock item.
* Records maintenance done (Huolto tehty) at the counter's latest
* reading and uses up the item's stock item. This resets the item: the
* whole counter interval is left again, counted from this reading, and
* the time interval starts again from today.
*
* @return array{recordId: int, stockRecorded: bool}
*
* @throws MaintenanceItemNotFound
* @throws InvalidReading
*/
public function recordMaintenance(int $itemId, int $actorUserId, string $reading = '', ?string $note = null): array
public function recordMaintenance(int $itemId, int $actorUserId, ?string $note = null): array
{
$readingMilli = Reading::parse($reading);
$note = $note === null ? '' : trim($note);
return $this->transactions->run(function () use ($itemId, $actorUserId, $readingMilli, $note): array {
return $this->transactions->run(function () use ($itemId, $actorUserId, $note): array {
$item = $this->maintenance->findItem($itemId) ?? throw new MaintenanceItemNotFound;
$now = $this->clock->now();
$readingMilli = $item->counterId() === null
? null
: ($this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli());
if ($item->counterId() !== null) {
if ($readingMilli !== null) {
$this->maintenance->addReading($item->counterId(), $readingMilli, $actorUserId, $now);
} else {
$readingMilli = $this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli();
}
}
$recordId = $this->maintenance->addRecord($itemId, $now, $actorUserId, $item->counterId() === null ? null : $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000));
$recordId = $this->maintenance->addRecord($itemId, $this->clock->now(), $actorUserId, $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000));
$stockRecorded = $item->stockItemId() === null
|| $this->materials->use($item->stockItemId(), (int) $item->stockQuantityMilli(), $item->machineId(), $recordId, $actorUserId);
@@ -164,6 +169,7 @@ final class MachineMaintenance
}
$this->maintenance->cancelRecord($recordId, $actorUserId, $this->clock->now());
$this->materials->returnUseOf($recordId, $actorUserId);
});
}
}
@@ -21,6 +21,14 @@ interface MaintenanceRepository
*/
public function machineOfCounter(int $counterId): ?int;
/**
* Locks the counter until the transaction ends, so usage recorded at
* the same time is added one after the other.
*
* @return bool Whether the counter exists.
*/
public function lockCounter(int $counterId): bool;
public function latestReading(int $counterId): ?int;
public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void;
@@ -12,7 +12,8 @@ use DateTimeImmutable;
/**
* Works out a maintenance item's state from what has accumulated since its
* last maintenance (spec 19.5). The counter interval counts the counter's
* latest reading minus its reading at the last maintenance; the time
* latest reading minus its reading at the last maintenance, so a
* maintenance starts the whole interval again; the time
* interval counts calendar periods from the day of the last maintenance.
* With both, maintenance is due when either is. The advance warning
* applies to both, but not to daily maintenance.
@@ -4,17 +4,22 @@ namespace App\Modules\Machines\Infrastructure\Adapters;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\ReverseMaintenanceStockUse;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Records stock used at machine maintenance through the Inventory module.
* A failure (e.g. the item is out of use) does not undo the maintenance.
* Records stock used at machine maintenance through the Inventory module,
* and returns it when the maintenance record is cancelled. A failure to
* record (e.g. the item is out of use) does not undo the maintenance.
*/
class StockForMachines implements MaintenanceMaterials
{
public function __construct(private RecordStockUse $recordUse) {}
public function __construct(
private RecordStockUse $recordUse,
private ReverseMaintenanceStockUse $reverseUse,
) {}
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool
{
@@ -31,4 +36,9 @@ class StockForMachines implements MaintenanceMaterials
return true;
}
public function returnUseOf(int $maintenanceRecordId, int $userId): void
{
$this->reverseUse->execute($maintenanceRecordId, $userId);
}
}

Some files were not shown because too many files have changed in this diff Show More