Add customer jobs with numbering, members, tags, links and history

Phase 1, item 4. New Jobs module:
- Customer jobs with the spec's fields except money (phase 2): yearly
  running numbers (2026-0001) from a locked counter row, service units,
  schedule, kind, status, priority, payment basis, estimated hours,
  PO reference, instructions, members (responsible, contact person,
  customer contact, biller, billing unit, other members), tags shared
  across jobs, and links.
- Every change is recorded field by field and shown on the job page with
  names and Finnish dates.
- References to other modules are checked through their query
  contracts: contact and billing unit must be the customer's own;
  service units and users must be in use unless already on the job.
- Job list with search, filters and "my jobs" on by default; job form
  with an accessible customer search and quick add; job page.
- Access: subcontractors see only jobs they are members of, read only;
  billing statuses for management and the job's biller; archiving for
  management.

Related changes:
- Customers: one internal customer (created by a migration) for internal
  work; contacts and billing units used by a job cannot be removed.
- Users and Catalog: batch name lookups and active user options with
  roles for other modules.
- <x-checkbox-group> component; spec and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 18:57:18 +02:00
co-authored by Claude Opus 5.5
parent 51b2d4a252
commit 70e107f6e2
95 changed files with 4631 additions and 26 deletions
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
* Read side of customer jobs, for the job pages and other modules (tasks,
* time entries, billing).
*/
interface CustomerJobQueries
{
/**
* Jobs by due date (none last), then newest first.
*
* @return LengthAwarePaginator<int, CustomerJobSummary>
*/
public function paginate(JobListFilter $filter, int $perPage = 25): LengthAwarePaginator;
public function findDetails(int $id): ?CustomerJobDetails;
/**
* The job's history, newest first.
*
* @return list<JobChangeEntry>
*/
public function changes(int $jobId): array;
/**
* Stored tag names that contain the term, for suggestions.
*
* @return list<string>
*/
public function tagSuggestions(string $term = '', int $limit = 20): array;
/**
* Whether the user is a named member of the job in any role.
*/
public function isMember(int $jobId, int $userId): bool;
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Input for opening a customer job or changing it. Dates are Y-m-d strings,
* enums their keys; empty optional values are null.
*/
final readonly class CustomerJobData
{
/**
* @param list<int> $serviceUnitIds
* @param list<int> $memberUserIds
* @param list<string> $tags
* @param list<array{title: string, url: string}> $links
*/
public function __construct(
public string $name,
public int $customerId,
public array $serviceUnitIds,
public int $responsibleUserId,
public string $kind,
public string $status,
public string $priority,
public ?string $description = null,
public ?string $startsOn = null,
public ?string $dueOn = null,
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
public ?string $paymentBasis = null,
public ?string $estimatedHours = null,
public ?string $customerReference = null,
public ?string $instructions = null,
public ?int $contactUserId = null,
public ?int $customerContactId = null,
public ?int $billerUserId = null,
public ?int $billingUnitId = null,
public array $memberUserIds = [],
public array $tags = [],
public array $links = [],
) {}
}
@@ -0,0 +1,61 @@
<?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\PaymentBasis;
use App\Modules\Jobs\Domain\Enums\Priority;
/**
* Everything the job page and the edit form show, with names resolved.
*/
final readonly class CustomerJobDetails
{
/**
* @param list<NamedId> $serviceUnits
* @param list<NamedId> $members
* @param list<string> $tags
* @param list<array{title: string, url: string}> $links
*/
public function __construct(
public int $id,
public string $number,
public string $name,
public ?string $description,
public NamedId $customer,
public array $serviceUnits,
public ?string $startsOn,
public ?string $dueOn,
public ?string $plannedFrom,
public ?string $plannedTo,
public JobKind $kind,
public JobStatus $status,
public Priority $priority,
public ?PaymentBasis $paymentBasis,
public ?string $estimatedHours,
public ?string $customerReference,
public ?string $instructions,
public NamedId $responsible,
public ?NamedId $contactUser,
public ?NamedId $customerContact,
public ?NamedId $biller,
public ?NamedId $billingUnit,
public array $members,
public array $tags,
public array $links,
public string $createdAt,
public string $createdByName,
) {}
/**
* Whether the user is a named member of the job in any role.
*/
public function involves(int $userId): bool
{
return in_array($userId, [$this->responsible->id, $this->contactUser?->id, $this->biller?->id], true)
|| in_array($userId, array_map(fn (NamedId $member): int => $member->id, $this->members), true);
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
/**
* A row of the customer job list.
*/
final readonly class CustomerJobSummary
{
public function __construct(
public int $id,
public string $number,
public string $name,
public int $customerId,
public string $customerName,
public JobStatus $status,
public Priority $priority,
public ?string $dueOn,
public string $responsibleName,
) {}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* A row of a job's history. Values are raw (ids, enum keys, Y-m-d dates):
* the job page turns them into names.
*/
final readonly class JobChangeEntry
{
public function __construct(
public string $field,
public ?string $oldValue,
public ?string $newValue,
public string $userName,
public string $changedAt,
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Filters of the customer job list.
*/
final readonly class JobListFilter
{
public function __construct(
public ?string $search = null,
public ?string $status = null,
public ?string $priority = null,
public ?int $serviceUnitId = null,
/** Only jobs this user is a named member of ("omat työt"). */
public ?int $mineForUserId = null,
/** Restricts everything to jobs the user is a member of (subcontractors). */
public ?int $onlyMemberUserId = null,
public bool $includeArchived = false,
) {}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* An id with the name to show for it.
*/
final readonly class NamedId
{
public function __construct(
public int $id,
public string $name,
) {}
}
@@ -0,0 +1,143 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
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\Exceptions\InvalidJobReference;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
use App\Modules\Jobs\Domain\ValueObjects\JobName;
use App\Modules\Jobs\Domain\ValueObjects\Tag;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use DateTimeImmutable;
/**
* Builds a job's details from form input and checks what it refers to in
* other modules: the customer exists, the contact and billing unit are the
* customer's own, service units and users are in use. Something already on
* the job stays allowed even after it was taken out of use.
*/
final class JobDetailsFactory
{
public function __construct(
private CustomerQueries $customers,
private CatalogQueries $catalog,
private UserAccountQueries $users,
) {}
/**
* @throws InvalidJobReference
*/
public function build(CustomerJobData $data, ?JobDetails $current = null): JobDetails
{
$this->checkReferences($data, $current);
return new JobDetails(
name: new JobName($data->name),
description: self::text($data->description),
customerId: $data->customerId,
serviceUnitIds: $data->serviceUnitIds,
startsOn: self::date($data->startsOn),
dueOn: self::date($data->dueOn),
plannedFrom: self::date($data->plannedFrom),
plannedTo: self::date($data->plannedTo),
kind: JobKind::from($data->kind),
status: JobStatus::from($data->status),
priority: Priority::from($data->priority),
paymentBasis: $data->paymentBasis === null ? null : PaymentBasis::from($data->paymentBasis),
estimatedHours: self::text($data->estimatedHours) === null ? null : EstimatedHours::fromString((string) $data->estimatedHours),
customerReference: self::text($data->customerReference),
instructions: self::text($data->instructions),
responsibleUserId: $data->responsibleUserId,
contactUserId: $data->contactUserId,
customerContactId: $data->customerContactId,
billerUserId: $data->billerUserId,
billingUnitId: $data->billingUnitId,
memberUserIds: $data->memberUserIds,
tags: array_map(fn (string $tag): Tag => new Tag($tag), $data->tags),
links: array_map(fn (array $link): JobLink => new JobLink($link['title'], $link['url']), $data->links),
);
}
private function checkReferences(CustomerJobData $data, ?JobDetails $current): void
{
if ($this->customers->findSummary($data->customerId) === null) {
throw new InvalidJobReference('customer');
}
foreach ($data->serviceUnitIds as $serviceUnitId) {
$unit = $this->catalog->findServiceUnit($serviceUnitId);
$wasOnJob = in_array($serviceUnitId, $current->serviceUnitIds ?? [], true);
if ($unit === null || $unit->isShared || (! $unit->isActive && ! $wasOnJob)) {
throw new InvalidJobReference('service_units');
}
}
if ($data->customerContactId !== null && $this->customers->findContact($data->customerId, $data->customerContactId) === null) {
throw new InvalidJobReference('customer_contact');
}
if ($data->billingUnitId !== null && $this->customers->findBillingUnit($data->customerId, $data->billingUnitId) === null) {
throw new InvalidJobReference('billing_unit');
}
$roles = [];
foreach ($this->users->activeUserOptions() as $option) {
$roles[$option->id] = $option->role;
}
$allowed = fn (?int $userId, ?int $currentId): bool => $userId === null || $userId === $currentId || array_key_exists($userId, $roles);
if (! $allowed($data->responsibleUserId, $current?->responsibleUserId)
|| ($data->responsibleUserId !== $current?->responsibleUserId && $roles[$data->responsibleUserId] === Role::Subcontractor)) {
throw new InvalidJobReference('responsible_user');
}
foreach (['contact_user' => [$data->contactUserId, $current?->contactUserId], 'biller_user' => [$data->billerUserId, $current?->billerUserId]] as $field => [$userId, $currentId]) {
if (! $allowed($userId, $currentId)) {
throw new InvalidJobReference($field);
}
}
foreach ($data->memberUserIds as $memberId) {
if (! array_key_exists($memberId, $roles) && ! in_array($memberId, $current->memberUserIds ?? [], true)) {
throw new InvalidJobReference('members');
}
}
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
return $value === '' ? null : $value;
}
private static function date(?string $value): ?DateTimeImmutable
{
$value = self::text($value);
if ($value === null) {
return null;
}
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($date === false || $date->format('Y-m-d') !== $value) {
throw new \InvalidArgumentException("Not a Y-m-d date: {$value}");
}
return $date;
}
}
@@ -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\JobStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a job to another status (e.g. on the Kanban board) and records it.
*/
final class ChangeJobStatus
{
public function __construct(
private CustomerJobRepository $jobs,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
*/
public function execute(int $jobId, JobStatus $status, int $actorUserId): void
{
$this->transactions->run(function () use ($jobId, $status, $actorUserId): void {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$changes = $job->changeStatus($status);
if ($changes === []) {
return;
}
$this->jobs->save($job);
$this->jobs->recordChanges($jobId, $actorUserId, $changes);
});
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\Clock;
/**
* Opens a customer job with the next number of the year and starts its
* history.
*/
final class CreateCustomerJob
{
public function __construct(
private CustomerJobRepository $jobs,
private JobNumberSequence $numbers,
private JobDetailsFactory $detailsFactory,
private TransactionManager $transactions,
private Clock $clock,
) {}
/**
* @return int The new job's id.
*
* @throws InvalidJobReference
*/
public function execute(CustomerJobData $data, int $actorUserId): int
{
$details = $this->detailsFactory->build($data);
$year = (int) $this->clock->today()->format('Y');
return $this->transactions->run(function () use ($details, $year, $actorUserId): int {
$job = CustomerJob::open($this->numbers->next($year), $details, $actorUserId);
$jobId = (int) $this->jobs->save($job)->id();
$this->jobs->recordChanges($jobId, $actorUserId, [new FieldChange('created', null, $job->number()->format())]);
return $jobId;
});
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Changes a customer job and records each changed field in its history.
* Who may set billing statuses or archive is checked by the caller.
*/
final class UpdateCustomerJob
{
public function __construct(
private CustomerJobRepository $jobs,
private JobDetailsFactory $detailsFactory,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
* @throws InvalidJobReference
*/
public function execute(int $jobId, CustomerJobData $data, int $actorUserId): void
{
$this->transactions->run(function () use ($jobId, $data, $actorUserId): void {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$changes = $job->changeDetails($this->detailsFactory->build($data, $job->details()));
if ($changes === []) {
return;
}
$this->jobs->save($job);
$this->jobs->recordChanges($jobId, $actorUserId, $changes);
});
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
interface CustomerJobRepository
{
public function findById(int $id): ?CustomerJob;
/**
* Inserts a new job or updates a stored one, with its service units,
* members, tags and links, and returns the stored job.
*/
public function save(CustomerJob $job): CustomerJob;
/**
* @param list<FieldChange> $changes
*/
public function recordChanges(int $jobId, int $userId, array $changes): void;
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
interface JobNumberSequence
{
/**
* The next free number of the year. Must be called inside the
* transaction that stores the job, so numbers are never reused.
*/
public function next(int $year): JobNumber;
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Entities;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\ValueObjects\FieldChange;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
/**
* A customer job (asiakastyö): the work done for a customer, which tasks,
* time entries and invoices are attached to.
*/
final class CustomerJob
{
private function __construct(
private ?int $id,
private JobNumber $number,
private JobDetails $details,
private int $createdBy,
) {}
public static function open(JobNumber $number, JobDetails $details, int $createdBy): self
{
return new self(null, $number, $details, $createdBy);
}
public static function reconstitute(int $id, JobNumber $number, JobDetails $details, int $createdBy): self
{
return new self($id, $number, $details, $createdBy);
}
/**
* Replaces the details and returns what changed, for the history.
*
* @return list<FieldChange>
*/
public function changeDetails(JobDetails $details): array
{
$before = $this->details->comparable();
$after = $details->comparable();
$this->details = $details;
$changes = [];
foreach ($after as $field => $value) {
if (($before[$field] ?? null) !== $value) {
$changes[] = new FieldChange($field, $before[$field] ?? null, $value);
}
}
return $changes;
}
/**
* @return list<FieldChange>
*/
public function changeStatus(JobStatus $status): array
{
return $this->changeDetails($this->details->withStatus($status));
}
public function id(): ?int
{
return $this->id;
}
public function number(): JobNumber
{
return $this->number;
}
public function details(): JobDetails
{
return $this->details;
}
public function createdBy(): int
{
return $this->createdBy;
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Kesto / laji (spec 5.2).
*/
enum JobKind: string
{
case Service = 'service';
case OneOff = 'one_off';
case FixedTerm = 'fixed_term';
case Ongoing = 'ongoing';
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Tila (spec 5.3). The cases are in their usual order; any status may be
* chosen. The statuses are also the columns of the job Kanban board.
*/
enum JobStatus: string
{
case Prospect = 'prospect';
case Tentative = 'tentative';
case QuoteRequest = 'quote_request';
case Order = 'order';
case InProduction = 'in_production';
case OnHold = 'on_hold';
case Done = 'done';
case Invoiced = 'invoiced';
case Billed = 'billed';
case Archived = 'archived';
/**
* Statuses set when the job is invoiced: only management and the
* job's biller may set them.
*/
public function isBillingStatus(): bool
{
return $this === self::Invoiced || $this === self::Billed;
}
/**
* The Kanban columns: every status except archived.
*
* @return list<self>
*/
public static function kanbanStatuses(): array
{
$statuses = [];
foreach (self::cases() as $status) {
if ($status !== self::Archived) {
$statuses[] = $status;
}
}
return $statuses;
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Maksuperuste (spec 5.5).
*/
enum PaymentBasis: string
{
case PriceList = 'price_list';
case FixedQuote = 'fixed_quote';
case MonthlyFee = 'monthly_fee';
case Hourly = 'hourly';
case NotBillable = 'not_billable';
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Prioriteetti (spec 5.4). Always shown with text, never colour alone.
*/
enum Priority: string
{
case Waiting = 'waiting';
case Normal = 'normal';
case First = 'first';
case Urgent = 'urgent';
case Immediate = 'immediate';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class CustomerJobNotFound extends DomainException
{
public function __construct(public readonly int $jobId)
{
parent::__construct("Customer job {$jobId} was not found.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class DueBeforeStart extends DomainException
{
public function __construct()
{
parent::__construct('The due date cannot be before the start date.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidEstimatedHours extends DomainException
{
public function __construct()
{
parent::__construct('Estimated hours must be zero or more, in quarters of an hour.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidJobLink extends DomainException
{
public function __construct()
{
parent::__construct('A link needs a title and an http or https address.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidJobName extends DomainException
{
public function __construct()
{
parent::__construct('The job name must be 1–255 characters.');
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A chosen customer, contact, billing unit, service unit or user does not
* exist, is not in use, or belongs to another customer.
*/
final class InvalidJobReference extends DomainException
{
public function __construct(public readonly string $field)
{
parent::__construct("The job's {$field} is not a valid choice.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidTag extends DomainException
{
public function __construct()
{
parent::__construct('A tag must be 1–50 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class PlanEndsBeforeStart extends DomainException
{
public function __construct()
{
parent::__construct('The planned end cannot be before the planned start.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ServiceUnitRequired extends DomainException
{
public function __construct()
{
parent::__construct('A customer job needs at least one service unit.');
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
/**
* Estimated work in hours, to the nearest quarter of an hour.
*/
final readonly class EstimatedHours
{
public const float MAX = 99999.75;
public float $value;
public function __construct(float $value)
{
if ($value < 0 || $value > self::MAX || fmod($value * 4, 1.0) !== 0.0) {
throw new InvalidEstimatedHours;
}
$this->value = $value;
}
public static function fromString(string $value): self
{
$value = str_replace(',', '.', trim($value));
if (! is_numeric($value)) {
throw new InvalidEstimatedHours;
}
return new self((float) $value);
}
/**
* E.g. "12.5", without trailing zeros.
*/
public function format(): string
{
return rtrim(rtrim(number_format($this->value, 2, '.', ''), '0'), '.');
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
/**
* One changed field in a job's history, with raw values (ids, enum keys,
* Y-m-d dates); the page turns them into names when shown.
*/
final readonly class FieldChange
{
public function __construct(
public string $field,
public ?string $oldValue,
public ?string $newValue,
) {}
}
@@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
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\Exceptions\DueBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
use DateTimeImmutable;
/**
* Everything about a customer job that users edit. Kept in one value so a
* change can be compared field by field for the job's history.
*/
final readonly class JobDetails
{
/** @var list<int> */
public array $serviceUnitIds;
/** @var list<int> */
public array $memberUserIds;
/** @var list<Tag> */
public array $tags;
/**
* @param list<int> $serviceUnitIds
* @param list<int> $memberUserIds
* @param list<Tag> $tags
* @param list<JobLink> $links
*/
public function __construct(
public JobName $name,
public ?string $description,
public int $customerId,
array $serviceUnitIds,
public ?DateTimeImmutable $startsOn,
public ?DateTimeImmutable $dueOn,
public ?DateTimeImmutable $plannedFrom,
public ?DateTimeImmutable $plannedTo,
public JobKind $kind,
public JobStatus $status,
public Priority $priority,
public ?PaymentBasis $paymentBasis,
public ?EstimatedHours $estimatedHours,
public ?string $customerReference,
public ?string $instructions,
public int $responsibleUserId,
public ?int $contactUserId,
public ?int $customerContactId,
public ?int $billerUserId,
public ?int $billingUnitId,
array $memberUserIds,
array $tags,
public array $links,
) {
$serviceUnitIds = array_values(array_unique($serviceUnitIds));
if ($serviceUnitIds === []) {
throw new ServiceUnitRequired;
}
if ($startsOn !== null && $dueOn !== null && $dueOn < $startsOn) {
throw new DueBeforeStart;
}
if ($plannedFrom !== null && $plannedTo !== null && $plannedTo < $plannedFrom) {
throw new PlanEndsBeforeStart;
}
sort($serviceUnitIds);
$memberUserIds = array_values(array_unique($memberUserIds));
sort($memberUserIds);
$uniqueTags = [];
foreach ($tags as $tag) {
$uniqueTags[mb_strtolower($tag->value)] ??= $tag;
}
$this->serviceUnitIds = $serviceUnitIds;
$this->memberUserIds = $memberUserIds;
$this->tags = array_values($uniqueTags);
}
public function withStatus(JobStatus $status): self
{
return new self(
$this->name, $this->description, $this->customerId, $this->serviceUnitIds,
$this->startsOn, $this->dueOn, $this->plannedFrom, $this->plannedTo,
$this->kind, $status, $this->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,
);
}
/**
* Whether the user is a named member of the job in any role.
*/
public function involves(int $userId): bool
{
return in_array($userId, [$this->responsibleUserId, $this->contactUserId, $this->billerUserId], true)
|| in_array($userId, $this->memberUserIds, true);
}
/**
* Every field as a comparable string (or null), keyed by the field name
* used in the job's history.
*
* @return array<string, string|null>
*/
public function comparable(): array
{
$date = fn (?DateTimeImmutable $date): ?string => $date?->format('Y-m-d');
$ids = fn (array $ids): ?string => $ids === [] ? null : implode(',', $ids);
// Tags are shared and matched ignoring case, so a change of case is no change.
$tagNames = array_map(fn (Tag $tag): string => mb_strtolower($tag->value), $this->tags);
sort($tagNames);
return [
'name' => $this->name->value,
'description' => $this->description,
'customer' => (string) $this->customerId,
'service_units' => $ids($this->serviceUnitIds),
'starts_on' => $date($this->startsOn),
'due_on' => $date($this->dueOn),
'planned_from' => $date($this->plannedFrom),
'planned_to' => $date($this->plannedTo),
'kind' => $this->kind->value,
'status' => $this->status->value,
'priority' => $this->priority->value,
'payment_basis' => $this->paymentBasis?->value,
'estimated_hours' => $this->estimatedHours?->format(),
'customer_reference' => $this->customerReference,
'instructions' => $this->instructions,
'responsible_user' => (string) $this->responsibleUserId,
'contact_user' => $this->contactUserId === null ? null : (string) $this->contactUserId,
'customer_contact' => $this->customerContactId === null ? null : (string) $this->customerContactId,
'biller_user' => $this->billerUserId === null ? null : (string) $this->billerUserId,
'billing_unit' => $this->billingUnitId === null ? null : (string) $this->billingUnitId,
'members' => $ids($this->memberUserIds),
'tags' => $tagNames === [] ? null : implode(', ', $tagNames),
'links' => $this->links === [] ? null : implode("\n", array_map(fn (JobLink $link): string => $link->title.' <'.$link->url.'>', $this->links)),
];
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
/**
* A link to material of the job (offer, brief, files in Drive or Dropbox).
* Files are not stored in the system (K26).
*/
final readonly class JobLink
{
public string $title;
public string $url;
public function __construct(string $title, string $url)
{
$title = trim(preg_replace('/\s+/u', ' ', $title) ?? $title);
$url = trim($url);
if ($title === '' || mb_strlen($title) > 255 || mb_strlen($url) > 2000
|| filter_var($url, FILTER_VALIDATE_URL) === false
|| ! in_array(strtolower((string) parse_url($url, PHP_URL_SCHEME)), ['http', 'https'], true)) {
throw new InvalidJobLink;
}
$this->title = $title;
$this->url = $url;
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobName;
/**
* Name of a customer job.
*/
final readonly class JobName
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidJobName;
}
$this->value = $value;
}
}
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use InvalidArgumentException;
/**
* Running job number, e.g. 2026-0042. The sequence restarts every year.
*/
final readonly class JobNumber
{
public function __construct(
public int $year,
public int $sequence,
) {
if ($year < 2000 || $year > 9999 || $sequence < 1) {
throw new InvalidArgumentException('A job number needs a four-digit year and a positive sequence.');
}
}
public static function fromString(string $value): self
{
if (preg_match('/^(\d{4})-(\d{4,})$/', $value, $parts) !== 1) {
throw new InvalidArgumentException("Not a job number: {$value}");
}
return new self((int) $parts[1], (int) $parts[2]);
}
public function format(): string
{
return sprintf('%04d-%04d', $this->year, $this->sequence);
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
/**
* A free-form tag of a customer job, e.g. "messut". Compared ignoring case.
*/
final readonly class Tag
{
public const int MAX_LENGTH = 50;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidTag;
}
$this->value = $value;
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Modules\Jobs\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use Illuminate\Support\Facades\DB;
/**
* Tells the Customers module whether a contact or billing unit is chosen
* on a customer job, so it is not removed while in use.
*/
class CustomerRowUsageFromJobs implements CustomerRowUsage
{
public function isContactInUse(int $contactId): bool
{
return DB::table('customer_jobs')->where('customer_contact_id', $contactId)->exists();
}
public function isBillingUnitInUse(int $billingUnitId): bool
{
return DB::table('customer_jobs')->where('billing_unit_id', $billingUnitId)->exists();
}
}
@@ -0,0 +1,25 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
use Illuminate\Support\Facades\DB;
/**
* One counter row per year, locked while the next number is taken, so two
* jobs saved at the same time never get the same number.
*/
class DatabaseJobNumberSequence implements JobNumberSequence
{
public function next(int $year): JobNumber
{
DB::table('job_number_sequences')->insertOrIgnore(['year' => $year, 'last_number' => 0]);
$last = (int) DB::table('job_number_sequences')->where('year', $year)->lockForUpdate()->value('last_number');
DB::table('job_number_sequences')->where('year', $year)->update(['last_number' => $last + 1]);
return new JobNumber($year, $last + 1);
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Eloquent;
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 Carbon\CarbonImmutable;
use Database\Factories\CustomerJobFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a customer job, used only inside the Jobs
* Infrastructure layer. Service units, members, tags and links are in
* their own tables, read and written by the repository.
*
* @property int $id
* @property string $number
* @property string $name
* @property string|null $description
* @property int $customer_id
* @property CarbonImmutable|null $starts_on
* @property CarbonImmutable|null $due_on
* @property CarbonImmutable|null $planned_from
* @property CarbonImmutable|null $planned_to
* @property JobKind $kind
* @property JobStatus $status
* @property Priority $priority
* @property PaymentBasis|null $payment_basis
* @property string|null $estimated_hours
* @property string|null $customer_reference
* @property string|null $instructions
* @property int $responsible_user_id
* @property int|null $contact_user_id
* @property int|null $customer_contact_id
* @property int|null $biller_user_id
* @property int|null $billing_unit_id
* @property int $created_by
* @property CarbonImmutable $created_at
*/
#[Table('customer_jobs')]
#[Fillable([
'number', 'name', 'description', 'customer_id', 'starts_on', 'due_on', 'planned_from', 'planned_to',
'kind', 'status', 'priority', 'payment_basis', 'estimated_hours', 'customer_reference', 'instructions',
'responsible_user_id', 'contact_user_id', 'customer_contact_id', 'biller_user_id', 'billing_unit_id', 'created_by',
])]
#[UseFactory(CustomerJobFactory::class)]
class CustomerJobModel extends Model
{
/** @use HasFactory<CustomerJobFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'customer_id' => 'integer',
'starts_on' => 'immutable_date',
'due_on' => 'immutable_date',
'planned_from' => 'immutable_date',
'planned_to' => 'immutable_date',
'kind' => JobKind::class,
'status' => JobStatus::class,
'priority' => Priority::class,
'payment_basis' => PaymentBasis::class,
'responsible_user_id' => 'integer',
'contact_user_id' => 'integer',
'customer_contact_id' => 'integer',
'biller_user_id' => 'integer',
'billing_unit_id' => 'integer',
'created_by' => 'integer',
'created_at' => 'immutable_datetime',
];
}
}
@@ -0,0 +1,206 @@
<?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\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
/**
* Names of customers, users, contacts and service units come from those
* modules' query contracts, never from their tables.
*/
class EloquentCustomerJobQueries implements CustomerJobQueries
{
public function __construct(
private CustomerQueries $customers,
private UserAccountQueries $users,
private CatalogQueries $catalog,
) {}
public function paginate(JobListFilter $filter, int $perPage = 25): LengthAwarePaginator
{
$page = $this->filtered($filter)
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderByDesc('id')
->paginate($perPage);
$models = collect($page->items());
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
$userNames = $this->users->namesByIds($models->pluck('responsible_user_id')->unique()->values()->all());
return $page->through(fn (CustomerJobModel $model): CustomerJobSummary => new CustomerJobSummary(
$model->id,
$model->number,
$model->name,
$model->customer_id,
$customerNames[$model->customer_id] ?? '',
$model->status,
$model->priority,
$model->due_on?->format('Y-m-d'),
$userNames[$model->responsible_user_id] ?? '',
));
}
public function findDetails(int $id): ?CustomerJobDetails
{
$model = CustomerJobModel::query()->find($id);
if ($model === null) {
return null;
}
$memberIds = DB::table('customer_job_members')->where('customer_job_id', $id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all();
$userIds = array_values(array_filter([$model->responsible_user_id, $model->contact_user_id, $model->biller_user_id, $model->created_by, ...$memberIds]));
$userNames = $this->users->namesByIds(array_values(array_unique($userIds)));
$user = fn (?int $userId): ?NamedId => $userId === null ? null : new NamedId($userId, $userNames[$userId] ?? '');
$serviceUnitIds = DB::table('customer_job_service_unit')->where('customer_job_id', $id)->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->all();
$serviceUnits = [];
foreach ($this->catalog->serviceUnitNames($serviceUnitIds) as $unitId => $name) {
$serviceUnits[] = new NamedId((int) $unitId, $name);
}
$contact = $model->customer_contact_id === null ? null : $this->customers->findContact($model->customer_id, $model->customer_contact_id);
$billingUnit = $model->billing_unit_id === null ? null : $this->customers->findBillingUnit($model->customer_id, $model->billing_unit_id);
return new CustomerJobDetails(
id: $model->id,
number: $model->number,
name: $model->name,
description: $model->description,
customer: new NamedId($model->customer_id, $this->customers->namesByIds([$model->customer_id])[$model->customer_id] ?? ''),
serviceUnits: $serviceUnits,
startsOn: $model->starts_on?->format('Y-m-d'),
dueOn: $model->due_on?->format('Y-m-d'),
plannedFrom: $model->planned_from?->format('Y-m-d'),
plannedTo: $model->planned_to?->format('Y-m-d'),
kind: $model->kind,
status: $model->status,
priority: $model->priority,
paymentBasis: $model->payment_basis,
estimatedHours: $model->estimated_hours === null ? null : rtrim(rtrim($model->estimated_hours, '0'), '.'),
customerReference: $model->customer_reference,
instructions: $model->instructions,
responsible: $user($model->responsible_user_id) ?? new NamedId($model->responsible_user_id, ''),
contactUser: $user($model->contact_user_id),
customerContact: $contact === null ? null : new NamedId($contact->id, $contact->name),
biller: $user($model->biller_user_id),
billingUnit: $billingUnit === null ? null : new NamedId($billingUnit->id, $billingUnit->name),
members: array_values(array_map(fn (int $memberId): NamedId => new NamedId($memberId, $userNames[$memberId] ?? ''), $memberIds)),
tags: DB::table('customer_job_tag')
->join('tags', 'tags.id', '=', 'customer_job_tag.tag_id')
->where('customer_job_id', $id)
->orderBy('tags.name')
->pluck('tags.name')
->map(fn ($name): string => (string) $name)
->all(),
links: DB::table('customer_job_links')
->where('customer_job_id', $id)
->orderBy('sort_order')
->get()
->map(fn ($row): array => ['title' => (string) $row->title, 'url' => (string) $row->url])
->all(),
createdAt: $model->created_at->format('Y-m-d H:i'),
createdByName: $userNames[$model->created_by] ?? '',
);
}
public function changes(int $jobId): array
{
$rows = DB::table('customer_job_changes')->where('customer_job_id', $jobId)->orderByDesc('id')->get();
$userNames = $this->users->namesByIds($rows->pluck('user_id')->map(fn ($id): int => (int) $id)->unique()->values()->all());
return $rows->map(fn ($row): JobChangeEntry => new JobChangeEntry(
(string) $row->field,
$row->old_value,
$row->new_value,
$userNames[(int) $row->user_id] ?? '',
(string) $row->created_at,
))->values()->all();
}
public function tagSuggestions(string $term = '', int $limit = 20): array
{
$term = trim($term);
return DB::table('tags')
->when($term !== '', fn ($query) => $query->where('name', 'like', '%'.addcslashes($term, '%_\\').'%'))
->orderBy('name')
->limit($limit)
->pluck('name')
->map(fn ($name): string => (string) $name)
->all();
}
public function isMember(int $jobId, int $userId): bool
{
return $this->involving(CustomerJobModel::query()->whereKey($jobId), $userId)->exists();
}
/**
* @return Builder<CustomerJobModel>
*/
private function filtered(JobListFilter $filter): Builder
{
$query = CustomerJobModel::query();
$search = trim((string) $filter->search);
if ($search !== '') {
$pattern = '%'.addcslashes($search, '%_\\').'%';
$customerIds = array_map(fn ($customer): int => $customer->id, $this->customers->search($search, 50));
$query->where(fn (Builder $query) => $query
->where('number', 'like', $pattern)
->orWhere('name', 'like', $pattern)
->orWhereIn('customer_id', $customerIds));
}
if ($filter->status !== null) {
$query->where('status', $filter->status);
} elseif (! $filter->includeArchived) {
$query->where('status', '!=', JobStatus::Archived->value);
}
if ($filter->priority !== null) {
$query->where('priority', $filter->priority);
}
if ($filter->serviceUnitId !== null) {
$query->whereIn('id', DB::table('customer_job_service_unit')->select('customer_job_id')->where('service_unit_id', $filter->serviceUnitId));
}
foreach (array_filter([$filter->mineForUserId, $filter->onlyMemberUserId]) as $userId) {
$this->involving($query, $userId);
}
return $query;
}
/**
* Restricts to jobs where the user is responsible, contact, biller or member.
*
* @param Builder<CustomerJobModel> $query
* @return Builder<CustomerJobModel>
*/
private function involving(Builder $query, int $userId): Builder
{
return $query->where(fn (Builder $query) => $query
->where('responsible_user_id', $userId)
->orWhere('contact_user_id', $userId)
->orWhere('biller_user_id', $userId)
->orWhereIn('id', DB::table('customer_job_members')->select('customer_job_id')->where('user_id', $userId)));
}
}
@@ -0,0 +1,154 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
use App\Modules\Jobs\Domain\ValueObjects\JobName;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
use App\Modules\Jobs\Domain\ValueObjects\Tag;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
class EloquentCustomerJobRepository implements CustomerJobRepository
{
public function findById(int $id): ?CustomerJob
{
$model = CustomerJobModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(CustomerJob $job): CustomerJob
{
$details = $job->details();
$model = $job->id() === null ? new CustomerJobModel : CustomerJobModel::query()->findOrFail($job->id());
$model->fill([
'number' => $job->number()->format(),
'name' => $details->name->value,
'description' => $details->description,
'customer_id' => $details->customerId,
'starts_on' => $details->startsOn?->format('Y-m-d'),
'due_on' => $details->dueOn?->format('Y-m-d'),
'planned_from' => $details->plannedFrom?->format('Y-m-d'),
'planned_to' => $details->plannedTo?->format('Y-m-d'),
'kind' => $details->kind,
'status' => $details->status,
'priority' => $details->priority,
'payment_basis' => $details->paymentBasis,
'estimated_hours' => $details->estimatedHours?->value,
'customer_reference' => $details->customerReference,
'instructions' => $details->instructions,
'responsible_user_id' => $details->responsibleUserId,
'contact_user_id' => $details->contactUserId,
'customer_contact_id' => $details->customerContactId,
'biller_user_id' => $details->billerUserId,
'billing_unit_id' => $details->billingUnitId,
'created_by' => $job->createdBy(),
])->save();
$this->syncPivot('customer_job_service_unit', 'service_unit_id', $model->id, $details->serviceUnitIds);
$this->syncPivot('customer_job_members', 'user_id', $model->id, $details->memberUserIds);
$this->syncPivot('customer_job_tag', 'tag_id', $model->id, $this->tagIds($details->tags));
DB::table('customer_job_links')->where('customer_job_id', $model->id)->delete();
DB::table('customer_job_links')->insert(array_map(fn (int $index, JobLink $link): array => [
'customer_job_id' => $model->id,
'title' => $link->title,
'url' => $link->url,
'sort_order' => $index + 1,
], array_keys($details->links), $details->links));
return $this->toEntity($model->refresh());
}
public function recordChanges(int $jobId, int $userId, array $changes): void
{
$now = now();
DB::table('customer_job_changes')->insert(array_map(fn ($change): array => [
'customer_job_id' => $jobId,
'user_id' => $userId,
'field' => $change->field,
'old_value' => $change->oldValue,
'new_value' => $change->newValue,
'created_at' => $now,
], $changes));
}
/**
* @param list<int> $ids
*/
private function syncPivot(string $table, string $column, int $jobId, array $ids): void
{
DB::table($table)->where('customer_job_id', $jobId)->whereNotIn($column, $ids)->delete();
DB::table($table)->insertOrIgnore(array_map(fn (int $id): array => ['customer_job_id' => $jobId, $column => $id], $ids));
}
/**
* Ids of the tags, adding names not seen before to the shared tag list.
*
* @param list<Tag> $tags
* @return list<int>
*/
private function tagIds(array $tags): array
{
$ids = [];
foreach ($tags as $tag) {
$existing = DB::table('tags')->whereRaw('LOWER(name) = ?', [mb_strtolower($tag->value)])->value('id');
$ids[] = (int) ($existing ?? DB::table('tags')->insertGetId(['name' => $tag->value, 'created_at' => now(), 'updated_at' => now()]));
}
return $ids;
}
private function toEntity(CustomerJobModel $model): CustomerJob
{
$date = fn ($value): ?DateTimeImmutable => $value === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $value->format('Y-m-d')) ?: null);
$details = new JobDetails(
name: new JobName($model->name),
description: $model->description,
customerId: $model->customer_id,
serviceUnitIds: DB::table('customer_job_service_unit')->where('customer_job_id', $model->id)->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->all(),
startsOn: $date($model->starts_on),
dueOn: $date($model->due_on),
plannedFrom: $date($model->planned_from),
plannedTo: $date($model->planned_to),
kind: $model->kind,
status: $model->status,
priority: $model->priority,
paymentBasis: $model->payment_basis,
estimatedHours: $model->estimated_hours === null ? null : new EstimatedHours((float) $model->estimated_hours),
customerReference: $model->customer_reference,
instructions: $model->instructions,
responsibleUserId: $model->responsible_user_id,
contactUserId: $model->contact_user_id,
customerContactId: $model->customer_contact_id,
billerUserId: $model->biller_user_id,
billingUnitId: $model->billing_unit_id,
memberUserIds: DB::table('customer_job_members')->where('customer_job_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(),
tags: DB::table('customer_job_tag')
->join('tags', 'tags.id', '=', 'customer_job_tag.tag_id')
->where('customer_job_id', $model->id)
->orderBy('tags.name')
->pluck('tags.name')
->map(fn ($name): Tag => new Tag((string) $name))
->all(),
links: DB::table('customer_job_links')
->where('customer_job_id', $model->id)
->orderBy('sort_order')
->get()
->map(fn ($row): JobLink => new JobLink((string) $row->title, (string) $row->url))
->all(),
);
return CustomerJob::reconstitute($model->id, JobNumber::fromString($model->number), $details, $model->created_by);
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs;
use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Jobs module (customer jobs) into Laravel: bindings, routes,
* the `jobs::` Livewire namespace and the job abilities.
*/
class JobsServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
CustomerJobRepository::class => EloquentCustomerJobRepository::class,
CustomerJobQueries::class => EloquentCustomerJobQueries::class,
JobNumberSequence::class => DatabaseJobNumberSequence::class,
CustomerRowUsage::class => CustomerRowUsageFromJobs::class,
];
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('jobs', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
$isManager = fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true);
// Everyone signed in reaches the job list; subcontractors see only their own jobs on it.
Gate::define('jobs.view', fn (User $user): bool => true);
// Subcontractors see only jobs they are attached to (K12).
Gate::define('jobs.view-job', fn (User $user, int $jobId): bool => $user->role !== Role::Subcontractor
|| app(CustomerJobQueries::class)->isMember($jobId, $user->id));
Gate::define('jobs.manage', fn (User $user): bool => $user->role !== Role::Subcontractor);
Gate::define('jobs.archive', $isManager);
// "Lasku luotu" and "Laskutettu" are set when invoicing: management or the job's biller.
Gate::define('jobs.set-billing-status', fn (User $user, ?CustomerJobDetails $job = null): bool => $isManager($user)
|| ($job !== null && $job->biller?->id === $user->id));
}
}
@@ -0,0 +1,238 @@
<?php
namespace App\Modules\Jobs\Presentation\Livewire\Forms;
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\NamedId;
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\Exceptions\DueBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobName;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* Customer job form shared by the create and edit pages. Validates the
* shape of the input; business rules stay in the Domain.
*/
class JobForm extends Form
{
public string $name = '';
public string $description = '';
public string $customer_id = '';
/** @var list<string> */
public array $service_unit_ids = [];
public string $starts_on = '';
public string $due_on = '';
public string $planned_from = '';
public string $planned_to = '';
public string $kind = JobKind::OneOff->value;
public string $status = JobStatus::Tentative->value;
public string $priority = Priority::Normal->value;
public string $payment_basis = '';
public string $estimated_hours = '';
public string $customer_reference = '';
public string $instructions = '';
public string $responsible_user_id = '';
public string $contact_user_id = '';
public string $customer_contact_id = '';
public string $biller_user_id = '';
public string $billing_unit_id = '';
/** @var list<string> */
public array $member_user_ids = [];
/** @var list<string> */
public array $tags = [];
/** @var list<array{title: string, url: string}> */
public array $links = [];
public function fillFromDetails(CustomerJobDetails $job): void
{
$this->name = $job->name;
$this->description = $job->description ?? '';
$this->customer_id = (string) $job->customer->id;
$this->service_unit_ids = array_map(fn (NamedId $unit): string => (string) $unit->id, $job->serviceUnits);
$this->starts_on = $job->startsOn ?? '';
$this->due_on = $job->dueOn ?? '';
$this->planned_from = $job->plannedFrom ?? '';
$this->planned_to = $job->plannedTo ?? '';
$this->kind = $job->kind->value;
$this->status = $job->status->value;
$this->priority = $job->priority->value;
$this->payment_basis = $job->paymentBasis->value ?? '';
$this->estimated_hours = $job->estimatedHours ?? '';
$this->customer_reference = $job->customerReference ?? '';
$this->instructions = $job->instructions ?? '';
$this->responsible_user_id = (string) $job->responsible->id;
$this->contact_user_id = (string) ($job->contactUser->id ?? '');
$this->customer_contact_id = (string) ($job->customerContact->id ?? '');
$this->biller_user_id = (string) ($job->biller->id ?? '');
$this->billing_unit_id = (string) ($job->billingUnit->id ?? '');
$this->member_user_ids = array_map(fn (NamedId $member): string => (string) $member->id, $job->members);
$this->tags = $job->tags;
$this->links = $job->links;
}
public function toData(): CustomerJobData
{
$this->validate();
$id = fn (string $value): ?int => $value === '' ? null : (int) $value;
$text = fn (string $value): ?string => trim($value) === '' ? null : $value;
return new CustomerJobData(
name: $this->name,
customerId: (int) $this->customer_id,
serviceUnitIds: array_map('intval', $this->service_unit_ids),
responsibleUserId: (int) $this->responsible_user_id,
kind: $this->kind,
status: $this->status,
priority: $this->priority,
description: $text($this->description),
startsOn: $text($this->starts_on),
dueOn: $text($this->due_on),
plannedFrom: $text($this->planned_from),
plannedTo: $text($this->planned_to),
paymentBasis: $text($this->payment_basis),
estimatedHours: $text($this->estimated_hours),
customerReference: $text($this->customer_reference),
instructions: $text($this->instructions),
contactUserId: $id($this->contact_user_id),
customerContactId: $id($this->customer_contact_id),
billerUserId: $id($this->biller_user_id),
billingUnitId: $id($this->billing_unit_id),
memberUserIds: array_map('intval', $this->member_user_ids),
tags: $this->tags,
links: array_values(array_filter($this->links, fn (array $link): bool => trim($link['title']) !== '' || trim($link['url']) !== '')),
);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match (true) {
$exception instanceof InvalidJobName => ['name', 'jobs.errors.invalid_name'],
$exception instanceof ServiceUnitRequired => ['service_unit_ids', 'jobs.errors.service_units_required'],
$exception instanceof DueBeforeStart => ['due_on', 'jobs.errors.due_before_start'],
$exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.errors.plan_ends_before_start'],
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
$exception instanceof InvalidTag => ['tags', 'jobs.errors.invalid_tag'],
$exception instanceof InvalidJobLink => ['links', 'jobs.errors.invalid_link'],
$exception instanceof InvalidJobReference => [self::referenceField($exception->field), 'jobs.errors.invalid_reference'],
default => throw $exception,
};
$this->addError($field, __($key));
}
private static function referenceField(string $field): string
{
return match ($field) {
'customer' => 'customer_id',
'service_units' => 'service_unit_ids',
'members' => 'member_user_ids',
default => $field.'_id',
};
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:10000'],
'customer_id' => ['required', 'integer'],
'service_unit_ids' => ['required', 'array', 'min:1'],
'service_unit_ids.*' => ['integer'],
'starts_on' => ['nullable', 'date_format:Y-m-d'],
'due_on' => ['nullable', 'date_format:Y-m-d'],
'planned_from' => ['nullable', 'date_format:Y-m-d'],
'planned_to' => ['nullable', 'date_format:Y-m-d'],
'kind' => ['required', Rule::enum(JobKind::class)],
'status' => ['required', Rule::enum(JobStatus::class)],
'priority' => ['required', Rule::enum(Priority::class)],
'payment_basis' => ['nullable', Rule::enum(PaymentBasis::class)],
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
'customer_reference' => ['nullable', 'string', 'max:255'],
'instructions' => ['nullable', 'string', 'max:10000'],
'responsible_user_id' => ['required', 'integer'],
'contact_user_id' => ['nullable', 'integer'],
'customer_contact_id' => ['nullable', 'integer'],
'biller_user_id' => ['nullable', 'integer'],
'billing_unit_id' => ['nullable', 'integer'],
'member_user_ids' => ['array'],
'member_user_ids.*' => ['integer'],
'tags' => ['array', 'max:30'],
'tags.*' => ['string', 'max:50'],
'links' => ['array', 'max:30'],
'links.*.title' => ['nullable', 'required_with:links.*.url', 'string', 'max:255'],
'links.*.url' => ['nullable', 'required_with:links.*.title', 'url:http,https', 'max:2000'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('jobs.errors.name_required'),
'name.max' => __('jobs.errors.invalid_name'),
'description.max' => __('jobs.errors.too_long', ['max' => 10000]),
'customer_id.required' => __('jobs.errors.customer_required'),
'customer_id.integer' => __('jobs.errors.customer_required'),
'service_unit_ids.required' => __('jobs.errors.service_units_required'),
'service_unit_ids.min' => __('jobs.errors.service_units_required'),
'*.date_format' => __('jobs.errors.invalid_date'),
'starts_on.date_format' => __('jobs.errors.invalid_date'),
'due_on.date_format' => __('jobs.errors.invalid_date'),
'planned_from.date_format' => __('jobs.errors.invalid_date'),
'planned_to.date_format' => __('jobs.errors.invalid_date'),
'estimated_hours.numeric' => __('jobs.errors.invalid_hours'),
'estimated_hours.min' => __('jobs.errors.invalid_hours'),
'estimated_hours.max' => __('jobs.errors.invalid_hours'),
'customer_reference.max' => __('jobs.errors.too_long', ['max' => 255]),
'instructions.max' => __('jobs.errors.too_long', ['max' => 10000]),
'responsible_user_id.required' => __('jobs.errors.responsible_required'),
'tags.*.max' => __('jobs.errors.invalid_tag'),
'links.*.title.required_with' => __('jobs.errors.invalid_link'),
'links.*.url.required_with' => __('jobs.errors.invalid_link'),
'links.*.url.url' => __('jobs.errors.invalid_link'),
];
}
}
@@ -0,0 +1,647 @@
<?php
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\Customers\Application\DTOs\CustomerDetailsData;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\UseCases\CreateCustomerJob;
use App\Modules\Jobs\Application\UseCases\UpdateCustomerJob;
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\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Presentation\Livewire\Forms\JobForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Create page (no {job}) and edit page (with {job}) of a customer job.
*/
new class extends Component
{
#[Locked]
public ?int $jobId = null;
#[Locked]
public string $jobNumber = '';
#[Locked]
public string $customerName = '';
/**
* The status stored before this edit: always offered, even when the
* user could not set it themselves.
*/
#[Locked]
public ?string $storedStatus = null;
public JobForm $form;
public string $customerSearch = '';
public string $newTag = '';
public string $statusMessage = '';
public function mount(CustomerJobQueries $jobQueries, ?int $job = null): void
{
$this->authorize('jobs.manage');
if ($job === null) {
$this->form->responsible_user_id = (string) auth()->id();
return;
}
$details = $jobQueries->findDetails($job);
abort_if($details === null, 404);
$this->jobId = $details->id;
$this->jobNumber = $details->number;
$this->customerName = $details->customer->name;
$this->storedStatus = $details->status->value;
$this->form->fillFromDetails($details);
}
/**
* @return list<CustomerSummary>
*/
#[Computed]
public function customerResults(): array
{
$term = trim($this->customerSearch);
return mb_strlen($term) < 2 ? [] : app(CustomerQueries::class)->search($term, 8);
}
/**
* @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 selectCustomer(int $customerId): void
{
$this->authorize('jobs.manage');
$customer = app(CustomerQueries::class)->findSummary($customerId);
if ($customer === null) {
return;
}
$this->useCustomer($customer->id, $customer->name);
}
public function createCustomer(RegisterCustomer $registerCustomer): void
{
$this->authorize('jobs.manage');
$this->authorize('customers.use');
$name = trim($this->customerSearch);
try {
$customerId = $registerCustomer->execute(new CustomerDetailsData($name, CustomerType::Company));
} catch (DomainException) {
$this->addError('customerSearch', __('customers.errors.invalid_name'));
return;
}
$this->useCustomer($customerId, $name);
$this->statusMessage = __('jobs.customer_picker.created', ['name' => $name]);
}
public function clearCustomer(): void
{
$this->form->customer_id = '';
$this->form->customer_contact_id = '';
$this->form->billing_unit_id = '';
$this->customerName = '';
$this->statusMessage = '';
$this->js("document.getElementById('customer-search')?.focus()");
}
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');
$status = JobStatus::tryFrom($this->form->status);
if ($status !== null && $status->value !== $this->storedStatus && ! $this->maySetStatus($status)) {
$this->addError('form.status', __('jobs.errors.status_not_allowed'));
return;
}
$data = $this->form->toData();
try {
if ($this->jobId === null) {
$jobId = $createJob->execute($data, (int) auth()->id());
$number = $jobQueries->findDetails($jobId)->number ?? '';
session()->flash('status', __('jobs.created', ['number' => $number, 'name' => trim($data->name)]));
} else {
$updateJob->execute($this->jobId, $data, (int) auth()->id());
$jobId = $this->jobId;
session()->flash('status', __('jobs.updated', ['number' => $this->jobNumber]));
}
} catch (CustomerJobNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('jobs.show', $jobId, navigate: true);
}
public function heading(): string
{
return $this->jobId === null ? __('jobs.create_title') : __('jobs.edit_title').' '.$this->jobNumber;
}
public function render(): mixed
{
return $this->view()->title($this->heading());
}
private function maySetStatus(JobStatus $status): bool
{
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]);
}
return true;
}
private function useCustomer(int $customerId, string $name): void
{
if ((string) $customerId !== $this->form->customer_id) {
$this->form->customer_contact_id = '';
$this->form->billing_unit_id = '';
}
$this->form->customer_id = (string) $customerId;
$this->customerName = $name;
$this->customerSearch = '';
$this->resetErrorBag(['customerSearch', 'form.customer_id']);
$this->js("document.getElementById('change-customer')?.focus()");
}
};
?>
@php
$userOptions = collect($this->users)->map(fn ($user) => [
'value' => $user->id,
'label' => $user->name,
'note' => $user->role === Role::Subcontractor ? __('users.roles.subcontractor') : null,
])->all();
$staffOptions = collect($this->users)->reject(fn ($user) => $user->role === Role::Subcontractor);
@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>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
<form wire:submit="save" class="space-y-8" novalidate>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.basics') }}</legend>
<x-input wire:model="form.name" :label="__('jobs.fields.name')" autocomplete="off" required />
{{-- Customer: search field and results as buttons, or the chosen customer. --}}
<div class="space-y-2">
@if ($form->customer_id !== '')
<p class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ __('jobs.fields.customer') }}</p>
<div class="flex flex-wrap items-center gap-3">
<span class="font-medium">{{ $customerName }}</span>
<x-button
id="change-customer"
wire:click="clearCustomer"
subtle
color="black"
sm
:text="__('jobs.customer_picker.change')"
:aria-label="__('jobs.customer_picker.change').': '.$customerName"
/>
</div>
@else
<x-input
id="customer-search"
wire:model.live.debounce.300ms="customerSearch"
type="search"
icon="magnifying-glass"
:label="__('jobs.customer_picker.search')"
:hint="__('jobs.customer_picker.search_description')"
autocomplete="off"
required
/>
@error('form.customer_id')
<p class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
@if (mb_strlen(trim($customerSearch)) >= 2)
<p role="status" aria-live="polite" class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('jobs.customer_picker.results', count($this->customerResults), ['count' => count($this->customerResults)]) }}
</p>
<ul class="space-y-1">
@foreach ($this->customerResults as $customer)
<li wire:key="customer-result-{{ $customer->id }}">
<button
type="button"
wire:click="selectCustomer({{ $customer->id }})"
class="w-full 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"
aria-label="{{ __('jobs.customer_picker.choose', ['name' => $customer->name]) }}"
>
<span class="font-medium">{{ $customer->name }}</span>
@if ($customer->businessId !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $customer->businessId }}</span>
@endif
</button>
</li>
@endforeach
</ul>
@can('customers.use')
<x-button
wire:click="createCustomer"
subtle
color="black"
sm
icon="plus"
:text="__('jobs.customer_picker.create', ['name' => trim($customerSearch)])"
/>
@endcan
@endif
@endif
</div>
<x-textarea wire:model="form.description" :label="__('jobs.fields.description')" resize-auto />
<x-checkbox-group
:legend="__('jobs.fields.service_units')"
model="form.service_unit_ids"
:options="$this->serviceUnitOptions"
/>
</fieldset>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.schedule') }}</legend>
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model="form.starts_on" type="date" :label="__('jobs.fields.starts_on')" />
<x-input wire:model="form.due_on" type="date" :label="__('jobs.fields.due_on')" />
<x-input wire:model="form.planned_from" type="date" :label="__('jobs.fields.planned_from')" />
<x-input wire:model="form.planned_to" type="date" :label="__('jobs.fields.planned_to')" />
</div>
</fieldset>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.classification') }}</legend>
<div class="grid gap-6 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.status" :label="__('jobs.fields.status')" :aria-label="__('jobs.fields.status')">
@foreach ($this->statusOptions as $status)
<option value="{{ $status->value }}">{{ __('jobs.statuses.'.$status->value) }}</option>
@endforeach
</x-select.native>
<x-select.native 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>
<x-select.native wire:model="form.kind" :label="__('jobs.fields.kind')" :aria-label="__('jobs.fields.kind')">
@foreach (JobKind::cases() as $kind)
<option value="{{ $kind->value }}">{{ __('jobs.kinds.'.$kind->value) }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model="form.payment_basis" :label="__('jobs.fields.payment_basis')" :aria-label="__('jobs.fields.payment_basis')">
<option value="">{{ __('jobs.fields.no_payment_basis') }}</option>
@foreach (PaymentBasis::cases() as $basis)
<option value="{{ $basis->value }}">{{ __('jobs.payment_bases.'.$basis->value) }}</option>
@endforeach
</x-select.native>
<x-input
wire:model="form.estimated_hours"
type="number"
step="0.25"
min="0"
inputmode="decimal"
:label="__('jobs.fields.estimated_hours')"
:hint="__('jobs.fields.estimated_hours_description')"
/>
</div>
</fieldset>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.members') }}</legend>
<div class="grid gap-6 sm:grid-cols-2">
<x-select.native 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 ($staffOptions as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model="form.contact_user_id" :label="__('jobs.fields.contact_user')" :aria-label="__('jobs.fields.contact_user')" :hint="__('jobs.fields.contact_user_description')">
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($staffOptions as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model="form.biller_user_id" :label="__('jobs.fields.biller_user')" :aria-label="__('jobs.fields.biller_user')" :hint="__('jobs.fields.biller_user_description')">
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($staffOptions as $user)
<option value="{{ $user->id }}">{{ $user->name }}</option>
@endforeach
</x-select.native>
<x-select.native
wire:model="form.customer_contact_id"
:label="__('jobs.fields.customer_contact')"
:aria-label="__('jobs.fields.customer_contact')"
:hint="$form->customer_id === '' ? __('jobs.customer_picker.choose_customer_first') : null"
:disabled="$form->customer_id === ''"
>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->contacts as $contact)
<option wire:key="contact-{{ $contact->id }}" value="{{ $contact->id }}">{{ $contact->name }}</option>
@endforeach
</x-select.native>
<x-select.native
wire:model="form.billing_unit_id"
:label="__('jobs.fields.billing_unit')"
:aria-label="__('jobs.fields.billing_unit')"
:hint="$form->customer_id === '' ? __('jobs.customer_picker.choose_customer_first') : null"
:disabled="$form->customer_id === ''"
>
<option value="">{{ __('jobs.fields.none_selected') }}</option>
@foreach ($this->billingUnits as $billingUnit)
<option wire:key="billing-unit-{{ $billingUnit->id }}" value="{{ $billingUnit->id }}">{{ $billingUnit->name }}</option>
@endforeach
</x-select.native>
</div>
<x-checkbox-group
:legend="__('jobs.fields.members')"
:hint="__('jobs.fields.members_description')"
model="form.member_user_ids"
:options="$userOptions"
/>
</fieldset>
<fieldset class="space-y-6">
<legend class="text-lg font-semibold">{{ __('jobs.sections.extra') }}</legend>
<x-input wire:model="form.customer_reference" :label="__('jobs.fields.customer_reference')" autocomplete="off" />
{{-- Tags: free text with suggestions from earlier tags, added one at a time. --}}
<div class="space-y-3">
<div class="flex flex-wrap items-end gap-3">
<div class="min-w-0 flex-1">
<x-input
id="new-tag"
wire:model.live.debounce.300ms="newTag"
wire:keydown.enter.prevent="addTag"
list="tag-suggestions"
:label="__('jobs.tags.new')"
:hint="__('jobs.tags.new_description')"
autocomplete="off"
/>
<datalist id="tag-suggestions">
@foreach ($this->tagSuggestions as $suggestion)
<option value="{{ $suggestion }}"></option>
@endforeach
</datalist>
</div>
<x-button wire:click="addTag" subtle color="black" icon="plus" :text="__('jobs.tags.add')" />
</div>
<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>
@else
<ul aria-labelledby="tags-label" class="flex flex-wrap gap-2">
@foreach ($form->tags as $index => $tag)
<li wire:key="tag-{{ $tag }}" class="inline-flex items-center gap-1 rounded-full border border-zinc-300 py-1 pr-1 pl-3 text-sm dark:border-zinc-600">
{{ $tag }}
<x-button.circle
wire:click="removeTag({{ $index }})"
subtle
color="black"
xs
icon="x-mark"
:aria-label="__('jobs.tags.remove', ['tag' => $tag])"
/>
</li>
@endforeach
</ul>
@endif
@error('form.tags')
<p class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</div>
{{-- Links: title and address per row. --}}
<div class="space-y-3">
<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>
@endif
@foreach ($form->links as $index => $link)
<fieldset wire:key="link-{{ $index }}" class="space-y-3 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
<legend class="px-1 text-sm font-medium">{{ __('jobs.links.link_number', ['number' => $index + 1]) }}</legend>
<div class="grid gap-3 sm:grid-cols-2">
<x-input id="link-title-{{ $index }}" wire:model="form.links.{{ $index }}.title" :label="__('jobs.links.title')" autocomplete="off" />
<x-input id="link-url-{{ $index }}" wire:model="form.links.{{ $index }}.url" type="url" :label="__('jobs.links.url')" :hint="__('jobs.links.url_description')" autocomplete="off" />
</div>
<x-button
wire:click="removeLink({{ $index }})"
subtle
color="black"
sm
icon="trash"
:text="__('jobs.links.remove', ['number' => $index + 1])"
/>
</fieldset>
@endforeach
<x-button id="add-link" wire:click="addLink" subtle color="black" sm icon="plus" :text="__('jobs.links.add')" />
@error('form.links')
<p class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</div>
<x-textarea wire:model="form.instructions" :label="__('jobs.fields.instructions')" :hint="__('jobs.fields.instructions_description')" resize-auto />
</fieldset>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('jobs.save')" />
<x-button
:href="$jobId === null ? route('jobs.index') : route('jobs.show', $jobId)"
wire:navigate
subtle
color="black"
:text="__('jobs.cancel')"
/>
</div>
</form>
</div>
@@ -0,0 +1,190 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
/**
* The customer job list: search, filters and "my jobs" on by default.
*/
new class extends Component
{
use WithPagination;
#[Url(as: 'q', except: '')]
public string $search = '';
#[Url(except: '')]
public string $status = '';
#[Url(except: '')]
public string $priority = '';
#[Url(as: 'unit', except: '')]
public string $serviceUnit = '';
#[Url(except: true)]
public bool $mine = true;
#[Url(except: false)]
public bool $archived = false;
public function mount(): void
{
$this->authorize('jobs.view');
}
public function updated(string $property): void
{
if (in_array($property, ['search', 'status', 'priority', 'serviceUnit', 'mine', 'archived'], true)) {
$this->resetPage();
}
}
public function isSubcontractor(): bool
{
return auth()->user()?->role === Role::Subcontractor;
}
/**
* @return LengthAwarePaginator<int, CustomerJobSummary>
*/
#[Computed]
public function jobs(): LengthAwarePaginator
{
$userId = (int) auth()->id();
return app(CustomerJobQueries::class)->paginate(new JobListFilter(
search: $this->search,
status: JobStatus::tryFrom($this->status)?->value,
priority: Priority::tryFrom($this->priority)?->value,
serviceUnitId: $this->serviceUnit === '' ? null : (int) $this->serviceUnit,
mineForUserId: $this->mine && ! $this->isSubcontractor() ? $userId : null,
onlyMemberUserId: $this->isSubcontractor() ? $userId : null,
includeArchived: $this->archived,
));
}
/**
* @return list<array{index: string, label: string, sortable: bool}>
*/
public function headers(): array
{
return [
['index' => 'number', 'label' => __('jobs.fields.number'), 'sortable' => false],
['index' => 'name', 'label' => __('jobs.fields.name'), 'sortable' => false],
['index' => 'customerName', 'label' => __('jobs.fields.customer'), 'sortable' => false],
['index' => 'status', 'label' => __('jobs.fields.status'), 'sortable' => false],
['index' => 'priority', 'label' => __('jobs.fields.priority'), 'sortable' => false],
['index' => 'dueOn', 'label' => __('jobs.fields.due_on'), 'sortable' => false],
['index' => 'responsibleName', 'label' => __('jobs.fields.responsible_user'), 'sortable' => false],
];
}
public function render(): mixed
{
return $this->view()->title(__('jobs.title'));
}
};
?>
<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">
<h1 class="text-2xl font-semibold">{{ __('jobs.title') }}</h1>
@can('jobs.manage')
<x-button :href="route('jobs.create')" wire:navigate icon="plus" :text="__('jobs.new')" />
@endcan
</div>
@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>
@endif
<div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<div class="md:col-span-2 xl:col-span-4">
<x-input
wire:model.live.debounce.300ms="search"
type="search"
icon="magnifying-glass"
:label="__('jobs.list.search')"
:hint="__('jobs.list.search_description')"
/>
</div>
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="status" :label="__('jobs.fields.status')" :aria-label="__('jobs.fields.status')">
<option value="">{{ __('jobs.list.all_statuses') }}</option>
@foreach (JobStatus::cases() as $option)
<option value="{{ $option->value }}">{{ __('jobs.statuses.'.$option->value) }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model.live="priority" :label="__('jobs.fields.priority')" :aria-label="__('jobs.fields.priority')">
<option value="">{{ __('jobs.list.all_priorities') }}</option>
@foreach (Priority::cases() as $option)
<option value="{{ $option->value }}">{{ __('jobs.priorities.'.$option->value) }}</option>
@endforeach
</x-select.native>
<x-select.native wire:model.live="serviceUnit" :label="__('jobs.fields.service_units')" :aria-label="__('jobs.fields.service_units')">
<option value="">{{ __('jobs.list.all_service_units') }}</option>
@foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit)
<option value="{{ $unit->id }}">{{ $unit->name }}</option>
@endforeach
</x-select.native>
<div class="space-y-2">
@unless ($this->isSubcontractor())
<x-checkbox id="only-mine" wire:model.live="mine" :label="__('jobs.list.only_mine')" />
@endunless
<x-checkbox id="include-archived" wire:model.live="archived" :label="__('jobs.list.include_archived')" />
</div>
</div>
<p role="status" aria-live="polite" aria-atomic="true" class="text-sm text-zinc-600 dark:text-zinc-300">
{{ trans_choice('jobs.list.result_count', $this->jobs->total(), ['count' => $this->jobs->total()]) }}
@if ($mine && ! $this->isSubcontractor())
– {{ __('jobs.list.only_mine_description') }}
@endif
</p>
@if ($this->jobs->total() === 0)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.list.empty') }}</p>
@else
<x-table :headers="$this->headers()" :rows="$this->jobs" paginate>
@interact('column_number', $job)
<span class="whitespace-nowrap">{{ $job->number }}</span>
@endinteract
@interact('column_name', $job)
<x-link :href="route('jobs.show', $job->id)" navigate class="font-medium">{{ $job->name }}</x-link>
@endinteract
@interact('column_status', $job)
{{ __('jobs.statuses.'.$job->status->value) }}
@endinteract
@interact('column_priority', $job)
<x-jobs.priority :priority="$job->priority" />
@endinteract
@interact('column_dueOn', $job)
<x-jobs.due-date :date="$job->dueOn" :status="$job->status" />
@endinteract
</x-table>
@endif
</div>
@@ -0,0 +1,240 @@
<?php
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\Users\Application\Contracts\UserAccountQueries;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A customer job's page: details, members, links, instructions and history.
*/
new class extends Component
{
#[Locked]
public int $jobId;
public function mount(CustomerJobQueries $jobQueries, int $job): void
{
$this->authorize('jobs.view');
abort_if($jobQueries->findDetails($job) === null, 404);
$this->authorize('jobs.view-job', $job);
$this->jobId = $job;
}
#[Computed]
public function job(): CustomerJobDetails
{
return app(CustomerJobQueries::class)->findDetails($this->jobId) ?? abort(404);
}
/**
* @return list<JobChangeEntry>
*/
#[Computed]
public function changes(): array
{
return app(CustomerJobQueries::class)->changes($this->jobId);
}
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),
'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);
}
};
?>
@php($job = $this->job)
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-4">
<div class="flex flex-wrap items-start justify-between gap-4">
<h1 class="text-2xl font-semibold break-words">
<span class="whitespace-nowrap">{{ $job->number }}</span> {{ $job->name }}
</h1>
@can('jobs.manage')
<x-button :href="route('jobs.edit', $job->id)" wire:navigate subtle color="black" icon="pencil" :text="__('jobs.edit')" />
@endcan
</div>
@if (session('status'))
<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>
<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">
<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]">
<dt class="font-medium">{{ __('jobs.fields.customer') }}</dt>
<dd>
@can('customers.use')
<x-link :href="route('customers.show', $job->customer->id)" navigate>{{ $job->customer->name }}</x-link>
@else
{{ $job->customer->name }}
@endcan
</dd>
<dt class="font-medium">{{ __('jobs.fields.service_units') }}</dt>
<dd>{{ collect($job->serviceUnits)->pluck('name')->join(', ') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.kind') }}</dt>
<dd>{{ __('jobs.kinds.'.$job->kind->value) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.payment_basis') }}</dt>
<dd>{{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.estimated_hours') }}</dt>
<dd>{{ $job->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $job->estimatedHours).' h' }}</dd>
<dt class="font-medium">{{ __('jobs.fields.customer_reference') }}</dt>
<dd class="break-words">{{ $job->customerReference ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.tags') }}</dt>
<dd>{{ $job->tags === [] ? __('jobs.tags.none') : implode(', ', $job->tags) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.created_at') }}</dt>
<dd>{{ CarbonImmutable::parse($job->createdAt)->format('j.n.Y H.i') }}, {{ $job->createdByName }}</dd>
</dl>
@if ($job->description !== null)
<h3 class="text-base font-semibold">{{ __('jobs.fields.description') }}</h3>
<p class="whitespace-pre-line text-sm">{{ $job->description }}</p>
@endif
</section>
<section aria-labelledby="schedule-heading" class="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]">
<dt class="font-medium">{{ __('jobs.fields.starts_on') }}</dt>
<dd>{{ $this->formatDate($job->startsOn) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.due_on') }}</dt>
<dd><x-jobs.due-date :date="$job->dueOn" :status="$job->status" /></dd>
<dt class="font-medium">{{ __('jobs.fields.planned_from') }}</dt>
<dd>{{ $this->formatDate($job->plannedFrom) }}</dd>
<dt class="font-medium">{{ __('jobs.fields.planned_to') }}</dt>
<dd>{{ $this->formatDate($job->plannedTo) }}</dd>
</dl>
</section>
<section aria-labelledby="members-heading" class="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]">
<dt class="font-medium">{{ __('jobs.fields.responsible_user') }}</dt>
<dd>{{ $job->responsible->name }}</dd>
<dt class="font-medium">{{ __('jobs.fields.contact_user') }}</dt>
<dd>{{ $job->contactUser->name ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.customer_contact') }}</dt>
<dd>{{ $job->customerContact->name ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.biller_user') }}</dt>
<dd>{{ $job->biller->name ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.billing_unit') }}</dt>
<dd>{{ $job->billingUnit->name ?? __('jobs.not_set') }}</dd>
<dt class="font-medium">{{ __('jobs.fields.members') }}</dt>
<dd>{{ $job->members === [] ? __('jobs.not_set') : collect($job->members)->pluck('name')->join(', ') }}</dd>
</dl>
</section>
<section aria-labelledby="links-heading" class="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>
@else
<ul class="list-disc space-y-1 pl-5 text-sm">
@foreach ($job->links as $link)
<li class="break-all">
<x-link :href="$link['url']" target="_blank" rel="noopener noreferrer">
{{ $link['title'] }}<span class="sr-only"> ({{ __('jobs.opens_in_new_tab') }})</span>
</x-link>
</li>
@endforeach
</ul>
@endif
</section>
<section aria-labelledby="instructions-heading" class="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">
<h2 id="history-heading" class="text-xl font-semibold">{{ __('jobs.sections.history') }}</h2>
@if ($this->changes === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.history.empty') }}</p>
@else
<ol class="space-y-2 text-sm">
@foreach ($this->changes as $change)
<li class="border-b border-zinc-200 pb-2 dark:border-zinc-700">
@if ($change->field === 'created')
{{ __('jobs.history.created', ['user' => $change->userName, 'number' => $change->newValue]) }}
@else
<span class="break-words">{{ __('jobs.history.changed', [
'field' => __('jobs.fields.'.$change->field),
'old' => $this->historyValue($change->field, $change->oldValue),
'new' => $this->historyValue($change->field, $change->newValue),
]) }}</span>
@endif
<span class="block text-zinc-600 dark:text-zinc-300">
{{ __('jobs.history.by', ['user' => $change->userName, 'time' => CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i')]) }}
</span>
</li>
@endforeach
</ol>
@endif
</section>
</div>
@@ -0,0 +1,13 @@
<?php
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth', 'can:jobs.view'])
->prefix('jobs')
->name('jobs.')
->group(function () {
Route::livewire('/', 'jobs::index')->name('index');
Route::livewire('/create', 'jobs::form')->middleware('can:jobs.manage')->name('create');
Route::livewire('/{job}', 'jobs::show')->whereNumber('job')->name('show');
Route::livewire('/{job}/edit', 'jobs::form')->whereNumber('job')->middleware('can:jobs.manage')->name('edit');
});