diff --git a/CLAUDE.md b/CLAUDE.md index 66637b2..c41b549 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## 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: ``, ``), 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: ``, ``), 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. - **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/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::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. -- **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`). - `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////` for classes, `make:test --pest [--unit] Modules//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 - ``: root-relative asset URLs that 404 in a subfolder (local XAMPP). The layout includes `resources/views/partials/tallstackui-script.blade.php` instead. - ``: the label is not tied to the control, so also pass `:aria-label` with the same text. - ``: `aria-labelledby` points at an id its title lacks, the close button has no name, and focus neither moves in nor returns. Use `` (`resources/views/components/confirm-dialog.blade.php`, native `` + `showModal()`), opened from Livewire with `$this->js("document.getElementById('').showModal()")`; see `customers::show`. + - Groups of checkboxes for an array property: `` (`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 ``. - Solid `color="red"` buttons: white on red-500 is 3.5:1, so the solid red is red-700 in the published `NormalButtonColors`. - `` without `wire:model` (e.g. a read-only value): pass an explicit `id`, or the label is not tied to it. `` has an unlabelled input and a button whose name changes; build copy fields from `` + `` + 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. diff --git a/app/Modules/Catalog/Application/Contracts/CatalogQueries.php b/app/Modules/Catalog/Application/Contracts/CatalogQueries.php index 5e97e3b..f974156 100644 --- a/app/Modules/Catalog/Application/Contracts/CatalogQueries.php +++ b/app/Modules/Catalog/Application/Contracts/CatalogQueries.php @@ -40,6 +40,14 @@ interface CatalogQueries public function findServiceUnit(int $id): ?ServiceUnitSummary; + /** + * Service unit names for many ids at once, active or not. + * + * @param list $ids + * @return array + */ + public function serviceUnitNames(array $ids): array; + public function findService(int $id): ?ServiceSummary; public function findWorkType(int $id): ?WorkTypeSummary; diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php index e1f66cf..ae2b7e8 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentCatalogQueries.php @@ -49,6 +49,11 @@ class EloquentCatalogQueries implements CatalogQueries 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 { $model = ServiceModel::query()->find($id); diff --git a/app/Modules/Customers/Application/Contracts/CustomerQueries.php b/app/Modules/Customers/Application/Contracts/CustomerQueries.php index 30abca7..101b850 100644 --- a/app/Modules/Customers/Application/Contracts/CustomerQueries.php +++ b/app/Modules/Customers/Application/Contracts/CustomerQueries.php @@ -17,6 +17,14 @@ interface CustomerQueries { public function findSummary(int $id): ?CustomerSummary; + /** + * Customer names for many ids at once (for lists in other modules). + * + * @param list $ids + * @return array + */ + public function namesByIds(array $ids): array; + /** * The full personal identity code. Sensitive: call only after checking * the customers.view-personal-identity-code ability, and never log it. diff --git a/app/Modules/Customers/Application/Contracts/CustomerRowUsage.php b/app/Modules/Customers/Application/Contracts/CustomerRowUsage.php new file mode 100644 index 0000000..867e37b --- /dev/null +++ b/app/Modules/Customers/Application/Contracts/CustomerRowUsage.php @@ -0,0 +1,17 @@ +billingUnits->findForCustomer($customerId, $billingUnitId) ?? throw new BillingUnitNotFound($customerId, $billingUnitId); + if ($this->usage->isBillingUnitInUse($billingUnitId)) { + throw new BillingUnitInUse; + } + $this->billingUnits->delete($billingUnit); }); } diff --git a/app/Modules/Customers/Application/UseCases/RemoveContact.php b/app/Modules/Customers/Application/UseCases/RemoveContact.php index c0184f5..e8a526b 100644 --- a/app/Modules/Customers/Application/UseCases/RemoveContact.php +++ b/app/Modules/Customers/Application/UseCases/RemoveContact.php @@ -4,23 +4,26 @@ declare(strict_types=1); 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\Exceptions\ContactInUse; use App\Modules\Customers\Domain\Exceptions\ContactNotFound; use App\Modules\Shared\Application\Contracts\TransactionManager; /** - * Deletes a contact. Nothing refers to contacts yet; once customer jobs do, - * a contact in use cannot be removed. + * Deletes a contact that no customer job has chosen. */ final class RemoveContact { public function __construct( private CustomerContactRepository $contacts, + private CustomerRowUsage $usage, private TransactionManager $transactions, ) {} /** * @throws ContactNotFound + * @throws ContactInUse */ public function execute(int $customerId, int $contactId): void { @@ -28,6 +31,10 @@ final class RemoveContact $contact = $this->contacts->findForCustomer($customerId, $contactId) ?? throw new ContactNotFound($customerId, $contactId); + if ($this->usage->isContactInUse($contactId)) { + throw new ContactInUse; + } + $this->contacts->delete($contact); }); } diff --git a/app/Modules/Customers/Domain/Entities/Customer.php b/app/Modules/Customers/Domain/Entities/Customer.php index 2607b9a..fcef73f 100644 --- a/app/Modules/Customers/Domain/Entities/Customer.php +++ b/app/Modules/Customers/Domain/Entities/Customer.php @@ -7,6 +7,7 @@ namespace App\Modules\Customers\Domain\Entities; use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; 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\CustomerName; use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode; @@ -25,8 +26,10 @@ final class Customer private CustomerType $type, private ?BusinessId $businessId, private ?PersonalIdentityCode $personalIdentityCode, + private bool $internal = false, ) { self::ensureIdentifiersFitType($type, $businessId, $personalIdentityCode); + self::ensureInternalIsCompany($internal, $type); } /** @@ -50,8 +53,9 @@ final class Customer CustomerType $type, ?BusinessId $businessId, ?PersonalIdentityCode $personalIdentityCode = null, + bool $internal = false, ): 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::ensureInternalIsCompany($this->internal, $type); $this->name = $name; $this->type = $type; @@ -106,6 +111,22 @@ final class Customer 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( CustomerType $type, ?BusinessId $businessId, diff --git a/app/Modules/Customers/Domain/Exceptions/BillingUnitInUse.php b/app/Modules/Customers/Domain/Exceptions/BillingUnitInUse.php new file mode 100644 index 0000000..ad39f1f --- /dev/null +++ b/app/Modules/Customers/Domain/Exceptions/BillingUnitInUse.php @@ -0,0 +1,15 @@ + CustomerType::class, 'personal_identity_code' => 'encrypted', + 'is_internal' => 'boolean', ]; } } diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php index 1196819..212ed09 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerQueries.php @@ -22,6 +22,11 @@ class EloquentCustomerQueries implements CustomerQueries 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 { return CustomerModel::query()->find($customerId)?->personal_identity_code; @@ -106,7 +111,7 @@ class EloquentCustomerQueries implements CustomerQueries ? null : (new PersonalIdentityCode($model->personal_identity_code))->masked(); - return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked); + return new CustomerSummary($model->id, $model->name, $model->type, $model->business_id, $masked, (bool) $model->is_internal); } private function toContactSummary(CustomerContactModel $model): ContactSummary diff --git a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php index 3a0e70e..857c447 100644 --- a/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php +++ b/app/Modules/Customers/Infrastructure/Persistence/Repositories/EloquentCustomerRepository.php @@ -62,6 +62,7 @@ class EloquentCustomerRepository implements CustomerRepository $model->type, $model->business_id === null ? null : new BusinessId($model->business_id), $model->personal_identity_code === null ? null : new PersonalIdentityCode($model->personal_identity_code), + (bool) $model->is_internal, ); } } diff --git a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php index ddb7d63..ef3cc17 100644 --- a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php +++ b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php @@ -4,9 +4,11 @@ namespace App\Modules\Customers\Infrastructure\Providers; use App\Models\User; 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\CustomerContactRepository; 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\EloquentCustomerContactRepository; use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries; @@ -30,6 +32,8 @@ class CustomersServiceProvider extends ServiceProvider CustomerQueries::class => EloquentCustomerQueries::class, CustomerContactRepository::class => EloquentCustomerContactRepository::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 diff --git a/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php b/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php index 519d953..87cec84 100644 --- a/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php +++ b/app/Modules/Customers/Presentation/Livewire/Forms/CustomerForm.php @@ -8,6 +8,7 @@ use App\Modules\Customers\Domain\Enums\CustomerType; use App\Modules\Customers\Domain\Exceptions\BusinessIdAlreadyInUse; use App\Modules\Customers\Domain\Exceptions\CompanyCannotHavePersonalIdentityCode; 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\InvalidCustomerName; use App\Modules\Customers\Domain\Exceptions\InvalidPersonalIdentityCode; @@ -71,6 +72,7 @@ class CustomerForm extends Form BusinessIdAlreadyInUse::class => ['business_id', 'customers.errors.business_id_taken'], InvalidPersonalIdentityCode::class => ['personal_identity_code', 'customers.errors.invalid_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'], default => throw $exception, }; diff --git a/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php b/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php index 1ff03b3..90c19e8 100644 --- a/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php @@ -90,6 +90,9 @@ new class extends Component @interact('column_name', $customer) {{ $customer->name }} + @if ($customer->isInternal) + ({{ __('customers.internal') }}) + @endif @endinteract @interact('column_type', $customer) diff --git a/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php b/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php index 5d22562..0611b75 100644 --- a/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Customers/Presentation/Livewire/⚡show.blade.php @@ -6,7 +6,9 @@ use App\Modules\Customers\Application\DTOs\ContactSummary; use App\Modules\Customers\Application\DTOs\CustomerSummary; use App\Modules\Customers\Application\UseCases\RemoveBillingUnit; 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\ContactInUse; use App\Modules\Customers\Domain\Exceptions\ContactNotFound; use App\Modules\Customers\Domain\Enums\CustomerType; use Illuminate\Support\Facades\Gate; @@ -137,6 +139,8 @@ new class extends Component $this->statusMessage = __('customers.removal.removed_'.$this->removalType, ['name' => $this->removalName]); } catch (ContactNotFound|BillingUnitNotFound) { $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. @@ -174,7 +178,12 @@ new class extends Component
{{ __('customers.fields.type') }}
-
{{ __('customers.types.'.$this->customer->type->value) }}
+
+ {{ __('customers.types.'.$this->customer->type->value) }} + @if ($this->customer->isInternal) + – {{ __('customers.internal') }}. {{ __('customers.internal_description') }} + @endif +
@if ($this->customer->businessId !== null)
{{ __('customers.fields.business_id') }}
diff --git a/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php new file mode 100644 index 0000000..424e217 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/CustomerJobQueries.php @@ -0,0 +1,46 @@ + + */ + public function paginate(JobListFilter $filter, int $perPage = 25): LengthAwarePaginator; + + public function findDetails(int $id): ?CustomerJobDetails; + + /** + * The job's history, newest first. + * + * @return list + */ + public function changes(int $jobId): array; + + /** + * Stored tag names that contain the term, for suggestions. + * + * @return list + */ + 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; +} diff --git a/app/Modules/Jobs/Application/DTOs/CustomerJobData.php b/app/Modules/Jobs/Application/DTOs/CustomerJobData.php new file mode 100644 index 0000000..23ec770 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CustomerJobData.php @@ -0,0 +1,44 @@ + $serviceUnitIds + * @param list $memberUserIds + * @param list $tags + * @param list $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 = [], + ) {} +} diff --git a/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php b/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php new file mode 100644 index 0000000..7ad0ffc --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CustomerJobDetails.php @@ -0,0 +1,61 @@ + $serviceUnits + * @param list $members + * @param list $tags + * @param list $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); + } +} diff --git a/app/Modules/Jobs/Application/DTOs/CustomerJobSummary.php b/app/Modules/Jobs/Application/DTOs/CustomerJobSummary.php new file mode 100644 index 0000000..ed9fdc1 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/CustomerJobSummary.php @@ -0,0 +1,26 @@ +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; + } +} diff --git a/app/Modules/Jobs/Application/UseCases/ChangeJobStatus.php b/app/Modules/Jobs/Application/UseCases/ChangeJobStatus.php new file mode 100644 index 0000000..dd83575 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ChangeJobStatus.php @@ -0,0 +1,39 @@ +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); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php b/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php new file mode 100644 index 0000000..d4f1ceb --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php @@ -0,0 +1,50 @@ +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; + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php b/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php new file mode 100644 index 0000000..35c6453 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php @@ -0,0 +1,45 @@ +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); + }); + } +} diff --git a/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php b/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php new file mode 100644 index 0000000..803fff6 --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/CustomerJobRepository.php @@ -0,0 +1,24 @@ + $changes + */ + public function recordChanges(int $jobId, int $userId, array $changes): void; +} diff --git a/app/Modules/Jobs/Domain/Contracts/JobNumberSequence.php b/app/Modules/Jobs/Domain/Contracts/JobNumberSequence.php new file mode 100644 index 0000000..21009ae --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/JobNumberSequence.php @@ -0,0 +1,16 @@ + + */ + 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 + */ + 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; + } +} diff --git a/app/Modules/Jobs/Domain/Enums/JobKind.php b/app/Modules/Jobs/Domain/Enums/JobKind.php new file mode 100644 index 0000000..d029704 --- /dev/null +++ b/app/Modules/Jobs/Domain/Enums/JobKind.php @@ -0,0 +1,16 @@ + + */ + public static function kanbanStatuses(): array + { + $statuses = []; + + foreach (self::cases() as $status) { + if ($status !== self::Archived) { + $statuses[] = $status; + } + } + + return $statuses; + } +} diff --git a/app/Modules/Jobs/Domain/Enums/PaymentBasis.php b/app/Modules/Jobs/Domain/Enums/PaymentBasis.php new file mode 100644 index 0000000..b6fd9ad --- /dev/null +++ b/app/Modules/Jobs/Domain/Enums/PaymentBasis.php @@ -0,0 +1,17 @@ + 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'), '.'); + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/FieldChange.php b/app/Modules/Jobs/Domain/ValueObjects/FieldChange.php new file mode 100644 index 0000000..9e20705 --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/FieldChange.php @@ -0,0 +1,18 @@ + */ + public array $serviceUnitIds; + + /** @var list */ + public array $memberUserIds; + + /** @var list */ + public array $tags; + + /** + * @param list $serviceUnitIds + * @param list $memberUserIds + * @param list $tags + * @param list $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 + */ + 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)), + ]; + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/JobLink.php b/app/Modules/Jobs/Domain/ValueObjects/JobLink.php new file mode 100644 index 0000000..6c52770 --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/JobLink.php @@ -0,0 +1,33 @@ + 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; + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/JobName.php b/app/Modules/Jobs/Domain/ValueObjects/JobName.php new file mode 100644 index 0000000..df7ccde --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/JobName.php @@ -0,0 +1,28 @@ + self::MAX_LENGTH) { + throw new InvalidJobName; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/JobNumber.php b/app/Modules/Jobs/Domain/ValueObjects/JobNumber.php new file mode 100644 index 0000000..6aecafd --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/JobNumber.php @@ -0,0 +1,36 @@ + 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); + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/Tag.php b/app/Modules/Jobs/Domain/ValueObjects/Tag.php new file mode 100644 index 0000000..43e9f38 --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/Tag.php @@ -0,0 +1,28 @@ + self::MAX_LENGTH) { + throw new InvalidTag; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Jobs/Infrastructure/CustomerRowUsageFromJobs.php b/app/Modules/Jobs/Infrastructure/CustomerRowUsageFromJobs.php new file mode 100644 index 0000000..d26911c --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/CustomerRowUsageFromJobs.php @@ -0,0 +1,23 @@ +where('customer_contact_id', $contactId)->exists(); + } + + public function isBillingUnitInUse(int $billingUnitId): bool + { + return DB::table('customer_jobs')->where('billing_unit_id', $billingUnitId)->exists(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/DatabaseJobNumberSequence.php b/app/Modules/Jobs/Infrastructure/Persistence/DatabaseJobNumberSequence.php new file mode 100644 index 0000000..d20eed2 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/DatabaseJobNumberSequence.php @@ -0,0 +1,25 @@ +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); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php new file mode 100644 index 0000000..75da550 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/CustomerJobModel.php @@ -0,0 +1,82 @@ + */ + use HasFactory; + + /** + * @return array + */ + 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', + ]; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php new file mode 100644 index 0000000..7298c35 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php @@ -0,0 +1,206 @@ +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 + */ + 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 $query + * @return Builder + */ + 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))); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php new file mode 100644 index 0000000..eccb6d5 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobRepository.php @@ -0,0 +1,154 @@ +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 $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 $tags + * @return list + */ + 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); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php new file mode 100644 index 0000000..3a61528 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -0,0 +1,63 @@ + + */ + 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)); + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php b/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php new file mode 100644 index 0000000..1378b9c --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/Forms/JobForm.php @@ -0,0 +1,238 @@ + */ + 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 */ + public array $member_user_ids = []; + + /** @var list */ + public array $tags = []; + + /** @var list */ + 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> + */ + 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 + */ + 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'), + ]; + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php new file mode 100644 index 0000000..f9d32fe --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡form.blade.php @@ -0,0 +1,647 @@ +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 + */ + #[Computed] + public function customerResults(): array + { + $term = trim($this->customerSearch); + + return mb_strlen($term) < 2 ? [] : app(CustomerQueries::class)->search($term, 8); + } + + /** + * @return list + */ + #[Computed] + public function serviceUnitOptions(): array + { + $catalog = app(CatalogQueries::class); + $options = []; + + foreach ($catalog->activeServiceUnits() as $unit) { + $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name]; + } + + // Units already on the job stay visible after being taken out of use. + foreach ($this->form->service_unit_ids as $id) { + if (! isset($options[(int) $id]) && ($unit = $catalog->findServiceUnit((int) $id)) !== null) { + $options[$unit->id] = ['value' => $unit->id, 'label' => $unit->name, 'note' => __('catalog.inactive')]; + } + } + + return array_values($options); + } + + /** + * @return list + */ + #[Computed] + public function users(): array + { + return app(UserAccountQueries::class)->activeUserOptions(); + } + + /** + * @return list + */ + #[Computed] + public function contacts(): array + { + return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->contactsOf((int) $this->form->customer_id); + } + + /** + * @return list + */ + #[Computed] + public function billingUnits(): array + { + return $this->form->customer_id === '' ? [] : app(CustomerQueries::class)->billingUnitsOf((int) $this->form->customer_id); + } + + /** + * Statuses this user may choose: billing statuses for management and the + * job's biller, archived for management, and always the stored one. + * + * @return list + */ + #[Computed] + public function statusOptions(): array + { + return array_values(array_filter( + JobStatus::cases(), + fn (JobStatus $status): bool => $status->value === $this->storedStatus || $this->maySetStatus($status), + )); + } + + /** + * @return list + */ + #[Computed] + public function tagSuggestions(): array + { + return array_values(array_diff(app(CustomerJobQueries::class)->tagSuggestions($this->newTag), $this->form->tags)); + } + + public function 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 + +
+

{{ $this->heading() }}

+ +

{{ $statusMessage }}

+ +
+
+ {{ __('jobs.sections.basics') }} + + + + {{-- Customer: search field and results as buttons, or the chosen customer. --}} +
+ @if ($form->customer_id !== '') +

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

+
+ {{ $customerName }} + +
+ @else + + + @error('form.customer_id') +

{{ $message }}

+ @enderror + + @if (mb_strlen(trim($customerSearch)) >= 2) +

+ {{ trans_choice('jobs.customer_picker.results', count($this->customerResults), ['count' => count($this->customerResults)]) }} +

+ +
    + @foreach ($this->customerResults as $customer) +
  • + +
  • + @endforeach +
+ + @can('customers.use') + + @endcan + @endif + @endif +
+ + + + +
+ +
+ {{ __('jobs.sections.schedule') }} + +
+ + + + +
+
+ +
+ {{ __('jobs.sections.classification') }} + +
+ {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + @foreach ($this->statusOptions as $status) + + @endforeach + + + + @foreach (Priority::cases() as $priority) + + @endforeach + + + + @foreach (JobKind::cases() as $kind) + + @endforeach + + + + + @foreach (PaymentBasis::cases() as $basis) + + @endforeach + + + +
+
+ +
+ {{ __('jobs.sections.members') }} + +
+ + + @foreach ($staffOptions as $user) + + @endforeach + + + + + @foreach ($staffOptions as $user) + + @endforeach + + + + + @foreach ($staffOptions as $user) + + @endforeach + + + + + @foreach ($this->contacts as $contact) + + @endforeach + + + + + @foreach ($this->billingUnits as $billingUnit) + + @endforeach + +
+ + +
+ +
+ {{ __('jobs.sections.extra') }} + + + + {{-- Tags: free text with suggestions from earlier tags, added one at a time. --}} +
+
+
+ + + @foreach ($this->tagSuggestions as $suggestion) + + @endforeach + +
+ +
+ +

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

+ @if ($form->tags === []) +

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

+ @else +
    + @foreach ($form->tags as $index => $tag) +
  • + {{ $tag }} + +
  • + @endforeach +
+ @endif + @error('form.tags') +

{{ $message }}

+ @enderror +
+ + {{-- Links: title and address per row. --}} +
+

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

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

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

+ @endif + + @foreach ($form->links as $index => $link) +
+ {{ __('jobs.links.link_number', ['number' => $index + 1]) }} +
+ + +
+ +
+ @endforeach + + + + @error('form.links') +

{{ $message }}

+ @enderror +
+ + +
+ +
+ + +
+
+
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡index.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..f7de9f5 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,190 @@ +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 + */ + #[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 + */ + 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')); + } +}; +?> + +
+
+

{{ __('jobs.title') }}

+ + @can('jobs.manage') + + @endcan +
+ + @if (session('status')) + + @endif + + @if ($this->isSubcontractor()) +

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

+ @endif + +
+
+ +
+ + {{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}} + + + @foreach (JobStatus::cases() as $option) + + @endforeach + + + + + @foreach (Priority::cases() as $option) + + @endforeach + + + + + @foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit) + + @endforeach + + +
+ @unless ($this->isSubcontractor()) + + @endunless + +
+
+ +

+ {{ trans_choice('jobs.list.result_count', $this->jobs->total(), ['count' => $this->jobs->total()]) }} + @if ($mine && ! $this->isSubcontractor()) + – {{ __('jobs.list.only_mine_description') }} + @endif +

+ + @if ($this->jobs->total() === 0) +

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

+ @else + + @interact('column_number', $job) + {{ $job->number }} + @endinteract + + @interact('column_name', $job) + {{ $job->name }} + @endinteract + + @interact('column_status', $job) + {{ __('jobs.statuses.'.$job->status->value) }} + @endinteract + + @interact('column_priority', $job) + + @endinteract + + @interact('column_dueOn', $job) + + @endinteract + + @endif +
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php new file mode 100644 index 0000000..14182cf --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -0,0 +1,240 @@ +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 + */ + #[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) + +
+
+
+

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

+ + @can('jobs.manage') + + @endcan +
+ + @if (session('status')) + + @endif + +
+
{{ __('jobs.fields.status') }}:
{{ __('jobs.statuses.'.$job->status->value) }}
+
{{ __('jobs.fields.priority') }}:
+
{{ __('jobs.fields.due_on') }}:
+
+
+ +
+

{{ __('jobs.sections.basics') }}

+ +
+
{{ __('jobs.fields.customer') }}
+
+ @can('customers.use') + {{ $job->customer->name }} + @else + {{ $job->customer->name }} + @endcan +
+ +
{{ __('jobs.fields.service_units') }}
+
{{ collect($job->serviceUnits)->pluck('name')->join(', ') }}
+ +
{{ __('jobs.fields.kind') }}
+
{{ __('jobs.kinds.'.$job->kind->value) }}
+ +
{{ __('jobs.fields.payment_basis') }}
+
{{ $job->paymentBasis === null ? __('jobs.not_set') : __('jobs.payment_bases.'.$job->paymentBasis->value) }}
+ +
{{ __('jobs.fields.estimated_hours') }}
+
{{ $job->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $job->estimatedHours).' h' }}
+ +
{{ __('jobs.fields.customer_reference') }}
+
{{ $job->customerReference ?? __('jobs.not_set') }}
+ +
{{ __('jobs.fields.tags') }}
+
{{ $job->tags === [] ? __('jobs.tags.none') : implode(', ', $job->tags) }}
+ +
{{ __('jobs.fields.created_at') }}
+
{{ CarbonImmutable::parse($job->createdAt)->format('j.n.Y H.i') }}, {{ $job->createdByName }}
+
+ + @if ($job->description !== null) +

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

+

{{ $job->description }}

+ @endif +
+ +
+

{{ __('jobs.sections.schedule') }}

+ +
+
{{ __('jobs.fields.starts_on') }}
+
{{ $this->formatDate($job->startsOn) }}
+
{{ __('jobs.fields.due_on') }}
+
+
{{ __('jobs.fields.planned_from') }}
+
{{ $this->formatDate($job->plannedFrom) }}
+
{{ __('jobs.fields.planned_to') }}
+
{{ $this->formatDate($job->plannedTo) }}
+
+
+ +
+

{{ __('jobs.sections.members') }}

+ +
+
{{ __('jobs.fields.responsible_user') }}
+
{{ $job->responsible->name }}
+
{{ __('jobs.fields.contact_user') }}
+
{{ $job->contactUser->name ?? __('jobs.not_set') }}
+
{{ __('jobs.fields.customer_contact') }}
+
{{ $job->customerContact->name ?? __('jobs.not_set') }}
+
{{ __('jobs.fields.biller_user') }}
+
{{ $job->biller->name ?? __('jobs.not_set') }}
+
{{ __('jobs.fields.billing_unit') }}
+
{{ $job->billingUnit->name ?? __('jobs.not_set') }}
+
{{ __('jobs.fields.members') }}
+
{{ $job->members === [] ? __('jobs.not_set') : collect($job->members)->pluck('name')->join(', ') }}
+
+
+ +
+ + + @if ($job->links === []) +

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

+ @else +
    + @foreach ($job->links as $link) +
  • + + {{ $link['title'] }} ({{ __('jobs.opens_in_new_tab') }}) + +
  • + @endforeach +
+ @endif +
+ +
+

{{ __('jobs.sections.instructions') }}

+

{{ $job->instructions ?? __('jobs.not_set') }}

+
+ +
+

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

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

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

+ @else +
    + @foreach ($this->changes as $change) +
  1. + @if ($change->field === 'created') + {{ __('jobs.history.created', ['user' => $change->userName, 'number' => $change->newValue]) }} + @else + {{ __('jobs.history.changed', [ + 'field' => __('jobs.fields.'.$change->field), + 'old' => $this->historyValue($change->field, $change->oldValue), + 'new' => $this->historyValue($change->field, $change->newValue), + ]) }} + @endif + + {{ __('jobs.history.by', ['user' => $change->userName, 'time' => CarbonImmutable::parse($change->changedAt)->format('j.n.Y H.i')]) }} + +
  2. + @endforeach +
+ @endif +
+
diff --git a/app/Modules/Jobs/Presentation/Routes/web.php b/app/Modules/Jobs/Presentation/Routes/web.php new file mode 100644 index 0000000..b29f1ff --- /dev/null +++ b/app/Modules/Jobs/Presentation/Routes/web.php @@ -0,0 +1,13 @@ +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'); + }); diff --git a/app/Modules/Users/Application/Contracts/UserAccountQueries.php b/app/Modules/Users/Application/Contracts/UserAccountQueries.php index 4141f52..b30c24c 100644 --- a/app/Modules/Users/Application/Contracts/UserAccountQueries.php +++ b/app/Modules/Users/Application/Contracts/UserAccountQueries.php @@ -28,4 +28,19 @@ interface UserAccountQueries * @return list */ public function supervisorOptions(?int $exceptUserId = null): array; + + /** + * Active users ordered by name, with their role, for choosing job members. + * + * @return list + */ + public function activeUserOptions(): array; + + /** + * User names for many ids at once, active or not (for lists and history). + * + * @param list $ids + * @return array + */ + public function namesByIds(array $ids): array; } diff --git a/app/Modules/Users/Application/DTOs/UserOption.php b/app/Modules/Users/Application/DTOs/UserOption.php index 2763b02..621ef8b 100644 --- a/app/Modules/Users/Application/DTOs/UserOption.php +++ b/app/Modules/Users/Application/DTOs/UserOption.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace App\Modules\Users\Application\DTOs; +use App\Modules\Users\Domain\Enums\Role; + /** * A user as a choice in a select list. */ @@ -12,5 +14,6 @@ final readonly class UserOption public function __construct( public int $id, public string $name, + public ?Role $role = null, ) {} } diff --git a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php index a6e2ead..0008042 100644 --- a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php +++ b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php @@ -50,6 +50,22 @@ class EloquentUserAccountQueries implements UserAccountQueries ->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 { return new UserSummary( diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 5b7bb22..0bcca4b 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -2,6 +2,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; +use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider; use App\Providers\AppServiceProvider; @@ -12,4 +13,6 @@ return [ UsersServiceProvider::class, CustomersServiceProvider::class, CatalogServiceProvider::class, + // After Customers: replaces its CustomerRowUsage binding. + JobsServiceProvider::class, ]; diff --git a/database/factories/CustomerJobFactory.php b/database/factories/CustomerJobFactory.php new file mode 100644 index 0000000..0acc819 --- /dev/null +++ b/database/factories/CustomerJobFactory.php @@ -0,0 +1,72 @@ + + */ +class CustomerJobFactory extends Factory +{ + protected $model = CustomerJobModel::class; + + private static int $sequence = 9000; + + /** + * @return array + */ + 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 $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, + )); + }); + } +} diff --git a/database/migrations/2026_11_23_163503_add_is_internal_to_customers_table.php b/database/migrations/2026_11_23_163503_add_is_internal_to_customers_table.php new file mode 100644 index 0000000..20e6403 --- /dev/null +++ b/database/migrations/2026_11_23_163503_add_is_internal_to_customers_table.php @@ -0,0 +1,28 @@ +boolean('is_internal')->default(false)->after('type'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('customers', function (Blueprint $table) { + $table->dropColumn('is_internal'); + }); + } +}; diff --git a/database/migrations/2026_11_23_163505_insert_internal_customer.php b/database/migrations/2026_11_23_163505_insert_internal_customer.php new file mode 100644 index 0000000..f9bb37d --- /dev/null +++ b/database/migrations/2026_11_23_163505_insert_internal_customer.php @@ -0,0 +1,31 @@ +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 {} +}; diff --git a/database/migrations/2026_11_23_163932_create_customer_jobs_tables.php b/database/migrations/2026_11_23_163932_create_customer_jobs_tables.php new file mode 100644 index 0000000..26f7e51 --- /dev/null +++ b/database/migrations/2026_11_23_163932_create_customer_jobs_tables.php @@ -0,0 +1,107 @@ +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'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 92a9daa..8a55da9 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -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. - 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. -- 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ö @@ -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ä) **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` - `customer_job_service_unit`: `customer_job_id`, `service_unit_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 - 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. -- Sisäinen asiakas on merkitty, eikä sitä voi poistaa. +- Kun asiakastyö viittaa yhteyshenkilöön tai laskutusyksikköön, sen poisto estetään ja asiakassivu kertoo syyn *(valmis)*. +- Sisäinen asiakas on merkitty listalla ja asiakassivulla, eikä sitä voi poistaa *(valmis)*. ### 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ä). @@ -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)*. ### 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. - Asiakkaan voi hakea kirjoittamalla tai lisätä nimellä, jos sitä ei löydy. - Tagin voi valita listasta tai lisätä uuden, joka jää listaan. diff --git a/lang/fi/customers.php b/lang/fi/customers.php index 7e626d9..63cd72b 100644 --- a/lang/fi/customers.php +++ b/lang/fi/customers.php @@ -20,6 +20,8 @@ return [ 'edit_details' => 'Muokkaa tietoja', 'remove' => 'Poista', 'customer_label' => 'Asiakas', + 'internal' => 'Sisäinen', + 'internal_description' => 'Oma yritys. Sen asiakastöille kirjataan sisäinen työ, kuten hallinto, myynti ja koulutus.', 'contacts' => [ 'title' => 'Yhteyshenkilöt', @@ -72,6 +74,8 @@ return [ 'removed_contact' => 'Yhteyshenkilö :name poistettu.', 'removed_billing_unit' => 'Laskutusyksikkö :name 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' => [ @@ -100,6 +104,7 @@ return [ '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.', '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ä.', 'contact_name_required' => 'Anna yhteyshenkilön nimi.', 'invalid_contact_name' => 'Nimen pituus voi olla enintään 255 merkkiä.', diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php new file mode 100644 index 0000000..2792208 --- /dev/null +++ b/lang/fi/jobs.php @@ -0,0 +1,170 @@ + '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ä.', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index 450dfd7..d006f20 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -4,6 +4,7 @@ return [ 'skip_to_content' => 'Siirry pääsisältöön', 'main_menu' => 'Päävalikko', 'home' => 'Etusivu', + 'jobs' => 'Asiakastyöt', 'customers' => 'Asiakkaat', 'users' => 'Käyttäjät', 'catalog' => 'Pohjatiedot', diff --git a/resources/views/components/checkbox-group.blade.php b/resources/views/components/checkbox-group.blade.php new file mode 100644 index 0000000..316c860 --- /dev/null +++ b/resources/views/components/checkbox-group.blade.php @@ -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 + +
class('space-y-2') }} + @if ($hint !== null || $errors->has($errorKey)) aria-describedby="{{ trim(($hint !== null ? $id.'-hint ' : '').($errors->has($errorKey) ? $id.'-error' : '')) }}" @endif +> + {{ $legend }} + + @if ($hint !== null) +

{{ $hint }}

+ @endif + +
$columns])> + @foreach ($options as $option) + + @endforeach +
+ + @error($errorKey) +

{{ $message }}

+ @enderror +
diff --git a/resources/views/components/jobs/due-date.blade.php b/resources/views/components/jobs/due-date.blade.php new file mode 100644 index 0000000..59929ad --- /dev/null +++ b/resources/views/components/jobs/due-date.blade.php @@ -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 + + class('inline-flex flex-wrap items-center gap-1') }}> + {{ \Carbon\CarbonImmutable::parse($date)->format('j.n.Y') }} + @if ($isLate) + + + @endif + +@endif diff --git a/resources/views/components/jobs/priority.blade.php b/resources/views/components/jobs/priority.blade.php new file mode 100644 index 0000000..29556fb --- /dev/null +++ b/resources/views/components/jobs/priority.blade.php @@ -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 + +class('inline-flex items-center gap-2') }}> + + {{ __('jobs.priorities.'.$priority->value) }} + diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index c3d4391..ab09f66 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -55,7 +55,11 @@