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
+3 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project ## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers` and `Catalog`: service units, services and work types, managed on the Pohjatiedot page); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page) and `Jobs` (customer jobs: numbering, members, tags, links, history)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
@@ -22,7 +22,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages.
- Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules.
- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`.
- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`).
- `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`.
- Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. - Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files.
@@ -39,6 +39,7 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
- `<tallstackui:script />`: root-relative asset URLs that 404 in a subfolder (local XAMPP). The layout includes `resources/views/partials/tallstackui-script.blade.php` instead. - `<tallstackui:script />`: root-relative asset URLs that 404 in a subfolder (local XAMPP). The layout includes `resources/views/partials/tallstackui-script.blade.php` instead.
- `<x-select.native>`: the label is not tied to the control, so also pass `:aria-label` with the same text. - `<x-select.native>`: the label is not tied to the control, so also pass `:aria-label` with the same text.
- `<x-modal>`: `aria-labelledby` points at an id its title lacks, the close button has no name, and focus neither moves in nor returns. Use `<x-confirm-dialog>` (`resources/views/components/confirm-dialog.blade.php`, native `<dialog>` + `showModal()`), opened from Livewire with `$this->js("document.getElementById('<id>').showModal()")`; see `customers::show`. - `<x-modal>`: `aria-labelledby` points at an id its title lacks, the close button has no name, and focus neither moves in nor returns. Use `<x-confirm-dialog>` (`resources/views/components/confirm-dialog.blade.php`, native `<dialog>` + `showModal()`), opened from Livewire with `$this->js("document.getElementById('<id>').showModal()")`; see `customers::show`.
- Groups of checkboxes for an array property: `<x-checkbox-group>` (`resources/views/components/checkbox-group.blade.php`, fieldset + legend + native inputs). Searchable choices (customer on the job form) are a search input with result buttons and a `role="status"` count, not `<x-select.styled>`.
- Solid `color="red"` buttons: white on red-500 is 3.5:1, so the solid red is red-700 in the published `NormalButtonColors`. - Solid `color="red"` buttons: white on red-500 is 3.5:1, so the solid red is red-700 in the published `NormalButtonColors`.
- `<x-input>` without `wire:model` (e.g. a read-only value): pass an explicit `id`, or the label is not tied to it. `<x-clipboard>` has an unlabelled input and a button whose name changes; build copy fields from `<x-input readonly>` + `<x-button>` + a `role="status"` message instead (see `users::form`). - `<x-input>` without `wire:model` (e.g. a read-only value): pass an explicit `id`, or the label is not tied to it. `<x-clipboard>` has an unlabelled input and a button whose name changes; build copy fields from `<x-input readonly>` + `<x-button>` + a `role="status"` message instead (see `users::form`).
- Contrast: the primary palette is one step darker (`resources/css/app.css`); error text, label error and asterisk, and input/select error colours are changed by soft customization in `App\Providers\AppServiceProvider`; light alert and link text colours are in published colour classes `app/View/Components/TallStackUi/Colors/`. `flat` and `outline` buttons have no dark-mode text colour: use `subtle color="black"` for neutral buttons. - Contrast: the primary palette is one step darker (`resources/css/app.css`); error text, label error and asterisk, and input/select error colours are changed by soft customization in `App\Providers\AppServiceProvider`; light alert and link text colours are in published colour classes `app/View/Components/TallStackUi/Colors/`. `flat` and `outline` buttons have no dark-mode text colour: use `subtle color="black"` for neutral buttons.
@@ -40,6 +40,14 @@ interface CatalogQueries
public function findServiceUnit(int $id): ?ServiceUnitSummary; public function findServiceUnit(int $id): ?ServiceUnitSummary;
/**
* Service unit names for many ids at once, active or not.
*
* @param list<int> $ids
* @return array<int, string>
*/
public function serviceUnitNames(array $ids): array;
public function findService(int $id): ?ServiceSummary; public function findService(int $id): ?ServiceSummary;
public function findWorkType(int $id): ?WorkTypeSummary; public function findWorkType(int $id): ?WorkTypeSummary;
@@ -49,6 +49,11 @@ class EloquentCatalogQueries implements CatalogQueries
return $model === null ? null : $this->toServiceUnitSummary($model); return $model === null ? null : $this->toServiceUnitSummary($model);
} }
public function serviceUnitNames(array $ids): array
{
return $ids === [] ? [] : ServiceUnitModel::query()->whereIn('id', $ids)->orderBy('sort_order')->pluck('name', 'id')->all();
}
public function findService(int $id): ?ServiceSummary public function findService(int $id): ?ServiceSummary
{ {
$model = ServiceModel::query()->find($id); $model = ServiceModel::query()->find($id);
@@ -17,6 +17,14 @@ interface CustomerQueries
{ {
public function findSummary(int $id): ?CustomerSummary; public function findSummary(int $id): ?CustomerSummary;
/**
* Customer names for many ids at once (for lists in other modules).
*
* @param list<int> $ids
* @return array<int, string>
*/
public function namesByIds(array $ids): array;
/** /**
* The full personal identity code. Sensitive: call only after checking * The full personal identity code. Sensitive: call only after checking
* the customers.view-personal-identity-code ability, and never log it. * the customers.view-personal-identity-code ability, and never log it.
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\Contracts;
/**
* Whether other modules refer to a contact or billing unit, so it is not
* removed while in use. The Jobs module provides the real answer; without
* it nothing is in use.
*/
interface CustomerRowUsage
{
public function isContactInUse(int $contactId): bool;
public function isBillingUnitInUse(int $billingUnitId): bool;
}
@@ -21,6 +21,7 @@ final readonly class CustomerSummary
public CustomerType $type, public CustomerType $type,
public ?string $businessId, public ?string $businessId,
public ?string $personalIdentityCodeMasked = null, public ?string $personalIdentityCodeMasked = null,
public bool $isInternal = false,
) {} ) {}
public function hasPersonalIdentityCode(): bool public function hasPersonalIdentityCode(): bool
@@ -4,23 +4,26 @@ declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases; namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository; use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Exceptions\BillingUnitInUse;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound; use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Application\Contracts\TransactionManager;
/** /**
* Deletes a billing unit. Nothing refers to billing units yet; once customer * Deletes a billing unit that no customer job has chosen.
* jobs and invoices do, a billing unit in use cannot be removed.
*/ */
final class RemoveBillingUnit final class RemoveBillingUnit
{ {
public function __construct( public function __construct(
private BillingUnitRepository $billingUnits, private BillingUnitRepository $billingUnits,
private CustomerRowUsage $usage,
private TransactionManager $transactions, private TransactionManager $transactions,
) {} ) {}
/** /**
* @throws BillingUnitNotFound * @throws BillingUnitNotFound
* @throws BillingUnitInUse
*/ */
public function execute(int $customerId, int $billingUnitId): void public function execute(int $customerId, int $billingUnitId): void
{ {
@@ -28,6 +31,10 @@ final class RemoveBillingUnit
$billingUnit = $this->billingUnits->findForCustomer($customerId, $billingUnitId) $billingUnit = $this->billingUnits->findForCustomer($customerId, $billingUnitId)
?? throw new BillingUnitNotFound($customerId, $billingUnitId); ?? throw new BillingUnitNotFound($customerId, $billingUnitId);
if ($this->usage->isBillingUnitInUse($billingUnitId)) {
throw new BillingUnitInUse;
}
$this->billingUnits->delete($billingUnit); $this->billingUnits->delete($billingUnit);
}); });
} }
@@ -4,23 +4,26 @@ declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases; namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository; use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Exceptions\ContactInUse;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound; use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Application\Contracts\TransactionManager;
/** /**
* Deletes a contact. Nothing refers to contacts yet; once customer jobs do, * Deletes a contact that no customer job has chosen.
* a contact in use cannot be removed.
*/ */
final class RemoveContact final class RemoveContact
{ {
public function __construct( public function __construct(
private CustomerContactRepository $contacts, private CustomerContactRepository $contacts,
private CustomerRowUsage $usage,
private TransactionManager $transactions, private TransactionManager $transactions,
) {} ) {}
/** /**
* @throws ContactNotFound * @throws ContactNotFound
* @throws ContactInUse
*/ */
public function execute(int $customerId, int $contactId): void public function execute(int $customerId, int $contactId): void
{ {
@@ -28,6 +31,10 @@ final class RemoveContact
$contact = $this->contacts->findForCustomer($customerId, $contactId) $contact = $this->contacts->findForCustomer($customerId, $contactId)
?? throw new ContactNotFound($customerId, $contactId); ?? throw new ContactNotFound($customerId, $contactId);
if ($this->usage->isContactInUse($contactId)) {
throw new ContactInUse;
}
$this->contacts->delete($contact); $this->contacts->delete($contact);
}); });
} }
@@ -7,6 +7,7 @@ namespace App\Modules\Customers\Domain\Entities;
use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId; use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany;
use App\Modules\Customers\Domain\ValueObjects\BusinessId; use App\Modules\Customers\Domain\ValueObjects\BusinessId;
use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
@@ -25,8 +26,10 @@ final class Customer
private CustomerType $type, private CustomerType $type,
private ?BusinessId $businessId, private ?BusinessId $businessId,
private ?PersonalIdentityCode $personalIdentityCode, private ?PersonalIdentityCode $personalIdentityCode,
private bool $internal = false,
) { ) {
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode); self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
self::ensureInternalIsCompany($internal, $type);
} }
/** /**
@@ -50,8 +53,9 @@ final class Customer
CustomerType $type, CustomerType $type,
?BusinessId $businessId, ?BusinessId $businessId,
?PersonalIdentityCode $personalIdentityCode = null, ?PersonalIdentityCode $personalIdentityCode = null,
bool $internal = false,
): self { ): self {
return new self($id, $name, $type, $businessId, $personalIdentityCode); return new self($id, $name, $type, $businessId, $personalIdentityCode, $internal);
} }
/** /**
@@ -69,6 +73,7 @@ final class Customer
} }
self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode); self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode);
self::ensureInternalIsCompany($this->internal, $type);
$this->name = $name; $this->name = $name;
$this->type = $type; $this->type = $type;
@@ -106,6 +111,22 @@ final class Customer
return $this->personalIdentityCode; return $this->personalIdentityCode;
} }
/**
* The company itself, whose jobs hold internal work (administration,
* sales, training). Created by a migration, never through the UI.
*/
public function isInternal(): bool
{
return $this->internal;
}
private static function ensureInternalIsCompany(bool $internal, CustomerType $type): void
{
if ($internal && $type !== CustomerType::Company) {
throw new InternalCustomerMustBeCompany;
}
}
private static function ensureIdentifiersFitType( private static function ensureIdentifiersFitType(
CustomerType $type, CustomerType $type,
?BusinessId $businessId, ?BusinessId $businessId,
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class BillingUnitInUse extends DomainException
{
public function __construct()
{
parent::__construct('The billing unit is chosen on a customer job.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class ContactInUse extends DomainException
{
public function __construct()
{
parent::__construct('The contact is chosen on a customer job.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InternalCustomerMustBeCompany extends DomainException
{
public function __construct()
{
parent::__construct('The internal customer is the company itself and cannot be a consumer.');
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Modules\Customers\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
/**
* Default when no module refers to contacts or billing units.
*/
class NothingUsesCustomerRows implements CustomerRowUsage
{
public function isContactInUse(int $contactId): bool
{
return false;
}
public function isBillingUnitInUse(int $billingUnitId): bool
{
return false;
}
}
@@ -22,6 +22,7 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $business_id * @property string|null $business_id
* @property string|null $personal_identity_code Decrypted by the cast; sensitive. * @property string|null $personal_identity_code Decrypted by the cast; sensitive.
* @property string|null $personal_identity_code_hash * @property string|null $personal_identity_code_hash
* @property bool $is_internal
*/ */
#[Table('customers')] #[Table('customers')]
#[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash'])] #[Fillable(['name', 'type', 'business_id', 'personal_identity_code', 'personal_identity_code_hash'])]
@@ -40,6 +41,7 @@ class CustomerModel extends Model
return [ return [
'type' => CustomerType::class, 'type' => CustomerType::class,
'personal_identity_code' => 'encrypted', 'personal_identity_code' => 'encrypted',
'is_internal' => 'boolean',
]; ];
} }
} }
@@ -22,6 +22,11 @@ class EloquentCustomerQueries implements CustomerQueries
return $model === null ? null : $this->toSummary($model); return $model === null ? null : $this->toSummary($model);
} }
public function namesByIds(array $ids): array
{
return $ids === [] ? [] : CustomerModel::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
}
public function personalIdentityCodeOf(int $customerId): ?string public function personalIdentityCodeOf(int $customerId): ?string
{ {
return CustomerModel::query()->find($customerId)?->personal_identity_code; return CustomerModel::query()->find($customerId)?->personal_identity_code;
@@ -106,7 +111,7 @@ class EloquentCustomerQueries implements CustomerQueries
? null ? null
: (new PersonalIdentityCode($model->personal_identity_code))->masked(); : (new PersonalIdentityCode($model->personal_identity_code))->masked();
return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked); return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal);
} }
private function toContactSummary(CustomerContactModel $model): ContactSummary private function toContactSummary(CustomerContactModel $model): ContactSummary
@@ -62,6 +62,7 @@ class EloquentCustomerRepository implements CustomerRepository
$model->type, $model->type,
$model->business_id === null ? null : new BusinessId($model->business_id), $model->business_id === null ? null : new BusinessId($model->business_id),
$model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code), $model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code),
(bool) $model->is_internal,
); );
} }
} }
@@ -4,9 +4,11 @@ namespace App\Modules\Customers\Infrastructure\Providers;
use App\Models\User; use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries; use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Customers\Domain\Contracts\BillingUnitRepository; use App\Modules\Customers\Domain\Contracts\BillingUnitRepository;
use App\Modules\Customers\Domain\Contracts\CustomerContactRepository; use App\Modules\Customers\Domain\Contracts\CustomerContactRepository;
use App\Modules\Customers\Domain\Contracts\CustomerRepository; use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Infrastructure\NothingUsesCustomerRows;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentBillingUnitRepository; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentBillingUnitRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerContactRepository; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerContactRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries;
@@ -30,6 +32,8 @@ class CustomersServiceProvider extends ServiceProvider
CustomerQueries::class => EloquentCustomerQueries::class, CustomerQueries::class => EloquentCustomerQueries::class,
CustomerContactRepository::class => EloquentCustomerContactRepository::class, CustomerContactRepository::class => EloquentCustomerContactRepository::class,
BillingUnitRepository::class => EloquentBillingUnitRepository::class, BillingUnitRepository::class => EloquentBillingUnitRepository::class,
// Replaced by the Jobs module, which knows which rows its jobs use.
CustomerRowUsage::class => NothingUsesCustomerRows::class,
]; ];
public function boot(): void public function boot(): void
@@ -8,6 +8,7 @@ use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse; use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse;
use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode;
use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId; use App\Modules\Customers\Domain\Exceptions\ConsumerCannotHaveBusinessId;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerMustBeCompany;
use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId; use App\Modules\Customers\Domain\Exceptions\InvalidBusinessId;
use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName; use App\Modules\Customers\Domain\Exceptions\InvalidCustomerName;
use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode; use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode;
@@ -71,6 +72,7 @@ class CustomerForm extends Form
BusinessIdAlreadyInUse::class => ['business_id', 'customers.errors.business_id_taken'], BusinessIdAlreadyInUse::class => ['business_id', 'customers.errors.business_id_taken'],
InvalidPersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.invalid_personal_identity_code'], InvalidPersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.invalid_personal_identity_code'],
CompanyCannotHavePersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.company_personal_identity_code'], CompanyCannotHavePersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.company_personal_identity_code'],
InternalCustomerMustBeCompany::class => ['type', 'customers.errors.internal_must_be_company'],
PersonalIdentityCodeAlreadyInUse::class => ['personal_identity_code', 'customers.errors.personal_identity_code_taken'], PersonalIdentityCodeAlreadyInUse::class => ['personal_identity_code', 'customers.errors.personal_identity_code_taken'],
default => throw $exception, default => throw $exception,
}; };
@@ -90,6 +90,9 @@ new class extends Component
<x-table :headers="$this->headers()" :rows="$this->customers" paginate> <x-table :headers="$this->headers()" :rows="$this->customers" paginate>
@interact('column_name', $customer) @interact('column_name', $customer)
<x-link :href="route('customers.show', $customer->id)" navigate class="font-medium">{{ $customer->name }}</x-link> <x-link :href="route('customers.show', $customer->id)" navigate class="font-medium">{{ $customer->name }}</x-link>
@if ($customer->isInternal)
<span class="ml-1 text-sm">({{ __('customers.internal') }})</span>
@endif
@endinteract @endinteract
@interact('column_type', $customer) @interact('column_type', $customer)
@@ -6,7 +6,9 @@ use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary; use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit; use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact; use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Domain\Exceptions\BillingUnitInUse;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound; use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\ContactInUse;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound; use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Enums\CustomerType;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
@@ -137,6 +139,8 @@ new class extends Component
$this->statusMessage = __('customers.removal.removed_'.$this->removalType, ['name' => $this->removalName]); $this->statusMessage = __('customers.removal.removed_'.$this->removalType, ['name' => $this->removalName]);
} catch (ContactNotFound|BillingUnitNotFound) { } catch (ContactNotFound|BillingUnitNotFound) {
$this->statusMessage = __('customers.removal.already_removed'); $this->statusMessage = __('customers.removal.already_removed');
} catch (ContactInUse|BillingUnitInUse) {
$this->statusMessage = __('customers.removal.in_use_'.$this->removalType, ['name' => $this->removalName]);
} }
// The removed row's button is gone, so focus moves to its section heading. // The removed row's button is gone, so focus moves to its section heading.
@@ -174,7 +178,12 @@ new class extends Component
<dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]"> <dl class="grid gap-x-6 gap-y-2 text-sm sm:grid-cols-[max-content_1fr]">
<dt class="font-medium">{{ __('customers.fields.type') }}</dt> <dt class="font-medium">{{ __('customers.fields.type') }}</dt>
<dd>{{ __('customers.types.'.$this->customer->type->value) }}</dd> <dd>
{{ __('customers.types.'.$this->customer->type->value) }}
@if ($this->customer->isInternal)
– {{ __('customers.internal') }}. {{ __('customers.internal_description') }}
@endif
</dd>
@if ($this->customer->businessId !== null) @if ($this->customer->businessId !== null)
<dt class="font-medium">{{ __('customers.fields.business_id') }}</dt> <dt class="font-medium">{{ __('customers.fields.business_id') }}</dt>
@@ -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');
});
@@ -28,4 +28,19 @@ interface UserAccountQueries
* @return list<UserOption> * @return list<UserOption>
*/ */
public function supervisorOptions(?int $exceptUserId = null): array; public function supervisorOptions(?int $exceptUserId = null): array;
/**
* Active users ordered by name, with their role, for choosing job members.
*
* @return list<UserOption>
*/
public function activeUserOptions(): array;
/**
* User names for many ids at once, active or not (for lists and history).
*
* @param list<int> $ids
* @return array<int, string>
*/
public function namesByIds(array $ids): array;
} }
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs; namespace App\Modules\Users\Application\DTOs;
use App\Modules\Users\Domain\Enums\Role;
/** /**
* A user as a choice in a select list. * A user as a choice in a select list.
*/ */
@@ -12,5 +14,6 @@ final readonly class UserOption
public function __construct( public function __construct(
public int $id, public int $id,
public string $name, public string $name,
public ?Role $role = null,
) {} ) {}
} }
@@ -50,6 +50,22 @@ class EloquentUserAccountQueries implements UserAccountQueries
->all(); ->all();
} }
public function activeUserOptions(): array
{
return User::query()
->where('is_active', true)
->orderBy('name')
->get(['id', 'name', 'role'])
->map(fn (User $model): UserOption => new UserOption($model->id, $model->name, $model->role))
->values()
->all();
}
public function namesByIds(array $ids): array
{
return $ids === [] ? [] : User::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
}
private function toSummary(User $model): UserSummary private function toSummary(User $model): UserSummary
{ {
return new UserSummary( return new UserSummary(
+3
View File
@@ -2,6 +2,7 @@
use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider;
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider;
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider; use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider;
use App\Providers\AppServiceProvider; use App\Providers\AppServiceProvider;
@@ -12,4 +13,6 @@ return [
UsersServiceProvider::class, UsersServiceProvider::class,
CustomersServiceProvider::class, CustomersServiceProvider::class,
CatalogServiceProvider::class, CatalogServiceProvider::class,
// After Customers: replaces its CustomerRowUsage binding.
JobsServiceProvider::class,
]; ];
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace Database\Factories;
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Domain\Enums\JobKind;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\DB;
/**
* @extends Factory<CustomerJobModel>
*/
class CustomerJobFactory extends Factory
{
protected $model = CustomerJobModel::class;
private static int $sequence = 9000;
/**
* @return array<string, mixed>
*/
public function definition(): array
{
$responsible = User::factory();
return [
'number' => sprintf('2026-%04d', ++self::$sequence),
'name' => fake()->sentence(3),
'customer_id' => CustomerModel::factory(),
'kind' => JobKind::OneOff,
'status' => JobStatus::Tentative,
'priority' => Priority::Normal,
'responsible_user_id' => $responsible,
'created_by' => $responsible,
];
}
/**
* Every job has a service unit: the first active one unless given.
*/
public function configure(): static
{
return $this->afterCreating(function (CustomerJobModel $job): void {
if (DB::table('customer_job_service_unit')->where('customer_job_id', $job->id)->exists()) {
return;
}
$unitId = ServiceUnitModel::query()->where('is_shared', false)->orderBy('sort_order')->value('id')
?? ServiceUnitModel::factory()->create()->id;
DB::table('customer_job_service_unit')->insert(['customer_job_id' => $job->id, 'service_unit_id' => $unitId]);
});
}
/**
* @param list<int> $userIds
*/
public function withMembers(array $userIds): static
{
return $this->afterCreating(function (CustomerJobModel $job) use ($userIds): void {
DB::table('customer_job_members')->insert(array_map(
fn (int $userId): array => ['customer_job_id' => $job->id, 'user_id' => $userId],
$userIds,
));
});
}
}
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Marks the company's own customer, whose jobs hold internal work.
*/
public function up(): void
{
Schema::table('customers', function (Blueprint $table) {
$table->boolean('is_internal')->default(false)->after('type');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('customers', function (Blueprint $table) {
$table->dropColumn('is_internal');
});
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* The one internal customer (the company itself), so internal work has
* a customer job to be recorded on. Its name can be changed later.
*/
public function up(): void
{
if (DB::table('customers')->where('is_internal', true)->exists()) {
return;
}
DB::table('customers')->insert([
'name' => 'Oma yritys (sisäinen)',
'type' => 'company',
'is_internal' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
/**
* The internal customer is not removed: jobs may refer to it.
*/
public function down(): void {}
};
@@ -0,0 +1,107 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Customer jobs with their numbering, service units, members, tags,
* links and history. Money columns come in phase 2. Rows other modules
* own (customers, users, contacts, billing units, service units) cannot
* be deleted while a job refers to them.
*/
public function up(): void
{
Schema::create('job_number_sequences', function (Blueprint $table) {
$table->unsignedSmallInteger('year')->primary();
$table->unsignedInteger('last_number');
});
Schema::create('customer_jobs', function (Blueprint $table) {
$table->id();
$table->string('number', 12)->unique();
$table->string('name');
$table->text('description')->nullable();
$table->foreignId('customer_id')->constrained()->restrictOnDelete();
$table->date('starts_on')->nullable();
$table->date('due_on')->nullable()->index();
$table->date('planned_from')->nullable();
$table->date('planned_to')->nullable();
$table->string('kind', 20);
$table->string('status', 20)->index();
$table->string('priority', 20);
$table->string('payment_basis', 20)->nullable();
$table->decimal('estimated_hours', 7, 2)->nullable();
$table->string('customer_reference')->nullable();
$table->text('instructions')->nullable();
$table->foreignId('responsible_user_id')->constrained('users')->restrictOnDelete();
$table->foreignId('contact_user_id')->nullable()->constrained('users')->restrictOnDelete();
$table->foreignId('customer_contact_id')->nullable()->constrained('customer_contacts')->restrictOnDelete();
$table->foreignId('biller_user_id')->nullable()->constrained('users')->restrictOnDelete();
$table->foreignId('billing_unit_id')->nullable()->constrained('billing_units')->restrictOnDelete();
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->timestamps();
});
Schema::create('customer_job_service_unit', function (Blueprint $table) {
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('service_unit_id')->constrained()->restrictOnDelete();
$table->primary(['customer_job_id', 'service_unit_id']);
});
Schema::create('customer_job_members', function (Blueprint $table) {
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->restrictOnDelete();
$table->primary(['customer_job_id', 'user_id']);
});
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name', 50)->unique();
$table->timestamps();
});
Schema::create('customer_job_tag', function (Blueprint $table) {
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('tag_id')->constrained()->restrictOnDelete();
$table->primary(['customer_job_id', 'tag_id']);
});
Schema::create('customer_job_links', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->string('url', 2000);
$table->unsignedSmallInteger('sort_order');
});
Schema::create('customer_job_changes', function (Blueprint $table) {
$table->id();
$table->foreignId('customer_job_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->restrictOnDelete();
$table->string('field', 40);
$table->text('old_value')->nullable();
$table->text('new_value')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->index(['customer_job_id', 'id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('customer_job_changes');
Schema::dropIfExists('customer_job_links');
Schema::dropIfExists('customer_job_tag');
Schema::dropIfExists('tags');
Schema::dropIfExists('customer_job_members');
Schema::dropIfExists('customer_job_service_unit');
Schema::dropIfExists('customer_jobs');
Schema::dropIfExists('job_number_sequences');
}
};
+8 -5
View File
@@ -96,7 +96,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli
- **Laskutusyksiköt**: useita; nimi (pakollinen, oletuksena asiakkaan nimi), laskutusosoite (vapaa teksti: postiosoite tai laskutussähköposti), verkkolaskuosoite (12–35 kirjainta tai numeroa), välittäjätunnus (pakollinen, jos verkkolaskuosoite on annettu) ja viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan. - **Laskutusyksiköt**: useita; nimi (pakollinen, oletuksena asiakkaan nimi), laskutusosoite (vapaa teksti: postiosoite tai laskutussähköposti), verkkolaskuosoite (12–35 kirjainta tai numeroa), välittäjätunnus (pakollinen, jos verkkolaskuosoite on annettu) ja viite. Saman asiakkaan eri laskutusyksiköt laskutetaan omilla laskuillaan.
- Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt ja laskutusyksiköt. Uuden asiakkaan tallennus vie asiakkaan sivulle. - Asiakkaalla on oma sivu, jolla näkyvät perustiedot, yhteyshenkilöt ja laskutusyksiköt. Uuden asiakkaan tallennus vie asiakkaan sivulle.
- Asiakastyön vastaanotossa riittää asiakkaan nimi (ja tyyppi); muut tiedot täydennetään myöhemmin. - Asiakastyön vastaanotossa riittää asiakkaan nimi (ja tyyppi); muut tiedot täydennetään myöhemmin.
- Yrityksen oma sisäinen asiakas, jonka asiakastöihin kirjataan sisäinen työ (hallinto, myynti, koulutus) *(K39)*. - Yrityksen oma sisäinen asiakas, jonka asiakastöihin kirjataan sisäinen työ (hallinto, myynti, koulutus) *(K39)*. Migraatio luo yhden sisäisen asiakkaan "Oma yritys (sisäinen)"; nimen voi muuttaa, mutta se on aina yritys, eikä uusia sisäisiä asiakkaita luoda käyttöliittymästä *(valmis)*.
## 5. Asiakastyö ## 5. Asiakastyö
@@ -324,7 +324,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
- `settings` *(V2)*: `key`, `value` (esim. km-hinta, työajanseuranta päällä) - `settings` *(V2)*: `key`, `value` (esim. km-hinta, työajanseuranta päällä)
**Jobs** (asiakastyöt) **Jobs** (asiakastyöt)
- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `quoted_amount_cents`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by`, `completed_at` - `customer_jobs`: `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` *(olemassa)*; `quoted_amount_cents`, `completed_at` *(V2)*
- `job_number_sequences`: `year`, `last_number` - `job_number_sequences`: `year`, `last_number`
- `customer_job_service_unit`: `customer_job_id`, `service_unit_id` - `customer_job_service_unit`: `customer_job_id`, `service_unit_id`
- `customer_job_members`: `customer_job_id`, `user_id` - `customer_job_members`: `customer_job_id`, `user_id`
@@ -390,8 +390,8 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
### 16.2 Asiakkaat ### 16.2 Asiakkaat
- Asiakkaalle voi lisätä, muokata ja poistaa yhteyshenkilöitä ja laskutusyksiköitä asiakkaan sivulla *(valmis)*. Poisto vahvistetaan dialogissa. - Asiakkaalle voi lisätä, muokata ja poistaa yhteyshenkilöitä ja laskutusyksiköitä asiakkaan sivulla *(valmis)*. Poisto vahvistetaan dialogissa.
- Kun asiakastyöt viittaavat yhteyshenkilöön tai laskutusyksikköön, käytössä olevan rivin poisto estetään. - Kun asiakastyö viittaa yhteyshenkilöön tai laskutusyksikköön, sen poisto estetään ja asiakassivu kertoo syyn *(valmis)*.
- Sisäinen asiakas on merkitty, eikä sitä voi poistaa. - Sisäinen asiakas on merkitty listalla ja asiakassivulla, eikä sitä voi poistaa *(valmis)*.
### 16.3 Pohjatiedot ### 16.3 Pohjatiedot
- Pääkäyttäjä ja johto voivat lisätä, nimetä uudelleen, järjestää ja poistaa käytöstä palveluyksiköitä, palveluita ja työtehtäviä Pohjatiedot-sivulla *(valmis)*. Käytössä olleita ei poisteta, vaan ne poistetaan käytöstä. Järjestys muutetaan Siirrä ylös / Siirrä alas -painikkeilla (toimii näppäimistöllä). - Pääkäyttäjä ja johto voivat lisätä, nimetä uudelleen, järjestää ja poistaa käytöstä palveluyksiköitä, palveluita ja työtehtäviä Pohjatiedot-sivulla *(valmis)*. Käytössä olleita ei poisteta, vaan ne poistetaan käytöstä. Järjestys muutetaan Siirrä ylös / Siirrä alas -painikkeilla (toimii näppäimistöllä).
@@ -399,7 +399,10 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
- Luvun 11.1 lista lisätään migraatiossa, jos taulut ovat tyhjiä *(valmis)*. - Luvun 11.1 lista lisätään migraatiossa, jos taulut ovat tyhjiä *(valmis)*.
### 16.4 Asiakastyöt ### 16.4 Asiakastyöt
- Työntekijä voi luoda ja muokata asiakastöitä; alihankkija ei. - *(valmis)* Työntekijä voi luoda ja muokata asiakastöitä; alihankkija näkee vain työt, joiden jäsen hän on, eikä voi muokata niitä.
- Uuden työn oletukset: tila Alustava, prioriteetti Normaali, laji Kertaluonteinen, vastuuhenkilönä luoja.
- Tilat "Lasku luotu" ja "Laskutettu" voi asettaa johto tai työn laskuttaja, "Arkistoitu" vain johto ja pääkäyttäjä.
- "Omat työt": työt, joissa käyttäjä on vastuuhenkilö, kontaktihenkilö, laskuttaja tai jäsen (tehtävien tekijät lisätään tehtävien osassa).
- Työ saa seuraavan numeron (`VVVV-NNNN`) tallennettaessa; juokseva osa alkaa alusta joka vuosi, eivätkä numerot toistu rinnakkaisissakaan tallennuksissa. - Työ saa seuraavan numeron (`VVVV-NNNN`) tallennettaessa; juokseva osa alkaa alusta joka vuosi, eivätkä numerot toistu rinnakkaisissakaan tallennuksissa.
- Asiakkaan voi hakea kirjoittamalla tai lisätä nimellä, jos sitä ei löydy. - Asiakkaan voi hakea kirjoittamalla tai lisätä nimellä, jos sitä ei löydy.
- Tagin voi valita listasta tai lisätä uuden, joka jää listaan. - Tagin voi valita listasta tai lisätä uuden, joka jää listaan.
+5
View File
@@ -20,6 +20,8 @@ return [
'edit_details' => 'Muokkaa tietoja', 'edit_details' => 'Muokkaa tietoja',
'remove' => 'Poista', 'remove' => 'Poista',
'customer_label' => 'Asiakas', 'customer_label' => 'Asiakas',
'internal' => 'Sisäinen',
'internal_description' => 'Oma yritys. Sen asiakastöille kirjataan sisäinen työ, kuten hallinto, myynti ja koulutus.',
'contacts' => [ 'contacts' => [
'title' => 'Yhteyshenkilöt', 'title' => 'Yhteyshenkilöt',
@@ -72,6 +74,8 @@ return [
'removed_contact' => 'Yhteyshenkilö :name poistettu.', 'removed_contact' => 'Yhteyshenkilö :name poistettu.',
'removed_billing_unit' => 'Laskutusyksikkö :name poistettu.', 'removed_billing_unit' => 'Laskutusyksikkö :name poistettu.',
'already_removed' => 'Riviä ei löytynyt. Se on ehkä jo poistettu.', 'already_removed' => 'Riviä ei löytynyt. Se on ehkä jo poistettu.',
'in_use_contact' => 'Yhteyshenkilöä :name ei poistettu, koska se on valittu asiakastyölle. Vaihda asiakastyölle ensin toinen yhteyshenkilö.',
'in_use_billing_unit' => 'Laskutusyksikköä :name ei poistettu, koska se on valittu asiakastyölle. Vaihda asiakastyölle ensin toinen laskutusyksikkö.',
], ],
'fields' => [ 'fields' => [
@@ -100,6 +104,7 @@ return [
'business_id_taken' => 'Tällä Y-tunnuksella on jo asiakas.', 'business_id_taken' => 'Tällä Y-tunnuksella on jo asiakas.',
'invalid_personal_identity_code' => 'Henkilötunnus ei ole kelvollinen. Tarkista päivämäärä, välimerkki ja tarkistusmerkki, esimerkiksi 131052-308T.', 'invalid_personal_identity_code' => 'Henkilötunnus ei ole kelvollinen. Tarkista päivämäärä, välimerkki ja tarkistusmerkki, esimerkiksi 131052-308T.',
'company_personal_identity_code' => 'Yritysasiakkaalla ei voi olla henkilötunnusta.', 'company_personal_identity_code' => 'Yritysasiakkaalla ei voi olla henkilötunnusta.',
'internal_must_be_company' => 'Sisäinen asiakas on oma yritys, joten se ei voi olla kuluttaja.',
'personal_identity_code_taken' => 'Tällä henkilötunnuksella on jo asiakas. Hae asiakas listasta nimellä.', 'personal_identity_code_taken' => 'Tällä henkilötunnuksella on jo asiakas. Hae asiakas listasta nimellä.',
'contact_name_required' => 'Anna yhteyshenkilön nimi.', 'contact_name_required' => 'Anna yhteyshenkilön nimi.',
'invalid_contact_name' => 'Nimen pituus voi olla enintään 255 merkkiä.', 'invalid_contact_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
+170
View File
@@ -0,0 +1,170 @@
<?php
return [
'title' => 'Asiakastyöt',
'new' => 'Uusi asiakastyö',
'create_title' => 'Uusi asiakastyö',
'edit_title' => 'Muokkaa asiakastyötä',
'edit' => 'Muokkaa',
'save' => 'Tallenna',
'cancel' => 'Peruuta',
'created' => 'Asiakastyö :number :name luotu.',
'updated' => 'Asiakastyön :number tiedot tallennettu.',
'not_set' => '–',
'late' => 'Myöhässä',
'opens_in_new_tab' => 'avautuu uuteen välilehteen',
'list' => [
'search' => 'Hae asiakastyötä',
'search_description' => 'Hae numerolla, nimellä tai asiakkaan nimellä.',
'all_statuses' => 'Kaikki tilat (paitsi arkistoidut)',
'all_priorities' => 'Kaikki prioriteetit',
'all_service_units' => 'Kaikki palveluyksiköt',
'only_mine' => 'Vain omat työt',
'only_mine_description' => 'Työt, joissa olet vastuuhenkilö, kontaktihenkilö, laskuttaja tai jäsen.',
'include_archived' => 'Näytä arkistoidut',
'empty' => 'Asiakastöitä ei löytynyt.',
'result_count' => '{0} Ei asiakastöitä|{1} :count asiakastyö|[2,*] :count asiakastyötä',
'subcontractor_note' => 'Näet asiakastyöt, joihin sinut on liitetty.',
],
'sections' => [
'basics' => 'Perustiedot',
'schedule' => 'Aikataulu',
'classification' => 'Luokittelu',
'members' => 'Jäsenet',
'extra' => 'Lisätiedot',
'links' => 'Linkit',
'instructions' => 'Ohjeistus',
'history' => 'Muutoshistoria',
],
'fields' => [
'number' => 'Numero',
'name' => 'Nimi',
'description' => 'Kuvaus',
'customer' => 'Asiakas',
'service_units' => 'Palveluyksiköt',
'starts_on' => 'Alkamispäivä',
'due_on' => 'Määräaika',
'planned_from' => 'Suunniteltu alku',
'planned_to' => 'Suunniteltu loppu',
'kind' => 'Kesto / laji',
'status' => 'Tila',
'priority' => 'Prioriteetti',
'payment_basis' => 'Maksuperuste',
'estimated_hours' => 'Arvioidut tunnit',
'estimated_hours_description' => 'Tunteina, esimerkiksi 7,5.',
'customer_reference' => 'Asiakkaan viite (PO)',
'instructions' => 'Ohjeistus',
'instructions_description' => 'Työhön liittyvät asiat ja huomiot tekijöille.',
'responsible_user' => 'Vastuuhenkilö',
'contact_user' => 'Kontaktihenkilö',
'contact_user_description' => 'Oma työntekijä, joka hoitaa yhteydenpidon asiakkaaseen.',
'customer_contact' => 'Asiakkaan yhteyshenkilö',
'biller_user' => 'Laskuttaja',
'biller_user_description' => 'Työntekijä, joka tekee laskun.',
'billing_unit' => 'Laskutusyksikkö',
'members' => 'Muut jäsenet',
'members_description' => 'Työ näkyy jäsenten omissa töissä. Alihankkija näkee vain työt, joiden jäsen hän on.',
'tags' => 'Tagit',
'links' => 'Linkit',
'created_at' => 'Luotu',
'created_by' => 'Luoja',
'none_selected' => 'Ei valittu',
'no_payment_basis' => 'Ei valittu',
],
'customer_picker' => [
'search' => 'Hae asiakasta',
'search_description' => 'Kirjoita vähintään kaksi merkkiä asiakkaan nimestä tai Y-tunnuksesta.',
'results' => '{0} Ei osumia.|{1} :count osuma.|[2,*] :count osumaa.',
'choose' => 'Valitse :name',
'create' => 'Lisää uusi asiakas: :name',
'selected' => 'Valittu asiakas: :name',
'change' => 'Vaihda asiakas',
'created' => 'Asiakas :name lisätty ja valittu. Muut tiedot voi täydentää asiakkaan sivulla.',
'choose_customer_first' => 'Valitse ensin asiakas.',
],
'tags' => [
'new' => 'Uusi tagi',
'new_description' => 'Valitse ehdotuksista tai kirjoita uusi, ja paina Lisää tagi.',
'add' => 'Lisää tagi',
'remove' => 'Poista tagi :tag',
'added' => 'Tagi :tag lisätty.',
'removed' => 'Tagi :tag poistettu.',
'none' => 'Ei tageja.',
],
'links' => [
'title' => 'Otsikko',
'url' => 'Osoite',
'url_description' => 'Esimerkiksi linkki Driveen tai Dropboxiin, alkaen https://',
'add' => 'Lisää linkki',
'remove' => 'Poista linkki :number',
'link_number' => 'Linkki :number',
'none' => 'Ei linkkejä.',
],
'history' => [
'empty' => 'Ei muutoksia.',
'created' => ':user loi työn :number.',
'changed' => ':field: :old → :new',
'by' => ':user, :time',
'unknown' => 'nro :id',
],
'kinds' => [
'service' => 'Palvelutyö (pieni, hinnastosta)',
'one_off' => 'Kertaluonteinen',
'fixed_term' => 'Määräaikainen',
'ongoing' => 'Toistaiseksi jatkuva',
],
'statuses' => [
'prospect' => 'Prospekti',
'tentative' => 'Alustava',
'quote_request' => 'Tarjouspyyntö',
'order' => 'Tilaus',
'in_production' => 'Tuotannossa',
'on_hold' => 'Keskeytetty',
'done' => 'Valmis',
'invoiced' => 'Lasku luotu',
'billed' => 'Laskutettu',
'archived' => 'Arkistoitu',
],
'priorities' => [
'waiting' => 'Odottaa',
'normal' => 'Normaali',
'first' => 'Ensin',
'urgent' => 'Kiire',
'immediate' => 'Heti',
],
'payment_bases' => [
'price_list' => 'Kiinteä hinnasto',
'fixed_quote' => 'Kiinteä tarjouksen perusteella',
'monthly_fee' => 'Kiinteä kk-laskutus',
'hourly' => 'Tuntityö',
'not_billable' => 'Ei laskutettava',
],
'errors' => [
'name_required' => 'Anna asiakastyön nimi.',
'invalid_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'customer_required' => 'Valitse asiakas tai lisää uusi.',
'service_units_required' => 'Valitse vähintään yksi palveluyksikkö.',
'responsible_required' => 'Valitse vastuuhenkilö.',
'invalid_date' => 'Anna päivämäärä muodossa pp.kk.vvvv.',
'due_before_start' => 'Määräaika ei voi olla ennen alkamispäivää.',
'plan_ends_before_start' => 'Suunniteltu loppu ei voi olla ennen suunniteltua alkua.',
'invalid_hours' => 'Anna tunnit nollana tai suurempana, vartin tarkkuudella (esim. 7,25).',
'invalid_tag' => 'Tagin pituus on 1–50 merkkiä.',
'invalid_link' => 'Anna linkille otsikko ja osoite, joka alkaa http:// tai https://.',
'invalid_reference' => 'Valinta ei ole enää käytettävissä. Valitse uudelleen.',
'status_not_allowed' => 'Sinulla ei ole oikeutta asettaa tätä tilaa.',
'too_long' => 'Teksti voi olla enintään :max merkkiä.',
],
];
+1
View File
@@ -4,6 +4,7 @@ return [
'skip_to_content' => 'Siirry pääsisältöön', 'skip_to_content' => 'Siirry pääsisältöön',
'main_menu' => 'Päävalikko', 'main_menu' => 'Päävalikko',
'home' => 'Etusivu', 'home' => 'Etusivu',
'jobs' => 'Asiakastyöt',
'customers' => 'Asiakkaat', 'customers' => 'Asiakkaat',
'users' => 'Käyttäjät', 'users' => 'Käyttäjät',
'catalog' => 'Pohjatiedot', 'catalog' => 'Pohjatiedot',
@@ -0,0 +1,53 @@
{{--
A group of checkboxes for one array property, in a fieldset whose
legend names the group. Native inputs with wrapping labels, so every
box has a name; the validation error is announced with the group.
$options: list of ['value' => ..., 'label' => ..., 'note' => ?string].
--}}
@props([
'legend',
'model',
'options',
'hint' => null,
'columns' => true,
])
@php
$errorKey = $model;
$id = 'group-'.str_replace('.', '-', $model);
@endphp
<fieldset
{{ $attributes->class('space-y-2') }}
@if ($hint !== null || $errors->has($errorKey)) aria-describedby="{{ trim(($hint !== null ? $id.'-hint ' : '').($errors->has($errorKey) ? $id.'-error' : '')) }}" @endif
>
<legend class="text-sm font-semibold text-gray-700 dark:text-dark-300">{{ $legend }}</legend>
@if ($hint !== null)
<p id="{{ $id }}-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ $hint }}</p>
@endif
<div @class(['grid gap-2', 'sm:grid-cols-2 lg:grid-cols-3' => $columns])>
@foreach ($options as $option)
<label wire:key="{{ $id }}-{{ $option['value'] }}" class="flex min-h-6 cursor-pointer items-start gap-2 text-sm">
<input
type="checkbox"
wire:model="{{ $model }}"
value="{{ $option['value'] }}"
class="mt-0.5 size-4 shrink-0 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800"
/>
<span>
{{ $option['label'] }}
@if (($option['note'] ?? null) !== null)
<span class="text-zinc-600 dark:text-zinc-300">({{ $option['note'] }})</span>
@endif
</span>
</label>
@endforeach
</div>
@error($errorKey)
<p id="{{ $id }}-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</fieldset>
@@ -0,0 +1,24 @@
{{--
A job's due date (Y-m-d) in Finnish format. A past due date of an open
job is marked with an icon and the word "Myöhässä", not colour alone.
--}}
@props(['date', 'status'])
@if ($date === null)
{{ __('jobs.not_set') }}
@else
@php
$isLate = \Carbon\CarbonImmutable::parse($date)->endOfDay()->isPast()
&& ! in_array($status->value, ['done', 'invoiced', 'billed', 'archived'], true);
@endphp
<span {{ $attributes->class('inline-flex flex-wrap items-center gap-1') }}>
{{ \Carbon\CarbonImmutable::parse($date)->format('j.n.Y') }}
@if ($isLate)
<span class="inline-flex items-center gap-1 font-medium text-red-700 dark:text-red-400">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />
{{ __('jobs.late') }}
</span>
@endif
</span>
@endif
@@ -0,0 +1,20 @@
{{--
A job's priority: the colour dot is decoration, the text carries the
meaning (never colour alone). "Heti" gets a striped dot.
--}}
@props(['priority'])
@php
$dot = match ($priority->value) {
'waiting' => 'bg-blue-600',
'normal' => 'bg-green-600',
'first' => 'bg-yellow-400',
'urgent' => 'bg-red-600',
'immediate' => 'bg-[repeating-linear-gradient(45deg,var(--color-orange-500)_0_3px,var(--color-red-700)_3px_6px)]',
};
@endphp
<span {{ $attributes->class('inline-flex items-center gap-2') }}>
<span class="inline-block size-3 shrink-0 rounded-full ring-1 ring-black/20 dark:ring-white/30 {{ $dot }}" aria-hidden="true"></span>
{{ __('jobs.priorities.'.$priority->value) }}
</span>
+4
View File
@@ -55,7 +55,11 @@
</a> </a>
<nav aria-label="{{ __('layout.main_menu') }}" class="flex flex-1 flex-wrap items-center gap-1"> <nav aria-label="{{ __('layout.main_menu') }}" class="flex flex-1 flex-wrap items-center gap-1">
@include('partials.nav-item', ['route' => 'jobs.index', 'pattern' => 'jobs.*', 'label' => __('layout.jobs')])
@can('customers.use')
@include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')]) @include('partials.nav-item', ['route' => 'customers.index', 'pattern' => 'customers.*', 'label' => __('layout.customers')])
@endcan
@can('catalog.manage') @can('catalog.manage')
@include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => 'catalog.*', 'label' => __('layout.catalog')]) @include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => 'catalog.*', 'label' => __('layout.catalog')])
+71
View File
@@ -0,0 +1,71 @@
<?php
use App\Models\User;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->user = User::factory()->management()->create(['name' => 'Johanna Johto']);
$this->actingAs($this->user);
$this->customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
$this->job = CustomerJobModel::factory()->create([
'name' => 'Messuvideo',
'customer_id' => $this->customer->id,
'responsible_user_id' => $this->user->id,
'priority' => 'immediate',
'due_on' => now()->subDay()->toDateString(),
'instructions' => 'Kuvaus klo 9.',
]);
DB::table('customer_job_links')->insert(['customer_job_id' => $this->job->id, 'title' => 'Briiffi', 'url' => 'https://drive.example.test/b', 'sort_order' => 1]);
});
it('has no accessibility issues on the job pages', function (string $page, string $device, string $colorScheme) {
$url = match ($page) {
'list' => route('jobs.index'),
'new job' => route('jobs.create'),
'edit job' => route('jobs.edit', $this->job->id),
'job page' => route('jobs.show', $this->job->id),
};
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['list', 'new job', 'edit job', 'job page'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('shows the form errors without accessibility issues', function (string $colorScheme) {
$page = visit(route('jobs.create'));
$page = $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
$page->press('Tallenna')
->assertSee('Anna asiakastyön nimi.')
->assertSee('Valitse vähintään yksi palveluyksikkö.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
it('finds and picks a customer, and adds and removes a tag, with the keyboard', function () {
visit(route('jobs.create'))
->type('#customer-search', 'Mainos')
->assertSee('1 osuma.')
->keys('[aria-label="Valitse Mainos Oy"]', 'Enter')
->assertSee('Vaihda asiakas')
->assertScript('document.activeElement.id', 'change-customer')
->type('#new-tag', 'messut')
->keys('#new-tag', 'Enter')
->assertSee('Tagi messut lisätty.')
->keys('[aria-label="Poista tagi messut"]', 'Enter')
->assertSee('Tagi messut poistettu.')
->assertScript('document.activeElement.id', 'new-tag')
->assertNoAccessibilityIssues(level: 2);
});
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\DTOs\ServiceSummary;
use App\Modules\Catalog\Application\DTOs\ServiceUnitSummary;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
/**
* Service units for unit tests of other modules.
*/
class FakeCatalogQueries implements CatalogQueries
{
/** @var array<int, ServiceUnitSummary> */
public array $serviceUnits = [];
public function addServiceUnit(int $id, string $name, bool $active = true, bool $shared = false): void
{
$this->serviceUnits[$id] = new ServiceUnitSummary($id, $name, $shared, $active);
}
public function tree(bool $includeInactive = true): array
{
return [];
}
public function activeServiceUnits(): array
{
return array_values(array_filter($this->serviceUnits, fn (ServiceUnitSummary $unit): bool => $unit->isActive && ! $unit->isShared));
}
public function activeWorkTypesFor(array $serviceUnitIds): array
{
return [];
}
public function findServiceUnit(int $id): ?ServiceUnitSummary
{
return $this->serviceUnits[$id] ?? null;
}
public function serviceUnitNames(array $ids): array
{
return array_map(fn (ServiceUnitSummary $unit): string => $unit->name, array_intersect_key($this->serviceUnits, array_flip($ids)));
}
public function findService(int $id): ?ServiceSummary
{
return null;
}
public function findWorkType(int $id): ?WorkTypeSummary
{
return null;
}
public function servicesOf(int $serviceUnitId): array
{
return [];
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
namespace Tests\Fakes;
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\CustomerSummary;
use App\Modules\Customers\Domain\Enums\CustomerType;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use LogicException;
/**
* Customers for unit tests of other modules: names by id, contacts and
* billing units as [customerId, id, name].
*/
class FakeCustomerQueries implements CustomerQueries
{
/** @var array<int, string> */
public array $customers = [];
/** @var list<array{int, int, string}> */
public array $contacts = [];
/** @var list<array{int, int, string}> */
public array $billingUnits = [];
public function findSummary(int $id): ?CustomerSummary
{
return isset($this->customers[$id]) ? new CustomerSummary($id, $this->customers[$id], CustomerType::Company, null) : null;
}
public function namesByIds(array $ids): array
{
return array_intersect_key($this->customers, array_flip($ids));
}
public function personalIdentityCodeOf(int $customerId): ?string
{
return null;
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
throw new LogicException('Not needed in unit tests.');
}
public function search(string $term, int $limit = 10): array
{
return [];
}
public function contactsOf(int $customerId): array
{
return [];
}
public function findContact(int $customerId, int $contactId): ?ContactSummary
{
foreach ($this->contacts as [$ownerId, $id, $name]) {
if ($ownerId === $customerId && $id === $contactId) {
return new ContactSummary($id, $ownerId, $name, null, null, null, null);
}
}
return null;
}
public function billingUnitsOf(int $customerId): array
{
return [];
}
public function findBillingUnit(int $customerId, int $billingUnitId): ?BillingUnitSummary
{
foreach ($this->billingUnits as [$ownerId, $id, $name]) {
if ($ownerId === $customerId && $id === $billingUnitId) {
return new BillingUnitSummary($id, $ownerId, $name, null, null, null, null);
}
}
return null;
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Tests\Fakes;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
class FakeCustomerRowUsage implements CustomerRowUsage
{
/** @var list<int> */
public array $contactsInUse = [];
/** @var list<int> */
public array $billingUnitsInUse = [];
public function isContactInUse(int $contactId): bool
{
return in_array($contactId, $this->contactsInUse, true);
}
public function isBillingUnitInUse(int $billingUnitId): bool
{
return in_array($billingUnitId, $this->billingUnitsInUse, true);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Tests\Fakes;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\DTOs\UserSummary;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use LogicException;
/**
* Users for unit tests of other modules.
*/
class FakeUserAccountQueries implements UserAccountQueries
{
/** @var array<int, array{string, Role, bool}> name, role, active */
public array $users = [];
public function addUser(int $id, string $name, Role $role = Role::Employee, bool $active = true): void
{
$this->users[$id] = [$name, $role, $active];
}
public function findSummary(int $id): ?UserSummary
{
throw new LogicException('Not needed in unit tests.');
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
throw new LogicException('Not needed in unit tests.');
}
public function supervisorOptions(?int $exceptUserId = null): array
{
return [];
}
public function activeUserOptions(): array
{
$options = [];
foreach ($this->users as $id => [$name, $role, $active]) {
if ($active) {
$options[] = new UserOption($id, $name, $role);
}
}
return $options;
}
public function namesByIds(array $ids): array
{
return array_map(fn (array $user): string => $user[0], array_intersect_key($this->users, array_flip($ids)));
}
}
@@ -0,0 +1,61 @@
<?php
namespace Tests\Fakes;
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\ValueObjects\FieldChange;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
/**
* Customer jobs, their history and the yearly numbering, in memory.
*/
class InMemoryCustomerJobRepository implements CustomerJobRepository, JobNumberSequence
{
/** @var array<int, CustomerJob> */
public array $jobs = [];
/** @var list<array{int, int, FieldChange}> job id, user id, change */
public array $changes = [];
/** @var array<int, int> */
private array $lastNumbers = [];
private int $nextId = 1;
public function findById(int $id): ?CustomerJob
{
return isset($this->jobs[$id]) ? clone $this->jobs[$id] : null;
}
public function save(CustomerJob $job): CustomerJob
{
$id = $job->id() ?? $this->nextId++;
$this->jobs[$id] = CustomerJob::reconstitute($id, $job->number(), $job->details(), $job->createdBy());
return clone $this->jobs[$id];
}
public function recordChanges(int $jobId, int $userId, array $changes): void
{
foreach ($changes as $change) {
$this->changes[] = [$jobId, $userId, $change];
}
}
public function next(int $year): JobNumber
{
$this->lastNumbers[$year] = ($this->lastNumbers[$year] ?? 0) + 1;
return new JobNumber($year, $this->lastNumbers[$year]);
}
/**
* @return list<string>
*/
public function changedFields(int $jobId): array
{
return array_values(array_map(fn (array $row): string => $row[2]->field, array_filter($this->changes, fn (array $row): bool => $row[0] === $jobId)));
}
}
+1 -1
View File
@@ -24,7 +24,7 @@ class InMemoryCustomerRepository implements CustomerRepository
public function save(Customer $customer): Customer public function save(Customer $customer): Customer
{ {
$id = $customer->id() ?? $this->nextId++; $id = $customer->id() ?? $this->nextId++;
$stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId(), $customer->personalIdentityCode()); $stored = Customer::reconstitute($id, $customer->name(), $customer->type(), $customer->businessId(), $customer->personalIdentityCode(), $customer->isInternal());
$this->customers[$id] = $stored; $this->customers[$id] = $stored;
@@ -36,9 +36,9 @@ it('registers a company customer', function () {
->set('form.business_id', '0737546-2') ->set('form.business_id', '0737546-2')
->call('save') ->call('save')
->assertHasNoErrors() ->assertHasNoErrors()
->assertRedirect(route('customers.show', CustomerModel::query()->sole()->id)); ->assertRedirect(route('customers.show', CustomerModel::query()->where('is_internal', false)->sole()->id));
$customer = CustomerModel::query()->sole(); $customer = CustomerModel::query()->where('is_internal', false)->sole();
expect($customer->name)->toBe('Mainos Oy') expect($customer->name)->toBe('Mainos Oy')
->and($customer->type)->toBe(CustomerType::Company) ->and($customer->type)->toBe(CustomerType::Company)
@@ -53,7 +53,7 @@ it('ignores a business id typed before switching to consumer', function () {
->call('save') ->call('save')
->assertHasNoErrors(); ->assertHasNoErrors();
expect(CustomerModel::query()->sole()->business_id)->toBeNull(); expect(CustomerModel::query()->where('is_internal', false)->sole()->business_id)->toBeNull();
}); });
it('shows validation and business rule errors on the fields', function (array $input, string $field, string $message) { it('shows validation and business rule errors on the fields', function (array $input, string $field, string $message) {
@@ -65,7 +65,7 @@ it('shows validation and business rule errors on the fields', function (array $i
->assertHasErrors([$field]) ->assertHasErrors([$field])
->assertSee($message); ->assertSee($message);
expect(CustomerModel::query()->count())->toBe(1); expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(1);
})->with([ })->with([
'missing name' => [['form.name' => ''], 'form.name', 'Anna asiakkaan nimi.'], 'missing name' => [['form.name' => ''], 'form.name', 'Anna asiakkaan nimi.'],
'bad check digit' => [['form.name' => 'Mainos Oy', 'form.business_id' => '0737546-3'], 'form.business_id', 'Y-tunnus ei ole kelvollinen.'], 'bad check digit' => [['form.name' => 'Mainos Oy', 'form.business_id' => '0737546-3'], 'form.business_id', 'Y-tunnus ei ole kelvollinen.'],
@@ -30,8 +30,8 @@ it('updates a stored customer', function () {
$customer->changeDetails(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, null); $customer->changeDetails(new CustomerName('Maija Meikäläinen'), CustomerType::Consumer, null);
$repository->save($customer); $repository->save($customer);
expect(CustomerModel::query()->count())->toBe(1) expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(1)
->and(CustomerModel::query()->sole()->type)->toBe(CustomerType::Consumer); ->and(CustomerModel::query()->where('is_internal', false)->sole()->type)->toBe(CustomerType::Consumer);
}); });
it('tells whether another customer has the business id', function () { it('tells whether another customer has the business id', function () {
@@ -52,6 +52,6 @@ it('returns summaries filtered by name or business id, ordered by name', functio
expect(array_map(fn ($summary) => $summary->name, $queries->search('media')))->toBe(['Alfa Media Oy', 'Bravo Media Oy']) expect(array_map(fn ($summary) => $summary->name, $queries->search('media')))->toBe(['Alfa Media Oy', 'Bravo Media Oy'])
->and($queries->paginate('0737546')->total())->toBe(1) ->and($queries->paginate('0737546')->total())->toBe(1)
->and($queries->paginate(null)->total())->toBe(3) ->and($queries->paginate(null)->total())->toBe(4) // and the internal customer
->and($queries->search('100%'))->toBe([]); ->and($queries->search('100%'))->toBe([]);
}); });
@@ -0,0 +1,206 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\BillingUnitModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerContactModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->employee = User::factory()->create(['name' => 'Eero Työntekijä']);
$this->actingAs($this->employee);
$this->customer = CustomerModel::factory()->create(['name' => 'Mainos Oy']);
$this->media = ServiceUnitModel::query()->where('name', 'Mediatuotanto')->sole();
});
/**
* Fills the job form with the required fields.
*/
function fillJobForm(mixed $form, int $customerId, int $serviceUnitId): mixed
{
return $form
->set('form.name', 'Messuvideo')
->call('selectCustomer', $customerId)
->set('form.service_unit_ids', [(string) $serviceUnitId]);
}
it('creates a job with the next number of the year and its history', function () {
$this->travelTo(now()->setDate(2026, 3, 1));
fillJobForm(Livewire::test('jobs::form'), $this->customer->id, $this->media->id)
->set('form.tags', ['messut'])
->set('form.links', [['title' => 'Briiffi', 'url' => 'https://drive.example.test/briiffi']])
->call('save')
->assertHasNoErrors();
fillJobForm(Livewire::test('jobs::form'), $this->customer->id, $this->media->id)->call('save')->assertHasNoErrors();
$jobs = CustomerJobModel::query()->orderBy('id')->get();
expect($jobs->pluck('number')->all())->toBe(['2026-0001', '2026-0002'])
->and($jobs[0]->responsible_user_id)->toBe($this->employee->id)
->and(DB::table('tags')->pluck('name')->all())->toBe(['messut'])
->and(DB::table('customer_job_changes')->where('customer_job_id', $jobs[0]->id)->value('field'))->toBe('created');
$this->get(route('jobs.show', $jobs[0]->id))
->assertOk()
->assertSee('2026-0001 Messuvideo')
->assertSee('Briiffi')
->assertSee('Eero Työntekijä loi työn 2026-0001.');
});
it('adds a new customer from the job form', function () {
Livewire::test('jobs::form')
->set('customerSearch', 'Uusi Asiakas Oy')
->assertSee('Lisää uusi asiakas: Uusi Asiakas Oy')
->call('createCustomer')
->assertSee('Asiakas Uusi Asiakas Oy lisätty ja valittu.');
$customer = CustomerModel::query()->where('name', 'Uusi Asiakas Oy')->sole();
expect($customer->type->value)->toBe('company');
});
it('finds customers by name and offers only their contacts and billing units', function () {
CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Maija']);
CustomerContactModel::factory()->create(['name' => 'Toisen kontakti']);
BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy, markkinointi']);
Livewire::test('jobs::form')
->set('customerSearch', 'main')
->assertSee('Valitse Mainos Oy')
->call('selectCustomer', $this->customer->id)
->assertSee('Maija')
->assertSee('Mainos Oy, markkinointi')
->assertDontSee('Toisen kontakti');
});
it('records changed fields and shows them in the history', function () {
$job = CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->set('form.priority', 'urgent')
->set('form.due_on', '2026-06-30')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('jobs.show', $job->id));
$this->get(route('jobs.show', $job->id))
->assertSee('Prioriteetti: Normaali → Kiire')
->assertSee('Määräaika: – → 30.6.2026');
});
it('shows Finnish errors for dates and missing fields', function () {
Livewire::test('jobs::form')
->set('form.starts_on', '2026-05-10')
->set('form.due_on', '2026-05-01')
->call('selectCustomer', $this->customer->id)
->set('form.service_unit_ids', [(string) $this->media->id])
->set('form.name', 'Messuvideo')
->call('save')
->assertHasErrors(['form.due_on'])
->assertSee('Määräaika ei voi olla ennen alkamispäivää.');
Livewire::test('jobs::form')
->call('save')
->assertHasErrors(['form.name', 'form.customer_id', 'form.service_unit_ids'])
->assertSee('Valitse vähintään yksi palveluyksikkö.');
});
it('lists my jobs by default, and all jobs on request', function () {
$mine = CustomerJobModel::factory()->create(['name' => 'Oma työ', 'responsible_user_id' => $this->employee->id]);
$member = CustomerJobModel::factory()->withMembers([$this->employee->id])->create(['name' => 'Jäsenenä']);
CustomerJobModel::factory()->create(['name' => 'Muiden työ']);
CustomerJobModel::factory()->create(['name' => 'Arkistoitu työ', 'status' => 'archived', 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::index')
->assertSee('Oma työ')
->assertSee('Jäsenenä')
->assertDontSee('Muiden työ')
->assertDontSee('Arkistoitu työ')
->set('mine', false)
->assertSee('Muiden työ')
->set('archived', true)
->assertSee('Arkistoitu työ')
->set('search', 'mainos')
->assertDontSee('Muiden työ');
expect($mine->id)->not->toBe($member->id);
});
it('lets a subcontractor see only the jobs they are a member of, read only', function () {
$subcontractor = User::factory()->subcontractor()->create();
$theirs = CustomerJobModel::factory()->withMembers([$subcontractor->id])->create(['name' => 'Alihankintatyö', 'instructions' => 'Kuvaus klo 9.']);
$other = CustomerJobModel::factory()->create(['name' => 'Muu työ']);
$this->actingAs($subcontractor);
$this->get(route('jobs.index'))->assertOk()->assertSee('Alihankintatyö')->assertDontSee('Muu työ')->assertDontSee('Uusi asiakastyö');
$this->get(route('jobs.show', $theirs->id))->assertOk()->assertSee('Kuvaus klo 9.')->assertDontSee('Muokkaa');
$this->get(route('jobs.show', $other->id))->assertForbidden();
$this->get(route('jobs.edit', $theirs->id))->assertForbidden();
$this->get(route('jobs.create'))->assertForbidden();
});
it('lets only management and the biller set billing statuses, and only management archive', function () {
$job = CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'status' => 'done', 'responsible_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->assertDontSee('Lasku luotu')
->set('form.status', 'invoiced')
->call('save')
->assertHasErrors(['form.status']);
$job->update(['biller_user_id' => $this->employee->id]);
Livewire::test('jobs::form', ['job' => $job->id])
->assertSee('Lasku luotu')
->assertDontSee('Arkistoitu')
->set('form.status', 'invoiced')
->call('save')
->assertHasNoErrors();
Livewire::actingAs(User::factory()->management()->create())
->test('jobs::form', ['job' => $job->id])
->set('form.status', 'archived')
->call('save')
->assertHasNoErrors();
expect($job->fresh()->status->value)->toBe('archived');
});
it('blocks removing a billing unit or contact a job uses', function () {
$contact = CustomerContactModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Maija']);
$billingUnit = BillingUnitModel::factory()->create(['customer_id' => $this->customer->id, 'name' => 'Mainos Oy']);
CustomerJobModel::factory()->create(['customer_id' => $this->customer->id, 'customer_contact_id' => $contact->id, 'billing_unit_id' => $billingUnit->id]);
Livewire::test('customers::show', ['customer' => $this->customer->id])
->call('confirmRemoval', 'billing_unit', $billingUnit->id)
->call('remove')
->assertSee('Laskutusyksikköä Mainos Oy ei poistettu')
->call('confirmRemoval', 'contact', $contact->id)
->call('remove')
->assertSee('Yhteyshenkilöä Maija ei poistettu');
expect($billingUnit->fresh())->not->toBeNull()
->and($contact->fresh())->not->toBeNull();
});
it('has the internal customer', function () {
expect(CustomerModel::query()->where('is_internal', true)->sole()->name)->toBe('Oma yritys (sisäinen)');
$this->get(route('customers.index'))->assertSee('(Sisäinen)');
});
it('does not let the job id be changed in the browser, and returns 404 for unknown jobs', function () {
$this->get(route('jobs.show', 999))->assertNotFound();
Livewire::test('jobs::form')->set('jobId', 1);
})->throws(CannotUpdateLockedPropertyException::class);
@@ -19,7 +19,7 @@ it('rolls back everything when the work fails', function () {
throw new RuntimeException('fail'); throw new RuntimeException('fail');
}))->toThrow(RuntimeException::class); }))->toThrow(RuntimeException::class);
expect(CustomerModel::query()->count())->toBe(0); expect(CustomerModel::query()->where('is_internal', false)->count())->toBe(0);
}); });
it('publishes events only after the transaction commits', function () { it('publishes events only after the transaction commits', function () {
@@ -10,12 +10,15 @@ use App\Modules\Customers\Application\UseCases\UpdateBillingUnit;
use App\Modules\Customers\Application\UseCases\UpdateContact; use App\Modules\Customers\Application\UseCases\UpdateContact;
use App\Modules\Customers\Domain\Entities\Customer; use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\BillingUnitInUse;
use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound; use App\Modules\Customers\Domain\Exceptions\BillingUnitNotFound;
use App\Modules\Customers\Domain\Exceptions\ContactInUse;
use App\Modules\Customers\Domain\Exceptions\ContactNotFound; use App\Modules\Customers\Domain\Exceptions\ContactNotFound;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound; use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired; use App\Modules\Customers\Domain\Exceptions\EInvoiceOperatorRequired;
use App\Modules\Customers\Domain\ValueObjects\CustomerName; use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress; use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress;
use Tests\Fakes\FakeCustomerRowUsage;
use Tests\Fakes\FakeTransactionManager; use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryBillingUnitRepository; use Tests\Fakes\InMemoryBillingUnitRepository;
use Tests\Fakes\InMemoryCustomerContactRepository; use Tests\Fakes\InMemoryCustomerContactRepository;
@@ -29,10 +32,11 @@ beforeEach(function () {
$this->addContact = new AddContact($this->customers, $this->contacts, $transactions); $this->addContact = new AddContact($this->customers, $this->contacts, $transactions);
$this->updateContact = new UpdateContact($this->contacts, $transactions); $this->updateContact = new UpdateContact($this->contacts, $transactions);
$this->removeContact = new RemoveContact($this->contacts, $transactions); $this->usage = new FakeCustomerRowUsage;
$this->removeContact = new RemoveContact($this->contacts, $this->usage, $transactions);
$this->addBillingUnit = new AddBillingUnit($this->customers, $this->billingUnits, $transactions); $this->addBillingUnit = new AddBillingUnit($this->customers, $this->billingUnits, $transactions);
$this->updateBillingUnit = new UpdateBillingUnit($this->billingUnits, $transactions); $this->updateBillingUnit = new UpdateBillingUnit($this->billingUnits, $transactions);
$this->removeBillingUnit = new RemoveBillingUnit($this->billingUnits, $transactions); $this->removeBillingUnit = new RemoveBillingUnit($this->billingUnits, $this->usage, $transactions);
$this->customerId = $this->customers->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company))->id(); $this->customerId = $this->customers->save(Customer::register(new CustomerName('Mainos Oy'), CustomerType::Company))->id();
$this->otherCustomerId = $this->customers->save(Customer::register(new CustomerName('Toinen Oy'), CustomerType::Company))->id(); $this->otherCustomerId = $this->customers->save(Customer::register(new CustomerName('Toinen Oy'), CustomerType::Company))->id();
@@ -102,3 +106,15 @@ it('does not touch a billing unit of another customer', function (string $action
'remove' => $this->removeBillingUnit->execute($this->customerId, $billingUnitId), 'remove' => $this->removeBillingUnit->execute($this->customerId, $billingUnitId),
}; };
})->throws(BillingUnitNotFound::class)->with(['update', 'remove']); })->throws(BillingUnitNotFound::class)->with(['update', 'remove']);
it('does not remove a contact or billing unit that a customer job uses', function () {
$contactId = $this->addContact->execute($this->customerId, new ContactData('Maija'));
$billingUnitId = $this->addBillingUnit->execute($this->customerId, new BillingUnitData('Mainos Oy'));
$this->usage->contactsInUse = [$contactId];
$this->usage->billingUnitsInUse = [$billingUnitId];
expect(fn () => $this->removeContact->execute($this->customerId, $contactId))->toThrow(ContactInUse::class)
->and(fn () => $this->removeBillingUnit->execute($this->customerId, $billingUnitId))->toThrow(BillingUnitInUse::class)
->and($this->contacts->contacts)->toHaveCount(1)
->and($this->billingUnits->billingUnits)->toHaveCount(1);
});
@@ -0,0 +1,106 @@
<?php
use App\Modules\Jobs\Application\DTOs\CustomerJobData;
use App\Modules\Jobs\Application\Services\JobDetailsFactory;
use App\Modules\Jobs\Application\UseCases\ChangeJobStatus;
use App\Modules\Jobs\Application\UseCases\CreateCustomerJob;
use App\Modules\Jobs\Application\UseCases\UpdateCustomerJob;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
use App\Modules\Users\Domain\Enums\Role;
use Tests\Fakes\FakeCatalogQueries;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\FakeUserAccountQueries;
use Tests\Fakes\InMemoryCustomerJobRepository;
beforeEach(function () {
$this->jobs = new InMemoryCustomerJobRepository;
$this->customers = new FakeCustomerQueries;
$this->catalog = new FakeCatalogQueries;
$this->users = new FakeUserAccountQueries;
$this->clock = new FakeClock(new DateTimeImmutable('2026-12-31'));
$transactions = new FakeTransactionManager;
$this->customers->customers = [1 => 'Mainos Oy', 2 => 'Toinen Oy'];
$this->customers->contacts = [[1, 5, 'Maija'], [2, 6, 'Toisen kontakti']];
$this->catalog->addServiceUnit(1, 'Mediatuotanto');
$this->catalog->addServiceUnit(2, 'Markkinointi', active: false);
$this->catalog->addServiceUnit(9, 'Kaikille yhteiset', shared: true);
$this->users->addUser(10, 'Eero');
$this->users->addUser(11, 'Aino', Role::Subcontractor);
$this->users->addUser(12, 'Pois', active: false);
$factory = new JobDetailsFactory($this->customers, $this->catalog, $this->users);
$this->create = new CreateCustomerJob($this->jobs, $this->jobs, $factory, $transactions, $this->clock);
$this->update = new UpdateCustomerJob($this->jobs, $factory, $transactions);
$this->changeStatus = new ChangeJobStatus($this->jobs, $transactions);
});
/**
* @param array<string, mixed> $overrides
*/
function jobData(array $overrides = []): CustomerJobData
{
return new CustomerJobData(...array_merge([
'name' => 'Messuvideo',
'customerId' => 1,
'serviceUnitIds' => [1],
'responsibleUserId' => 10,
'kind' => 'one_off',
'status' => 'tentative',
'priority' => 'normal',
], $overrides));
}
it('numbers jobs per year and starts the history', function () {
$first = $this->create->execute(jobData(), 10);
$second = $this->create->execute(jobData(), 10);
$this->clock->today = new DateTimeImmutable('2027-01-01');
$nextYear = $this->create->execute(jobData(), 10);
expect($this->jobs->findById($first)?->number()->format())->toBe('2026-0001')
->and($this->jobs->findById($second)?->number()->format())->toBe('2026-0002')
->and($this->jobs->findById($nextYear)?->number()->format())->toBe('2027-0001')
->and($this->jobs->changedFields($first))->toBe(['created']);
});
it('rejects references that do not fit the job', function (array $overrides, string $field) {
try {
$this->create->execute(jobData($overrides), 10);
$this->fail('No exception');
} catch (InvalidJobReference $exception) {
expect($exception->field)->toBe($field);
}
})->with([
'unknown customer' => [['customerId' => 99], 'customer'],
'contact of another customer' => [['customerContactId' => 6], 'customer_contact'],
'inactive service unit' => [['serviceUnitIds' => [2]], 'service_units'],
'shared service unit' => [['serviceUnitIds' => [9]], 'service_units'],
'subcontractor as responsible' => [['responsibleUserId' => 11], 'responsible_user'],
'inactive member' => [['memberUserIds' => [12]], 'members'],
]);
it('keeps an inactive unit or user that is already on the job', function () {
$this->catalog->addServiceUnit(2, 'Markkinointi');
$this->users->addUser(12, 'Pois');
$jobId = $this->create->execute(jobData(['serviceUnitIds' => [1, 2], 'memberUserIds' => [12]]), 10);
$this->catalog->addServiceUnit(2, 'Markkinointi', active: false);
$this->users->addUser(12, 'Pois', active: false);
$this->update->execute($jobId, jobData(['name' => 'Messuvideo 2', 'serviceUnitIds' => [1, 2], 'memberUserIds' => [12]]), 10);
expect($this->jobs->findById($jobId)?->details()->name->value)->toBe('Messuvideo 2');
});
it('records each changed field, and nothing when nothing changed', function () {
$jobId = $this->create->execute(jobData(), 10);
$this->update->execute($jobId, jobData(['priority' => 'urgent', 'customerContactId' => 5, 'tags' => ['messut']]), 10);
$this->update->execute($jobId, jobData(['priority' => 'urgent', 'customerContactId' => 5, 'tags' => ['Messut']]), 10);
$this->changeStatus->execute($jobId, JobStatus::Order, 10);
expect($this->jobs->changedFields($jobId))->toBe(['created', 'priority', 'customer_contact', 'tags', 'status']);
});
@@ -0,0 +1,99 @@
<?php
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\Enums\JobKind;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\Priority;
use App\Modules\Jobs\Domain\Exceptions\DueBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
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;
/**
* @param array<string, mixed> $overrides
*/
function jobDetails(array $overrides = []): JobDetails
{
return new JobDetails(...array_merge([
'name' => new JobName('Messuvideo'),
'description' => null,
'customerId' => 1,
'serviceUnitIds' => [1],
'startsOn' => null,
'dueOn' => null,
'plannedFrom' => null,
'plannedTo' => null,
'kind' => JobKind::OneOff,
'status' => JobStatus::Tentative,
'priority' => Priority::Normal,
'paymentBasis' => null,
'estimatedHours' => null,
'customerReference' => null,
'instructions' => null,
'responsibleUserId' => 10,
'contactUserId' => null,
'customerContactId' => null,
'billerUserId' => null,
'billingUnitId' => null,
'memberUserIds' => [],
'tags' => [],
'links' => [],
], $overrides));
}
it('formats and parses job numbers', function () {
expect((new JobNumber(2026, 42))->format())->toBe('2026-0042')
->and(JobNumber::fromString('2027-0001')->sequence)->toBe(1);
});
it('accepts estimated hours in quarters only', function () {
expect(EstimatedHours::fromString('7,25')->format())->toBe('7.25')
->and(EstimatedHours::fromString('8')->format())->toBe('8')
->and(fn () => EstimatedHours::fromString('1.1'))->toThrow(InvalidEstimatedHours::class)
->and(fn () => new EstimatedHours(-1))->toThrow(InvalidEstimatedHours::class);
});
it('accepts only http and https links with a title', function () {
expect((new JobLink(' Briiffi ', 'https://drive.example.test/x'))->title)->toBe('Briiffi')
->and(fn () => new JobLink('Tiedosto', 'javascript:alert(1)'))->toThrow(InvalidJobLink::class)
->and(fn () => new JobLink('', 'https://example.test'))->toThrow(InvalidJobLink::class)
->and(fn () => new Tag(str_repeat('a', 51)))->toThrow(InvalidTag::class);
});
it('checks the dates and service units of a job', function (array $overrides, string $exception) {
expect(fn () => jobDetails($overrides))->toThrow($exception);
})->with([
'due before start' => [['startsOn' => new DateTimeImmutable('2026-05-10'), 'dueOn' => new DateTimeImmutable('2026-05-09')], DueBeforeStart::class],
'plan ends before start' => [['plannedFrom' => new DateTimeImmutable('2026-05-10'), 'plannedTo' => new DateTimeImmutable('2026-05-01')], PlanEndsBeforeStart::class],
'no service unit' => [['serviceUnitIds' => []], ServiceUnitRequired::class],
]);
it('removes duplicate tags ignoring case, and sorts ids', function () {
$details = jobDetails(['tags' => [new Tag('Messut'), new Tag('messut'), new Tag('video')], 'memberUserIds' => [3, 1, 3]]);
expect(array_map(fn (Tag $tag) => $tag->value, $details->tags))->toBe(['Messut', 'video'])
->and($details->memberUserIds)->toBe([1, 3])
->and($details->involves(3))->toBeTrue()
->and($details->involves(99))->toBeFalse();
});
it('returns only the fields that changed', function () {
$job = CustomerJob::open(new JobNumber(2026, 1), jobDetails(), 10);
$changes = $job->changeDetails(jobDetails(['priority' => Priority::Urgent, 'tags' => [new Tag('messut')]]));
expect(array_map(fn ($change) => [$change->field, $change->oldValue, $change->newValue], $changes))->toBe([
['priority', 'normal', 'urgent'],
['tags', null, 'messut'],
])
->and($job->changeStatus(JobStatus::Tentative))->toBe([])
->and(JobStatus::kanbanStatuses())->not->toContain(JobStatus::Archived);
});