Add the task calendar, holidays, workflow templates and customer removal

Task calendar (/jobs/calendar) replaces per-unit task Kanban columns
(K34): a two-week Gantt of tasks per person. Bars move, resize and
change person by dragging or through a keyboard dialog. Each task's
estimate is booked evenly over working days into task_bookings, and
what exceeds the daily maximum (jobs.daily_capacity_hours, 8 h) moves
to the next working day. Tasks get planned_from/planned_to on the form.

Holidays (/settings/holidays): Finnish public holidays calculated per
year, which the admin can take out of use, plus company days off.

Also includes the earlier uncommitted work: workflow templates with
adding tasks from a template, and removing customers no module refers to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 18:13:11 +02:00
co-authored by Claude Opus 5.5
parent dfe4941f02
commit b4f2f1cfaa
134 changed files with 6930 additions and 45 deletions
@@ -0,0 +1,18 @@
<?php
namespace App\Modules\Billing\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use Illuminate\Support\Facades\DB;
/**
* Tells the Customers module whether a customer is on billing material.
*/
class CustomerReferencesFromBilling implements CustomerReferences
{
public function refersTo(int $customerId): bool
{
return DB::table('billing_invoices')->where('customer_id', $customerId)->exists()
|| DB::table('billing_invoice_jobs')->where('customer_id', $customerId)->exists();
}
}
@@ -10,6 +10,7 @@ use App\Modules\Billing\Application\Contracts\BillingJobs;
use App\Modules\Billing\Application\Contracts\BillingPrices;
use App\Modules\Billing\Application\Contracts\BillingQueries;
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
use App\Modules\Billing\Infrastructure\CustomerReferencesFromBilling;
use App\Modules\Billing\Infrastructure\CustomersForBilling;
use App\Modules\Billing\Infrastructure\ExpensesForBilling;
use App\Modules\Billing\Infrastructure\HoursForBilling;
@@ -17,6 +18,7 @@ use App\Modules\Billing\Infrastructure\JobsForBilling;
use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingExportRepository;
use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingQueries;
use App\Modules\Billing\Infrastructure\PricesForBilling;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
@@ -41,6 +43,12 @@ class BillingServiceProvider extends ServiceProvider
BillingCustomers::class => CustomersForBilling::class,
];
public function register(): void
{
// A customer with invoices cannot be removed.
$this->app->tag([CustomerReferencesFromBilling::class], CustomerReferences::TAG);
}
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\Contracts;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary;
/**
* Read side of workflow templates (työnkulkupohjat). Customer jobs use it
* to make tasks from a template.
*/
interface WorkflowTemplateQueries
{
/**
* All templates, active or not, in the order of their work types in the
* catalog (the shared unit last) and by name.
*
* @return list<WorkflowTemplateSummary>
*/
public function all(): array;
public function find(int $id): ?WorkflowTemplateDetails;
/**
* Active templates whose work type is in use in the given service units
* or in the shared unit, in catalog order and by name.
*
* @param list<int> $serviceUnitIds
* @return list<WorkflowTemplateDetails>
*/
public function activeFor(array $serviceUnitIds): array;
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A step of a workflow template as entered. A null work type means the template's own.
*/
final readonly class WorkflowStepData
{
public function __construct(
public string $title,
public ?string $description = null,
public ?int $workTypeId = null,
) {}
/**
* @param array{title?: string, description?: string|null, work_type_id?: int|string|null} $input
*/
public static function fromArray(array $input): self
{
$workTypeId = $input['work_type_id'] ?? null;
return new self(
(string) ($input['title'] ?? ''),
$input['description'] ?? null,
$workTypeId === null || $workTypeId === '' ? null : (int) $workTypeId,
);
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A step of a workflow template. $workTypeId is the step's own work type
* (null: the template's), $effectiveWorkTypeId the one its task gets.
*/
final readonly class WorkflowStepSummary
{
public function __construct(
public string $title,
public ?string $description,
public ?int $workTypeId,
public int $effectiveWorkTypeId,
public string $workTypeName,
) {}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A workflow template as entered on its form.
*/
final readonly class WorkflowTemplateData
{
/**
* @param list<WorkflowStepData> $steps
*/
public function __construct(
public string $name,
public int $workTypeId,
public array $steps,
) {}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A workflow template with its steps in order.
*/
final readonly class WorkflowTemplateDetails
{
/**
* @param list<WorkflowStepSummary> $steps
*/
public function __construct(
public int $id,
public string $name,
public int $workTypeId,
public string $workTypeName,
public int $serviceUnitId,
public bool $isActive,
public array $steps,
) {}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A workflow template on the template list.
*/
final readonly class WorkflowTemplateSummary
{
public function __construct(
public int $id,
public string $name,
public int $workTypeId,
public string $workTypeName,
public int $serviceUnitId,
public string $serviceUnitName,
public bool $isActive,
public int $stepCount,
) {}
}
@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\Services;
use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\WorkType;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
/**
* Builds the steps of a workflow template from input and checks their own work types.
*/
final class WorkflowStepBuilder
{
public function __construct(
private WorkTypeRepository $workTypes,
private ServiceUnitRepository $serviceUnits,
) {}
/**
* @param list<WorkflowStepData> $input
* @return list<WorkflowStep>
*
* @throws InvalidWorkflowStepTitle with the index of the step
*/
public function build(array $input): array
{
$steps = [];
foreach ($input as $index => $step) {
try {
$title = new WorkflowStepTitle($step->title);
} catch (InvalidWorkflowStepTitle) {
throw new InvalidWorkflowStepTitle($index);
}
$steps[] = new WorkflowStep($title, $step->description, $step->workTypeId);
}
return $steps;
}
/**
* A step's own work type must be in use and belong to the template work
* type's unit or to the shared unit. A work type the template already
* uses stays allowed after it is taken out of use.
*
* @param list<WorkflowStep> $steps
* @param list<WorkflowStep> $currentSteps
*
* @throws WorkflowStepWorkTypeNotAllowed
*/
public function checkWorkTypes(WorkType $templateWorkType, array $steps, array $currentSteps = []): void
{
$currentIds = array_map(fn (WorkflowStep $step): ?int => $step->workTypeId, $currentSteps);
foreach ($steps as $index => $step) {
if ($step->workTypeId === null || $step->workTypeId === $templateWorkType->id()) {
continue;
}
$workType = $this->workTypes->findById($step->workTypeId);
if ($workType === null
|| (! $workType->isActive() && ! in_array($workType->id(), $currentIds, true))
|| ! $this->sameOrSharedUnit($templateWorkType, $workType)) {
throw new WorkflowStepWorkTypeNotAllowed($index);
}
}
}
private function sameOrSharedUnit(WorkType $templateWorkType, WorkType $workType): bool
{
return $workType->serviceUnitId() === $templateWorkType->serviceUnitId()
|| ($this->serviceUnits->findById($workType->serviceUnitId())?->isShared() ?? false);
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Application\Services\WorkflowStepBuilder;
use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Entities\WorkflowTemplate;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNeedsSteps;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Adds a workflow template to an active work type and returns its id.
*/
final class AddWorkflowTemplate
{
public function __construct(
private WorkflowTemplateRepository $templates,
private WorkTypeRepository $workTypes,
private WorkflowStepBuilder $stepBuilder,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound when the work type is missing or not in use
* @throws InvalidCatalogName
* @throws InvalidWorkflowStepTitle
* @throws WorkflowStepWorkTypeNotAllowed
* @throws WorkflowTemplateNameTaken
* @throws WorkflowTemplateNeedsSteps
*/
public function execute(WorkflowTemplateData $data): int
{
$name = new CatalogName($data->name);
$steps = $this->stepBuilder->build($data->steps);
$template = WorkflowTemplate::create($data->workTypeId, $name, $steps);
return $this->transactions->run(function () use ($data, $name, $steps, $template): int {
$workType = $this->workTypes->findById($data->workTypeId);
if ($workType === null || ! $workType->isActive()) {
throw new CatalogItemNotFound(CatalogLevel::WorkType, $data->workTypeId);
}
if ($this->templates->isNameTaken($data->workTypeId, $name->value)) {
throw new WorkflowTemplateNameTaken;
}
$this->stepBuilder->checkWorkTypes($workType, $steps);
return (int) $this->templates->save($template)->id();
});
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a workflow template out of use or back into use. A template out of
* use is not offered on customer jobs.
*/
final class SetWorkflowTemplateActive
{
public function __construct(
private WorkflowTemplateRepository $templates,
private TransactionManager $transactions,
) {}
/**
* @throws WorkflowTemplateNotFound
*/
public function execute(int $templateId, bool $active): void
{
$this->transactions->run(function () use ($templateId, $active): void {
$template = $this->templates->findById($templateId) ?? throw new WorkflowTemplateNotFound($templateId);
$active ? $template->activate() : $template->deactivate();
$this->templates->save($template);
});
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Application\Services\WorkflowStepBuilder;
use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Domain\Enums\CatalogLevel;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNeedsSteps;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Saves a workflow template's name, work type and steps. Tasks already made
* from the template do not change.
*/
final class UpdateWorkflowTemplate
{
public function __construct(
private WorkflowTemplateRepository $templates,
private WorkTypeRepository $workTypes,
private WorkflowStepBuilder $stepBuilder,
private TransactionManager $transactions,
) {}
/**
* @throws CatalogItemNotFound when a new work type is missing or not in use
* @throws InvalidCatalogName
* @throws InvalidWorkflowStepTitle
* @throws WorkflowStepWorkTypeNotAllowed
* @throws WorkflowTemplateNameTaken
* @throws WorkflowTemplateNeedsSteps
* @throws WorkflowTemplateNotFound
*/
public function execute(int $templateId, WorkflowTemplateData $data): void
{
$name = new CatalogName($data->name);
$steps = $this->stepBuilder->build($data->steps);
$this->transactions->run(function () use ($templateId, $data, $name, $steps): void {
$template = $this->templates->findById($templateId) ?? throw new WorkflowTemplateNotFound($templateId);
$workType = $this->workTypes->findById($data->workTypeId);
$workTypeChanged = $data->workTypeId !== $template->workTypeId();
if ($workType === null || ($workTypeChanged && ! $workType->isActive())) {
throw new CatalogItemNotFound(CatalogLevel::WorkType, $data->workTypeId);
}
if ($this->templates->isNameTaken($data->workTypeId, $name->value, $templateId)) {
throw new WorkflowTemplateNameTaken;
}
$this->stepBuilder->checkWorkTypes($workType, $steps, $template->steps());
$template->change($data->workTypeId, $name, $steps);
$this->templates->save($template);
});
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\WorkflowTemplate;
interface WorkflowTemplateRepository
{
public function findById(int $id): ?WorkflowTemplate;
/**
* Inserts a new template or updates a stored one, replacing its steps,
* and returns the stored template.
*/
public function save(WorkflowTemplate $template): WorkflowTemplate;
/**
* Whether another template of the work type than $exceptId has this name, ignoring case.
*/
public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool;
}
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNeedsSteps;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
/**
* A workflow template (työnkulkupohja) of a work type, e.g. videokuvaus:
* suunnittelu → kuvaus → editointi → tarkastus → toimitus. Its steps, in
* order, become tasks of a customer job. A work type can have many
* templates with different names. Templates are not deleted, only taken
* out of use.
*/
final class WorkflowTemplate
{
/**
* @param list<WorkflowStep> $steps
*/
private function __construct(
private ?int $id,
private int $workTypeId,
private CatalogName $name,
private bool $active,
private array $steps,
) {}
/**
* @param list<WorkflowStep> $steps
*
* @throws WorkflowTemplateNeedsSteps
*/
public static function create(int $workTypeId, CatalogName $name, array $steps): self
{
self::ensureSteps($steps);
return new self(null, $workTypeId, $name, true, $steps);
}
/**
* @param list<WorkflowStep> $steps
*/
public static function reconstitute(int $id, int $workTypeId, CatalogName $name, bool $active, array $steps): self
{
return new self($id, $workTypeId, $name, $active, $steps);
}
public function id(): ?int
{
return $this->id;
}
public function workTypeId(): int
{
return $this->workTypeId;
}
public function name(): CatalogName
{
return $this->name;
}
public function isActive(): bool
{
return $this->active;
}
/**
* @return list<WorkflowStep>
*/
public function steps(): array
{
return $this->steps;
}
/**
* Changes the name, the work type and the steps at once, as the template form saves them.
*
* @param list<WorkflowStep> $steps
*
* @throws WorkflowTemplateNeedsSteps
*/
public function change(int $workTypeId, CatalogName $name, array $steps): void
{
self::ensureSteps($steps);
$this->workTypeId = $workTypeId;
$this->name = $name;
$this->steps = $steps;
}
public function activate(): void
{
$this->active = true;
}
public function deactivate(): void
{
$this->active = false;
}
/**
* @param list<WorkflowStep> $steps
*/
private static function ensureSteps(array $steps): void
{
if ($steps === []) {
throw new WorkflowTemplateNeedsSteps;
}
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A step title is empty or longer than 255 characters. $stepIndex (from 0)
* tells which step, when the caller knows it.
*/
final class InvalidWorkflowStepTitle extends DomainException
{
public function __construct(public readonly ?int $stepIndex = null)
{
parent::__construct('A workflow step title must be 1–255 characters long.');
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* A step's own work type is not in use, or belongs neither to the template
* work type's service unit nor to the shared unit. $stepIndex counts from 0.
*/
final class WorkflowStepWorkTypeNotAllowed extends DomainException
{
public function __construct(public readonly int $stepIndex)
{
parent::__construct("The work type of workflow step {$stepIndex} is not allowed.");
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class WorkflowTemplateNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('The work type already has a workflow template with this name.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class WorkflowTemplateNeedsSteps extends DomainException
{
public function __construct()
{
parent::__construct('A workflow template needs at least one step.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class WorkflowTemplateNotFound extends DomainException
{
public function __construct(public readonly int $id)
{
parent::__construct("Workflow template {$id} was not found.");
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
/**
* One step of a workflow template. A task is made of it: the title, the
* description and the work type, which is the template's own when
* $workTypeId is null.
*/
final readonly class WorkflowStep
{
public ?string $description;
public function __construct(
public WorkflowStepTitle $title,
?string $description = null,
public ?int $workTypeId = null,
) {
$description = $description === null ? '' : trim($description);
$this->description = $description === '' ? null : $description;
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\ValueObjects;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
/**
* Title of a workflow step, e.g. "Editointi". It becomes a task title, so
* its length limit is the same as a task title's.
*/
final readonly class WorkflowStepTitle
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidWorkflowStepTitle;
}
$this->value = $value;
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property int $work_type_id
* @property string $name
* @property bool $is_active
*/
#[Table('workflow_templates')]
#[Fillable(['work_type_id', 'name', 'is_active'])]
class WorkflowTemplateModel extends Model
{
/**
* @return HasMany<WorkflowTemplateStepModel, $this>
*/
public function steps(): HasMany
{
return $this->hasMany(WorkflowTemplateStepModel::class, 'workflow_template_id')->orderBy('sort_order');
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'work_type_id' => 'integer',
'is_active' => 'boolean',
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property int $workflow_template_id
* @property int|null $work_type_id
* @property string $title
* @property string|null $description
* @property int $sort_order
*/
#[Table('workflow_template_steps')]
#[Fillable(['workflow_template_id', 'work_type_id', 'title', 'description', 'sort_order'])]
class WorkflowTemplateStepModel extends Model
{
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'workflow_template_id' => 'integer',
'work_type_id' => 'integer',
'sort_order' => 'integer',
];
}
}
@@ -0,0 +1,128 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowStepSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
class EloquentWorkflowTemplateQueries implements WorkflowTemplateQueries
{
public function all(): array
{
return $this->ordered()
->withCount('steps')
->get()
->map(fn (WorkflowTemplateModel $model): WorkflowTemplateSummary => new WorkflowTemplateSummary(
$model->id,
$model->name,
$model->work_type_id,
(string) $model->getAttribute('work_type_name'),
(int) $model->getAttribute('service_unit_id'),
(string) $model->getAttribute('service_unit_name'),
$model->is_active,
(int) $model->getAttribute('steps_count'),
))
->values()
->all();
}
public function find(int $id): ?WorkflowTemplateDetails
{
$models = $this->ordered()->whereKey($id)->get();
return $this->toDetails($models)[0] ?? null;
}
public function activeFor(array $serviceUnitIds): array
{
$models = $this->ordered()
->where('workflow_templates.is_active', true)
->where('work_types.is_active', true)
->where('service_units.is_active', true)
->where(fn (Builder $query) => $query->whereNull('services.id')->orWhere('services.is_active', true))
->where(fn (Builder $query) => $query
->whereIn('service_units.id', $serviceUnitIds)
->orWhere('service_units.is_shared', true))
->get();
return $this->toDetails($models);
}
/**
* Templates with their work type and unit, in catalog order: units (the
* shared one last), services, work types under no service last, then by name.
*
* @return Builder<WorkflowTemplateModel>
*/
private function ordered(): Builder
{
return WorkflowTemplateModel::query()
->join('work_types', 'work_types.id', '=', 'workflow_templates.work_type_id')
->join('service_units', 'service_units.id', '=', 'work_types.service_unit_id')
->leftJoin('services', 'services.id', '=', 'work_types.service_id')
->select('workflow_templates.*')
->addSelect([
'work_types.name as work_type_name',
'service_units.id as service_unit_id',
'service_units.name as service_unit_name',
])
->orderBy('service_units.is_shared')
->orderBy('service_units.sort_order')
->orderByRaw('services.sort_order IS NULL')
->orderBy('services.sort_order')
->orderBy('work_types.sort_order')
->orderBy('workflow_templates.name')
->orderBy('workflow_templates.id');
}
/**
* @param Collection<int, WorkflowTemplateModel> $models
* @return list<WorkflowTemplateDetails>
*/
private function toDetails(Collection $models): array
{
if ($models->isEmpty()) {
return [];
}
$steps = WorkflowTemplateStepModel::query()
->whereIn('workflow_template_id', $models->pluck('id'))
->orderBy('sort_order')
->get()
->groupBy('workflow_template_id');
$workTypeNames = WorkTypeModel::query()
->whereIn('id', $steps->flatten(1)->pluck('work_type_id')->filter()->unique())
->pluck('name', 'id');
return $models->map(function (WorkflowTemplateModel $model) use ($steps, $workTypeNames): WorkflowTemplateDetails {
$workTypeName = (string) $model->getAttribute('work_type_name');
return new WorkflowTemplateDetails(
$model->id,
$model->name,
$model->work_type_id,
$workTypeName,
(int) $model->getAttribute('service_unit_id'),
$model->is_active,
($steps->get($model->id) ?? collect())
->map(fn (WorkflowTemplateStepModel $step): WorkflowStepSummary => new WorkflowStepSummary(
$step->title,
$step->description,
$step->work_type_id,
$step->work_type_id ?? $model->work_type_id,
$step->work_type_id === null ? $workTypeName : (string) $workTypeNames->get($step->work_type_id),
))
->values()
->all(),
);
})->values()->all();
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Entities\WorkflowTemplate;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStep;
use App\Modules\Catalog\Domain\ValueObjects\WorkflowStepTitle;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkflowTemplateStepModel;
class EloquentWorkflowTemplateRepository implements WorkflowTemplateRepository
{
public function findById(int $id): ?WorkflowTemplate
{
$model = WorkflowTemplateModel::query()->with('steps')->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(WorkflowTemplate $template): WorkflowTemplate
{
$model = $template->id() === null ? new WorkflowTemplateModel : WorkflowTemplateModel::query()->findOrFail($template->id());
$model->fill([
'work_type_id' => $template->workTypeId(),
'name' => $template->name()->value,
'is_active' => $template->isActive(),
])->save();
// Steps have no identity of their own: the saved list replaces the old one.
WorkflowTemplateStepModel::query()->where('workflow_template_id', $model->id)->delete();
foreach ($template->steps() as $index => $step) {
WorkflowTemplateStepModel::query()->create([
'workflow_template_id' => $model->id,
'work_type_id' => $step->workTypeId,
'title' => $step->title->value,
'description' => $step->description,
'sort_order' => $index + 1,
]);
}
return $this->toEntity($model->load('steps'));
}
public function isNameTaken(int $workTypeId, string $name, ?int $exceptId = null): bool
{
return WorkflowTemplateModel::query()
->where('work_type_id', $workTypeId)
->whereRaw('LOWER(name) = ?', [mb_strtolower($name)])
->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId))
->exists();
}
private function toEntity(WorkflowTemplateModel $model): WorkflowTemplate
{
return WorkflowTemplate::reconstitute(
$model->id,
$model->work_type_id,
new CatalogName($model->name),
$model->is_active,
$model->steps
->map(fn (WorkflowTemplateStepModel $step): WorkflowStep => new WorkflowStep(
new WorkflowStepTitle($step->title),
$step->description,
$step->work_type_id,
))
->values()
->all(),
);
}
}
@@ -5,10 +5,12 @@ namespace App\Modules\Catalog\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Domain\Contracts\ProductRepository;
use App\Modules\Catalog\Domain\Contracts\ServiceRepository;
use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Contracts\WorkflowTemplateRepository;
use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentCatalogQueries;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentPriceListQueries;
@@ -16,6 +18,8 @@ use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentProductR
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceUnitRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentVatRateRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkflowTemplateQueries;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkflowTemplateRepository;
use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkTypeRepository;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
@@ -40,6 +44,8 @@ class CatalogServiceProvider extends ServiceProvider
ProductRepository::class => EloquentProductRepository::class,
PriceListQueries::class => EloquentPriceListQueries::class,
VatRateRepository::class => EloquentVatRateRepository::class,
WorkflowTemplateRepository::class => EloquentWorkflowTemplateRepository::class,
WorkflowTemplateQueries::class => EloquentWorkflowTemplateQueries::class,
];
public function boot(): void
@@ -0,0 +1,103 @@
<?php
namespace App\Modules\Catalog\Presentation\Livewire\Forms;
use App\Modules\Catalog\Application\DTOs\WorkflowStepData;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateData;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\InvalidWorkflowStepTitle;
use App\Modules\Catalog\Domain\Exceptions\WorkflowStepWorkTypeNotAllowed;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNameTaken;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNeedsSteps;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Form;
/**
* Name, work type and steps of a workflow template. Each step has a `key`
* that stays the same while steps are moved, for wire:key and element ids.
*/
class WorkflowTemplateForm extends Form
{
public string $name = '';
public string $work_type_id = '';
/**
* @var list<array{key: int, title: string, work_type_id: string, description: string}>
*/
public array $steps = [];
public int $nextKey = 1;
public function addStep(string $title = '', string $workTypeId = '', string $description = ''): int
{
$key = $this->nextKey++;
$this->steps[] = ['key' => $key, 'title' => $title, 'work_type_id' => $workTypeId, 'description' => $description];
return $key;
}
public function toData(): WorkflowTemplateData
{
$this->validate();
return new WorkflowTemplateData(
$this->name,
(int) $this->work_type_id,
array_map(fn (array $step): WorkflowStepData => WorkflowStepData::fromArray($step), $this->steps),
);
}
/**
* 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 InvalidCatalogName => ['name', 'catalog.errors.invalid_name'],
$exception instanceof WorkflowTemplateNameTaken => ['name', 'catalog.workflows.errors.name_taken'],
$exception instanceof CatalogItemNotFound => ['work_type_id', 'catalog.errors.work_type_unavailable'],
$exception instanceof WorkflowTemplateNeedsSteps => ['steps', 'catalog.workflows.errors.steps_required'],
$exception instanceof InvalidWorkflowStepTitle => ['steps.'.($exception->stepIndex ?? 0).'.title', 'catalog.workflows.errors.invalid_step_title'],
$exception instanceof WorkflowStepWorkTypeNotAllowed => ['steps.'.$exception->stepIndex.'.work_type_id', 'catalog.workflows.errors.step_work_type_not_allowed'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, string>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:100'],
'work_type_id' => ['required', 'integer'],
'steps' => ['required', 'array', 'min:1'],
'steps.*.title' => ['required', 'string', 'max:255'],
'steps.*.work_type_id' => ['nullable', 'integer'],
'steps.*.description' => ['nullable', 'string', 'max:5000'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('catalog.errors.name_required'),
'name.max' => __('catalog.errors.invalid_name'),
'work_type_id.required' => __('catalog.workflows.errors.work_type_required'),
'work_type_id.integer' => __('catalog.errors.work_type_unavailable'),
'steps.required' => __('catalog.workflows.errors.steps_required'),
'steps.min' => __('catalog.workflows.errors.steps_required'),
'steps.*.title.required' => __('catalog.workflows.errors.step_title_required'),
'steps.*.title.max' => __('catalog.workflows.errors.invalid_step_title'),
'steps.*.work_type_id.integer' => __('catalog.workflows.errors.step_work_type_not_allowed'),
'steps.*.description.max' => __('catalog.workflows.errors.description_too_long'),
];
}
}
@@ -122,6 +122,7 @@ new class extends Component
<div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.intro') }}</p>
<p><x-link :href="route('catalog.prices')" navigate>{{ __('catalog.prices_link') }}</x-link></p>
<p><x-link :href="route('catalog.workflow-templates')" navigate>{{ __('catalog.workflows_link') }}</x-link></p>
</div>
@if (session('status'))
@@ -0,0 +1,353 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkTypeSummary;
use App\Modules\Catalog\Application\UseCases\AddWorkflowTemplate;
use App\Modules\Catalog\Application\UseCases\UpdateWorkflowTemplate;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use App\Modules\Catalog\Presentation\Livewire\Forms\WorkflowTemplateForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page and edit page (with {template}) of a workflow template: its name,
* work type and steps. Steps are added, moved and removed with buttons, and
* everything is saved at once.
*/
new class extends Component
{
#[Locked]
public ?int $templateId = null;
/**
* Work types the stored template uses, offered even if out of use.
*
* @var list<int>
*/
#[Locked]
public array $storedWorkTypeIds = [];
public WorkflowTemplateForm $form;
public string $statusMessage = '';
public function mount(WorkflowTemplateQueries $templates, ?int $template = null): void
{
$this->authorize('catalog.manage');
if ($template === null) {
$this->form->addStep();
return;
}
$details = $templates->find($template);
abort_if($details === null, 404);
$this->templateId = $details->id;
$this->form->name = $details->name;
$this->form->work_type_id = (string) $details->workTypeId;
$this->storedWorkTypeIds = [$details->workTypeId];
foreach ($details->steps as $step) {
$this->form->addStep($step->title, $step->workTypeId === null ? '' : (string) $step->workTypeId, $step->description ?? '');
if ($step->workTypeId !== null) {
$this->storedWorkTypeIds[] = $step->workTypeId;
}
}
}
/**
* Work types for the template, as optgroups "Unit" or "Unit – Service".
*
* @return array<string, list<WorkTypeSummary>>
*/
#[Computed]
public function workTypeGroups(): array
{
return $this->groups(app(CatalogQueries::class)->tree(includeInactive: false));
}
/**
* Work types a step can have: those of the template work type's unit and the shared ones.
*
* @return array<string, list<WorkTypeSummary>>
*/
#[Computed]
public function stepWorkTypeGroups(): array
{
$catalog = app(CatalogQueries::class);
$workType = $this->form->work_type_id === '' ? null : $catalog->findWorkType((int) $this->form->work_type_id);
return $workType === null ? [] : $this->groups($catalog->activeWorkTypesFor([$workType->serviceUnitId]));
}
public function addStep(): void
{
$this->authorize('catalog.manage');
$key = $this->form->addStep();
$this->statusMessage = __('catalog.workflows.status.step_added', ['number' => count($this->form->steps)]);
$this->js("document.getElementById('step-{$key}-title')?.focus()");
}
public function moveStep(int $index, string $direction): void
{
$this->authorize('catalog.manage');
$steps = array_values($this->form->steps);
$target = $direction === 'up' ? $index - 1 : $index + 1;
if (! isset($steps[$index])) {
return;
}
$key = $steps[$index]['key'];
if (! isset($steps[$target])) {
$this->statusMessage = __($direction === 'up' ? 'catalog.workflows.status.already_first' : 'catalog.workflows.status.already_last', ['number' => $index + 1]);
return;
}
[$steps[$index], $steps[$target]] = [$steps[$target], $steps[$index]];
$this->form->steps = $steps;
$this->resetErrorBag();
$this->statusMessage = __('catalog.workflows.status.step_moved', ['from' => $index + 1, 'to' => $target + 1]);
$this->js("document.getElementById('step-{$key}-{$direction}')?.focus()");
}
public function removeStep(int $index): void
{
$this->authorize('catalog.manage');
$steps = array_values($this->form->steps);
if (! isset($steps[$index]) || count($steps) === 1) {
return;
}
array_splice($steps, $index, 1);
$this->form->steps = $steps;
$this->resetErrorBag();
$this->statusMessage = __('catalog.workflows.status.step_removed', ['number' => $index + 1]);
// Focus the step that took its place, the new last one, or the add button.
$next = $steps[$index] ?? $steps[count($steps) - 1];
$this->js(count($steps) > 1
? "document.getElementById('step-{$next['key']}-remove')?.focus()"
: "document.getElementById('add-step')?.focus()");
}
public function save(AddWorkflowTemplate $add, UpdateWorkflowTemplate $update): void
{
$this->authorize('catalog.manage');
$data = $this->form->toData();
try {
if ($this->templateId === null) {
$add->execute($data);
session()->flash('status', __('catalog.status.created', ['name' => trim($data->name)]));
} else {
$update->execute($this->templateId, $data);
session()->flash('status', __('catalog.status.updated', ['name' => trim($data->name)]));
}
} catch (WorkflowTemplateNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('catalog.workflow-templates', navigate: true);
}
public function heading(): string
{
return __($this->templateId === null ? 'catalog.workflows.create_title' : 'catalog.workflows.edit_title');
}
public function render(): mixed
{
return $this->view()->title($this->heading());
}
/**
* @param list<\App\Modules\Catalog\Application\DTOs\ServiceUnitNode> $tree
* @return array<string, list<WorkTypeSummary>>
*/
private function groups(array $tree): array
{
$groups = [];
$offered = [];
foreach ($tree as $node) {
foreach ($node->services as $serviceNode) {
if ($serviceNode->workTypes !== []) {
$groups[$node->serviceUnit->name.' – '.$serviceNode->service->name] = $serviceNode->workTypes;
}
}
if ($node->workTypes !== []) {
$groups[$node->serviceUnit->name] = $node->workTypes;
}
}
foreach ($groups as $workTypes) {
foreach ($workTypes as $workType) {
$offered[] = $workType->id;
}
}
// Keep the stored choices, even when they are out of use now.
$catalog = app(CatalogQueries::class);
$inactive = [];
foreach (array_unique($this->storedWorkTypeIds) as $id) {
if (! in_array($id, $offered, true) && ($workType = $catalog->findWorkType($id)) !== null) {
$inactive[] = $workType;
}
}
if ($inactive !== []) {
$groups[__('catalog.inactive')] = $inactive;
}
return $groups;
}
};
?>
<div class="mx-auto max-w-3xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="form.name" :label="__('catalog.fields.name')" :hint="__('catalog.workflows.name_help')" autocomplete="off" required />
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native
wire:model.live="form.work_type_id"
:label="__('catalog.workflows.work_type')"
:aria-label="__('catalog.workflows.work_type')"
:hint="__('catalog.workflows.work_type_help')"
required
>
<option value="">{{ __('catalog.workflows.choose_work_type') }}</option>
@foreach ($this->workTypeGroups as $group => $workTypes)
<optgroup label="{{ $group }}">
@foreach ($workTypes as $workType)
<option wire:key="work-type-option-{{ $workType->id }}" value="{{ $workType->id }}">{{ $workType->name }}</option>
@endforeach
</optgroup>
@endforeach
</x-select.native>
<section aria-labelledby="steps-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="steps-heading" class="text-xl font-semibold">{{ __('catalog.workflows.steps') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.steps_help') }}</p>
</div>
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
@error('form.steps')
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
<ol class="space-y-4">
@foreach ($form->steps as $index => $step)
{{-- The index is part of the key: a moved step is rendered anew, so its fields bind to their new position. --}}
<li wire:key="step-{{ $step['key'] }}-{{ $index }}">
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
<legend class="px-1 font-medium">{{ __('catalog.workflows.step_legend', ['number' => $index + 1]) }}</legend>
<x-input
id="step-{{ $step['key'] }}-title"
wire:model="form.steps.{{ $index }}.title"
:label="__('catalog.workflows.step_title')"
autocomplete="off"
required
/>
<x-select.native
id="step-{{ $step['key'] }}-work-type"
wire:model="form.steps.{{ $index }}.work_type_id"
:label="__('catalog.workflows.step_work_type')"
:aria-label="__('catalog.workflows.step_work_type_named', ['number' => $index + 1])"
:hint="__('catalog.workflows.step_work_type_help')"
>
<option value="">{{ __('catalog.workflows.template_work_type') }}</option>
@foreach ($this->stepWorkTypeGroups as $group => $workTypes)
<optgroup label="{{ $group }}">
@foreach ($workTypes as $workType)
<option value="{{ $workType->id }}">{{ $workType->name }}</option>
@endforeach
</optgroup>
@endforeach
</x-select.native>
<x-textarea
id="step-{{ $step['key'] }}-description"
wire:model="form.steps.{{ $index }}.description"
:label="__('catalog.workflows.step_description')"
resize-auto
/>
<div class="flex flex-wrap gap-2">
<x-button
id="step-{{ $step['key'] }}-up"
wire:click="moveStep({{ $index }}, 'up')"
subtle
color="black"
sm
icon="arrow-up"
:text="__('catalog.workflows.move_up')"
:aria-label="__('catalog.workflows.move_up_named', ['number' => $index + 1])"
/>
<x-button
id="step-{{ $step['key'] }}-down"
wire:click="moveStep({{ $index }}, 'down')"
subtle
color="black"
sm
icon="arrow-down"
:text="__('catalog.workflows.move_down')"
:aria-label="__('catalog.workflows.move_down_named', ['number' => $index + 1])"
/>
@if (count($form->steps) > 1)
<x-button
id="step-{{ $step['key'] }}-remove"
wire:click="removeStep({{ $index }})"
subtle
color="black"
sm
icon="trash"
:text="__('catalog.workflows.remove_step')"
:aria-label="__('catalog.workflows.remove_step_named', ['number' => $index + 1])"
/>
@endif
</div>
</fieldset>
</li>
@endforeach
</ol>
<x-button id="add-step" wire:click="addStep" subtle color="black" icon="plus" :text="__('catalog.workflows.add_step')" />
</section>
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.workflow-templates')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
</div>
@@ -0,0 +1,152 @@
<?php
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateSummary;
use App\Modules\Catalog\Application\UseCases\SetWorkflowTemplateActive;
use App\Modules\Catalog\Domain\Exceptions\WorkflowTemplateNotFound;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* Workflow templates (työnkulkupohjat) grouped by service unit: adding,
* editing and taking out of use.
*/
new class extends Component
{
public string $statusMessage = '';
public function mount(): void
{
$this->authorize('catalog.manage');
}
/**
* @return array<string, list<WorkflowTemplateSummary>>
*/
#[Computed]
public function groups(): array
{
$groups = [];
foreach (app(WorkflowTemplateQueries::class)->all() as $template) {
$groups[$template->serviceUnitName][] = $template;
}
return $groups;
}
public function toggleActive(int $templateId, SetWorkflowTemplateActive $setActive): void
{
$this->authorize('catalog.manage');
$template = app(WorkflowTemplateQueries::class)->find($templateId);
if ($template === null) {
$this->statusMessage = __('catalog.status.not_found');
return;
}
try {
$setActive->execute($templateId, ! $template->isActive);
} catch (WorkflowTemplateNotFound) {
$this->statusMessage = __('catalog.status.not_found');
return;
}
unset($this->groups);
$this->statusMessage = __($template->isActive ? 'catalog.workflows.status.deactivated' : 'catalog.status.activated', ['name' => $template->name]);
}
/**
* @return list<array{index: string, label: string, sortable: bool}>
*/
public function headers(): array
{
return [
['index' => 'name', 'label' => __('catalog.fields.name'), 'sortable' => false],
['index' => 'work_type', 'label' => __('catalog.workflows.work_type'), 'sortable' => false],
['index' => 'steps', 'label' => __('catalog.workflows.step_count'), 'sortable' => false],
['index' => 'actions', 'label' => __('catalog.products.actions'), 'sortable' => false],
];
}
public function render(): mixed
{
return $this->view()->title(__('catalog.workflows.title'));
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold">{{ __('catalog.workflows.title') }}</h1>
<x-button :href="route('catalog.workflow-templates.create')" wire:navigate icon="plus" :text="__('catalog.workflows.add')" />
</div>
<div class="space-y-1 text-sm">
<p class="text-zinc-600 dark:text-zinc-300">{{ __('catalog.workflows.intro') }}</p>
<p><x-link :href="route('catalog.index')" navigate>{{ __('catalog.workflows.back_to_catalog') }}</x-link></p>
</div>
@if (session('status'))
<x-alert role="status" color="green" light icon="check-circle" :text="session('status')" />
@endif
<p role="status" aria-live="polite" class="text-sm">{{ $statusMessage }}</p>
@forelse ($this->groups as $unitName => $templates)
<section wire:key="unit-{{ $loop->index }}" aria-labelledby="unit-{{ $loop->index }}-heading" class="space-y-3">
<h2 id="unit-{{ $loop->index }}-heading" class="text-xl font-semibold break-words">{{ $unitName }}</h2>
<x-table :headers="$this->headers()" :rows="$templates">
@interact('column_name', $template)
<span class="font-medium break-words">{{ $template->name }}</span>
@unless ($template->isActive)
<span class="ml-1 text-sm">({{ __('catalog.inactive') }})</span>
@endunless
@endinteract
@interact('column_work_type', $template)
{{ $template->workTypeName }}
@endinteract
@interact('column_steps', $template)
{{ $template->stepCount }}
@endinteract
@interact('column_actions', $template)
<div class="flex flex-wrap items-center gap-2">
<x-button
:href="route('catalog.workflow-templates.edit', $template->id)"
wire:navigate
subtle
color="black"
sm
icon="pencil"
:text="__('catalog.actions.edit')"
:aria-label="__('catalog.actions.edit_named', ['name' => $template->name])"
/>
<label class="inline-flex min-h-6 cursor-pointer items-center gap-2 text-sm">
<input
type="checkbox"
id="active-template-{{ $template->id }}"
wire:click="toggleActive({{ $template->id }})"
@checked($template->isActive)
aria-label="{{ __('catalog.actions.active_named', ['name' => $template->name]) }}"
class="size-4 rounded border-zinc-400 text-primary-600 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-500 dark:bg-zinc-800"
/>
<span aria-hidden="true">{{ __('catalog.actions.active') }}</span>
</label>
</div>
@endinteract
</x-table>
</section>
@empty
<p>{{ __('catalog.workflows.none') }}</p>
@endforelse
</div>
@@ -27,6 +27,12 @@ Route::middleware(['web', 'auth', 'can:catalog.manage'])
->whereNumber('workType')
->name('work-types.edit');
Route::livewire('/workflow-templates', 'catalog::workflow-templates')->name('workflow-templates');
Route::livewire('/workflow-templates/create', 'catalog::workflow-template-form')->name('workflow-templates.create');
Route::livewire('/workflow-templates/{template}/edit', 'catalog::workflow-template-form')
->whereNumber('template')
->name('workflow-templates.edit');
Route::livewire('/prices', 'catalog::prices')->name('prices');
Route::livewire('/products/create', 'catalog::product-form')->name('products.create');
Route::livewire('/products/{product}/edit', 'catalog::product-form')
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\Contracts;
/**
* Whether another module has rows that refer to a customer (customer jobs,
* quick sales, invoices), so the customer cannot be removed. Each such module
* tags its own implementation with `customers.references`.
*/
interface CustomerReferences
{
public const string TAG = 'customers.references';
public function refersTo(int $customerId): bool;
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\Services;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
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\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved;
/**
* Whether a customer may be removed: it is not the internal customer and
* nothing is linked to it (no contacts, no billing units, no rows of other
* modules).
*/
final class CustomerRemoval
{
public function __construct(
private CustomerRepository $customers,
private CustomerContactRepository $contacts,
private BillingUnitRepository $billingUnits,
private CustomerReferences $references,
) {}
public function canRemove(int $customerId): bool
{
try {
$this->ensureCanRemove($customerId);
return true;
} catch (CustomerNotFound|InternalCustomerCannotBeRemoved|CustomerInUse) {
return false;
}
}
/**
* @throws CustomerNotFound
* @throws InternalCustomerCannotBeRemoved
* @throws CustomerInUse
*/
public function ensureCanRemove(int $customerId): Customer
{
$customer = $this->customers->findById($customerId)
?? throw new CustomerNotFound($customerId);
if ($customer->isInternal()) {
throw new InternalCustomerCannotBeRemoved;
}
if ($this->contacts->existsForCustomer($customerId)
|| $this->billingUnits->existsForCustomer($customerId)
|| $this->references->refersTo($customerId)) {
throw new CustomerInUse;
}
return $customer;
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Application\UseCases;
use App\Modules\Customers\Application\Services\CustomerRemoval;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Deletes a customer that has nothing but its own details: no contacts,
* no billing units, and nothing in other modules (customer jobs, quick
* sales, invoices) that refers to it.
*/
final class RemoveCustomer
{
public function __construct(
private CustomerRepository $customers,
private CustomerRemoval $removal,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerNotFound
* @throws InternalCustomerCannotBeRemoved
* @throws CustomerInUse
*/
public function execute(int $customerId): void
{
$this->transactions->run(function () use ($customerId): void {
$this->customers->delete($this->removal->ensureCanRemove($customerId));
});
}
}
@@ -20,4 +20,6 @@ interface BillingUnitRepository
public function save(BillingUnit $billingUnit): BillingUnit;
public function delete(BillingUnit $billingUnit): void;
public function existsForCustomer(int $customerId): bool;
}
@@ -20,4 +20,6 @@ interface CustomerContactRepository
public function save(CustomerContact $contact): CustomerContact;
public function delete(CustomerContact $contact): void;
public function existsForCustomer(int $customerId): bool;
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Customers\Domain\Contracts;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
@@ -18,6 +19,11 @@ interface CustomerRepository
*/
public function save(Customer $customer): Customer;
/**
* @throws CustomerInUse when other rows refer to the customer
*/
public function delete(Customer $customer): void;
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool;
public function isPersonalIdentityCodeTaken(PersonalIdentityCode $code, ?int $exceptCustomerId = null): bool;
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The customer has contacts, billing units, or rows of other modules
* (customer jobs, quick sales, invoices) refer to it.
*/
final class CustomerInUse extends DomainException
{
public function __construct()
{
parent::__construct('The customer has rows that refer to it.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Customers\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InternalCustomerCannotBeRemoved extends DomainException
{
public function __construct()
{
parent::__construct('The internal customer cannot be removed.');
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Modules\Customers\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
/**
* Asks every module that tagged a `CustomerReferences` implementation.
* Without any, nothing refers to customers.
*/
class AnyModuleRefersToCustomer implements CustomerReferences
{
/**
* @param iterable<CustomerReferences> $references
*/
public function __construct(private iterable $references) {}
public function refersTo(int $customerId): bool
{
foreach ($this->references as $references) {
if ($references->refersTo($customerId)) {
return true;
}
}
return false;
}
}
@@ -40,6 +40,11 @@ class EloquentBillingUnitRepository implements BillingUnitRepository
BillingUnitModel::query()->whereKey($billingUnit->id())->delete();
}
public function existsForCustomer(int $customerId): bool
{
return BillingUnitModel::query()->where('customer_id', $customerId)->exists();
}
private function toEntity(BillingUnitModel $model): BillingUnit
{
return BillingUnit::reconstitute(
@@ -40,6 +40,11 @@ class EloquentCustomerContactRepository implements CustomerContactRepository
CustomerContactModel::query()->whereKey($contact->id())->delete();
}
public function existsForCustomer(int $customerId): bool
{
return CustomerContactModel::query()->where('customer_id', $customerId)->exists();
}
private function toEntity(CustomerContactModel $model): CustomerContact
{
return CustomerContact::reconstitute(
@@ -4,11 +4,13 @@ namespace App\Modules\Customers\Infrastructure\Persistence\Repositories;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Domain\Entities\Customer;
use App\Modules\Customers\Domain\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\ValueObjects\CustomerName;
use App\Modules\Customers\Domain\ValueObjects\PersonalIdentityCode;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Customers\Infrastructure\Persistence\PersonalIdentityCodeHasher;
use App\Modules\Shared\Domain\ValueObjects\BusinessId;
use Illuminate\Database\QueryException;
class EloquentCustomerRepository implements CustomerRepository
{
@@ -38,6 +40,24 @@ class EloquentCustomerRepository implements CustomerRepository
return $this->toEntity($model);
}
/**
* Customer jobs, quick sales and invoices refer to customers with
* restricting foreign keys, so the database refuses the delete while
* any of them exists. That keeps this module unaware of their tables.
*/
public function delete(Customer $customer): void
{
try {
CustomerModel::query()->whereKey($customer->id())->delete();
} catch (QueryException $exception) {
if (str_starts_with((string) $exception->getCode(), '23')) {
throw new CustomerInUse;
}
throw $exception;
}
}
public function isBusinessIdTaken(BusinessId $businessId, ?int $exceptCustomerId = null): bool
{
return CustomerModel::query()
@@ -4,10 +4,12 @@ namespace App\Modules\Customers\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
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\AnyModuleRefersToCustomer;
use App\Modules\Customers\Infrastructure\NothingUsesCustomerRows;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentBillingUnitRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerContactRepository;
@@ -36,6 +38,15 @@ class CustomersServiceProvider extends ServiceProvider
CustomerRowUsage::class => NothingUsesCustomerRows::class,
];
public function register(): void
{
// Jobs, Sales and Billing tag their own checks of rows that refer to a customer.
$this->app->bind(
CustomerReferences::class,
fn ($app): CustomerReferences => new AnyModuleRefersToCustomer($app->tagged(CustomerReferences::TAG)),
);
}
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
@@ -4,12 +4,17 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\DTOs\BillingUnitSummary;
use App\Modules\Customers\Application\DTOs\ContactSummary;
use App\Modules\Customers\Application\DTOs\CustomerSummary;
use App\Modules\Customers\Application\Services\CustomerRemoval;
use App\Modules\Customers\Application\UseCases\RemoveBillingUnit;
use App\Modules\Customers\Application\UseCases\RemoveContact;
use App\Modules\Customers\Application\UseCases\RemoveCustomer;
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\Exceptions\CustomerInUse;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Domain\Exceptions\InternalCustomerCannotBeRemoved;
use App\Modules\Customers\Domain\Enums\CustomerType;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
@@ -17,7 +22,8 @@ use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* A customer's page: details, contacts and billing units.
* A customer's page: details, contacts and billing units. A customer with
* nothing linked to it can be removed here.
*/
new class extends Component
{
@@ -27,7 +33,7 @@ new class extends Component
public int $customerId;
/**
* The row the remove dialog asks about: 'contact' or 'billing_unit'.
* What the remove dialog asks about: 'customer', 'contact' or 'billing_unit'.
*/
#[Locked]
public ?string $removalType = null;
@@ -42,9 +48,12 @@ new class extends Component
protected CustomerQueries $customerQueries;
public function boot(CustomerQueries $customerQueries): void
protected CustomerRemoval $customerRemoval;
public function boot(CustomerQueries $customerQueries, CustomerRemoval $customerRemoval): void
{
$this->customerQueries = $customerQueries;
$this->customerRemoval = $customerRemoval;
}
public function mount(int $customer): void
@@ -77,6 +86,15 @@ new class extends Component
return $this->customer->personalIdentityCodeMasked;
}
/**
* Whether nothing is linked to this customer, so the remove button is shown.
*/
#[Computed]
public function canBeRemoved(): bool
{
return $this->customerRemoval->canRemove($this->customerId);
}
/**
* @return list<ContactSummary>
*/
@@ -96,13 +114,15 @@ new class extends Component
}
/**
* Opens the remove dialog for a contact or a billing unit of this customer.
* Opens the remove dialog for this customer, or for one of its contacts
* or billing units.
*/
public function confirmRemoval(string $type, int $id): void
{
$this->authorize('customers.use');
$name = match ($type) {
'customer' => $id === $this->customerId ? $this->customerQueries->findSummary($id)?->name : null,
'contact' => $this->customerQueries->findContact($this->customerId, $id)?->name,
'billing_unit' => $this->customerQueries->findBillingUnit($this->customerId, $id)?->name,
default => null,
@@ -122,7 +142,7 @@ new class extends Component
$this->js("document.getElementById('".self::REMOVE_DIALOG."').showModal()");
}
public function remove(RemoveContact $removeContact, RemoveBillingUnit $removeBillingUnit): void
public function remove(RemoveContact $removeContact, RemoveBillingUnit $removeBillingUnit, RemoveCustomer $removeCustomer): void
{
$this->authorize('customers.use');
@@ -130,6 +150,12 @@ new class extends Component
return;
}
if ($this->removalType === 'customer') {
$this->removeCustomer($removeCustomer);
return;
}
try {
match ($this->removalType) {
'contact' => $removeContact->execute($this->customerId, $this->removalId),
@@ -150,6 +176,32 @@ new class extends Component
$this->reset('removalType', 'removalId', 'removalName');
}
/**
* Removes this customer and returns to the customer list, or tells why
* it was kept and moves focus back to the page heading.
*/
private function removeCustomer(RemoveCustomer $removeCustomer): void
{
try {
$removeCustomer->execute($this->customerId);
session()->flash('status', __('customers.removal.removed_customer', ['name' => $this->removalName]));
$this->redirectRoute('customers.index', navigate: true);
return;
} catch (CustomerNotFound) {
$this->statusMessage = __('customers.removal.already_removed');
} catch (InternalCustomerCannotBeRemoved) {
$this->statusMessage = __('customers.removal.internal_customer');
} catch (CustomerInUse) {
$this->statusMessage = __('customers.removal.in_use_customer', ['name' => $this->removalName]);
}
$this->js("document.getElementById('".self::REMOVE_DIALOG."').close(); document.getElementById('customer-heading').focus()");
$this->reset('removalType', 'removalId', 'removalName');
}
public function render(): mixed
{
return $this->view()->title($this->customer->name);
@@ -160,16 +212,28 @@ new class extends Component
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<div class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h1 class="text-2xl font-semibold break-words">{{ $this->customer->name }}</h1>
<h1 id="customer-heading" tabindex="-1" class="text-2xl font-semibold break-words focus:outline-none">{{ $this->customer->name }}</h1>
<x-button
:href="route('customers.edit', $customerId)"
wire:navigate
subtle
color="black"
icon="pencil"
:text="__('customers.edit_details')"
/>
<div class="flex flex-wrap gap-2">
<x-button
:href="route('customers.edit', $customerId)"
wire:navigate
subtle
color="black"
icon="pencil"
:text="__('customers.edit_details')"
/>
@if ($this->canBeRemoved)
<x-button
wire:click="confirmRemoval('customer', {{ $customerId }})"
subtle
color="black"
icon="trash"
:text="__('customers.remove_customer')"
/>
@endif
</div>
</div>
@if (session('status'))
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Contracts;
use App\Modules\Jobs\Application\DTOs\CalendarTask;
/**
* Read side of the task calendar. Dates are Y-m-d and inclusive. The
* service unit limits tasks to jobs of that unit; onlyAssigneeUserId to
* tasks of that person on jobs they are involved in (subcontractors).
*/
interface TaskCalendarQueries
{
/**
* Tasks whose planned period overlaps the dates.
*
* @return list<CalendarTask>
*/
public function scheduledTasks(string $from, string $to, ?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null): array;
/**
* Tasks that are not done and have no planned period, on jobs that are
* not archived, by due date.
*
* @return list<CalendarTask>
*/
public function unscheduledOpenTasks(?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null, int $limit = 100): array;
/**
* Minutes each person's tasks that are not done book per day.
*
* @param list<int> $userIds
* @return array<int, array<string, int>> user id => Y-m-d => minutes.
*/
public function openMinutesByUser(array $userIds, string $from, string $to): array;
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* One assignee's part of a scheduled task: the first and last booked day
* (null when the task books no time, e.g. without an estimate) and the
* booked minutes.
*/
final readonly class CalendarAssignment
{
public function __construct(
public int $userId,
public ?string $from,
public ?string $to,
public int $minutes,
) {}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* A task's bar on one row of the task calendar. Start and span are in
* visible day columns (0 = the first day shown); a bar that continues
* past the shown days is cut at the edge. Lane is the bar's line inside
* the row, so that overlapping tasks do not cover each other.
*/
final readonly class CalendarBar
{
public function __construct(
public CalendarTask $task,
public ?int $userId,
public string $from,
public string $to,
public int $minutes,
public int $start,
public int $span,
public int $lane,
public bool $late,
) {}
public function key(): string
{
return $this->task->taskId.'-'.($this->userId ?? 'none');
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* One person's row of the task calendar (userId null: tasks without an
* assignee), with the minutes their open tasks book per shown day.
*/
final readonly class CalendarRow
{
/**
* @param array<string, int> $minutesByDay Y-m-d => minutes, for every shown day.
* @param list<CalendarBar> $bars Ordered by start.
*/
public function __construct(
public ?int $userId,
public string $name,
public array $minutesByDay,
public array $bars,
public int $lanes,
) {}
/**
* @return list<CalendarBar> The bars that are on the day.
*/
public function barsOn(int $dayIndex): array
{
return array_values(array_filter($this->bars, fn (CalendarBar $bar): bool => $bar->start <= $dayIndex && $dayIndex < $bar->start + $bar->span));
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* A task as the task calendar shows it. Dates are Y-m-d.
*/
final readonly class CalendarTask
{
/**
* @param list<CalendarAssignment> $assignments One per assignee.
*/
public function __construct(
public int $taskId,
public int $jobId,
public string $jobNumber,
public string $jobName,
public string $title,
public TaskStatus $status,
public ?string $dueOn,
public ?string $estimatedHours,
public ?string $plannedFrom,
public ?string $plannedTo,
public array $assignments,
) {}
public function assignmentOf(int $userId): ?CalendarAssignment
{
foreach ($this->assignments as $assignment) {
if ($assignment->userId === $userId) {
return $assignment;
}
}
return null;
}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* A task's planned schedule after it was moved, resized or given to
* another person. Extended: the assignee's days were full, so the task
* ends later than asked.
*/
final readonly class ScheduleResult
{
public function __construct(
public string $plannedFrom,
public string $plannedTo,
public bool $extended,
) {}
}
@@ -5,7 +5,8 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Input for adding or changing a task. The due date is Y-m-d.
* Input for adding or changing a task. Dates are Y-m-d; a planned start
* without an end plans one day.
*/
final readonly class TaskData
{
@@ -20,5 +21,7 @@ final readonly class TaskData
public ?string $dueOn = null,
public ?string $estimatedHours = null,
public array $assigneeUserIds = [],
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
) {}
}
@@ -24,5 +24,7 @@ final readonly class TaskSummary
public ?string $estimatedHours,
public NamedId $workType,
public array $assignees,
public ?string $plannedFrom = null,
public ?string $plannedTo = null,
) {}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\DTOs;
/**
* Due date (Y-m-d) and estimated hours ("1,5") entered for the task of one
* workflow template step. Both are optional.
*/
final readonly class TemplateTaskSchedule
{
public function __construct(
public ?string $dueOn = null,
public ?string $estimatedHours = null,
) {}
}
@@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Jobs\Application\DTOs\CalendarBar;
use App\Modules\Jobs\Application\DTOs\CalendarRow;
use App\Modules\Jobs\Application\DTOs\CalendarTask;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
/**
* Lays scheduled tasks out on the task calendar's rows: one row per
* person (a task with several assignees is on each of their rows) and a
* row for tasks without an assignee. Overlapping bars get their own lanes.
*/
final class TaskCalendarLayout
{
/**
* @param list<string> $days The shown days, Y-m-d, consecutive.
* @param list<array{id: ?int, name: string}> $people Rows in order; id null is the "no assignee" row.
* @param list<CalendarTask> $tasks
* @param array<int, array<string, int>> $minutesByUser user id => Y-m-d => booked minutes.
* @return list<CalendarRow>
*/
public static function build(array $days, array $people, array $tasks, array $minutesByUser): array
{
$rows = [];
foreach ($people as $person) {
$bars = [];
foreach ($tasks as $task) {
$bar = self::bar($task, $person['id'], $days);
if ($bar !== null) {
$bars[] = $bar;
}
}
[$bars, $lanes] = self::stack($bars);
$minutes = [];
foreach ($days as $day) {
$minutes[$day] = $person['id'] === null ? 0 : ($minutesByUser[$person['id']][$day] ?? 0);
}
$rows[] = new CalendarRow($person['id'], $person['name'], $minutes, $bars, $lanes);
}
return $rows;
}
/**
* @param list<string> $days
*/
private static function bar(CalendarTask $task, ?int $userId, array $days): ?CalendarBar
{
if ($task->plannedFrom === null || $task->plannedTo === null || $days === []) {
return null;
}
if ($userId === null) {
if ($task->assignments !== []) {
return null;
}
$from = $task->plannedFrom;
$to = $task->plannedTo;
$minutes = 0;
} else {
$assignment = $task->assignmentOf($userId);
if ($assignment === null) {
return null;
}
$from = $task->plannedFrom;
$to = max($from, $assignment->to ?? $task->plannedTo);
$minutes = $assignment->minutes;
}
$first = $days[0];
$last = $days[count($days) - 1];
if ($to < $first || $from > $last) {
return null;
}
$start = $from < $first ? 0 : (int) array_search($from, $days, true);
$end = $to > $last ? count($days) - 1 : (int) array_search($to, $days, true);
$late = $task->status !== TaskStatus::Done && $task->dueOn !== null && $to > $task->dueOn;
return new CalendarBar($task, $userId, $from, $to, $minutes, $start, $end - $start + 1, 0, $late);
}
/**
* Puts each bar on the first lane where it does not overlap another.
*
* @param list<CalendarBar> $bars
* @return array{0: list<CalendarBar>, 1: int}
*/
private static function stack(array $bars): array
{
usort($bars, fn (CalendarBar $a, CalendarBar $b): int => [$a->start, -$a->span, $a->task->taskId] <=> [$b->start, -$b->span, $b->task->taskId]);
$laneEnds = [];
$stacked = [];
foreach ($bars as $bar) {
$lane = 0;
while (isset($laneEnds[$lane]) && $laneEnds[$lane] >= $bar->start) {
$lane++;
}
$laneEnds[$lane] = $bar->start + $bar->span - 1;
$stacked[] = new CalendarBar($bar->task, $bar->userId, $bar->from, $bar->to, $bar->minutes, $bar->start, $bar->span, $lane, $bar->late);
}
return [$stacked, max(1, count($laneEnds))];
}
}
@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\Services;
use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Services\TaskScheduler;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use DateInterval;
use DateTimeImmutable;
/**
* Books a saved task's estimate from each assignee's days with the
* TaskScheduler, using the holidays in use and the daily maximum
* (setting `jobs.daily_capacity_hours`, 8 h by default). When the days
* are full, the task's planned end moves later.
*/
final class TaskPlanner
{
public const string CAPACITY_KEY = 'jobs.daily_capacity_hours';
private const int DEFAULT_CAPACITY_HOURS = 8;
/** Days past the start in which holidays and other bookings are looked up. */
private const int LOOKAHEAD_DAYS = 400;
public function __construct(
private TaskBookingRepository $bookings,
private HolidayCalendar $holidays,
private Settings $settings,
) {}
public function capacityMinutes(): int
{
$hours = (float) str_replace(',', '.', $this->settings->get(self::CAPACITY_KEY) ?? '');
return (int) round(($hours > 0 && $hours <= 24 ? $hours : self::DEFAULT_CAPACITY_HOURS) * 60);
}
/**
* Rebooks the task's assignees and, if their days were full, moves the
* task's planned end later. The task must be saved (have an id);
* save it again afterwards.
*
* @return bool Whether the planned end moved later.
*/
public function plan(Task $task): bool
{
$taskId = (int) $task->id();
$from = $task->plannedFrom();
$to = $task->plannedTo();
if ($from === null || $to === null) {
$this->bookings->deleteForTask($taskId);
return false;
}
$this->bookings->deleteForTask($taskId, $task->assigneeUserIds());
$minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60);
$lookahead = $to->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
$holidays = $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead);
$capacity = $this->capacityMinutes();
$end = $to;
foreach ($task->assigneeUserIds() as $userId) {
$schedule = TaskScheduler::schedule(
$from,
$to,
$minutes,
$this->bookings->otherOpenMinutes($userId, $from->format('Y-m-d'), $lookahead, $taskId),
$capacity,
$holidays,
);
$this->bookings->replaceFor($taskId, $userId, $schedule->minutesByDay);
if ($schedule->end > $end) {
$end = $schedule->end;
}
}
if ($end > $to) {
$task->schedule($from, $end);
return true;
}
return false;
}
/**
* The end of a task placed on a day without an end (TaskScheduler::defaultEnd).
*/
public function defaultEnd(DateTimeImmutable $from, Task $task): DateTimeImmutable
{
$minutes = (int) round(($task->estimatedHours()->value ?? 0) * 60);
$lookahead = $from->add(new DateInterval('P'.self::LOOKAHEAD_DAYS.'D'))->format('Y-m-d');
return TaskScheduler::defaultEnd($from, $minutes, $this->capacityMinutes(), $this->holidays->activeDatesBetween($from->format('Y-m-d'), $lookahead));
}
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
@@ -12,6 +13,7 @@ use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
@@ -22,6 +24,7 @@ final class AddTask
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private TaskReferenceChecker $references,
private TaskPlanner $planner,
private TransactionManager $transactions,
) {}
@@ -31,6 +34,7 @@ final class AddTask
* @throws CustomerJobNotFound
* @throws TasksNotAllowedYet
* @throws InvalidTaskReference
* @throws PlanEndsBeforeStart
*/
public function execute(int $jobId, TaskData $data, int $actorUserId): int
{
@@ -51,9 +55,17 @@ final class AddTask
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
$actorUserId,
TaskInput::date($data->plannedFrom),
TaskInput::date($data->plannedTo),
);
return (int) $this->tasks->save($task)->id();
$task = $this->tasks->save($task);
if ($task->isScheduled() && $this->planner->plan($task)) {
$task = $this->tasks->save($task);
}
return (int) $task->id();
});
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Jobs\Application\DTOs\TemplateTaskSchedule;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\Exceptions\WorkflowTemplateNotAvailable;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Makes a task of every step of a workflow template, in the template's
* order: waiting, with the step's work type and the due date and estimate
* entered for it, assigned to the user who adds them. The tasks are
* copies, so later changes to the template do not touch them.
*/
final class AddTasksFromWorkflowTemplate
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private WorkflowTemplateQueries $templates,
private TaskReferenceChecker $references,
private TransactionManager $transactions,
) {}
/**
* @param list<TemplateTaskSchedule> $schedules In step order; a missing one leaves the task without a due date and estimate.
* @return int How many tasks were added.
*
* @throws CustomerJobNotFound
* @throws InvalidEstimatedHours
* @throws TasksNotAllowedYet
* @throws WorkflowTemplateNotAvailable
* @throws InvalidTaskReference when a step's work type is not available for the job
*/
public function execute(int $jobId, int $templateId, int $actorUserId, array $schedules = []): int
{
$dueDates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::date($schedule->dueOn), $schedules);
$estimates = array_map(fn (TemplateTaskSchedule $schedule) => TaskInput::hours($schedule->estimatedHours), $schedules);
return $this->transactions->run(function () use ($jobId, $templateId, $actorUserId, $dueDates, $estimates): int {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$template = $this->availableTemplate($templateId, $job->details()->serviceUnitIds);
foreach ($template->steps as $index => $step) {
$this->references->check($job, $step->effectiveWorkTypeId, [$actorUserId]);
$this->tasks->save(Task::create(
$jobId,
$job->details()->status,
$step->effectiveWorkTypeId,
new TaskTitle($step->title),
$step->description,
TaskStatus::Waiting,
$dueDates[$index] ?? null,
$estimates[$index] ?? null,
[$actorUserId],
$actorUserId,
));
}
return count($template->steps);
});
}
/**
* @param list<int> $serviceUnitIds
*/
private function availableTemplate(int $templateId, array $serviceUnitIds): WorkflowTemplateDetails
{
foreach ($this->templates->activeFor($serviceUnitIds) as $template) {
if ($template->id === $templateId) {
return $template;
}
}
throw new WorkflowTemplateNotAvailable($templateId);
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a task out of the task calendar: no planned period, no bookings.
*/
final class ClearTaskSchedule
{
public function __construct(
private TaskRepository $tasks,
private TaskPlanner $planner,
private TransactionManager $transactions,
) {}
/**
* @throws TaskNotFound
*/
public function execute(int $jobId, int $taskId): void
{
$this->transactions->run(function () use ($jobId, $taskId): void {
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$task->schedule(null, null);
$this->planner->plan($task);
$this->tasks->save($task);
});
}
}
@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\ScheduleResult;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a task in the task calendar: a new planned period, and possibly
* from one person's row to another's (the person on the row it left is
* replaced as an assignee; null is the "no assignee" row). Without an
* end, the task lasts as many working days as its estimate needs.
*/
final class ScheduleTask
{
public function __construct(
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private TaskReferenceChecker $references,
private TaskPlanner $planner,
private TransactionManager $transactions,
) {}
/**
* @throws CustomerJobNotFound
* @throws TaskNotFound
* @throws InvalidTaskReference
* @throws PlanEndsBeforeStart
*/
public function execute(int $jobId, int $taskId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo): ScheduleResult
{
$from = TaskInput::date($plannedFrom) ?? throw new PlanEndsBeforeStart;
$to = TaskInput::date($plannedTo);
return $this->transactions->run(function () use ($jobId, $taskId, $fromUserId, $toUserId, $from, $to): ScheduleResult {
$job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId);
$task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId);
$assignees = $task->assigneeUserIds();
if ($fromUserId !== $toUserId) {
$assignees = array_values(array_filter($assignees, fn (int $userId): bool => $userId !== $fromUserId));
if ($toUserId !== null) {
$assignees[] = $toUserId;
}
}
$this->references->check($job, $task->workTypeId(), $assignees, $task);
$task->changeAssignees($assignees);
$task->schedule($from, $to ?? $this->planner->defaultEnd($from, $task));
$task = $this->tasks->save($task);
$extended = $this->planner->plan($task);
$task = $this->tasks->save($task);
return new ScheduleResult(
(string) $task->plannedFrom()?->format('Y-m-d'),
(string) $task->plannedTo()?->format('Y-m-d'),
$extended,
);
});
}
}
@@ -5,12 +5,15 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Application\UseCases;
use App\Modules\Jobs\Application\DTOs\TaskData;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Application\Services\TaskReferenceChecker;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Shared\Application\Contracts\TransactionManager;
@@ -21,6 +24,7 @@ final class UpdateTask
private CustomerJobRepository $jobs,
private TaskRepository $tasks,
private TaskReferenceChecker $references,
private TaskPlanner $planner,
private TransactionManager $transactions,
) {}
@@ -28,6 +32,7 @@ final class UpdateTask
* @throws CustomerJobNotFound
* @throws TaskNotFound
* @throws InvalidTaskReference
* @throws PlanEndsBeforeStart
*/
public function execute(int $jobId, int $taskId, TaskData $data): void
{
@@ -39,6 +44,8 @@ final class UpdateTask
$this->references->check($job, $data->workTypeId, $data->assigneeUserIds, $task);
$before = self::planningInput($task);
$task->changeDetails(
$data->workTypeId,
$title,
@@ -48,8 +55,28 @@ final class UpdateTask
TaskInput::hours($data->estimatedHours),
$data->assigneeUserIds,
);
$task->schedule(TaskInput::date($data->plannedFrom), TaskInput::date($data->plannedTo));
$this->tasks->save($task);
$task = $this->tasks->save($task);
// Rebook only when what the bookings depend on changed.
if (self::planningInput($task) !== $before) {
$this->planner->plan($task);
$this->tasks->save($task);
}
});
}
/**
* @return array{0: ?string, 1: ?string, 2: ?float, 3: list<int>}
*/
private static function planningInput(Task $task): array
{
return [
$task->plannedFrom()?->format('Y-m-d'),
$task->plannedTo()?->format('Y-m-d'),
$task->estimatedHours()?->value,
$task->assigneeUserIds(),
];
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Contracts;
/**
* The minutes each assignee's days are booked for tasks (task calendar).
*/
interface TaskBookingRepository
{
/**
* Replaces the assignee's bookings of the task.
*
* @param array<string, int> $minutesByDay Y-m-d => minutes.
*/
public function replaceFor(int $taskId, int $userId, array $minutesByDay): void;
/**
* Removes the task's bookings, except those of the given assignees.
*
* @param list<int> $keepUserIds
*/
public function deleteForTask(int $taskId, array $keepUserIds = []): void;
/**
* Minutes the user's other tasks that are not done book per day.
*
* @return array<string, int> Y-m-d => minutes.
*/
public function otherOpenMinutes(int $userId, string $from, string $to, int $exceptTaskId): array;
}
+73 -2
View File
@@ -6,6 +6,7 @@ namespace App\Modules\Jobs\Domain\Entities;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
@@ -14,6 +15,7 @@ use DateTimeImmutable;
/**
* A task (tehtävä) of a customer job: one step of the work, done by its
* assignees under one work type. Time entries are recorded on tasks.
* Its planned schedule (planned from–to) places it in the task calendar.
*/
final class Task
{
@@ -31,14 +33,18 @@ final class Task
private ?EstimatedHours $estimatedHours,
private array $assigneeUserIds,
private int $createdBy,
private ?DateTimeImmutable $plannedFrom = null,
private ?DateTimeImmutable $plannedTo = null,
) {
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
self::checkPlan($plannedFrom, $plannedTo);
}
/**
* @param list<int> $assigneeUserIds
*
* @throws TasksNotAllowedYet
* @throws PlanEndsBeforeStart
*/
public static function create(
int $jobId,
@@ -51,12 +57,14 @@ final class Task
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
int $createdBy,
?DateTimeImmutable $plannedFrom = null,
?DateTimeImmutable $plannedTo = null,
): self {
if (! $jobStatus->allowsTasks()) {
throw new TasksNotAllowedYet;
}
return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy);
return new self(null, $jobId, $workTypeId, $title, self::text($description), $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, ...self::plan($plannedFrom, $plannedTo));
}
/**
@@ -73,8 +81,10 @@ final class Task
?EstimatedHours $estimatedHours,
array $assigneeUserIds,
int $createdBy,
?DateTimeImmutable $plannedFrom = null,
?DateTimeImmutable $plannedTo = null,
): self {
return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy);
return new self($id, $jobId, $workTypeId, $title, $description, $status, $dueOn, $estimatedHours, $assigneeUserIds, $createdBy, $plannedFrom, $plannedTo);
}
/**
@@ -103,6 +113,25 @@ final class Task
$this->status = $status;
}
/**
* Sets the planned schedule. A start without an end lasts one day;
* null as the start removes the schedule.
*
* @throws PlanEndsBeforeStart
*/
public function schedule(?DateTimeImmutable $from, ?DateTimeImmutable $to): void
{
[$this->plannedFrom, $this->plannedTo] = self::plan($from, $to);
}
/**
* @param list<int> $assigneeUserIds
*/
public function changeAssignees(array $assigneeUserIds): void
{
$this->assigneeUserIds = self::normaliseIds($assigneeUserIds);
}
public function id(): ?int
{
return $this->id;
@@ -143,6 +172,21 @@ final class Task
return $this->estimatedHours;
}
public function plannedFrom(): ?DateTimeImmutable
{
return $this->plannedFrom;
}
public function plannedTo(): ?DateTimeImmutable
{
return $this->plannedTo;
}
public function isScheduled(): bool
{
return $this->plannedFrom !== null;
}
/**
* @return list<int>
*/
@@ -168,6 +212,33 @@ final class Task
return $ids;
}
/**
* @return array{0: ?DateTimeImmutable, 1: ?DateTimeImmutable}
*
* @throws PlanEndsBeforeStart
*/
private static function plan(?DateTimeImmutable $from, ?DateTimeImmutable $to): array
{
if ($from === null) {
return [null, null];
}
$to ??= $from;
self::checkPlan($from, $to);
return [$from, $to];
}
/**
* @throws PlanEndsBeforeStart
*/
private static function checkPlan(?DateTimeImmutable $from, ?DateTimeImmutable $to): void
{
if ($from !== null && $to !== null && $to < $from) {
throw new PlanEndsBeforeStart;
}
}
private static function text(?string $value): ?string
{
$value = $value === null ? '' : trim($value);
+2 -1
View File
@@ -5,7 +5,8 @@ declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Enums;
/**
* Status of a task (spec 8.2). Per-service-unit columns come in phase 3.
* Status of a task (spec 8.2). The statuses are fixed: tasks are arranged
* per person in the task calendar instead of per-unit Kanban columns.
*/
enum TaskStatus: string
{
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* The workflow template is missing, out of use, or not for the job's service units.
*/
final class WorkflowTemplateNotAvailable extends DomainException
{
public function __construct(public readonly int $templateId)
{
parent::__construct("Workflow template {$templateId} is not available for this job.");
}
}
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\Services;
use App\Modules\Jobs\Domain\ValueObjects\TaskSchedule;
use DateInterval;
use DateTimeImmutable;
/**
* Books a task's estimated time from an assignee's days (spec 18.3).
*
* The estimate is split evenly over the working days of the planned
* period (not Saturdays, Sundays or holidays); a period of only such days
* splits it over all its days. No day gets more than the assignee's free
* capacity (the daily maximum minus what other open tasks already book):
* what does not fit moves to the next day of the period, and past its
* end to the next working days, which makes the task end later. Other
* tasks' bookings never move.
*/
final class TaskScheduler
{
/** Bookings are made in quarter hours, like time entries. */
private const int STEP_MINUTES = 15;
/** How far past the planned end the overflow may go. */
private const int MAX_EXTRA_DAYS = 366;
/**
* @param array<string, int> $otherMinutes Y-m-d => minutes booked by the assignee's other open tasks.
* @param list<string> $holidays Y-m-d dates of the holidays in use.
*/
public static function schedule(
DateTimeImmutable $from,
DateTimeImmutable $to,
int $minutes,
array $otherMinutes,
int $capacityMinutes,
array $holidays,
): TaskSchedule {
if ($minutes <= 0) {
return new TaskSchedule([], $to, false);
}
$holidaySet = array_flip($holidays);
$days = self::days($from, $to);
$targets = array_values(array_filter($days, fn (string $day): bool => self::isWorkingDay($day, $holidaySet)));
if ($targets === []) {
$targets = $days;
}
$shares = self::split($minutes, count($targets));
$booked = [];
$carry = 0;
foreach ($targets as $index => $day) {
$wanted = $shares[$index] + $carry;
$booking = min($wanted, self::free($day, $otherMinutes, $capacityMinutes));
$carry = $wanted - $booking;
if ($booking > 0) {
$booked[$day] = $booking;
}
}
$day = $to;
for ($extra = 0; $carry > 0 && $extra < self::MAX_EXTRA_DAYS; $extra++) {
$day = $day->add(new DateInterval('P1D'));
$date = $day->format('Y-m-d');
if (! self::isWorkingDay($date, $holidaySet)) {
continue;
}
$booking = min($carry, self::free($date, $otherMinutes, $capacityMinutes));
$carry -= $booking;
if ($booking > 0) {
$booked[$date] = $booking;
}
}
if ($carry > 0) {
$date = $day->format('Y-m-d');
$booked[$date] = ($booked[$date] ?? 0) + $carry;
}
ksort($booked);
$lastDay = array_key_last($booked);
$end = $lastDay !== null && $lastDay > $to->format('Y-m-d') ? new DateTimeImmutable($lastDay) : $to;
return new TaskSchedule($booked, $end, $end > $to);
}
/**
* The end of a task placed on a day without an end: as many working
* days as the estimate needs at the daily maximum; without an estimate, the day itself.
*
* @param list<string> $holidays
*/
public static function defaultEnd(DateTimeImmutable $from, int $minutes, int $capacityMinutes, array $holidays): DateTimeImmutable
{
if ($minutes <= 0 || $capacityMinutes <= 0) {
return $from;
}
$needed = (int) ceil($minutes / $capacityMinutes);
$holidaySet = array_flip($holidays);
$day = $from;
$counted = self::isWorkingDay($from->format('Y-m-d'), $holidaySet) ? 1 : 0;
for ($extra = 0; $counted < $needed && $extra < self::MAX_EXTRA_DAYS; $extra++) {
$day = $day->add(new DateInterval('P1D'));
if (self::isWorkingDay($day->format('Y-m-d'), $holidaySet)) {
$counted++;
}
}
return $day;
}
/**
* @param array<string, int> $holidaySet
*/
public static function isWorkingDay(string $date, array $holidaySet): bool
{
$day = new DateTimeImmutable($date);
return (int) $day->format('N') <= 5 && ! isset($holidaySet[$date]);
}
/**
* @return list<string>
*/
private static function days(DateTimeImmutable $from, DateTimeImmutable $to): array
{
$days = [];
for ($day = $from; $day <= $to; $day = $day->add(new DateInterval('P1D'))) {
$days[] = $day->format('Y-m-d');
}
return $days;
}
/**
* Splits the minutes into equal quarter-hour shares; the first days get
* the remainder. Odd minutes go to the first day.
*
* @return list<int>
*/
private static function split(int $minutes, int $parts): array
{
$steps = intdiv($minutes, self::STEP_MINUTES);
$odd = $minutes % self::STEP_MINUTES;
$shares = [];
for ($index = 0; $index < $parts; $index++) {
$shares[] = (intdiv($steps, $parts) + ($index < $steps % $parts ? 1 : 0)) * self::STEP_MINUTES;
}
$shares[0] += $odd;
return $shares;
}
/**
* @param array<string, int> $otherMinutes
*/
private static function free(string $day, array $otherMinutes, int $capacityMinutes): int
{
return max(0, $capacityMinutes - ($otherMinutes[$day] ?? 0));
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Jobs\Domain\ValueObjects;
use DateTimeImmutable;
/**
* The days one assignee spends on a task: minutes booked per day, and
* the day the work ends. The end is later than planned when the
* assignee's days were full and the rest moved to the next working days.
*/
final readonly class TaskSchedule
{
/**
* @param array<string, int> $minutesByDay Y-m-d => minutes, in date order.
*/
public function __construct(
public array $minutesByDay,
public DateTimeImmutable $end,
public bool $extended,
) {}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Modules\Jobs\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use Illuminate\Support\Facades\DB;
/**
* Tells the Customers module whether a customer has customer jobs.
*/
class CustomerReferencesFromJobs implements CustomerReferences
{
public function refersTo(int $customerId): bool
{
return DB::table('customer_jobs')->where('customer_id', $customerId)->exists();
}
}
@@ -13,7 +13,7 @@ use Illuminate\Database\Eloquent\Model;
/**
* Persistence model of a task, used only inside the Jobs Infrastructure
* layer. Assignees are in task_assignees.
* layer. Assignees are in task_assignees, day bookings in task_bookings.
*
* @property int $id
* @property int $customer_job_id
@@ -22,11 +22,13 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $description
* @property TaskStatus $status
* @property CarbonImmutable|null $due_on
* @property CarbonImmutable|null $planned_from
* @property CarbonImmutable|null $planned_to
* @property string|null $estimated_hours
* @property int $created_by
*/
#[Table('tasks')]
#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'estimated_hours', 'created_by'])]
#[Fillable(['customer_job_id', 'work_type_id', 'title', 'description', 'status', 'due_on', 'planned_from', 'planned_to', 'estimated_hours', 'created_by'])]
#[UseFactory(TaskFactory::class)]
class TaskModel extends Model
{
@@ -43,6 +45,8 @@ class TaskModel extends Model
'work_type_id' => 'integer',
'status' => TaskStatus::class,
'due_on' => 'immutable_date',
'planned_from' => 'immutable_date',
'planned_to' => 'immutable_date',
'created_by' => 'integer',
];
}
@@ -0,0 +1,50 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use Illuminate\Support\Facades\DB;
class EloquentTaskBookingRepository implements TaskBookingRepository
{
public function replaceFor(int $taskId, int $userId, array $minutesByDay): void
{
DB::table('task_bookings')->where('task_id', $taskId)->where('user_id', $userId)->delete();
$rows = [];
foreach ($minutesByDay as $day => $minutes) {
if ($minutes > 0) {
$rows[] = ['task_id' => $taskId, 'user_id' => $userId, 'day' => $day, 'minutes' => $minutes];
}
}
if ($rows !== []) {
DB::table('task_bookings')->insert($rows);
}
}
public function deleteForTask(int $taskId, array $keepUserIds = []): void
{
DB::table('task_bookings')
->where('task_id', $taskId)
->when($keepUserIds !== [], fn ($query) => $query->whereNotIn('user_id', $keepUserIds))
->delete();
}
public function otherOpenMinutes(int $userId, string $from, string $to, int $exceptTaskId): array
{
return DB::table('task_bookings')
->join('tasks', 'tasks.id', '=', 'task_bookings.task_id')
->where('task_bookings.user_id', $userId)
->where('task_bookings.task_id', '!=', $exceptTaskId)
->where('tasks.status', '!=', TaskStatus::Done->value)
->whereBetween('task_bookings.day', [$from, $to])
->groupBy('task_bookings.day')
->selectRaw('task_bookings.day as day, SUM(task_bookings.minutes) as minutes')
->pluck('minutes', 'day')
->mapWithKeys(fn ($minutes, $day): array => [substr((string) $day, 0, 10) => (int) $minutes])
->all();
}
}
@@ -0,0 +1,132 @@
<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\DTOs\CalendarAssignment;
use App\Modules\Jobs\Application\DTOs\CalendarTask;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Facades\DB;
class EloquentTaskCalendarQueries implements TaskCalendarQueries
{
public function scheduledTasks(string $from, string $to, ?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null): array
{
$query = $this->tasks($serviceUnitId, $onlyAssigneeUserId)
->whereNotNull('tasks.planned_from')
->where('tasks.planned_from', '<=', $to)
->where('tasks.planned_to', '>=', $from)
->orderBy('tasks.planned_from')
->orderBy('tasks.id');
return $this->calendarTasks($query);
}
public function unscheduledOpenTasks(?int $serviceUnitId = null, ?int $onlyAssigneeUserId = null, int $limit = 100): array
{
$query = $this->tasks($serviceUnitId, $onlyAssigneeUserId)
->whereNull('tasks.planned_from')
->where('tasks.status', '!=', TaskStatus::Done->value)
->where('customer_jobs.status', '!=', JobStatus::Archived->value)
->orderByRaw('tasks.due_on IS NULL')
->orderBy('tasks.due_on')
->orderBy('tasks.id')
->limit($limit);
return $this->calendarTasks($query);
}
public function openMinutesByUser(array $userIds, string $from, string $to): array
{
if ($userIds === []) {
return [];
}
$minutes = [];
DB::table('task_bookings')
->join('tasks', 'tasks.id', '=', 'task_bookings.task_id')
->whereIn('task_bookings.user_id', $userIds)
->where('tasks.status', '!=', TaskStatus::Done->value)
->whereBetween('task_bookings.day', [$from, $to])
->groupBy('task_bookings.user_id', 'task_bookings.day')
->selectRaw('task_bookings.user_id as user_id, task_bookings.day as day, SUM(task_bookings.minutes) as minutes')
->get()
->each(function ($row) use (&$minutes): void {
$minutes[(int) $row->user_id][substr((string) $row->day, 0, 10)] = (int) $row->minutes;
});
return $minutes;
}
private function tasks(?int $serviceUnitId, ?int $onlyAssigneeUserId): Builder
{
$query = DB::table('tasks')->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id');
if ($serviceUnitId !== null) {
$query->whereIn('customer_jobs.id', DB::table('customer_job_service_unit')->select('customer_job_id')->where('service_unit_id', $serviceUnitId));
}
if ($onlyAssigneeUserId !== null) {
JobInvolvement::restrict($query, $onlyAssigneeUserId);
$query->whereIn('tasks.id', DB::table('task_assignees')->select('task_id')->where('user_id', $onlyAssigneeUserId));
}
return $query;
}
/**
* @return list<CalendarTask>
*/
private function calendarTasks(Builder $query): array
{
$rows = $query->get([
'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.status', 'tasks.due_on', 'tasks.estimated_hours',
'tasks.planned_from', 'tasks.planned_to', 'customer_jobs.number', 'customer_jobs.name',
]);
$taskIds = $rows->pluck('id')->map(fn ($id): int => (int) $id)->all();
if ($taskIds === []) {
return [];
}
$assignees = DB::table('task_assignees')->whereIn('task_id', $taskIds)->orderBy('user_id')->get()->groupBy('task_id');
$bookings = DB::table('task_bookings')
->whereIn('task_id', $taskIds)
->groupBy('task_id', 'user_id')
->selectRaw('task_id, user_id, MIN(day) as first_day, MAX(day) as last_day, SUM(minutes) as minutes')
->get()
->keyBy(fn ($row): string => $row->task_id.'-'.$row->user_id);
return $rows->map(fn ($row): CalendarTask => new CalendarTask(
(int) $row->id,
(int) $row->customer_job_id,
(string) $row->number,
(string) $row->name,
(string) $row->title,
TaskStatus::from((string) $row->status),
self::date($row->due_on),
$row->estimated_hours === null ? null : (string) (float) $row->estimated_hours,
self::date($row->planned_from),
self::date($row->planned_to),
($assignees->get($row->id) ?? collect())->map(function ($assignee) use ($bookings, $row): CalendarAssignment {
$booking = $bookings->get($row->id.'-'.$assignee->user_id);
return new CalendarAssignment(
(int) $assignee->user_id,
self::date($booking?->first_day),
self::date($booking?->last_day),
(int) ($booking->minutes ?? 0),
);
})->values()->all(),
))->values()->all();
}
private static function date(mixed $value): ?string
{
return $value === null ? null : substr((string) $value, 0, 10);
}
}
@@ -164,6 +164,8 @@ class EloquentTaskQueries implements TaskQueries
->sortBy('name')
->values()
->all(),
plannedFrom: $model->planned_from?->format('Y-m-d'),
plannedTo: $model->planned_to?->format('Y-m-d'),
))->values()->all();
}
}
@@ -7,6 +7,7 @@ use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
@@ -37,6 +38,8 @@ class EloquentTaskRepository implements TaskRepository
'description' => $task->description(),
'status' => $task->status(),
'due_on' => $task->dueOn()?->format('Y-m-d'),
'planned_from' => $task->plannedFrom()?->format('Y-m-d'),
'planned_to' => $task->plannedTo()?->format('Y-m-d'),
'estimated_hours' => $task->estimatedHours()?->value,
'created_by' => $task->createdBy(),
])->save();
@@ -64,10 +67,17 @@ class EloquentTaskRepository implements TaskRepository
new TaskTitle($model->title),
$model->description,
$model->status,
$model->due_on === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $model->due_on->format('Y-m-d')) ?: null),
self::date($model->due_on),
$model->estimated_hours === null ? null : new EstimatedHours((float) $model->estimated_hours),
DB::table('task_assignees')->where('task_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(),
$model->created_by,
self::date($model->planned_from),
self::date($model->planned_to),
);
}
private static function date(?CarbonImmutable $value): ?DateTimeImmutable
{
return $value === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $value->format('Y-m-d')) ?: null);
}
}
@@ -3,15 +3,19 @@
namespace App\Modules\Jobs\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use App\Modules\Customers\Application\Contracts\CustomerRowUsage;
use App\Modules\Jobs\Application\Contracts\ChecklistQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\Jobs\Application\Contracts\TaskUsage;
use App\Modules\Jobs\Domain\Contracts\ChecklistItemRepository;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Contracts\JobNumberSequence;
use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository;
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
use App\Modules\Jobs\Infrastructure\CustomerReferencesFromJobs;
use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs;
use App\Modules\Jobs\Infrastructure\NothingUsesTasks;
use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence;
@@ -19,6 +23,8 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistIt
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentCustomerJobRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBookingRepository;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries;
use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository;
use App\Modules\Users\Domain\Enums\Role;
@@ -42,12 +48,20 @@ class JobsServiceProvider extends ServiceProvider
CustomerRowUsage::class => CustomerRowUsageFromJobs::class,
TaskRepository::class => EloquentTaskRepository::class,
TaskQueries::class => EloquentTaskQueries::class,
TaskBookingRepository::class => EloquentTaskBookingRepository::class,
TaskCalendarQueries::class => EloquentTaskCalendarQueries::class,
ChecklistItemRepository::class => EloquentChecklistItemRepository::class,
ChecklistQueries::class => EloquentChecklistQueries::class,
// Replaced by the TimeTracking module, which knows which tasks have time entries.
TaskUsage::class => NothingUsesTasks::class,
];
public function register(): void
{
// A customer with customer jobs cannot be removed.
$this->app->tag([CustomerReferencesFromJobs::class], CustomerReferences::TAG);
}
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
@@ -9,6 +9,7 @@ use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Illuminate\Validation\Rule;
@@ -29,6 +30,10 @@ class TaskForm extends Form
public string $estimated_hours = '';
public string $planned_from = '';
public string $planned_to = '';
public string $description = '';
/** @var list<string> */
@@ -41,6 +46,8 @@ class TaskForm extends Form
$this->status = $task->status->value;
$this->due_on = $task->dueOn ?? '';
$this->estimated_hours = $task->estimatedHours ?? '';
$this->planned_from = $task->plannedFrom ?? '';
$this->planned_to = $task->plannedTo ?? '';
$this->description = $task->description ?? '';
$this->assignee_user_ids = array_map(fn (NamedId $user): string => (string) $user->id, $task->assignees);
}
@@ -57,6 +64,8 @@ class TaskForm extends Form
dueOn: $this->due_on === '' ? null : $this->due_on,
estimatedHours: trim($this->estimated_hours) === '' ? null : $this->estimated_hours,
assigneeUserIds: array_map('intval', $this->assignee_user_ids),
plannedFrom: $this->planned_from === '' ? null : $this->planned_from,
plannedTo: $this->planned_from === '' || $this->planned_to === '' ? null : $this->planned_to,
);
}
@@ -66,6 +75,7 @@ class TaskForm extends Form
$exception instanceof InvalidTaskTitle => ['title', 'jobs.tasks.errors.invalid_title'],
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
$exception instanceof TasksNotAllowedYet => ['title', 'jobs.tasks.not_allowed_yet'],
$exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.calendar.errors.to'],
$exception instanceof InvalidTaskReference => [$exception->field === 'work_type' ? 'work_type_id' : 'assignee_user_ids', 'jobs.errors.invalid_reference'],
default => throw $exception,
};
@@ -83,6 +93,8 @@ class TaskForm extends Form
'work_type_id' => ['required', 'integer'],
'status' => ['required', Rule::enum(TaskStatus::class)],
'due_on' => ['nullable', 'date_format:Y-m-d'],
'planned_from' => ['nullable', 'date_format:Y-m-d'],
'planned_to' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:planned_from'],
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
'description' => ['nullable', 'string', 'max:10000'],
'assignee_user_ids' => ['array'],
@@ -100,6 +112,9 @@ class TaskForm extends Form
'title.max' => __('jobs.tasks.errors.invalid_title'),
'work_type_id.required' => __('jobs.tasks.errors.work_type_required'),
'due_on.date_format' => __('jobs.errors.invalid_date'),
'planned_from.date_format' => __('jobs.errors.invalid_date'),
'planned_to.date_format' => __('jobs.errors.invalid_date'),
'planned_to.after_or_equal' => __('jobs.calendar.errors.to'),
'estimated_hours.numeric' => __('jobs.errors.invalid_hours'),
'estimated_hours.min' => __('jobs.errors.invalid_hours'),
'estimated_hours.max' => __('jobs.errors.invalid_hours'),
@@ -0,0 +1,787 @@
<?php
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries;
use App\Modules\Jobs\Application\DTOs\CalendarBar;
use App\Modules\Jobs\Application\DTOs\CalendarRow;
use App\Modules\Jobs\Application\DTOs\CalendarTask;
use App\Modules\Jobs\Application\Services\TaskCalendarLayout;
use App\Modules\Jobs\Application\Services\TaskPlanner;
use App\Modules\Jobs\Application\UseCases\ChangeTaskStatus;
use App\Modules\Jobs\Application\UseCases\ClearTaskSchedule;
use App\Modules\Jobs\Application\UseCases\ScheduleTask;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* The task calendar (Gantt): two weeks from today, one row per person
* and a bar per task. Bars move and resize by dragging; every bar is also
* a button that opens a dialog for the same changes with the keyboard.
*/
new class extends Component
{
private const int DAYS = 14;
#[Url(except: '')]
public string $from = '';
#[Url(as: 'unit', except: '')]
public string $serviceUnit = '';
#[Url(except: false)]
public bool $mine = false;
#[Locked]
public string $statusMessage = '';
#[Locked]
public ?int $dialogTaskId = null;
#[Locked]
public ?int $dialogJobId = null;
#[Locked]
public ?int $dialogUserId = null;
#[Locked]
public string $dialogTitle = '';
#[Locked]
public string $dialogStatus = '';
public string $plannedFrom = '';
public string $plannedTo = '';
public string $assignee = '';
public string $status = '';
public function mount(): void
{
$this->authorize('jobs.view');
}
public function isSubcontractor(): bool
{
return auth()->user()?->role === Role::Subcontractor;
}
public function startDate(): CarbonImmutable
{
$start = $this->from === '' ? null : CarbonImmutable::createFromFormat('!Y-m-d', $this->from);
return $start instanceof CarbonImmutable && $start->format('Y-m-d') === $this->from ? $start : CarbonImmutable::today();
}
/**
* @return list<string>
*/
#[Computed]
public function days(): array
{
$start = $this->startDate();
return array_map(fn (int $offset): string => $start->addDays($offset)->format('Y-m-d'), range(0, self::DAYS - 1));
}
/**
* Holidays in use on the shown days, date => name.
*
* @return array<string, string>
*/
#[Computed]
public function holidays(): array
{
$names = [];
foreach (app(HolidayCalendar::class)->between($this->days[0], $this->days[self::DAYS - 1]) as $holiday) {
if ($holiday->active) {
$names[$holiday->date] = $holiday->key === null ? (string) $holiday->name : __('holidays.names.'.$holiday->key);
}
}
return $names;
}
/**
* Rows: the signed-in user first, then the others by name, then tasks
* without an assignee. A subcontractor sees only their own row.
*
* @return list<array{id: ?int, name: string}>
*/
#[Computed]
public function people(): array
{
$userId = (int) auth()->id();
$own = ['id' => $userId, 'name' => (string) auth()->user()?->name];
if ($this->isSubcontractor() || $this->mine) {
return [$own];
}
$others = [];
foreach (app(UserAccountQueries::class)->activeUserOptions() as $user) {
if ($user->id !== $userId) {
$others[] = ['id' => $user->id, 'name' => $user->name];
}
}
return [$own, ...$others, ['id' => null, 'name' => __('jobs.calendar.no_assignee')]];
}
/**
* @return list<CalendarRow>
*/
#[Computed]
public function rows(): array
{
$queries = app(TaskCalendarQueries::class);
$first = $this->days[0];
$last = $this->days[self::DAYS - 1];
$userIds = array_values(array_filter(array_column($this->people, 'id')));
return TaskCalendarLayout::build(
$this->days,
$this->people,
$queries->scheduledTasks($first, $last, $this->serviceUnitId(), $this->onlyAssigneeUserId()),
$queries->openMinutesByUser($userIds, $first, $last),
);
}
/**
* @return list<CalendarTask>
*/
#[Computed]
public function unscheduled(): array
{
$tasks = app(TaskCalendarQueries::class)->unscheduledOpenTasks($this->serviceUnitId(), $this->onlyAssigneeUserId());
if ($this->mine) {
$userId = (int) auth()->id();
$tasks = array_values(array_filter($tasks, fn (CalendarTask $task): bool => $task->assignmentOf($userId) !== null));
}
return $tasks;
}
/**
* Names of the people on the rows, user id => name, for assignee lists.
*
* @return array<int, string>
*/
#[Computed]
public function userNames(): array
{
$names = [];
foreach (app(UserAccountQueries::class)->activeUserOptions() as $user) {
$names[$user->id] = $user->name;
}
return $names;
}
#[Computed]
public function capacityMinutes(): int
{
return app(TaskPlanner::class)->capacityMinutes();
}
public function canManage(): bool
{
return Gate::allows('jobs.manage-tasks', 0);
}
public function showPrevious(): void
{
$this->moveRange(-self::DAYS);
}
public function showNext(): void
{
$this->moveRange(self::DAYS);
}
public function showToday(): void
{
$this->from = '';
$this->refresh();
$this->statusMessage = $this->showingMessage();
}
/**
* A bar was dropped (drag and drop). Without an end, the task gets as
* many working days as its estimate needs.
*/
public function reschedule(int $taskId, int $jobId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo, ScheduleTask $scheduleTask): void
{
$this->authorize('jobs.manage-tasks', $jobId);
$this->schedule($scheduleTask, $taskId, $jobId, $fromUserId, $toUserId, $plannedFrom, $plannedTo);
}
/**
* Opens the dialog of a bar or an unscheduled task (keyboard alternative to dragging).
*/
public function openDialog(int $taskId, ?int $userId): void
{
$task = $this->findTask($taskId);
if ($task === null) {
$this->statusMessage = __('jobs.calendar.not_changed');
return;
}
$this->authorize('jobs.update-task-status', $task->jobId);
$this->resetErrorBag();
$this->dialogTaskId = $task->taskId;
$this->dialogJobId = $task->jobId;
$this->dialogUserId = $userId;
$this->dialogTitle = __('jobs.calendar.dialog_task', ['title' => $task->title, 'job' => $task->jobNumber]);
$this->dialogStatus = $task->status->value;
$this->plannedFrom = $task->plannedFrom ?? CarbonImmutable::today()->format('Y-m-d');
$this->plannedTo = $task->plannedTo ?? '';
$this->assignee = $userId === null ? '' : (string) $userId;
$this->status = $task->status->value;
$this->js("document.getElementById('task-schedule-dialog').showModal()");
}
public function saveDialog(ScheduleTask $scheduleTask, ChangeTaskStatus $changeTaskStatus): void
{
if ($this->dialogTaskId === null || $this->dialogJobId === null) {
return;
}
$this->authorize('jobs.update-task-status', $this->dialogJobId);
$taskId = $this->dialogTaskId;
$jobId = $this->dialogJobId;
$task = $this->findTask($taskId);
$toUserId = $this->dialogUserId;
$messages = [];
if (Gate::allows('jobs.manage-tasks', $jobId)) {
$this->validate([
'plannedFrom' => ['required', 'date_format:Y-m-d'],
'plannedTo' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:plannedFrom'],
'assignee' => ['nullable', 'integer'],
], [
'plannedFrom.*' => __('jobs.calendar.errors.from'),
'plannedTo.*' => __('jobs.calendar.errors.to'),
]);
$toUserId = $this->assignee === '' ? null : (int) $this->assignee;
if (! $this->schedule($scheduleTask, $taskId, $jobId, $this->dialogUserId, $toUserId, $this->plannedFrom, $this->plannedTo === '' ? null : $this->plannedTo)) {
return;
}
$messages[] = $this->statusMessage;
}
$status = TaskStatus::tryFrom($this->status);
if ($status !== null && $status->value !== $this->dialogStatus) {
try {
$changeTaskStatus->execute($jobId, $taskId, $status);
} catch (TaskNotFound) {
$this->statusMessage = __('jobs.calendar.not_changed');
return;
}
$this->refresh();
$messages[] = __('jobs.calendar.status_changed', ['title' => $task->title ?? '', 'status' => __('jobs.tasks.statuses.'.$status->value)]);
}
$this->statusMessage = implode(' ', $messages);
$this->closeDialogAndFocus($taskId, $toUserId);
}
public function clearSchedule(ClearTaskSchedule $clearTaskSchedule): void
{
if ($this->dialogTaskId === null || $this->dialogJobId === null) {
return;
}
$this->authorize('jobs.manage-tasks', $this->dialogJobId);
$task = $this->findTask($this->dialogTaskId);
try {
$clearTaskSchedule->execute($this->dialogJobId, $this->dialogTaskId);
} catch (TaskNotFound) {
$this->statusMessage = __('jobs.calendar.not_changed');
return;
}
$this->refresh();
$this->statusMessage = __('jobs.calendar.cleared', ['title' => $task->title ?? '']);
$taskId = $this->dialogTaskId;
$this->js("document.getElementById('task-schedule-dialog').close(); document.getElementById('unscheduled-{$taskId}')?.focus()");
}
public function updatedServiceUnit(): void
{
$this->refresh();
}
public function updatedMine(): void
{
$this->refresh();
}
public function dayLabel(string $date): string
{
$day = CarbonImmutable::createFromFormat('!Y-m-d', $date);
return $day instanceof CarbonImmutable ? __('holidays.weekdays.'.$day->dayOfWeekIso).' '.$day->format('j.n.') : $date;
}
public function isDayOff(string $date): bool
{
$day = CarbonImmutable::createFromFormat('!Y-m-d', $date);
return isset($this->holidays[$date]) || ($day instanceof CarbonImmutable && $day->dayOfWeekIso >= 6);
}
public function hours(int $minutes): string
{
return rtrim(rtrim(number_format($minutes / 60, 2, ',', ''), '0'), ',');
}
public function shortDate(string $date): string
{
$day = CarbonImmutable::createFromFormat('!Y-m-d', $date);
return $day instanceof CarbonImmutable ? $day->format('j.n.Y') : $date;
}
public function barLabel(CalendarBar $bar): string
{
return __('jobs.calendar.bar_label', [
'title' => $bar->task->title,
'job' => $bar->task->jobNumber.' '.$bar->task->jobName,
'status' => __('jobs.tasks.statuses.'.$bar->task->status->value),
'from' => $this->shortDate($bar->from),
'to' => $this->shortDate($bar->to),
'hours' => $bar->minutes > 0 ? __('jobs.calendar.bar_hours', ['hours' => $this->hours($bar->minutes)]) : '',
]).($bar->late ? ', '.__('jobs.late') : '');
}
/**
* The person an unscheduled task is moved from when it is dropped on a
* row: its only assignee, so that the task moves rather than gets a
* second assignee.
*/
public function onlyAssignee(CalendarTask $task): ?int
{
return count($task->assignments) === 1 ? $task->assignments[0]->userId : null;
}
public function render(): mixed
{
return $this->view()->title(__('jobs.calendar.title'));
}
private function schedule(ScheduleTask $scheduleTask, int $taskId, int $jobId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo): bool
{
$task = $this->findTask($taskId);
try {
$result = $scheduleTask->execute($jobId, $taskId, $fromUserId, $toUserId, $plannedFrom, $plannedTo);
} catch (CustomerJobNotFound|TaskNotFound|InvalidArgumentException) {
$this->statusMessage = __('jobs.calendar.not_changed');
return false;
} catch (PlanEndsBeforeStart) {
$this->addError('plannedTo', __('jobs.calendar.errors.to'));
$this->statusMessage = __('jobs.calendar.errors.to');
return false;
} catch (InvalidTaskReference) {
$this->statusMessage = __('jobs.calendar.inactive_person');
return false;
}
$this->refresh();
$this->statusMessage = __($result->extended ? 'jobs.calendar.moved_extended' : 'jobs.calendar.moved', [
'title' => $task->title ?? '',
'person' => $toUserId === null ? __('jobs.calendar.no_assignee') : ($this->userNames[$toUserId] ?? ''),
'from' => $this->shortDate($result->plannedFrom),
'to' => $this->shortDate($result->plannedTo),
]);
return true;
}
private function closeDialogAndFocus(int $taskId, ?int $userId): void
{
$key = $taskId.'-'.($userId ?? 'none');
$this->js("document.getElementById('task-schedule-dialog').close();"
."const bar = document.getElementById('bar-{$key}');"
."(bar && bar.offsetParent !== null ? bar : document.getElementById('agenda-bar-{$key}'))?.focus();");
}
private function findTask(int $taskId): ?CalendarTask
{
foreach ($this->rows as $row) {
foreach ($row->bars as $bar) {
if ($bar->task->taskId === $taskId) {
return $bar->task;
}
}
}
foreach ($this->unscheduled as $task) {
if ($task->taskId === $taskId) {
return $task;
}
}
return null;
}
private function moveRange(int $days): void
{
$this->from = $this->startDate()->addDays($days)->format('Y-m-d');
$this->refresh();
$this->statusMessage = $this->showingMessage();
}
private function showingMessage(): string
{
return __('jobs.calendar.showing', ['from' => $this->shortDate($this->days[0]), 'to' => $this->shortDate($this->days[self::DAYS - 1])]);
}
private function refresh(): void
{
unset($this->days, $this->holidays, $this->people, $this->rows, $this->unscheduled);
}
private function serviceUnitId(): ?int
{
return $this->serviceUnit === '' ? null : (int) $this->serviceUnit;
}
private function onlyAssigneeUserId(): ?int
{
return $this->isSubcontractor() ? (int) auth()->id() : null;
}
};
?>
@php
$canManage = $this->canManage();
$days = $this->days;
$capacity = $this->hours($this->capacityMinutes);
$columns = 'grid-template-columns: 11rem repeat('.count($days).', minmax(0, 1fr));';
@endphp
<div class="mx-auto max-w-[120rem] space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.calendar.title') }}</h1>
<p class="max-w-3xl text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.intro') }}</p>
</div>
<div class="flex flex-wrap items-end gap-4">
<div class="flex flex-wrap gap-2">
<x-button subtle color="black" icon="chevron-left" wire:click="showPrevious" :text="__('jobs.calendar.previous')" />
<x-button subtle color="black" wire:click="showToday" :text="__('jobs.calendar.today')" />
<x-button subtle color="black" icon="chevron-right" position="right" wire:click="showNext" :text="__('jobs.calendar.next')" />
</div>
<div class="w-full sm:w-64">
{{-- TallStackUI's native select does not tie its label to the control, so aria-label names it. --}}
<x-select.native wire:model.live="serviceUnit" :label="__('jobs.fields.service_units')" :aria-label="__('jobs.fields.service_units')">
<option value="">{{ __('jobs.list.all_service_units') }}</option>
@foreach (app(CatalogQueries::class)->activeServiceUnits() as $unit)
<option value="{{ $unit->id }}">{{ $unit->name }}</option>
@endforeach
</x-select.native>
</div>
@if ($this->isSubcontractor())
<p class="pb-2 text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.subcontractor_note') }}</p>
@else
<div class="pb-2">
<x-checkbox id="calendar-only-mine" wire:model.live="mine" :label="__('jobs.calendar.only_mine')" />
</div>
@endif
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm font-medium">{{ $statusMessage }}</p>
<section aria-labelledby="calendar-range-heading" class="space-y-3">
<h2 id="calendar-range-heading" class="text-lg font-semibold">
{{ __('jobs.calendar.range', ['from' => $this->shortDate($days[0]), 'to' => $this->shortDate($days[count($days) - 1])]) }}
</h2>
{{-- Desktop: the Gantt grid. Dragging is a pointer shortcut; every bar is a button that opens the dialog. --}}
<div
class="hidden lg:block"
x-data="taskCalendar(@js($canManage))"
x-on:pointermove.window="track($event)"
x-on:pointerup.window="drop($event)"
x-on:keydown.escape.window="cancel()"
x-on:task-calendar-place.window="begin($event.detail.event, 'place', $event.detail.bar)"
>
<div class="grid border-b border-zinc-300 text-sm dark:border-zinc-600" style="{{ $columns }}" aria-hidden="true">
<div></div>
@foreach ($days as $index => $day)
<div
wire:key="head-{{ $day }}"
@class([
'border-l border-zinc-200 px-1 py-2 text-center dark:border-zinc-700',
'bg-zinc-200 dark:bg-zinc-800' => $this->isDayOff($day),
])
>
<div @class(['font-semibold' => $day === now()->format('Y-m-d')])>{{ $this->dayLabel($day) }}</div>
@if ($day === now()->format('Y-m-d'))
<div class="text-xs font-semibold">{{ __('jobs.calendar.today_marker') }}</div>
@endif
@isset($this->holidays[$day])
<div class="truncate text-xs" title="{{ $this->holidays[$day] }}">{{ $this->holidays[$day] }}</div>
@endisset
</div>
@endforeach
</div>
{{-- The day headings for screen readers, since the visual header above is hidden from them. --}}
<p class="sr-only">
@foreach ($days as $day)
@isset($this->holidays[$day])
{{ $this->dayLabel($day) }}: {{ __('jobs.calendar.holiday') }} {{ $this->holidays[$day] }}.
@endisset
@endforeach
</p>
@foreach ($this->rows as $row)
@php($rowKey = $row->userId ?? 'none')
<section
wire:key="row-{{ $rowKey }}"
aria-labelledby="row-{{ $rowKey }}-name"
class="grid border-b border-zinc-200 dark:border-zinc-700"
style="{{ $columns }} grid-template-rows: auto repeat({{ $row->lanes }}, 3rem);"
>
<h3
id="row-{{ $rowKey }}-name"
class="px-2 py-2 text-sm font-semibold break-words"
style="grid-column: 1; grid-row: 1 / span {{ $row->lanes + 1 }};"
>{{ $row->name }}</h3>
@foreach ($days as $index => $day)
@php($booked = $row->minutesByDay[$day] ?? 0)
<div
wire:key="cell-{{ $rowKey }}-{{ $day }}"
data-calendar-day="{{ $day }}"
data-calendar-user="{{ $row->userId ?? '' }}"
x-bind:class="isTarget('{{ $day }}', '{{ $row->userId ?? '' }}') && 'outline-2 -outline-offset-2 outline-blue-700 dark:outline-blue-300'"
@class([
'min-h-12 border-l border-zinc-200 px-1 pt-1 pb-2 text-right text-xs dark:border-zinc-700',
'bg-zinc-200 dark:bg-zinc-800' => $this->isDayOff($day),
])
style="grid-column: {{ $index + 2 }}; grid-row: 1 / span {{ $row->lanes + 1 }};"
>
@if ($booked > 0)
<span class="sr-only">{{ $this->dayLabel($day) }}:</span>
<span @class(['font-semibold' => $booked > $this->capacityMinutes])>
{{ __('jobs.calendar.load', ['booked' => $this->hours($booked), 'capacity' => $capacity]) }}
@if ($booked > $this->capacityMinutes)
<x-icon name="exclamation-triangle" class="inline size-3" aria-hidden="true" />
{{ __('jobs.calendar.over_capacity') }}
@endif
</span>
@endif
</div>
@endforeach
@foreach ($row->bars as $bar)
<button
type="button"
id="bar-{{ $bar->key() }}"
wire:key="bar-{{ $bar->key() }}"
aria-label="{{ $this->barLabel($bar) }}"
x-on:pointerdown="begin($event, 'move', @js(['task' => $bar->task->taskId, 'job' => $bar->task->jobId, 'user' => $bar->userId, 'from' => $bar->from, 'to' => $bar->to]))"
x-on:click="if (! consumeDrag()) $wire.openDialog({{ $bar->task->taskId }}, {{ $bar->userId ?? 'null' }})"
@class([
'relative z-10 mx-0.5 my-1 flex min-w-0 touch-none flex-col justify-center overflow-hidden border px-2 text-left text-xs leading-tight select-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-300',
'cursor-grab' => $canManage,
'border-primary-300 bg-primary-100 text-primary-950 dark:border-primary-600 dark:bg-primary-900 dark:text-white' => $bar->task->status !== TaskStatus::Done,
'border-zinc-300 bg-zinc-100 text-zinc-800 dark:border-zinc-600 dark:bg-zinc-700 dark:text-zinc-100' => $bar->task->status === TaskStatus::Done,
'rounded-l-md' => $bar->from >= $days[0],
'rounded-r-md' => $bar->to <= $days[count($days) - 1],
])
style="grid-column: {{ $bar->start + 2 }} / span {{ $bar->span }}; grid-row: {{ $bar->lane + 2 }};"
>
<span class="truncate font-semibold">{{ $bar->task->title }}</span>
<span class="flex min-w-0 items-center gap-1 truncate">
@if ($bar->late)
<x-icon name="exclamation-triangle" class="size-3 shrink-0" aria-hidden="true" />
<span class="font-semibold">{{ __('jobs.late') }}</span>
@endif
<span class="truncate">{{ $bar->task->jobNumber }} · {{ __('jobs.tasks.statuses.'.$bar->task->status->value) }}@if ($bar->minutes > 0) · {{ $this->hours($bar->minutes) }} h @endif</span>
</span>
@if ($canManage)
<span
class="absolute inset-y-0 left-0 w-2 cursor-ew-resize"
aria-hidden="true"
x-on:pointerdown.stop="begin($event, 'start', @js(['task' => $bar->task->taskId, 'job' => $bar->task->jobId, 'user' => $bar->userId, 'from' => $bar->from, 'to' => $bar->to]))"
></span>
<span
class="absolute inset-y-0 right-0 w-2 cursor-ew-resize"
aria-hidden="true"
x-on:pointerdown.stop="begin($event, 'end', @js(['task' => $bar->task->taskId, 'job' => $bar->task->jobId, 'user' => $bar->userId, 'from' => $bar->from, 'to' => $bar->to]))"
></span>
@endif
</button>
@endforeach
</section>
@endforeach
</div>
{{-- Phones and narrow windows: the same tasks as a list per person. --}}
<div class="space-y-4 lg:hidden">
@foreach ($this->rows as $row)
@php($rowKey = $row->userId ?? 'none')
<section wire:key="agenda-{{ $rowKey }}" aria-labelledby="agenda-{{ $rowKey }}-name" class="space-y-2 rounded-lg border border-zinc-200 p-3 dark:border-zinc-700">
<h3 id="agenda-{{ $rowKey }}-name" class="font-semibold break-words">{{ $row->name }}</h3>
@if ($row->bars === [])
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.no_tasks') }}</p>
@else
<ul class="space-y-2">
@foreach ($row->bars as $bar)
<li wire:key="agenda-bar-{{ $bar->key() }}">
<button
type="button"
id="agenda-bar-{{ $bar->key() }}"
wire:click="openDialog({{ $bar->task->taskId }}, {{ $bar->userId ?? 'null' }})"
class="flex w-full flex-col gap-1 rounded-md border border-zinc-300 p-2 text-left text-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:border-zinc-600 dark:focus-visible:outline-blue-300"
>
<span class="font-semibold break-words">{{ $bar->task->title }}</span>
<span>{{ $this->shortDate($bar->from) }}–{{ $this->shortDate($bar->to) }}@if ($bar->minutes > 0), {{ $this->hours($bar->minutes) }} h @endif</span>
<span class="break-words">{{ $bar->task->jobNumber }} {{ $bar->task->jobName }} · {{ __('jobs.tasks.statuses.'.$bar->task->status->value) }}</span>
@if ($bar->late)
<span class="inline-flex items-center gap-1 font-semibold">
<x-icon name="exclamation-triangle" class="size-4" aria-hidden="true" />{{ __('jobs.late') }}
</span>
@endif
</button>
</li>
@endforeach
</ul>
@endif
</section>
@endforeach
</div>
</section>
<section aria-labelledby="unscheduled-heading" class="space-y-3" x-data>
<h2 id="unscheduled-heading" class="text-lg font-semibold">{{ __('jobs.calendar.unscheduled') }}</h2>
@if ($this->unscheduled === [])
<p class="text-sm">{{ __('jobs.calendar.unscheduled_none') }}</p>
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.calendar.unscheduled_intro') }}</p>
<ul class="grid gap-2 sm:grid-cols-2 xl:grid-cols-4">
@foreach ($this->unscheduled as $task)
<li
wire:key="unscheduled-{{ $task->taskId }}"
@if ($canManage)
x-on:pointerdown="$dispatch('task-calendar-place', { event: $event, bar: @js(['task' => $task->taskId, 'job' => $task->jobId, 'user' => $this->onlyAssignee($task), 'from' => null, 'to' => null]) })"
@endif
@class([
'flex flex-col gap-1 rounded-md border border-zinc-300 p-2 text-sm select-none dark:border-zinc-600',
'lg:cursor-grab lg:touch-none' => $canManage,
])
>
<span class="font-semibold break-words">{{ $task->title }}</span>
<span class="break-words">{{ $task->jobNumber }} {{ $task->jobName }}</span>
<span class="break-words">
{{ $task->assignments === [] ? __('jobs.calendar.no_assignee') : implode(', ', array_map(fn ($assignment) => $this->userNames[$assignment->userId] ?? '', $task->assignments)) }}
@if ($task->estimatedHours !== null) · {{ str_replace('.', ',', $task->estimatedHours) }} h @endif
</span>
@if ($task->dueOn !== null)
<span>{{ __('jobs.tasks.fields.due_on') }}: <x-jobs.due-date :date="$task->dueOn" :status="$task->status" /></span>
@endif
<div>
<x-button
sm
subtle
color="black"
id="unscheduled-{{ $task->taskId }}"
wire:click="openDialog({{ $task->taskId }}, {{ $this->onlyAssignee($task) ?? 'null' }})"
x-on:pointerdown.stop
:text="__('jobs.calendar.schedule')"
:aria-label="__('jobs.calendar.schedule_named', ['title' => $task->title])"
/>
</div>
</li>
@endforeach
</ul>
@endif
</section>
<x-confirm-dialog id="task-schedule-dialog" :title="__('jobs.calendar.dialog_title')">
<p class="font-medium break-words">{{ $dialogTitle }}</p>
<form id="task-schedule-form" wire:submit="saveDialog" class="mt-4 space-y-4" novalidate>
@if ($dialogJobId !== null && Gate::allows('jobs.manage-tasks', $dialogJobId))
<x-input wire:model="plannedFrom" type="date" :label="__('jobs.calendar.fields.from')" required />
<x-input wire:model="plannedTo" type="date" :label="__('jobs.calendar.fields.to')" :hint="__('jobs.calendar.fields.to_hint')" />
<x-select.native wire:model="assignee" :label="__('jobs.calendar.fields.assignee')" :aria-label="__('jobs.calendar.fields.assignee')" :hint="__('jobs.calendar.fields.assignee_hint')">
<option value="">{{ __('jobs.calendar.no_assignee') }}</option>
@foreach ($this->userNames as $userId => $name)
<option value="{{ $userId }}">{{ $name }}</option>
@endforeach
</x-select.native>
@endif
<x-select.native wire:model="status" :label="__('jobs.calendar.fields.status')" :aria-label="__('jobs.calendar.fields.status')">
@foreach (TaskStatus::cases() as $option)
<option value="{{ $option->value }}">{{ __('jobs.tasks.statuses.'.$option->value) }}</option>
@endforeach
</x-select.native>
@if ($dialogJobId !== null)
<p class="flex flex-wrap gap-x-4 gap-y-1">
<x-link :href="route('jobs.show', $dialogJobId).'#tasks'" navigate>{{ __('jobs.calendar.open_job') }}</x-link>
@if (Gate::allows('jobs.manage-tasks', $dialogJobId) && $dialogTaskId !== null)
<x-link :href="route('jobs.tasks.edit', [$dialogJobId, $dialogTaskId])" navigate>{{ __('jobs.calendar.edit_task') }}</x-link>
@endif
</p>
@endif
</form>
<x-slot:actions>
@if ($dialogJobId !== null && Gate::allows('jobs.manage-tasks', $dialogJobId))
<x-button subtle color="black" wire:click="clearSchedule" :text="__('jobs.calendar.clear')" />
@endif
<x-button wire:click="saveDialog" :text="__('jobs.calendar.save')" />
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -313,7 +313,10 @@ new class extends Component
@can('jobs.manage-tasks', $job->id)
@if ($job->status->allowsTasks())
<x-button :href="route('jobs.tasks.create', $job->id)" wire:navigate icon="plus" :text="__('jobs.tasks.new')" />
<div class="flex flex-wrap gap-2">
<x-button :href="route('jobs.tasks.create', $job->id)" wire:navigate icon="plus" :text="__('jobs.tasks.new')" />
<x-button :href="route('jobs.tasks.from-template', $job->id)" wire:navigate subtle color="black" icon="queue-list" :text="__('jobs.tasks.from_template.title')" />
</div>
@endif
@endcan
</div>
@@ -348,6 +351,14 @@ new class extends Component
<dd>{{ $task->assignees === [] ? __('jobs.not_set') : collect($task->assignees)->pluck('name')->join(', ') }}</dd>
<dt class="font-medium">{{ __('jobs.tasks.fields.due_on') }}</dt>
<dd><x-jobs.due-date :date="$task->dueOn" :status="$task->status" /></dd>
<dt class="font-medium">{{ __('jobs.tasks.schedule') }}</dt>
<dd>
@if ($task->plannedFrom === null)
{{ __('jobs.not_set') }}
@else
{{ __('jobs.tasks.schedule_range', ['from' => $this->formatDate($task->plannedFrom), 'to' => $this->formatDate($task->plannedTo)]) }}
@endif
</dd>
<dt class="font-medium">{{ __('jobs.tasks.fields.estimated_hours') }}</dt>
<dd>{{ $task->estimatedHours === null ? __('jobs.not_set') : str_replace('.', ',', $task->estimatedHours).' h' }}</dd>
</dl>
@@ -260,7 +260,8 @@ new class extends Component
};
?>
<section aria-labelledby="checklist-{{ $taskId }}-heading" class="space-y-2">
{{-- Named by the task, so the checklists of a job's tasks are distinguishable landmarks. --}}
<section aria-label="{{ __('jobs.tasks.checklist.list_of', ['title' => $taskTitle]) }}" class="space-y-2">
@php($canCheck = Gate::allows('jobs.update-task-status', $jobId))
@php($canManage = Gate::allows('jobs.manage-tasks', $jobId))
@php($doneCount = count(array_filter($this->items, fn ($item) => $item->done)))
@@ -13,6 +13,7 @@ use App\Modules\Jobs\Presentation\Livewire\Forms\TaskForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Enums\Role;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
@@ -130,11 +131,12 @@ new class extends Component
try {
if ($this->taskId === null) {
$addTask->execute($this->jobId, $data, (int) auth()->id());
session()->flash('status', __('jobs.tasks.created', ['title' => trim($data->title)]));
$taskId = $addTask->execute($this->jobId, $data, (int) auth()->id());
$message = __('jobs.tasks.created', ['title' => trim($data->title)]);
} else {
$updateTask->execute($this->jobId, $this->taskId, $data);
session()->flash('status', __('jobs.tasks.updated', ['title' => trim($data->title)]));
$taskId = $this->taskId;
$updateTask->execute($this->jobId, $taskId, $data);
$message = __('jobs.tasks.updated', ['title' => trim($data->title)]);
}
} catch (CustomerJobNotFound|TaskNotFound) {
abort(404);
@@ -144,6 +146,14 @@ new class extends Component
return;
}
$plannedTo = app(TaskQueries::class)->findTask($this->jobId, $taskId)?->plannedTo;
if ($data->plannedFrom !== null && $plannedTo !== null && $plannedTo !== ($data->plannedTo ?? $data->plannedFrom)) {
$message .= ' '.__('jobs.tasks.extended', ['to' => CarbonImmutable::parse($plannedTo)->format('j.n.Y')]);
}
session()->flash('status', $message);
$this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true);
}
@@ -208,6 +218,15 @@ new class extends Component
/>
</div>
<fieldset class="space-y-2">
<legend class="text-sm font-semibold">{{ __('jobs.tasks.schedule') }}</legend>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.fields.planned_hint') }}</p>
<div class="grid gap-6 sm:grid-cols-2">
<x-input wire:model="form.planned_from" type="date" :label="__('jobs.tasks.fields.planned_from')" />
<x-input wire:model="form.planned_to" type="date" :label="__('jobs.tasks.fields.planned_to')" />
</div>
</fieldset>
<x-textarea wire:model="form.description" :label="__('jobs.tasks.fields.description')" resize-auto />
<div class="flex flex-wrap gap-3">
@@ -0,0 +1,261 @@
<?php
use App\Modules\Catalog\Application\Contracts\WorkflowTemplateQueries;
use App\Modules\Catalog\Application\DTOs\WorkflowStepSummary;
use App\Modules\Catalog\Application\DTOs\WorkflowTemplateDetails;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Application\DTOs\TemplateTaskSchedule;
use App\Modules\Jobs\Application\UseCases\AddTasksFromWorkflowTemplate;
use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound;
use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference;
use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet;
use App\Modules\Jobs\Domain\Exceptions\WorkflowTemplateNotAvailable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Adds a job's tasks from a workflow template (työnkulkupohja): one task per
* step. Once a template is chosen, a table of its tasks takes an optional
* due date and estimate for each.
*/
new class extends Component
{
#[Locked]
public int $jobId;
#[Locked]
public string $jobTitle = '';
/** @var list<int> */
#[Locked]
public array $serviceUnitIds = [];
public string $templateId = '';
/**
* One row per step of the chosen template, in step order.
*
* @var list<array{due_on: string, estimated_hours: string}>
*/
public array $rows = [];
public function mount(CustomerJobQueries $jobQueries, int $job): void
{
$details = $jobQueries->findDetails($job);
abort_if($details === null, 404);
$this->authorize('jobs.manage-tasks', $details->id);
abort_unless($details->status->allowsTasks(), 404);
$this->jobId = $details->id;
$this->jobTitle = $details->number.' '.$details->name;
$this->serviceUnitIds = array_map(fn (NamedId $unit): int => $unit->id, $details->serviceUnits);
}
/**
* @return list<WorkflowTemplateDetails>
*/
#[Computed]
public function templates(): array
{
return app(WorkflowTemplateQueries::class)->activeFor($this->serviceUnitIds);
}
/**
* The templates as radio options; the description lists the steps.
*
* @return list<array{label: string, value: string, description: string}>
*/
#[Computed]
public function options(): array
{
return array_map(fn (WorkflowTemplateDetails $template): array => [
'label' => $this->labelOf($template),
'value' => (string) $template->id,
'description' => __('jobs.tasks.from_template.steps', [
'steps' => implode(' → ', array_map(
fn (WorkflowStepSummary $step): string => $step->workTypeId === null ? $step->title : $step->title.' ('.$step->workTypeName.')',
$template->steps,
)),
]),
], $this->templates);
}
#[Computed]
public function selectedTemplate(): ?WorkflowTemplateDetails
{
foreach ($this->templates as $template) {
if ((string) $template->id === $this->templateId) {
return $template;
}
}
return null;
}
/**
* A new template gets empty rows for its steps.
*/
public function updatedTemplateId(): void
{
$this->resetErrorBag();
$this->rows = array_map(fn (): array => ['due_on' => '', 'estimated_hours' => ''], $this->selectedTemplate?->steps ?? []);
}
public function add(AddTasksFromWorkflowTemplate $addTasks): void
{
$this->authorize('jobs.manage-tasks', $this->jobId);
$this->validate(
[
'templateId' => ['required', 'integer'],
'rows' => ['array'],
'rows.*.due_on' => ['nullable', 'date_format:Y-m-d'],
'rows.*.estimated_hours' => ['nullable', 'regex:/^\s*\d{1,5}([.,]\d{1,2})?\s*$/'],
],
[
'templateId.required' => __('jobs.tasks.from_template.choose'),
'templateId.integer' => __('jobs.tasks.from_template.not_available'),
'rows.*.due_on.date_format' => __('jobs.errors.invalid_date'),
'rows.*.estimated_hours.regex' => __('jobs.errors.invalid_hours'),
],
);
$template = $this->selectedTemplate;
$schedules = array_map(fn (array $row): TemplateTaskSchedule => new TemplateTaskSchedule(
$row['due_on'] === '' ? null : $row['due_on'],
trim($row['estimated_hours']) === '' ? null : $row['estimated_hours'],
), $this->rows);
try {
$count = $addTasks->execute($this->jobId, (int) $this->templateId, (int) auth()->id(), $schedules);
} catch (CustomerJobNotFound) {
abort(404);
} catch (TasksNotAllowedYet) {
$this->addError('templateId', __('jobs.tasks.not_allowed_yet'));
return;
} catch (InvalidEstimatedHours) {
$this->addError('templateId', __('jobs.errors.invalid_hours'));
return;
} catch (WorkflowTemplateNotAvailable|InvalidTaskReference) {
unset($this->templates, $this->options, $this->selectedTemplate);
$this->addError('templateId', __('jobs.tasks.from_template.not_available'));
return;
}
session()->flash('status', trans_choice('jobs.tasks.from_template.added', $count, [
'count' => $count,
'name' => $template === null ? '' : $this->labelOf($template),
]));
$this->redirect(route('jobs.show', $this->jobId).'#tasks', navigate: true);
}
public function render(): mixed
{
return $this->view()->title(__('jobs.tasks.from_template.title').' – '.$this->jobTitle);
}
private function labelOf(WorkflowTemplateDetails $template): string
{
return __('jobs.tasks.from_template.option', ['name' => $template->name, 'work_type' => $template->workTypeName]);
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('jobs.tasks.from_template.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.job_label') }}: {{ $jobTitle }}</p>
</div>
<p class="text-sm">{{ __('jobs.tasks.from_template.intro') }}</p>
@if ($this->options === [])
@error('templateId')
<p role="alert" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
<p>{{ __('jobs.tasks.from_template.none') }}</p>
<x-button :href="route('jobs.show', $jobId)" wire:navigate subtle color="black" :text="__('jobs.tasks.from_template.back')" />
@else
<form wire:submit="add" class="space-y-6" novalidate>
<x-radio.group
id="template"
wire:model.live="templateId"
:label="__('jobs.tasks.from_template.template')"
:options="$this->options"
required
/>
@if (($template = $this->selectedTemplate) !== null)
{{-- An input grid is a form, so a native table rather than <x-table>. --}}
<div class="space-y-2">
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.from_template.schedule_help') }}</p>
<table class="w-full border-collapse text-sm">
<caption class="mb-2 text-left font-medium">{{ __('jobs.tasks.from_template.table_caption', ['name' => $template->name]) }}</caption>
<thead>
<tr class="border-b border-zinc-200 dark:border-zinc-700">
<th scope="col" class="py-2 pr-2 text-left font-semibold">{{ __('jobs.tasks.from_template.task') }}</th>
<th scope="col" class="px-1 py-2 text-left font-semibold">{{ __('jobs.tasks.fields.due_on') }}</th>
<th scope="col" class="py-2 pl-1 text-left font-semibold">{{ __('jobs.tasks.fields.estimated_hours') }}</th>
</tr>
</thead>
<tbody>
@foreach ($template->steps as $index => $step)
<tr wire:key="row-{{ $template->id }}-{{ $index }}" class="border-b border-zinc-200 align-top dark:border-zinc-700">
<th scope="row" class="py-2 pr-2 text-left font-normal break-words">
<span class="font-medium">{{ $step->title }}</span>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ $step->workTypeName }}</span>
</th>
<td class="px-1 py-2">
<input
type="date"
id="row-{{ $index }}-due-on"
wire:model="rows.{{ $index }}.due_on"
aria-label="{{ __('jobs.tasks.from_template.due_on_of', ['title' => $step->title]) }}"
@error('rows.'.$index.'.due_on') aria-invalid="true" aria-describedby="row-{{ $index }}-due-on-error" @enderror
class="w-full min-w-0 rounded-md border border-zinc-500 bg-white px-1 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800 dark:[color-scheme:dark]"
/>
@error('rows.'.$index.'.due_on')
<p id="row-{{ $index }}-due-on-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</td>
<td class="py-2 pl-1">
<input
type="text"
inputmode="decimal"
autocomplete="off"
id="row-{{ $index }}-hours"
wire:model="rows.{{ $index }}.estimated_hours"
aria-label="{{ __('jobs.tasks.from_template.hours_of', ['title' => $step->title]) }}"
@error('rows.'.$index.'.estimated_hours') aria-invalid="true" aria-describedby="row-{{ $index }}-hours-error" @enderror
class="w-16 rounded-md border border-zinc-500 bg-white px-2 py-1 text-sm dark:border-zinc-400 dark:bg-zinc-800"
/>
@error('rows.'.$index.'.estimated_hours')
<p id="row-{{ $index }}-hours-error" class="mt-1 text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
@enderror
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('jobs.tasks.from_template.submit')" />
<x-button :href="route('jobs.show', $jobId)" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
@endif
</div>
@@ -10,8 +10,10 @@ Route::middleware(['web', 'auth', 'can:jobs.view'])
Route::livewire('/create', 'jobs::form')->middleware('can:jobs.manage')->name('create');
Route::livewire('/quick', 'jobs::quick')->middleware('can:jobs.manage')->name('quick');
Route::livewire('/board', 'jobs::board')->name('board');
Route::livewire('/calendar', 'jobs::calendar')->name('calendar');
Route::livewire('/{job}', 'jobs::show')->whereNumber('job')->name('show');
Route::livewire('/{job}/edit', 'jobs::form')->whereNumber('job')->middleware('can:jobs.manage')->name('edit');
Route::livewire('/{job}/tasks/create', 'jobs::task-form')->whereNumber('job')->name('tasks.create');
Route::livewire('/{job}/tasks/from-template', 'jobs::tasks-from-template')->whereNumber('job')->name('tasks.from-template');
Route::livewire('/{job}/tasks/{task}/edit', 'jobs::task-form')->whereNumber(['job', 'task'])->name('tasks.edit');
});
@@ -0,0 +1,17 @@
<?php
namespace App\Modules\Sales\Infrastructure;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use Illuminate\Support\Facades\DB;
/**
* Tells the Customers module whether a customer has quick sales.
*/
class CustomerReferencesFromSales implements CustomerReferences
{
public function refersTo(int $customerId): bool
{
return DB::table('quick_sales')->where('customer_id', $customerId)->exists();
}
}
@@ -3,11 +3,13 @@
namespace App\Modules\Sales\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerReferences;
use App\Modules\Sales\Application\Contracts\QuickSaleHours;
use App\Modules\Sales\Application\Contracts\QuickSaleProducts;
use App\Modules\Sales\Application\Contracts\QuickSaleQueries;
use App\Modules\Sales\Domain\Contracts\CashDayRepository;
use App\Modules\Sales\Domain\Contracts\QuickSaleRepository;
use App\Modules\Sales\Infrastructure\CustomerReferencesFromSales;
use App\Modules\Sales\Infrastructure\HoursForQuickSales;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentCashDayRepository;
use App\Modules\Sales\Infrastructure\Persistence\Repositories\EloquentQuickSaleQueries;
@@ -36,6 +38,12 @@ class SalesServiceProvider extends ServiceProvider
QuickSaleHours::class => HoursForQuickSales::class,
];
public function register(): void
{
// A customer with quick sales cannot be removed.
$this->app->tag([CustomerReferencesFromSales::class], CustomerReferences::TAG);
}
public function boot(): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\Contracts;
use App\Modules\Shared\Application\DTOs\HolidayOverride;
/**
* Stored changes to the calculated Finnish holidays, one per date.
*/
interface HolidayOverrides
{
/**
* @return list<HolidayOverride> In date order; dates are Y-m-d and inclusive.
*/
public function between(string $from, string $to): array;
public function find(string $date): ?HolidayOverride;
public function save(HolidayOverride $override): void;
public function delete(string $date): void;
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\DTOs;
/**
* A holiday of the calendar. A Finnish public holiday has a key (named in
* the UI's language) and can be taken out of use; a company's own day off
* has a name and can be removed.
*/
final readonly class Holiday
{
public function __construct(
public string $date,
public ?string $key,
public ?string $name,
public bool $active,
) {}
public function isCompanyDay(): bool
{
return $this->key === null;
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\DTOs;
/**
* A change to the calculated holidays: a Finnish holiday taken out of use
* (isHoliday false) or a company's own day off (isHoliday true, named).
*/
final readonly class HolidayOverride
{
public function __construct(
public string $date,
public bool $isHoliday,
public ?string $name = null,
) {}
}
@@ -0,0 +1,148 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Application\UseCases;
use App\Modules\Shared\Application\Contracts\HolidayOverrides;
use App\Modules\Shared\Application\DTOs\Holiday;
use App\Modules\Shared\Application\DTOs\HolidayOverride;
use App\Modules\Shared\Domain\Exceptions\HolidayAlreadyExists;
use App\Modules\Shared\Domain\Exceptions\InvalidHolidayName;
use App\Modules\Shared\Domain\Exceptions\NotAHoliday;
use App\Modules\Shared\Domain\Services\FinnishHolidays;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* The holidays (arkipyhät) of the calendar: the Finnish public holidays,
* calculated for every year, minus those the admin has taken out of use,
* plus the company's own days off (Asetukset → Arkipyhät). Holidays are
* shown like weekends, but work can still be scheduled on them. Who may
* change them is checked by the caller (admin).
*/
final class HolidayCalendar
{
public function __construct(private HolidayOverrides $overrides) {}
/**
* Every holiday between the dates, including those out of use.
*
* @return list<Holiday> In date order.
*/
public function between(string $from, string $to): array
{
$fromDate = self::date($from);
$toDate = self::date($to);
$holidays = [];
for ($year = (int) $fromDate->format('Y'); $year <= (int) $toDate->format('Y'); $year++) {
foreach (FinnishHolidays::forYear($year) as $date => $key) {
if ($date >= $from && $date <= $to) {
$holidays[$date] = new Holiday($date, $key, null, true);
}
}
}
foreach ($this->overrides->between($from, $to) as $override) {
$calculated = $holidays[$override->date] ?? null;
if ($calculated !== null) {
$holidays[$override->date] = new Holiday($override->date, $calculated->key, null, $override->isHoliday);
} elseif ($override->isHoliday) {
$holidays[$override->date] = new Holiday($override->date, null, $override->name, true);
}
}
ksort($holidays);
return array_values($holidays);
}
/**
* The holidays in use between the dates.
*
* @return list<string> Y-m-d dates in order.
*/
public function activeDatesBetween(string $from, string $to): array
{
return array_values(array_map(
fn (Holiday $holiday): string => $holiday->date,
array_filter($this->between($from, $to), fn (Holiday $holiday): bool => $holiday->active),
));
}
/**
* @throws NotAHoliday
*/
public function disable(string $date): void
{
$this->calculatedKey($date);
$this->overrides->save(new HolidayOverride($date, false));
}
/**
* @throws NotAHoliday
*/
public function enable(string $date): void
{
$this->calculatedKey($date);
$this->overrides->delete($date);
}
/**
* @throws InvalidHolidayName
* @throws HolidayAlreadyExists
*/
public function addCompanyDay(string $date, string $name): void
{
$name = trim((string) preg_replace('/\s+/u', ' ', $name));
if ($name === '' || mb_strlen($name) > 100) {
throw new InvalidHolidayName;
}
self::date($date);
if (isset(FinnishHolidays::forYear((int) substr($date, 0, 4))[$date]) || $this->overrides->find($date) !== null) {
throw new HolidayAlreadyExists;
}
$this->overrides->save(new HolidayOverride($date, true, $name));
}
/**
* @throws NotAHoliday
*/
public function removeCompanyDay(string $date): void
{
$override = $this->overrides->find($date);
if ($override === null || ! $override->isHoliday || isset(FinnishHolidays::forYear((int) substr($date, 0, 4))[$date])) {
throw new NotAHoliday;
}
$this->overrides->delete($date);
}
/**
* @throws NotAHoliday
*/
private function calculatedKey(string $date): string
{
self::date($date);
return FinnishHolidays::forYear((int) substr($date, 0, 4))[$date] ?? throw new NotAHoliday;
}
private static function date(string $value): DateTimeImmutable
{
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
if ($date === false || $date->format('Y-m-d') !== $value) {
throw new InvalidArgumentException("Not a Y-m-d date: {$value}");
}
return $date;
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
final class HolidayAlreadyExists extends DomainException
{
public function __construct()
{
parent::__construct('The day is already a holiday.');
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
final class InvalidHolidayName extends DomainException
{
public function __construct()
{
parent::__construct('A company holiday needs a name of 1–100 characters.');
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
final class NotAHoliday extends DomainException
{
public function __construct()
{
parent::__construct('The day is not a holiday that can be changed this way.');
}
}
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Services;
use DateInterval;
use DateTimeImmutable;
/**
* The Finnish public holidays (arkipyhät) of a year that can fall on a
* weekday, plus Midsummer Eve and Christmas Eve, which are days off in
* practice. Sunday and Saturday holidays (Easter Sunday, Whitsunday,
* Midsummer Day, All Saints' Day) are weekend days anyway.
*/
final class FinnishHolidays
{
public const array KEYS = [
'new_years_day',
'epiphany',
'good_friday',
'easter_monday',
'may_day',
'ascension_day',
'midsummer_eve',
'independence_day',
'christmas_eve',
'christmas_day',
'st_stephens_day',
];
/**
* @return array<string, string> Y-m-d date => holiday key, in date order.
*/
public static function forYear(int $year): array
{
$easter = self::easterSunday($year);
$midsummerEve = new DateTimeImmutable(sprintf('%04d-06-19', $year));
while ($midsummerEve->format('N') !== '5') {
$midsummerEve = $midsummerEve->add(new DateInterval('P1D'));
}
$holidays = [
sprintf('%04d-01-01', $year) => 'new_years_day',
sprintf('%04d-01-06', $year) => 'epiphany',
$easter->sub(new DateInterval('P2D'))->format('Y-m-d') => 'good_friday',
$easter->add(new DateInterval('P1D'))->format('Y-m-d') => 'easter_monday',
sprintf('%04d-05-01', $year) => 'may_day',
$easter->add(new DateInterval('P39D'))->format('Y-m-d') => 'ascension_day',
$midsummerEve->format('Y-m-d') => 'midsummer_eve',
sprintf('%04d-12-06', $year) => 'independence_day',
sprintf('%04d-12-24', $year) => 'christmas_eve',
sprintf('%04d-12-25', $year) => 'christmas_day',
sprintf('%04d-12-26', $year) => 'st_stephens_day',
];
ksort($holidays);
return $holidays;
}
/**
* Easter Sunday by the anonymous Gregorian algorithm (Meeus/Jones/Butcher).
*/
public static function easterSunday(int $year): DateTimeImmutable
{
$a = $year % 19;
$b = intdiv($year, 100);
$c = $year % 100;
$d = intdiv($b, 4);
$e = $b % 4;
$f = intdiv($b + 8, 25);
$g = intdiv($b - $f + 1, 3);
$h = (19 * $a + $b - $d - $g + 15) % 30;
$i = intdiv($c, 4);
$k = $c % 4;
$l = (32 + 2 * $e + 2 * $i - $h - $k) % 7;
$m = intdiv($a + 11 * $h + 22 * $l, 451);
$month = intdiv($h + $l - 7 * $m + 114, 31);
$day = (($h + $l - 7 * $m + 114) % 31) + 1;
return new DateTimeImmutable(sprintf('%04d-%02d-%02d', $year, $month, $day));
}
}
@@ -0,0 +1,52 @@
<?php
namespace App\Modules\Shared\Infrastructure\Persistence;
use App\Modules\Shared\Application\Contracts\HolidayOverrides;
use App\Modules\Shared\Application\DTOs\HolidayOverride;
use Illuminate\Support\Facades\DB;
/**
* Holiday changes in the `holiday_overrides` table.
*/
class DatabaseHolidayOverrides implements HolidayOverrides
{
public function between(string $from, string $to): array
{
return DB::table('holiday_overrides')
->whereBetween('date', [$from, $to])
->orderBy('date')
->get()
->map(fn ($row): HolidayOverride => self::toOverride($row))
->values()
->all();
}
public function find(string $date): ?HolidayOverride
{
$row = DB::table('holiday_overrides')->where('date', $date)->first();
return $row === null ? null : self::toOverride($row);
}
public function save(HolidayOverride $override): void
{
$now = now();
DB::table('holiday_overrides')->upsert(
[['date' => $override->date, 'is_holiday' => $override->isHoliday, 'name' => $override->name, 'created_at' => $now, 'updated_at' => $now]],
['date'],
['is_holiday', 'name', 'updated_at'],
);
}
public function delete(string $date): void
{
DB::table('holiday_overrides')->where('date', $date)->delete();
}
private static function toOverride(object $row): HolidayOverride
{
return new HolidayOverride(substr((string) $row->date, 0, 10), (bool) $row->is_holiday, $row->name === null ? null : (string) $row->name);
}
}
@@ -4,9 +4,11 @@ namespace App\Modules\Shared\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Shared\Application\Contracts\EventDispatcher;
use App\Modules\Shared\Application\Contracts\HolidayOverrides;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Infrastructure\Events\LaravelEventDispatcher;
use App\Modules\Shared\Infrastructure\Persistence\DatabaseHolidayOverrides;
use App\Modules\Shared\Infrastructure\Persistence\DatabaseSettings;
use App\Modules\Shared\Infrastructure\Persistence\LaravelTransactionManager;
use App\Modules\Shared\Presentation\Http\Middleware\SetSecurityHeaders;
@@ -25,6 +27,7 @@ class SharedServiceProvider extends ServiceProvider
TransactionManager::class => LaravelTransactionManager::class,
EventDispatcher::class => LaravelEventDispatcher::class,
Settings::class => DatabaseSettings::class,
HolidayOverrides::class => DatabaseHolidayOverrides::class,
];
public function boot(): void
@@ -0,0 +1,222 @@
<?php
use App\Modules\Shared\Application\DTOs\Holiday;
use App\Modules\Shared\Application\UseCases\HolidayCalendar;
use App\Modules\Shared\Domain\Exceptions\HolidayAlreadyExists;
use App\Modules\Shared\Domain\Exceptions\InvalidHolidayName;
use App\Modules\Shared\Domain\Exceptions\NotAHoliday;
use Carbon\CarbonImmutable;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* Holidays (Arkipyhät): the Finnish public holidays of a year, calculated
* automatically, which the admin can take out of use, and the company's
* own days off. The task calendar shows them like weekends.
*/
new class extends Component
{
#[Url(except: 0)]
public int $year = 0;
public string $date = '';
public string $name = '';
#[Locked]
public string $statusMessage = '';
public function mount(): void
{
$this->authorize('settings.manage');
if ($this->year < 2000 || $this->year > 2100) {
$this->year = (int) now()->format('Y');
}
}
/**
* @return list<array{date: string, day: string, name: string, kind: string, active: bool, company: bool}>
*/
#[Computed]
public function holidays(): array
{
return array_map(fn (Holiday $holiday): array => [
'date' => $holiday->date,
'day' => $this->formatDay($holiday->date),
'name' => $this->holidayName($holiday),
'kind' => __($holiday->isCompanyDay() ? 'holidays.kinds.company' : 'holidays.kinds.public'),
'active' => $holiday->active,
'company' => $holiday->isCompanyDay(),
], app(HolidayCalendar::class)->between($this->year.'-01-01', $this->year.'-12-31'));
}
/**
* @return list<array{index: string, label: string, sortable: bool}>
*/
public function headers(): array
{
return [
['index' => 'day', 'label' => __('holidays.columns.date'), 'sortable' => false],
['index' => 'name', 'label' => __('holidays.columns.name'), 'sortable' => false],
['index' => 'kind', 'label' => __('holidays.columns.kind'), 'sortable' => false],
['index' => 'state', 'label' => __('holidays.columns.state'), 'sortable' => false],
['index' => 'actions', 'label' => __('holidays.columns.actions'), 'sortable' => false],
];
}
public function changeYear(int $step): void
{
$this->authorize('settings.manage');
$this->year = max(2000, min(2100, $this->year + ($step < 0 ? -1 : 1)));
$this->statusMessage = __('holidays.showing_year', ['year' => $this->year]);
unset($this->holidays);
}
public function disable(string $date, HolidayCalendar $calendar): void
{
$this->change($date, fn () => $calendar->disable($date), 'holidays.disabled');
}
public function enable(string $date, HolidayCalendar $calendar): void
{
$this->change($date, fn () => $calendar->enable($date), 'holidays.enabled');
}
public function remove(string $date, HolidayCalendar $calendar): void
{
$this->change($date, fn () => $calendar->removeCompanyDay($date), 'holidays.removed');
}
public function add(HolidayCalendar $calendar): void
{
$this->authorize('settings.manage');
$this->statusMessage = '';
$this->validate([
'date' => ['required', 'date_format:Y-m-d', 'after_or_equal:2000-01-01', 'before_or_equal:2100-12-31'],
'name' => ['required', 'string', 'max:100'],
], [
'date.*' => __('holidays.errors.date'),
'name.*' => __('holidays.errors.name'),
]);
try {
$calendar->addCompanyDay($this->date, $this->name);
} catch (InvalidHolidayName) {
$this->addError('name', __('holidays.errors.name'));
return;
} catch (HolidayAlreadyExists) {
$this->addError('date', __('holidays.errors.exists'));
return;
}
$this->statusMessage = __('holidays.added', ['day' => $this->formatDay($this->date), 'name' => trim($this->name)]);
$this->year = (int) substr($this->date, 0, 4);
$this->reset('date', 'name');
unset($this->holidays);
}
public function render(): mixed
{
return $this->view()->title(__('holidays.title'));
}
private function change(string $date, \Closure $action, string $messageKey): void
{
$this->authorize('settings.manage');
$holiday = collect($this->holidays)->firstWhere('date', $date);
try {
$action();
} catch (NotAHoliday|\InvalidArgumentException) {
$this->statusMessage = __('holidays.not_changed');
return;
}
unset($this->holidays);
$this->statusMessage = __($messageKey, ['day' => $this->formatDay($date), 'name' => $holiday['name'] ?? '']);
}
private function holidayName(Holiday $holiday): string
{
return $holiday->key === null ? (string) $holiday->name : __('holidays.names.'.$holiday->key);
}
private function formatDay(string $date): string
{
$day = CarbonImmutable::createFromFormat('!Y-m-d', $date);
return ! $day instanceof CarbonImmutable ? $date :__('holidays.weekdays.'.$day->dayOfWeekIso).' '.$day->format('j.n.Y');
}
};
?>
<div class="mx-auto max-w-4xl space-y-6 p-4 sm:p-6">
<div class="space-y-1">
<h1 class="text-2xl font-semibold">{{ __('holidays.title') }}</h1>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('holidays.intro') }}</p>
<p class="text-sm"><x-link :href="route('settings.company')" navigate>{{ __('company.title') }}</x-link></p>
</div>
<p role="status" aria-live="polite" class="min-h-5 text-sm font-medium">{{ $statusMessage }}</p>
<section aria-labelledby="holidays-year-heading" class="space-y-4">
<div class="flex flex-wrap items-center gap-3">
<x-button subtle color="black" icon="chevron-left" wire:click="changeYear(-1)" :text="__('holidays.previous_year')" />
<h2 id="holidays-year-heading" class="text-lg font-semibold">{{ __('holidays.year_heading', ['year' => $year]) }}</h2>
<x-button subtle color="black" icon="chevron-right" position="right" wire:click="changeYear(1)" :text="__('holidays.next_year')" />
</div>
<x-table :headers="$this->headers()" :rows="$this->holidays">
@interact('column_day', $holiday)
<span class="whitespace-nowrap">{{ $holiday['day'] }}</span>
@endinteract
@interact('column_name', $holiday)
<span class="break-words">{{ $holiday['name'] }}</span>
@endinteract
@interact('column_kind', $holiday)
{{ $holiday['kind'] }}
@endinteract
@interact('column_state', $holiday)
@if ($holiday['active'])
<span class="inline-flex items-center gap-1"><x-icon name="check" class="size-4" aria-hidden="true" />{{ __('holidays.in_use') }}</span>
@else
<span class="inline-flex items-center gap-1"><x-icon name="x-mark" class="size-4" aria-hidden="true" />{{ __('holidays.not_in_use') }}</span>
@endif
@endinteract
@interact('column_actions', $holiday)
@if ($holiday['company'])
<x-button sm subtle color="black" wire:click="remove('{{ $holiday['date'] }}')" :text="__('holidays.remove')" :aria-label="__('holidays.remove_named', ['name' => $holiday['name'], 'day' => $holiday['day']])" />
@elseif ($holiday['active'])
<x-button sm subtle color="black" wire:click="disable('{{ $holiday['date'] }}')" :text="__('holidays.disable')" :aria-label="__('holidays.disable_named', ['name' => $holiday['name'], 'day' => $holiday['day']])" />
@else
<x-button sm subtle color="black" wire:click="enable('{{ $holiday['date'] }}')" :text="__('holidays.enable')" :aria-label="__('holidays.enable_named', ['name' => $holiday['name'], 'day' => $holiday['day']])" />
@endif
@endinteract
</x-table>
</section>
<section aria-labelledby="holidays-add-heading" class="space-y-4">
<h2 id="holidays-add-heading" class="text-lg font-semibold">{{ __('holidays.add_heading') }}</h2>
<form wire:submit="add" class="grid gap-4 sm:grid-cols-[12rem_1fr_auto] sm:items-start" novalidate>
<x-input wire:model="date" type="date" :label="__('holidays.fields.date')" required />
<x-input wire:model="name" :label="__('holidays.fields.name')" :hint="__('holidays.fields.name_hint')" autocomplete="off" required />
<div class="sm:pt-6">
<x-button submit :text="__('holidays.add')" />
</div>
</form>
</section>
</div>
@@ -7,4 +7,5 @@ Route::middleware(['web', 'auth', 'can:settings.manage'])
->name('settings.')
->group(function () {
Route::livewire('/company', 'shared::company')->name('company');
Route::livewire('/holidays', 'shared::holidays')->name('holidays');
});