From f906f9a43fad539dad38ac4fdc66cda58dc57d4d Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 08:28:01 +0200 Subject: [PATCH] Add notifications: header bell, task start run and assignment notices A new Notifications module shows a bell beside the profile menu with the number of unseen notifications and a panel of the last 7 days; opening it marks them seen, and each notification links to its job or task. - A daily run at 14.00 (notifications:task-starts) tells the assignee and members of tasks that start by the next working day, skipping holidays and days off, done tasks and archived jobs. - Jobs publishes PeopleAddedToTask and PeopleAddedToJob when someone else makes a user a task's assignee or member or gives them a role on a job; those users are notified at once. UpdateTask and ScheduleTask now take the acting user. - A notification link to #task- opens that task card on the job page. Also: simplifying job fields per service unit (K31) moves to the end of phase 4, and the workflow template browser test waits for Livewire's progress bar before its last accessibility check. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 3 +- .../Application/Contracts/UpcomingTasks.php | 21 ++ .../Jobs/Application/DTOs/UpcomingTask.php | 25 +++ .../Jobs/Application/UseCases/AddTask.php | 9 + .../UseCases/AddTasksFromWorkflowTemplate.php | 9 + .../UseCases/CreateCustomerJob.php | 12 +- .../Application/UseCases/ScheduleTask.php | 14 +- .../UseCases/UpdateCustomerJob.php | 14 +- .../Jobs/Application/UseCases/UpdateTask.php | 14 +- .../Jobs/Domain/Events/PeopleAddedToJob.php | 82 ++++++++ .../Jobs/Domain/Events/PeopleAddedToTask.php | 67 ++++++ .../Repositories/EloquentUpcomingTasks.php | 50 +++++ .../Providers/JobsServiceProvider.php | 3 + .../Livewire/⚡calendar.blade.php | 2 +- .../Presentation/Livewire/⚡show.blade.php | 6 +- .../Livewire/⚡task-form.blade.php | 2 +- .../Contracts/NotificationQueries.php | 20 ++ .../Application/DTOs/NotificationSummary.php | 25 +++ .../Application/Services/WorkingDays.php | 39 ++++ .../UseCases/MarkNotificationsSeen.php | 24 +++ .../UseCases/NotifyAddedPeople.php | 66 ++++++ .../UseCases/NotifyTasksStartingSoon.php | 73 +++++++ .../Contracts/NotificationRepository.php | 25 +++ .../Domain/Enums/NotificationType.php | 27 +++ .../Domain/ValueObjects/NewNotification.php | 44 ++++ .../Eloquent/NotificationModel.php | 41 ++++ .../EloquentNotificationQueries.php | 39 ++++ .../EloquentNotificationRepository.php | 39 ++++ .../NotificationsServiceProvider.php | 45 ++++ .../NotifyTasksStartingSoonCommand.php | 22 ++ .../Presentation/Livewire/⚡bell.blade.php | 193 ++++++++++++++++++ bootstrap/providers.php | 2 + ...060256_create_user_notifications_table.php | 36 ++++ docs/maarittely.md | 10 +- lang/en/notifications.php | 25 +++ lang/fi/notifications.php | 25 +++ resources/views/layouts/app.blade.php | 5 +- routes/console.php | 7 + tests/Browser/JobsAccessibilityTest.php | 2 + .../NotificationsAccessibilityTest.php | 71 +++++++ tests/Fakes/FakeUpcomingTasks.php | 19 ++ .../Fakes/InMemoryNotificationRepository.php | 51 +++++ .../Notifications/NotificationsTest.php | 165 +++++++++++++++ .../Application/CustomerJobUseCasesTest.php | 25 ++- .../Jobs/Application/TaskUseCasesTest.php | 56 +++-- .../Application/TasksFromTemplateTest.php | 6 +- .../Notifications/NotifyAddedPeopleTest.php | 46 +++++ .../NotifyTasksStartingSoonTest.php | 90 ++++++++ 48 files changed, 1665 insertions(+), 31 deletions(-) create mode 100644 app/Modules/Jobs/Application/Contracts/UpcomingTasks.php create mode 100644 app/Modules/Jobs/Application/DTOs/UpcomingTask.php create mode 100644 app/Modules/Jobs/Domain/Events/PeopleAddedToJob.php create mode 100644 app/Modules/Jobs/Domain/Events/PeopleAddedToTask.php create mode 100644 app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentUpcomingTasks.php create mode 100644 app/Modules/Notifications/Application/Contracts/NotificationQueries.php create mode 100644 app/Modules/Notifications/Application/DTOs/NotificationSummary.php create mode 100644 app/Modules/Notifications/Application/Services/WorkingDays.php create mode 100644 app/Modules/Notifications/Application/UseCases/MarkNotificationsSeen.php create mode 100644 app/Modules/Notifications/Application/UseCases/NotifyAddedPeople.php create mode 100644 app/Modules/Notifications/Application/UseCases/NotifyTasksStartingSoon.php create mode 100644 app/Modules/Notifications/Domain/Contracts/NotificationRepository.php create mode 100644 app/Modules/Notifications/Domain/Enums/NotificationType.php create mode 100644 app/Modules/Notifications/Domain/ValueObjects/NewNotification.php create mode 100644 app/Modules/Notifications/Infrastructure/Persistence/Eloquent/NotificationModel.php create mode 100644 app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationQueries.php create mode 100644 app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationRepository.php create mode 100644 app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php create mode 100644 app/Modules/Notifications/Presentation/Console/NotifyTasksStartingSoonCommand.php create mode 100644 app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php create mode 100644 database/migrations/2026_11_25_060256_create_user_notifications_table.php create mode 100644 lang/en/notifications.php create mode 100644 lang/fi/notifications.php create mode 100644 tests/Browser/NotificationsAccessibilityTest.php create mode 100644 tests/Fakes/FakeUpcomingTasks.php create mode 100644 tests/Fakes/InMemoryNotificationRepository.php create mode 100644 tests/Feature/Modules/Notifications/NotificationsTest.php create mode 100644 tests/Unit/Modules/Notifications/NotifyAddedPeopleTest.php create mode 100644 tests/Unit/Modules/Notifications/NotifyTasksStartingSoonTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 06ab029..e6d6e0f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -9,7 +9,7 @@ An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5 - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification is in Finnish. The UI is in Finnish (default) and English: every UI string lives in `lang/fi/*.php` **and** `lang/en/*.php` with the same keys and placeholders (`tests/Unit/TranslationFilesTest.php` fails otherwise). Number, money and date formats stay Finnish in both languages; the quick sale receipt is always Finnish. - **Language choice:** a user's language is `users.locale` (`Users\Domain\Enums\Locale`), changed in the profile menu (`resources/views/components/profile-menu.blade.php`, which also holds the theme radios and logout) through `POST /locale` (`SwitchLocaleController` → `ChangePreferredLocale`). Signed-out pages keep it in the session (`partials/locale-switch.blade.php`). The `SetLocale` web middleware applies the account's language, then the session's, then `APP_LOCALE`; `User` implements `HasLocalePreference`, so emails go out in the user's language. -- **Build in phases, not all at once** (spec chapter 15). (1) auth and users, customers with contacts and billing units, service units/work types, customer jobs, mobile quick intake, job Kanban, basic tasks, time entries on tasks with a weekly view; (2) pricing and products, money fields and visibility, expenses, hour approval and locking, Fennoa CSV/Excel export, quick sales; (3) task columns, checklists, comments, images, workflow templates, calendar; (4) subcontractor views, reports, notifications, Fennoa API. +- **Build in phases, not all at once** (spec chapter 15). (1) auth and users, customers with contacts and billing units, service units/work types, customer jobs, mobile quick intake, job Kanban, basic tasks, time entries on tasks with a weekly view; (2) pricing and products, money fields and visibility, expenses, hour approval and locking, Fennoa CSV/Excel export, quick sales; (3) task columns, checklists, comments, images, workflow templates, calendar; (4) subcontractor views, reports, notifications, Fennoa API, and last the simplification of job fields per service unit (K31, moved from phase 3). - **Access control is central.** Roles: admin (*pääkäyttäjä*), management (*johto*), employee (*työntekijä*), intern (*harjoittelija*), subcontractor (*alihankkija*). Management is admin minus user management, settings and permanent deletion. Employees and interns see all jobs ("my jobs" filter on by default) and may create jobs and customers; they see only consumer product prices unless given personal money permissions. Interns have an end date after which they can't log in, plus a supervisor (information only). Subcontractors see only jobs they are attached to and no rates or quote/billing amounts. - **UI targets:** logged-in users only (no public pages besides login). It must work on phones (new-job intake, time entry) and on FullHD desktops. @@ -26,6 +26,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `jobs.remove-any-task-comment`, `jobs.remove-any-task-image`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Main menu**: the layout renders the groups of `App\View\MainMenu` (Työt, Oma kirjaus, Asiakkaat ja myynti, Hallinto, Ylläpito) as disclosure popovers (`resources/views/components/nav-group.blade.php`). A new page is added to `MainMenu::definition()` with the Gate ability of its route; groups with no allowed links disappear. +- **Notifications** are their own module (`Notifications`): the header's bell `notifications::bell` (beside the profile menu) shows the unseen count and the last 7 days of `user_notifications`, and opening it marks them seen. Texts are made at display time from `NotificationType` and its `params` (`lang/*/notifications.php`). `NotifyTasksStartingSoon` (`notifications:task-starts`, scheduled daily at 14.00 business time in `routes/console.php`) notifies the assignee and members of tasks starting by the next working day through Jobs' `UpcomingTasks` port; `dedupe_key` keeps reruns from notifying twice. Jobs' use cases publish `PeopleAddedToTask` and `PeopleAddedToJob` (Domain events, after commit) when someone else is made a task's assignee or member or gets a role on a job; `NotifyAddedPeople` turns them into notifications at once, never for the actor's own changes. The scheduler needs `php artisan schedule:run` every minute (cron / Windows Task Scheduler; locally `php artisan schedule:work`). - **Holidays** are Shared: `Shared\Application\UseCases\HolidayCalendar` gives the Finnish public holidays (`FinnishHolidays`, calculated) minus those the admin took out of use plus company days off (`holiday_overrides`), edited on `shared::holidays` (`/settings/holidays`, gate `settings.manage`). - **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object. The name at the left of the main menu is the optional "Valikon nimi" (`shared.company_menu_name`), read with `CompanyDetailsStore::menuName()` (falls back to `config('app.name')`). - **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`). diff --git a/app/Modules/Jobs/Application/Contracts/UpcomingTasks.php b/app/Modules/Jobs/Application/Contracts/UpcomingTasks.php new file mode 100644 index 0000000..9dda647 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/UpcomingTasks.php @@ -0,0 +1,21 @@ + + */ + public function startingBetween(string $after, string $to): array; +} diff --git a/app/Modules/Jobs/Application/DTOs/UpcomingTask.php b/app/Modules/Jobs/Application/DTOs/UpcomingTask.php new file mode 100644 index 0000000..1df9f82 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/UpcomingTask.php @@ -0,0 +1,25 @@ + $recipientIds + */ + public function __construct( + public int $taskId, + public string $title, + public int $jobId, + public string $jobNumber, + public string $jobName, + public string $plannedFrom, + public array $recipientIds, + ) {} +} diff --git a/app/Modules/Jobs/Application/UseCases/AddTask.php b/app/Modules/Jobs/Application/UseCases/AddTask.php index 700ae03..13f3ae1 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTask.php +++ b/app/Modules/Jobs/Application/UseCases/AddTask.php @@ -11,11 +11,13 @@ 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\Events\PeopleAddedToTask; 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\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; final class AddTask @@ -26,6 +28,7 @@ final class AddTask private TaskReferenceChecker $references, private TaskPlanner $planner, private TransactionManager $transactions, + private EventDispatcher $events, ) {} /** @@ -66,6 +69,12 @@ final class AddTask $task = $this->tasks->save($task); } + $added = PeopleAddedToTask::between(null, $task, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } + return (int) $task->id(); }); } diff --git a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php index 656c91f..1160538 100644 --- a/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php +++ b/app/Modules/Jobs/Application/UseCases/AddTasksFromWorkflowTemplate.php @@ -14,12 +14,14 @@ 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\Events\PeopleAddedToTask; 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\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Users\Application\Contracts\Clock; @@ -41,6 +43,7 @@ final class AddTasksFromWorkflowTemplate private TaskPlanner $planner, private Clock $clock, private TransactionManager $transactions, + private EventDispatcher $events, ) {} /** @@ -89,6 +92,12 @@ final class AddTasksFromWorkflowTemplate $scheduled++; $this->tasks->save($task); } + + $added = PeopleAddedToTask::between(null, $task, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } } return new TemplateTasksResult(count($template->steps), $scheduled, $late); diff --git a/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php b/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php index e7cf27e..781efaf 100644 --- a/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php +++ b/app/Modules/Jobs/Application/UseCases/CreateCustomerJob.php @@ -9,8 +9,10 @@ use App\Modules\Jobs\Application\Services\JobDetailsFactory; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\JobNumberSequence; use App\Modules\Jobs\Domain\Entities\CustomerJob; +use App\Modules\Jobs\Domain\Events\PeopleAddedToJob; use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference; use App\Modules\Jobs\Domain\ValueObjects\FieldChange; +use App\Modules\Shared\Application\Contracts\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Users\Application\Contracts\Clock; @@ -26,6 +28,7 @@ final class CreateCustomerJob private JobDetailsFactory $detailsFactory, private TransactionManager $transactions, private Clock $clock, + private EventDispatcher $events, ) {} /** @@ -41,10 +44,17 @@ final class CreateCustomerJob return $this->transactions->run(function () use ($details, $year, $actorUserId): int { $job = CustomerJob::open($this->numbers->next($year), $details, $actorUserId); $job->recordCompletion($this->clock->now()); - $jobId = (int) $this->jobs->save($job)->id(); + $job = $this->jobs->save($job); + $jobId = (int) $job->id(); $this->jobs->recordChanges($jobId, $actorUserId, [new FieldChange('created', null, $job->number()->format())]); + $added = PeopleAddedToJob::between(null, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } + return $jobId; }); } diff --git a/app/Modules/Jobs/Application/UseCases/ScheduleTask.php b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php index d5ed350..8a24de0 100644 --- a/app/Modules/Jobs/Application/UseCases/ScheduleTask.php +++ b/app/Modules/Jobs/Application/UseCases/ScheduleTask.php @@ -9,10 +9,12 @@ 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\Events\PeopleAddedToTask; 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\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; /** @@ -29,6 +31,7 @@ final class ScheduleTask private TaskReferenceChecker $references, private TaskPlanner $planner, private TransactionManager $transactions, + private EventDispatcher $events, ) {} /** @@ -37,14 +40,15 @@ final class ScheduleTask * @throws InvalidTaskReference * @throws PlanEndsBeforeStart */ - public function execute(int $jobId, int $taskId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo): ScheduleResult + public function execute(int $jobId, int $taskId, ?int $fromUserId, ?int $toUserId, string $plannedFrom, ?string $plannedTo, int $actorUserId): 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 { + return $this->transactions->run(function () use ($jobId, $taskId, $fromUserId, $toUserId, $from, $to, $actorUserId): ScheduleResult { $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); + $peopleBefore = PeopleAddedToTask::peopleOf($task); if ($fromUserId !== $toUserId) { $this->references->check($job, $task->workTypeId(), $toUserId, [], $task); @@ -57,6 +61,12 @@ final class ScheduleTask $extended = $this->planner->plan($task); $task = $this->tasks->save($task); + $added = PeopleAddedToTask::between($peopleBefore, $task, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } + return new ScheduleResult( (string) $task->plannedFrom()?->format('Y-m-d'), (string) $task->plannedTo()?->format('Y-m-d'), diff --git a/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php b/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php index 1f5147c..c99b3fa 100644 --- a/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php +++ b/app/Modules/Jobs/Application/UseCases/UpdateCustomerJob.php @@ -7,8 +7,10 @@ namespace App\Modules\Jobs\Application\UseCases; use App\Modules\Jobs\Application\DTOs\CustomerJobData; use App\Modules\Jobs\Application\Services\JobDetailsFactory; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; +use App\Modules\Jobs\Domain\Events\PeopleAddedToJob; use App\Modules\Jobs\Domain\Exceptions\CustomerJobNotFound; use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference; +use App\Modules\Shared\Application\Contracts\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Users\Application\Contracts\Clock; @@ -23,6 +25,7 @@ final class UpdateCustomerJob private JobDetailsFactory $detailsFactory, private TransactionManager $transactions, private Clock $clock, + private EventDispatcher $events, ) {} /** @@ -34,15 +37,22 @@ final class UpdateCustomerJob $this->transactions->run(function () use ($jobId, $data, $actorUserId): void { $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); - $changes = $job->changeDetails($this->detailsFactory->build($data, $job->details())); + $before = $job->details(); + $changes = $job->changeDetails($this->detailsFactory->build($data, $before)); $job->recordCompletion($this->clock->now()); if ($changes === []) { return; } - $this->jobs->save($job); + $job = $this->jobs->save($job); $this->jobs->recordChanges($jobId, $actorUserId, $changes); + + $added = PeopleAddedToJob::between($before, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } }); } } diff --git a/app/Modules/Jobs/Application/UseCases/UpdateTask.php b/app/Modules/Jobs/Application/UseCases/UpdateTask.php index 866707d..2e827d8 100644 --- a/app/Modules/Jobs/Application/UseCases/UpdateTask.php +++ b/app/Modules/Jobs/Application/UseCases/UpdateTask.php @@ -11,11 +11,13 @@ 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\Events\PeopleAddedToTask; 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\EventDispatcher; use App\Modules\Shared\Application\Contracts\TransactionManager; final class UpdateTask @@ -26,6 +28,7 @@ final class UpdateTask private TaskReferenceChecker $references, private TaskPlanner $planner, private TransactionManager $transactions, + private EventDispatcher $events, ) {} /** @@ -34,17 +37,18 @@ final class UpdateTask * @throws InvalidTaskReference * @throws PlanEndsBeforeStart */ - public function execute(int $jobId, int $taskId, TaskData $data): void + public function execute(int $jobId, int $taskId, TaskData $data, int $actorUserId): void { $title = new TaskTitle($data->title); - $this->transactions->run(function () use ($jobId, $taskId, $data, $title): void { + $this->transactions->run(function () use ($jobId, $taskId, $data, $title, $actorUserId): void { $job = $this->jobs->findById($jobId) ?? throw new CustomerJobNotFound($jobId); $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); $this->references->check($job, $data->workTypeId, $data->assigneeUserId, $data->memberUserIds, $task); $before = self::planningInput($task); + $peopleBefore = PeopleAddedToTask::peopleOf($task); $task->changeDetails( $data->workTypeId, @@ -65,6 +69,12 @@ final class UpdateTask $this->planner->plan($task); $this->tasks->save($task); } + + $added = PeopleAddedToTask::between($peopleBefore, $task, $job, $actorUserId); + + if ($added !== null) { + $this->events->dispatch($added); + } }); } diff --git a/app/Modules/Jobs/Domain/Events/PeopleAddedToJob.php b/app/Modules/Jobs/Domain/Events/PeopleAddedToJob.php new file mode 100644 index 0000000..79ccfca --- /dev/null +++ b/app/Modules/Jobs/Domain/Events/PeopleAddedToJob.php @@ -0,0 +1,82 @@ +> $newRoles The new roles by user id. + */ + public function __construct( + public int $jobId, + public string $jobNumber, + public string $jobName, + public array $newRoles, + public int $actorUserId, + ) {} + + /** + * The roles the saved job gives that the details before did not (a new + * job has none before); null when nobody got a new role. + */ + public static function between(?JobDetails $before, CustomerJob $after, int $actorUserId): ?self + { + $old = $before === null ? [] : self::rolesOf($before); + $newRoles = []; + + foreach (self::rolesOf($after->details()) as $userId => $roles) { + $added = array_values(array_diff($roles, $old[$userId] ?? [])); + + if ($added !== []) { + $newRoles[$userId] = $added; + } + } + + if ($newRoles === []) { + return null; + } + + return new self((int) $after->id(), $after->number()->format(), $after->details()->name->value, $newRoles, $actorUserId); + } + + /** + * @return array> + */ + private static function rolesOf(JobDetails $details): array + { + $roles = []; + $roles[$details->responsibleUserId][] = self::RESPONSIBLE; + + if ($details->contactUserId !== null) { + $roles[$details->contactUserId][] = self::CONTACT; + } + + if ($details->billerUserId !== null) { + $roles[$details->billerUserId][] = self::BILLER; + } + + foreach ($details->memberUserIds as $memberId) { + $roles[$memberId][] = self::MEMBER; + } + + return $roles; + } +} diff --git a/app/Modules/Jobs/Domain/Events/PeopleAddedToTask.php b/app/Modules/Jobs/Domain/Events/PeopleAddedToTask.php new file mode 100644 index 0000000..7c8dd13 --- /dev/null +++ b/app/Modules/Jobs/Domain/Events/PeopleAddedToTask.php @@ -0,0 +1,67 @@ + $newMemberIds + */ + public function __construct( + public int $taskId, + public string $taskTitle, + public int $jobId, + public string $jobNumber, + public string $jobName, + public ?int $newAssigneeId, + public array $newMemberIds, + public int $actorUserId, + ) {} + + /** + * The people the saved task has that it did not have before (a new task + * has none before); null when nobody was added. + * + * @param array{assignee: ?int, members: list}|null $before + */ + public static function between(?array $before, Task $after, CustomerJob $job, int $actorUserId): ?self + { + $assignee = $after->assigneeUserId(); + $newAssignee = $assignee !== null && $assignee !== ($before['assignee'] ?? null) ? $assignee : null; + $newMembers = array_values(array_diff($after->memberUserIds(), $before['members'] ?? [], $newAssignee === null ? [] : [$newAssignee])); + + if ($newAssignee === null && $newMembers === []) { + return null; + } + + return new self( + (int) $after->id(), + $after->title()->value, + $job->id() ?? $after->jobId(), + $job->number()->format(), + $job->details()->name->value, + $newAssignee, + $newMembers, + $actorUserId, + ); + } + + /** + * Who the task has now, to compare with after a change. + * + * @return array{assignee: ?int, members: list} + */ + public static function peopleOf(Task $task): array + { + return ['assignee' => $task->assigneeUserId(), 'members' => $task->memberUserIds()]; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentUpcomingTasks.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentUpcomingTasks.php new file mode 100644 index 0000000..8c37829 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentUpcomingTasks.php @@ -0,0 +1,50 @@ +join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id') + ->where('tasks.planned_from', '>=', CarbonImmutable::parse($after)->addDay()->toDateString()) + ->where('tasks.planned_from', '<', CarbonImmutable::parse($to)->addDay()->toDateString()) + ->where('tasks.status', '!=', TaskStatus::Done->value) + ->where('customer_jobs.status', '!=', JobStatus::Archived->value) + ->orderBy('tasks.planned_from') + ->orderBy('tasks.id') + ->get(['tasks.id', 'tasks.title', 'tasks.planned_from', 'tasks.assignee_user_id', 'customer_jobs.id as job_id', 'customer_jobs.number', 'customer_jobs.name']); + + $members = DB::table('task_members') + ->whereIn('task_id', $rows->pluck('id')->all()) + ->get(['task_id', 'user_id']) + ->groupBy('task_id'); + + return $rows->map(function (object $row) use ($members): UpcomingTask { + $recipients = ($members->get($row->id) ?? collect())->pluck('user_id'); + + if ($row->assignee_user_id !== null) { + $recipients->prepend($row->assignee_user_id); + } + + return new UpcomingTask( + (int) $row->id, + (string) $row->title, + (int) $row->job_id, + (string) $row->number, + (string) $row->name, + substr((string) $row->planned_from, 0, 10), + $recipients->map(fn ($id): int => (int) $id)->unique()->values()->all(), + ); + })->values()->all(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index 6987546..f7bc221 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -13,6 +13,7 @@ use App\Modules\Jobs\Application\Contracts\TaskImageFiles; use App\Modules\Jobs\Application\Contracts\TaskImageQueries; use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Application\Contracts\TaskUsage; +use App\Modules\Jobs\Application\Contracts\UpcomingTasks; use App\Modules\Jobs\Domain\Contracts\ChecklistItemRepository; use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\JobNumberSequence; @@ -37,6 +38,7 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskImageQu use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskImageRepository; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentUpcomingTasks; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; @@ -67,6 +69,7 @@ class JobsServiceProvider extends ServiceProvider TaskImageRepository::class => EloquentTaskImageRepository::class, TaskImageQueries::class => EloquentTaskImageQueries::class, TaskImageFiles::class => GdTaskImageFiles::class, + UpcomingTasks::class => EloquentUpcomingTasks::class, // Replaced by the TimeTracking module, which knows which tasks have time entries. TaskUsage::class => NothingUsesTasks::class, ]; diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php index cb5c9cd..6d2aaf7 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡calendar.blade.php @@ -410,7 +410,7 @@ new class extends Component $task = $this->findTask($taskId); try { - $result = $scheduleTask->execute($jobId, $taskId, $fromUserId, $toUserId, $plannedFrom, $plannedTo); + $result = $scheduleTask->execute($jobId, $taskId, $fromUserId, $toUserId, $plannedFrom, $plannedTo, (int) auth()->id()); } catch (CustomerJobNotFound|TaskNotFound|InvalidArgumentException) { $this->statusMessage = __('jobs.calendar.not_changed'); diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index 12efc25..31a587e 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -378,9 +378,13 @@ new class extends Component
    @foreach ($this->tasks as $task) + {{-- A notification links to #task-: that card opens and comes into view. --}}
  • diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php index 0f80e95..eb55a13 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-form.blade.php @@ -135,7 +135,7 @@ new class extends Component $message = __('jobs.tasks.created', ['title' => trim($data->title)]); } else { $taskId = $this->taskId; - $updateTask->execute($this->jobId, $taskId, $data); + $updateTask->execute($this->jobId, $taskId, $data, (int) auth()->id()); $message = __('jobs.tasks.updated', ['title' => trim($data->title)]); } } catch (CustomerJobNotFound|TaskNotFound) { diff --git a/app/Modules/Notifications/Application/Contracts/NotificationQueries.php b/app/Modules/Notifications/Application/Contracts/NotificationQueries.php new file mode 100644 index 0000000..099d7ee --- /dev/null +++ b/app/Modules/Notifications/Application/Contracts/NotificationQueries.php @@ -0,0 +1,20 @@ + + */ + public function recentFor(int $userId, DateTimeImmutable $since): array; + + public function unseenCount(int $userId, DateTimeImmutable $since): int; +} diff --git a/app/Modules/Notifications/Application/DTOs/NotificationSummary.php b/app/Modules/Notifications/Application/DTOs/NotificationSummary.php new file mode 100644 index 0000000..847f655 --- /dev/null +++ b/app/Modules/Notifications/Application/DTOs/NotificationSummary.php @@ -0,0 +1,25 @@ + $params + */ + public function __construct( + public int $id, + public NotificationType $type, + public array $params, + public string $createdAt, + public bool $seen, + ) {} +} diff --git a/app/Modules/Notifications/Application/Services/WorkingDays.php b/app/Modules/Notifications/Application/Services/WorkingDays.php new file mode 100644 index 0000000..9cec838 --- /dev/null +++ b/app/Modules/Notifications/Application/Services/WorkingDays.php @@ -0,0 +1,39 @@ +format('Y-m-d'); + + return (int) $day->format('N') <= 5 && $this->holidays->activeDatesBetween($date, $date) === []; + } + + /** + * The first working day after the given day. + */ + public function nextAfter(DateTimeImmutable $day): DateTimeImmutable + { + $next = $day->modify('+1 day'); + + // A month of days off in a row would be a mistake in the settings. + for ($i = 0; $i < 31 && ! $this->isWorkingDay($next); $i++) { + $next = $next->modify('+1 day'); + } + + return $next; + } +} diff --git a/app/Modules/Notifications/Application/UseCases/MarkNotificationsSeen.php b/app/Modules/Notifications/Application/UseCases/MarkNotificationsSeen.php new file mode 100644 index 0000000..fe37ee8 --- /dev/null +++ b/app/Modules/Notifications/Application/UseCases/MarkNotificationsSeen.php @@ -0,0 +1,24 @@ +notifications->markSeen($userId, $this->clock->now()); + } +} diff --git a/app/Modules/Notifications/Application/UseCases/NotifyAddedPeople.php b/app/Modules/Notifications/Application/UseCases/NotifyAddedPeople.php new file mode 100644 index 0000000..46e5ef7 --- /dev/null +++ b/app/Modules/Notifications/Application/UseCases/NotifyAddedPeople.php @@ -0,0 +1,66 @@ +clock->now(); + $params = [ + 'task_id' => $event->taskId, + 'task_title' => $event->taskTitle, + 'job_id' => $event->jobId, + 'job_number' => $event->jobNumber, + 'job_name' => $event->jobName, + ]; + $roles = $event->newAssigneeId === null ? [] : [$event->newAssigneeId => 'assignee']; + + foreach ($event->newMemberIds as $memberId) { + $roles[$memberId] ??= 'member'; + } + + foreach ($roles as $userId => $role) { + if ($userId !== $event->actorUserId) { + $this->notifications->addIfNew(NewNotification::assigned(NotificationType::TaskAssigned, $userId, $event->taskId, [...$params, 'role' => $role], $now)); + } + } + } + + public function forJob(PeopleAddedToJob $event): void + { + $now = $this->clock->now(); + + foreach ($event->newRoles as $userId => $roles) { + if ($userId === $event->actorUserId) { + continue; + } + + $this->notifications->addIfNew(NewNotification::assigned(NotificationType::JobAssigned, $userId, $event->jobId, [ + 'job_id' => $event->jobId, + 'job_number' => $event->jobNumber, + 'job_name' => $event->jobName, + 'roles' => implode(',', $roles), + ], $now)); + } + } +} diff --git a/app/Modules/Notifications/Application/UseCases/NotifyTasksStartingSoon.php b/app/Modules/Notifications/Application/UseCases/NotifyTasksStartingSoon.php new file mode 100644 index 0000000..9525e92 --- /dev/null +++ b/app/Modules/Notifications/Application/UseCases/NotifyTasksStartingSoon.php @@ -0,0 +1,73 @@ +clock->today(); + $now = $this->clock->now(); + + return $this->transactions->run(function () use ($today, $now): int { + $this->notifications->deleteOlderThan($now->modify('-'.self::KEEP_DAYS.' days')); + + if (! $this->workingDays->isWorkingDay($today)) { + return 0; + } + + $until = $this->workingDays->nextAfter($today)->format('Y-m-d'); + $added = 0; + + foreach ($this->tasks->startingBetween($today->format('Y-m-d'), $until) as $task) { + $params = [ + 'task_id' => $task->taskId, + 'task_title' => $task->title, + 'job_id' => $task->jobId, + 'job_number' => $task->jobNumber, + 'job_name' => $task->jobName, + 'starts_on' => $task->plannedFrom, + ]; + + foreach ($task->recipientIds as $userId) { + if ($this->notifications->addIfNew(NewNotification::taskStartsSoon($userId, $task->taskId, $task->plannedFrom, $params, $now))) { + $added++; + } + } + } + + return $added; + }); + } +} diff --git a/app/Modules/Notifications/Domain/Contracts/NotificationRepository.php b/app/Modules/Notifications/Domain/Contracts/NotificationRepository.php new file mode 100644 index 0000000..8456e6f --- /dev/null +++ b/app/Modules/Notifications/Domain/Contracts/NotificationRepository.php @@ -0,0 +1,25 @@ +` with the notification's parameters. + */ +enum NotificationType: string +{ + /** + * A task the user does or is a member of starts on the next working day. + */ + case TaskStartsSoon = 'task_starts_soon'; + + /** + * Someone else made the user a task's assignee or member. + */ + case TaskAssigned = 'task_assigned'; + + /** + * Someone else gave the user a role on a customer job. + */ + case JobAssigned = 'job_assigned'; +} diff --git a/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php b/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php new file mode 100644 index 0000000..f6f3a38 --- /dev/null +++ b/app/Modules/Notifications/Domain/ValueObjects/NewNotification.php @@ -0,0 +1,44 @@ + $params + */ + public function __construct( + public int $userId, + public NotificationType $type, + public array $params, + public string $dedupeKey, + public DateTimeImmutable $createdAt, + ) {} + + /** + * @param array $params + */ + public static function taskStartsSoon(int $userId, int $taskId, string $startsOn, array $params, DateTimeImmutable $at): self + { + return new self($userId, NotificationType::TaskStartsSoon, $params, "task_starts:{$taskId}:{$startsOn}:{$userId}", $at); + } + + /** + * Each assignment is its own notification: one removed and added again + * is told again. + * + * @param array $params + */ + public static function assigned(NotificationType $type, int $userId, int $subjectId, array $params, DateTimeImmutable $at): self + { + return new self($userId, $type, $params, "{$type->value}:{$subjectId}:{$userId}:".$at->format('U.u').':'.bin2hex(random_bytes(4)), $at); + } +} diff --git a/app/Modules/Notifications/Infrastructure/Persistence/Eloquent/NotificationModel.php b/app/Modules/Notifications/Infrastructure/Persistence/Eloquent/NotificationModel.php new file mode 100644 index 0000000..5621858 --- /dev/null +++ b/app/Modules/Notifications/Infrastructure/Persistence/Eloquent/NotificationModel.php @@ -0,0 +1,41 @@ + $params + * @property string $dedupe_key + * @property CarbonImmutable|null $seen_at + * @property CarbonImmutable $created_at + */ +#[Table('user_notifications')] +#[Fillable(['user_id', 'type', 'params', 'dedupe_key', 'seen_at', 'created_at'])] +class NotificationModel extends Model +{ + /** + * @return array + */ + protected function casts(): array + { + return [ + 'user_id' => 'integer', + 'type' => NotificationType::class, + 'params' => 'array', + 'seen_at' => 'immutable_datetime', + 'created_at' => 'immutable_datetime', + 'updated_at' => 'immutable_datetime', + ]; + } +} diff --git a/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationQueries.php b/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationQueries.php new file mode 100644 index 0000000..c512a8d --- /dev/null +++ b/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationQueries.php @@ -0,0 +1,39 @@ +where('user_id', $userId) + ->where('created_at', '>=', $since) + ->orderByDesc('created_at') + ->orderByDesc('id') + ->get() + ->map(fn (NotificationModel $model): NotificationSummary => new NotificationSummary( + $model->id, + $model->type, + $model->params, + $model->created_at->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'), + $model->seen_at !== null, + )) + ->values() + ->all(); + } + + public function unseenCount(int $userId, DateTimeImmutable $since): int + { + return NotificationModel::query() + ->where('user_id', $userId) + ->where('created_at', '>=', $since) + ->whereNull('seen_at') + ->count(); + } +} diff --git a/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationRepository.php b/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationRepository.php new file mode 100644 index 0000000..6432d28 --- /dev/null +++ b/app/Modules/Notifications/Infrastructure/Persistence/Repositories/EloquentNotificationRepository.php @@ -0,0 +1,39 @@ +firstOrCreate( + ['dedupe_key' => $notification->dedupeKey], + [ + 'user_id' => $notification->userId, + 'type' => $notification->type, + 'params' => $notification->params, + 'created_at' => $notification->createdAt, + ], + ); + + return $model->wasRecentlyCreated; + } + + public function markSeen(int $userId, DateTimeImmutable $at): void + { + NotificationModel::query() + ->where('user_id', $userId) + ->whereNull('seen_at') + ->update(['seen_at' => $at]); + } + + public function deleteOlderThan(DateTimeImmutable $moment): void + { + NotificationModel::query()->where('created_at', '<', $moment)->delete(); + } +} diff --git a/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php b/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php new file mode 100644 index 0000000..b1eef4b --- /dev/null +++ b/app/Modules/Notifications/Infrastructure/Providers/NotificationsServiceProvider.php @@ -0,0 +1,45 @@ + + */ + public array $bindings = [ + NotificationRepository::class => EloquentNotificationRepository::class, + NotificationQueries::class => EloquentNotificationQueries::class, + ]; + + public function boot(): void + { + Livewire::addNamespace('notifications', viewPath: dirname(__DIR__, 2).'/Presentation/Livewire'); + + // Published by Jobs after the change is committed. + Event::listen(PeopleAddedToTask::class, fn (PeopleAddedToTask $event) => app(NotifyAddedPeople::class)->forTask($event)); + Event::listen(PeopleAddedToJob::class, fn (PeopleAddedToJob $event) => app(NotifyAddedPeople::class)->forJob($event)); + + if ($this->app->runningInConsole()) { + $this->commands([NotifyTasksStartingSoonCommand::class]); + } + } +} diff --git a/app/Modules/Notifications/Presentation/Console/NotifyTasksStartingSoonCommand.php b/app/Modules/Notifications/Presentation/Console/NotifyTasksStartingSoonCommand.php new file mode 100644 index 0000000..4fe3a3d --- /dev/null +++ b/app/Modules/Notifications/Presentation/Console/NotifyTasksStartingSoonCommand.php @@ -0,0 +1,22 @@ +execute(); + + $this->components->info("{$added} notifications added."); + + return self::SUCCESS; + } +} diff --git a/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php b/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php new file mode 100644 index 0000000..5d0b868 --- /dev/null +++ b/app/Modules/Notifications/Presentation/Livewire/⚡bell.blade.php @@ -0,0 +1,193 @@ + + */ + #[Locked] + public array $newIds = []; + + /** + * @return list + */ + #[Computed] + public function notifications(): array + { + return app(NotificationQueries::class)->recentFor((int) auth()->id(), $this->since()); + } + + #[Computed] + public function unseenCount(): int + { + return app(NotificationQueries::class)->unseenCount((int) auth()->id(), $this->since()); + } + + public function open(MarkNotificationsSeen $markSeen): void + { + $unseen = array_values(array_map( + fn (NotificationSummary $notification): int => $notification->id, + array_filter($this->notifications, fn (NotificationSummary $notification): bool => ! $notification->seen), + )); + + if ($unseen === []) { + return; + } + + $this->newIds = array_values(array_unique([...$this->newIds, ...$unseen])); + $markSeen->execute((int) auth()->id()); + unset($this->notifications, $this->unseenCount); + } + + public function text(NotificationSummary $notification): string + { + return match ($notification->type) { + NotificationType::TaskStartsSoon => __('notifications.types.task_starts_soon', [ + 'task' => (string) $notification->params['task_title'], + 'number' => (string) $notification->params['job_number'], + 'job' => (string) $notification->params['job_name'], + 'date' => $this->formatDay((string) $notification->params['starts_on']), + ]), + NotificationType::TaskAssigned => __('notifications.types.task_assigned.'.$notification->params['role'], [ + 'task' => (string) $notification->params['task_title'], + 'number' => (string) $notification->params['job_number'], + 'job' => (string) $notification->params['job_name'], + ]), + NotificationType::JobAssigned => __('notifications.types.job_assigned', [ + 'number' => (string) $notification->params['job_number'], + 'job' => (string) $notification->params['job_name'], + 'roles' => $this->roleList((string) $notification->params['roles']), + ]), + }; + } + + public function url(NotificationSummary $notification): string + { + return match ($notification->type) { + NotificationType::TaskStartsSoon, NotificationType::TaskAssigned => route('jobs.show', (int) $notification->params['job_id']).'#task-'.$notification->params['task_id'], + NotificationType::JobAssigned => route('jobs.show', (int) $notification->params['job_id']), + }; + } + + /** + * "vastuuhenkilöksi ja jäseneksi" from "responsible,member". + */ + private function roleList(string $roles): string + { + $names = array_map(fn (string $role): string => __('notifications.job_roles.'.$role), array_filter(explode(',', $roles))); + $last = array_pop($names); + + return $names === [] ? (string) $last : implode(', ', $names).' '.__('notifications.and').' '.$last; + } + + /** + * "25.11.2026 klo 14.05" from "2026-11-25 14:05". + */ + public function formatTime(string $moment): string + { + $time = CarbonImmutable::createFromFormat('Y-m-d H:i', $moment); + + return __('notifications.at', ['date' => $time->format('j.n.Y'), 'time' => $time->format('H.i')]); + } + + /** + * "ma 30.11.2026" from "2026-11-30". + */ + private function formatDay(string $date): string + { + $day = CarbonImmutable::createFromFormat('Y-m-d', $date); + + return __('holidays.weekdays.'.$day->dayOfWeekIso).' '.$day->format('j.n.Y'); + } + + private function since(): DateTimeImmutable + { + return CarbonImmutable::now()->subDays(NotifyTasksStartingSoon::KEEP_DAYS)->toDateTimeImmutable(); + } +}; +?> + +{{-- + A disclosure like the profile menu (not role="menu"): the bell's name stays "Ilmoitukset", and the number of + unseen notifications is visible text that the button refers to with aria-describedby. Opening the panel marks + them seen. Escape, a click outside and moving focus out close it. +--}} +
    + @php($count = $this->unseenCount) + + + {{ trans_choice('notifications.unseen', $count, ['count' => $count]) }} + +
    + {{-- Not a heading: the header comes before the page's h1. --}} +

    {{ __('notifications.recent') }}

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

    {{ __('notifications.empty') }}

    + @else + + @endif +
    +
    diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 98eaae4..0594142 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -5,6 +5,7 @@ use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; +use App\Modules\Notifications\Infrastructure\Providers\NotificationsServiceProvider; use App\Modules\Sales\Infrastructure\Providers\SalesServiceProvider; use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider; use App\Modules\TimeTracking\Infrastructure\Providers\TimeTrackingServiceProvider; @@ -24,4 +25,5 @@ return [ ExpensesServiceProvider::class, SalesServiceProvider::class, BillingServiceProvider::class, + NotificationsServiceProvider::class, ]; diff --git a/database/migrations/2026_11_25_060256_create_user_notifications_table.php b/database/migrations/2026_11_25_060256_create_user_notifications_table.php new file mode 100644 index 0000000..75257b1 --- /dev/null +++ b/database/migrations/2026_11_25_060256_create_user_notifications_table.php @@ -0,0 +1,36 @@ +id(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('type', 40); + $table->json('params'); + $table->string('dedupe_key')->unique(); + $table->timestamp('seen_at')->nullable(); + $table->timestamps(); + + $table->index(['user_id', 'created_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('user_notifications'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 35ead70..3c8224c 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -329,7 +329,10 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. ## 13. Ilmoitukset ja raportit *(K52, K53)* -- Ilmoitukset lisätään myöhemmin (esim. työ osoitettu sinulle, määräaika lähestyy). +- Ilmoitukset *(osittain valmis)*: yläpalkin kello näyttää lukemattomien ilmoitusten määrän, ja sen paneelissa ovat viimeisen 7 päivän ilmoitukset uusimmasta alkaen; vanhemmat poistetaan. Paneelin avaaminen kuittaa ilmoitukset luetuiksi. Jokainen ilmoitus on linkki asiaan. +- Tehtävä alkaa *(valmis)*: ajo joka päivä klo 14.00 (`notifications:task-starts`) ilmoittaa arkipäivänä tehtävän tekijälle ja jäsenille tehtävistä, joiden suunniteltu alku (tehtäväkalenteri) on seuraavana arkipäivänä tai sitä ennen (perjantaina myös la–ma alkavista). Arkipyhät ja yrityksen vapaapäivät eivät ole arkipäiviä. Valmiista tehtävistä ja arkistoiduista töistä ei ilmoiteta, eikä samasta alusta ilmoiteta kahdesti. +- Lisätty tehtävään tai työhön *(valmis)*: kun joku toinen tekee käyttäjästä tehtävän tekijän tai jäsenen (myös tehtävän siirto kalenterissa hänen rivilleen ja tehtävät työnkulkupohjasta) tai antaa hänelle roolin asiakastyössä (vastuuhenkilö, yhteyshenkilö, laskuttaja tai jäsen), käyttäjä saa ilmoituksen heti. Omista muutoksista ei ilmoiteta. +- Myöhemmin muita ilmoituksia (esim. määräpäivä lähestyy). - Johdon raportit (myöhemmin): tunnit henkilöittäin, laskuttamattomat tunnit, kannattavuus asiakastöittäin ja palveluyksiköittäin, pikamyynnit, kulukorvaukset. ## 14. Tietomalli @@ -371,6 +374,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `task_members`: `task_id`, `user_id` (tehtävän jäsenet; tekijä on `tasks.assignee_user_id`) *(olemassa)* - `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order` - `task_comments` *(V3, olemassa)*: `task_id`, `user_id`, `body`, `edited_at` (kirjoittaja muokkaa ja poistaa omiaan, pääkäyttäjä ja johto poistavat kenen tahansa) +- `user_notifications` *(V4, olemassa)*: `user_id`, `type`, `params` (json), `dedupe_key` (yksilöivä), `seen_at` - `task_images` *(V3, olemassa)*: `task_id`, `user_id`, `path`, `thumbnail_path`, `original_name`, `caption`, `width`, `height` (palvelin tallentaa enintään 2560 px JPEG-kopion ilman EXIF-tietoja ja 400 px pikkukuvan yksityiselle levylle; lähettäjä muokkaa kuvatekstiä ja poistaa omansa, pääkäyttäjä ja johto poistavat kenen tahansa) **TimeTracking** @@ -409,10 +413,10 @@ Tunnit kirjataan tehtäville, joten perustehtävät ja palveluyksiköiden työte Hinnasto ja tuotteet, rahakentät ja henkilökohtaiset näkyvyysoikeudet, kulut, tuntien hyväksyntä ja lukitus, laskuaineiston vienti Fennoaan (CSV/Excel), kuukausilaskutusrivit, pikamyynti. **Vaihe 3 – tehtävien hallinta** -Tarkistuslistat *(valmis)*, kommentit *(valmis)*, kuvat *(valmis)*, työnkulkupohjat *(valmis)*, tehtäväkalenteri henkilöittäin ja arkipyhät *(valmis; korvaa tehtävien Kanban-sarakkeet, K34)*, kenttien yksinkertaistus palveluyksiköittäin. +Tarkistuslistat *(valmis)*, kommentit *(valmis)*, kuvat *(valmis)*, työnkulkupohjat *(valmis)*, tehtäväkalenteri henkilöittäin ja arkipyhät *(valmis; korvaa tehtävien Kanban-sarakkeet, K34)*. **Vaihe 4 – laajennukset** -Alihankkijoiden näkymät ja rajaukset, raportit, ilmoitukset, Fennoa-rajapinta, PWA. +Alihankkijoiden näkymät ja rajaukset, raportit, ilmoitukset *(osittain: kello ja tehtävän alku)*, Fennoa-rajapinta, PWA, kenttien yksinkertaistus palveluyksiköittäin *(K31; siirretty vaiheesta 3)*. ## 16. Vaiheen 1 tarkka sisältö diff --git a/lang/en/notifications.php b/lang/en/notifications.php new file mode 100644 index 0000000..e65d7a9 --- /dev/null +++ b/lang/en/notifications.php @@ -0,0 +1,25 @@ + 'Notifications', + 'recent' => 'Notifications of the last 7 days', + 'unseen' => '{0} No unread notifications|{1} :count unread notification|[2,*] :count unread notifications', + 'empty' => 'No notifications in the last 7 days.', + 'new' => 'New', + 'at' => ':date at :time', + 'types' => [ + 'task_starts_soon' => 'Task :task (job :number :job) starts on :date.', + 'task_assigned' => [ + 'assignee' => 'You were made the assignee of task :task (job :number :job).', + 'member' => 'You were made a member of task :task (job :number :job).', + ], + 'job_assigned' => 'You were made :roles of job :number :job.', + ], + 'job_roles' => [ + 'responsible' => 'the responsible person', + 'contact' => 'the contact person', + 'biller' => 'the biller', + 'member' => 'a member', + ], + 'and' => 'and', +]; diff --git a/lang/fi/notifications.php b/lang/fi/notifications.php new file mode 100644 index 0000000..f1ba824 --- /dev/null +++ b/lang/fi/notifications.php @@ -0,0 +1,25 @@ + 'Ilmoitukset', + 'recent' => 'Viimeisen 7 päivän ilmoitukset', + 'unseen' => '{0} Ei lukemattomia ilmoituksia|{1} :count lukematon ilmoitus|[2,*] :count lukematonta ilmoitusta', + 'empty' => 'Ei ilmoituksia viimeiseltä 7 päivältä.', + 'new' => 'Uusi', + 'at' => ':date klo :time', + 'types' => [ + 'task_starts_soon' => 'Tehtävä :task (työ :number :job) alkaa :date.', + 'task_assigned' => [ + 'assignee' => 'Sinut lisättiin tehtävän :task tekijäksi (työ :number :job).', + 'member' => 'Sinut lisättiin tehtävän :task jäseneksi (työ :number :job).', + ], + 'job_assigned' => 'Sinut lisättiin työn :number :job :roles.', + ], + 'job_roles' => [ + 'responsible' => 'vastuuhenkilöksi', + 'contact' => 'yhteyshenkilöksi', + 'biller' => 'laskuttajaksi', + 'member' => 'jäseneksi', + ], + 'and' => 'ja', +]; diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 526459e..e670443 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -61,7 +61,10 @@ @endforeach - +
    + + +
    @else diff --git a/routes/console.php b/routes/console.php index 3c9adf1..cd3367c 100644 --- a/routes/console.php +++ b/routes/console.php @@ -2,7 +2,14 @@ use Illuminate\Foundation\Inspiring; use Illuminate\Support\Facades\Artisan; +use Illuminate\Support\Facades\Schedule; Artisan::command('inspire', function () { $this->comment(Inspiring::quote()); })->purpose('Display an inspiring quote'); + +// Tasks starting on the next working day: notify their assignees and members in the afternoon. +Schedule::command('notifications:task-starts') + ->dailyAt('14:00') + ->timezone((string) config('app.business_timezone')) + ->onOneServer(); diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index 31f0c58..09d9023 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -394,6 +394,8 @@ it('adds tasks from a workflow template with the keyboard, without accessibility ->keys('main form button[type="submit"]', 'Enter') ->assertSee('Lisättiin 2 tehtävää pohjasta Lyhyt video (videokuvaus).') ->assertSee('Suunnittelu') + // The page was reached with wire:navigate: wait until Livewire's progress bar (role="bar", not an ARIA role) is gone. + ->assertMissing('#nprogress .bar') ->assertNoAccessibilityIssues(level: 2); expect(TaskModel::query()->where('customer_job_id', $this->job->id)->orderBy('id')->pluck('estimated_hours')->map(fn ($hours) => $hours === null ? null : (float) $hours)->all())->toBe([null, 2.5]); diff --git a/tests/Browser/NotificationsAccessibilityTest.php b/tests/Browser/NotificationsAccessibilityTest.php new file mode 100644 index 0000000..92b32fd --- /dev/null +++ b/tests/Browser/NotificationsAccessibilityTest.php @@ -0,0 +1,71 @@ +user = User::factory()->create(['name' => 'Eetu Esimerkki']); + $this->actingAs($this->user); + $this->job = CustomerJobModel::factory()->create(['status' => 'order', 'number' => '2026-0042', 'name' => 'Messuvideo']); + $this->task = TaskModel::factory()->assignedTo([$this->user->id])->create(['customer_job_id' => $this->job->id, 'title' => 'Kuvauspäivä']); + + foreach ([1, 2] as $number) { + NotificationModel::query()->create([ + 'user_id' => $this->user->id, + 'type' => 'task_starts_soon', + 'params' => ['task_id' => $this->task->id, 'task_title' => 'Kuvauspäivä', 'job_id' => $this->job->id, 'job_number' => '2026-0042', 'job_name' => 'Messuvideo', 'starts_on' => '2026-11-30'], + 'dedupe_key' => 'browser:'.$number, + 'created_at' => now()->subHours($number), + ]); + } +}); + +it('has no accessibility issues with the notifications closed and open', function (string $device, string $colorScheme) { + $visit = visit(route('jobs.index')); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertNoJavaScriptErrors() + ->assertSeeIn('[data-notifications-bell]', '2') + ->assertNoAccessibilityIssues(level: 2) + ->click('[data-notifications-bell]') + ->assertVisible('#notifications-panel') + ->assertSee('Uusi') + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); + +it('opens with the keyboard, marks the notifications seen and closes with Escape', function () { + visit(route('jobs.index')) + ->assertScript("document.querySelector('[data-notifications-bell]').getAttribute('aria-describedby')", 'notifications-count') + ->assertSeeIn('#notifications-count', '2 lukematonta ilmoitusta') + ->keys('[data-notifications-bell]', 'Enter') + ->assertVisible('#notifications-panel') + ->assertSeeIn('#notifications-count', 'Ei lukemattomia ilmoituksia') + ->assertScript("document.querySelector('[data-notifications-bell]').getAttribute('aria-expanded')", 'true') + ->keys('[data-notifications-bell]', 'Escape') + ->assertMissing('#notifications-panel') + ->assertScript("document.activeElement.hasAttribute('data-notifications-bell')", true) + ->resize(320, 900) + ->click('[data-notifications-bell]') + ->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true); + + expect(NotificationModel::query()->whereNull('seen_at')->count())->toBe(0); +}); + +it('opens the task from a notification', function () { + visit(route('jobs.index')) + ->click('[data-notifications-bell]') + ->click('#notifications-panel li:first-child a') + ->assertPathIs('/jobs/'.$this->job->id) + ->assertVisible('#task-'.$this->task->id.'-details'); +}); diff --git a/tests/Fakes/FakeUpcomingTasks.php b/tests/Fakes/FakeUpcomingTasks.php new file mode 100644 index 0000000..e04f271 --- /dev/null +++ b/tests/Fakes/FakeUpcomingTasks.php @@ -0,0 +1,19 @@ + $tasks + */ + public function __construct(public array $tasks = []) {} + + public function startingBetween(string $after, string $to): array + { + return array_values(array_filter($this->tasks, fn (UpcomingTask $task): bool => $task->plannedFrom > $after && $task->plannedFrom <= $to)); + } +} diff --git a/tests/Fakes/InMemoryNotificationRepository.php b/tests/Fakes/InMemoryNotificationRepository.php new file mode 100644 index 0000000..53ad0c0 --- /dev/null +++ b/tests/Fakes/InMemoryNotificationRepository.php @@ -0,0 +1,51 @@ + By dedupe key. */ + public array $notifications = []; + + /** @var array */ + public array $seenAt = []; + + public function addIfNew(NewNotification $notification): bool + { + if (isset($this->notifications[$notification->dedupeKey])) { + return false; + } + + $this->notifications[$notification->dedupeKey] = $notification; + + return true; + } + + public function markSeen(int $userId, DateTimeImmutable $at): void + { + foreach ($this->notifications as $key => $notification) { + if ($notification->userId === $userId && ! isset($this->seenAt[$key])) { + $this->seenAt[$key] = $at; + } + } + } + + public function deleteOlderThan(DateTimeImmutable $moment): void + { + $this->notifications = array_filter($this->notifications, fn (NewNotification $notification): bool => $notification->createdAt >= $moment); + } + + /** + * Who was told about which task: "userId:taskId", in order of adding. + * + * @return list + */ + public function recipients(): array + { + return array_values(array_map(fn (NewNotification $notification): string => $notification->userId.':'.$notification->params['task_id'], $this->notifications)); + } +} diff --git a/tests/Feature/Modules/Notifications/NotificationsTest.php b/tests/Feature/Modules/Notifications/NotificationsTest.php new file mode 100644 index 0000000..f319c68 --- /dev/null +++ b/tests/Feature/Modules/Notifications/NotificationsTest.php @@ -0,0 +1,165 @@ +travelTo(CarbonImmutable::parse('2026-11-26 14:00', 'Europe/Helsinki')); + $this->user = User::factory()->create(); + $this->member = User::factory()->create(); + $this->job = CustomerJobModel::factory()->create(['status' => 'order', 'number' => '2026-0042', 'name' => 'Messuvideo']); +}); + +function notificationFor(User $user, array $overrides = []): NotificationModel +{ + static $sequence = 0; + $sequence++; + + return NotificationModel::query()->create([ + 'user_id' => $user->id, + 'type' => 'task_starts_soon', + 'params' => ['task_id' => 7, 'task_title' => 'Kuvauspäivä', 'job_id' => 3, 'job_number' => '2026-0042', 'job_name' => 'Messuvideo', 'starts_on' => '2026-11-30'], + 'dedupe_key' => 'test:'.$sequence, + 'created_at' => now(), + ...$overrides, + ]); +} + +it('finds tasks starting in the period with their assignee and members, without done tasks and archived jobs', function () { + $task = TaskModel::factory()->assignedTo([$this->user->id, $this->member->id])->create(['customer_job_id' => $this->job->id, 'title' => 'Kuvauspäivä', 'planned_from' => '2026-11-27', 'planned_to' => '2026-11-27']); + TaskModel::factory()->assignedTo([$this->user->id])->create(['customer_job_id' => $this->job->id, 'status' => 'done', 'planned_from' => '2026-11-27']); + TaskModel::factory()->assignedTo([$this->user->id])->create(['customer_job_id' => CustomerJobModel::factory()->create(['status' => 'archived'])->id, 'planned_from' => '2026-11-27']); + TaskModel::factory()->assignedTo([$this->user->id])->create(['customer_job_id' => $this->job->id, 'planned_from' => '2026-11-26']); + + $tasks = app(UpcomingTasks::class)->startingBetween('2026-11-26', '2026-11-27'); + + expect($tasks)->toHaveCount(1) + ->and($tasks[0]->taskId)->toBe($task->id) + ->and($tasks[0]->jobNumber)->toBe('2026-0042') + ->and($tasks[0]->plannedFrom)->toBe('2026-11-27') + ->and($tasks[0]->recipientIds)->toBe([$this->user->id, $this->member->id]); +}); + +it('notifies with the daily command, scheduled at 14.00 Finnish time', function () { + $task = TaskModel::factory()->assignedTo([$this->user->id, $this->member->id])->create(['customer_job_id' => $this->job->id, 'title' => 'Kuvauspäivä', 'planned_from' => '2026-11-27']); + + $this->artisan('notifications:task-starts')->expectsOutputToContain('2 notifications added.')->assertSuccessful(); + $this->artisan('notifications:task-starts')->expectsOutputToContain('0 notifications added.'); + + expect(NotificationModel::query()->where('user_id', $this->member->id)->sole()->params['task_id'])->toBe($task->id); + + $event = collect(app(Schedule::class)->events())->first(fn (Event $event): bool => str_contains((string) $event->command, 'notifications:task-starts')); + + expect($event)->not->toBeNull() + ->and($event->expression)->toBe('0 14 * * *') + ->and($event->timezone)->toBe('Europe/Helsinki'); +}); + +it('shows the unseen count of the user\'s own notifications of the last 7 days', function () { + notificationFor($this->user); + notificationFor($this->user, ['created_at' => now()->subDays(8)]); + notificationFor($this->member); + + $this->actingAs($this->user); + + Livewire::test('notifications::bell') + ->assertSee('1 lukematon ilmoitus') + ->assertSee('Tehtävä Kuvauspäivä (työ 2026-0042 Messuvideo) alkaa ma 30.11.2026.') + ->assertSee(route('jobs.show', 3).'#task-7', false) + ->assertSee('26.11.2026 klo 14.00'); +}); + +it('marks the notifications seen when the panel is opened, keeping them marked new for now', function () { + $notification = notificationFor($this->user); + $this->actingAs($this->user); + + Livewire::test('notifications::bell') + ->call('open') + ->assertSee('Ei lukemattomia ilmoituksia') + ->assertSet('newIds', [$notification->id]) + ->assertSee('Uusi'); + + expect($notification->fresh()->seen_at)->not->toBeNull(); + + Livewire::test('notifications::bell')->assertDontSee('Uusi'); +}); + +it('tells when there are no notifications, and in the user\'s language', function () { + $this->actingAs($this->user); + Livewire::test('notifications::bell')->assertSee('Ei ilmoituksia viimeiseltä 7 päivältä.'); + + notificationFor($this->member); + $this->member->forceFill(['locale' => 'en'])->save(); + $this->actingAs($this->member); + app()->setLocale('en'); + + Livewire::test('notifications::bell') + ->assertSee('Task Kuvauspäivä (job 2026-0042 Messuvideo) starts on Mon 30.11.2026.') + ->assertSee('1 unread notification'); +}); + +it('shows the bell in the header of signed-in pages', function () { + $this->actingAs($this->user); + + $this->get(route('jobs.index')) + ->assertOk() + ->assertSee('data-notifications-bell', false); +}); + +it('notifies people at once when someone else adds them to a task, not the one who added', function () { + $marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole(); + DB::table('customer_job_service_unit')->where('customer_job_id', $this->job->id)->update(['service_unit_id' => $marketing->id]); + $this->actingAs($this->user); + + Livewire::test('jobs::task-form', ['job' => $this->job->id]) + ->set('form.title', 'Mainoskuvat') + ->set('form.work_type_id', (string) WorkTypeModel::query()->where('name', 'graafinen työ')->value('id')) + ->set('form.member_user_ids', [(string) $this->member->id]) + ->call('save') + ->assertHasNoErrors(); + + expect(NotificationModel::query()->where('user_id', $this->user->id)->count())->toBe(0) + ->and(NotificationModel::query()->where('user_id', $this->member->id)->sole()->type->value)->toBe('task_assigned'); + + $this->actingAs($this->member); + Livewire::test('notifications::bell') + ->assertSee('Sinut lisättiin tehtävän Mainoskuvat jäseneksi (työ 2026-0042 Messuvideo).') + ->assertSee(route('jobs.show', $this->job->id).'#task-'.TaskModel::query()->sole()->id, false); +}); + +it('notifies people at once about their new roles on a job', function () { + $jobId = app(CreateCustomerJob::class)->execute(new CustomerJobData( + name: 'Esite', + customerId: CustomerModel::factory()->create()->id, + serviceUnitIds: [ServiceUnitModel::query()->value('id')], + responsibleUserId: $this->member->id, + kind: 'one_off', + status: 'order', + priority: 'normal', + memberUserIds: [$this->member->id, $this->user->id], + ), $this->user->id); + + $this->actingAs($this->member); + Livewire::test('notifications::bell') + ->assertSee('Sinut lisättiin työn '.CustomerJobModel::query()->find($jobId)->number.' Esite vastuuhenkilöksi ja jäseneksi.') + ->assertSee(route('jobs.show', $jobId), false); + + expect(NotificationModel::query()->where('user_id', $this->user->id)->count())->toBe(0); +}); diff --git a/tests/Unit/Modules/Jobs/Application/CustomerJobUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/CustomerJobUseCasesTest.php index 1ff185e..9f4ec80 100644 --- a/tests/Unit/Modules/Jobs/Application/CustomerJobUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/CustomerJobUseCasesTest.php @@ -6,16 +6,19 @@ use App\Modules\Jobs\Application\UseCases\ChangeJobStatus; use App\Modules\Jobs\Application\UseCases\CreateCustomerJob; use App\Modules\Jobs\Application\UseCases\UpdateCustomerJob; use App\Modules\Jobs\Domain\Enums\JobStatus; +use App\Modules\Jobs\Domain\Events\PeopleAddedToJob; use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference; use App\Modules\Users\Domain\Enums\Role; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; use Tests\Fakes\FakeCustomerQueries; +use Tests\Fakes\FakeEventDispatcher; use Tests\Fakes\FakeTransactionManager; use Tests\Fakes\FakeUserAccountQueries; use Tests\Fakes\InMemoryCustomerJobRepository; beforeEach(function () { + $this->events = new FakeEventDispatcher; $this->jobs = new InMemoryCustomerJobRepository; $this->customers = new FakeCustomerQueries; $this->catalog = new FakeCatalogQueries; @@ -33,8 +36,8 @@ beforeEach(function () { $this->users->addUser(12, 'Pois', active: false); $factory = new JobDetailsFactory($this->customers, $this->catalog, $this->users); - $this->create = new CreateCustomerJob($this->jobs, $this->jobs, $factory, $transactions, $this->clock); - $this->update = new UpdateCustomerJob($this->jobs, $factory, $transactions, $this->clock); + $this->create = new CreateCustomerJob($this->jobs, $this->jobs, $factory, $transactions, $this->clock, $this->events); + $this->update = new UpdateCustomerJob($this->jobs, $factory, $transactions, $this->clock, $this->events); $this->changeStatus = new ChangeJobStatus($this->jobs, $transactions, new FakeClock(new DateTimeImmutable('2026-05-01'))); }); @@ -104,3 +107,21 @@ it('records each changed field, and nothing when nothing changed', function () { expect($this->jobs->changedFields($jobId))->toBe(['created', 'priority', 'customer_contact', 'tags', 'status']); }); + +it('publishes the new roles people got on a job', function () { + $jobId = $this->create->execute(jobData(['memberUserIds' => [11]]), 10); + $added = end($this->events->dispatched); + + expect($added)->toBeInstanceOf(PeopleAddedToJob::class) + ->and($added->jobId)->toBe($jobId) + ->and($added->jobName)->toBe('Messuvideo') + ->and($added->newRoles)->toBe([10 => ['responsible'], 11 => ['member']]) + ->and($added->actorUserId)->toBe(10); + + $count = count($this->events->dispatched); + $this->update->execute($jobId, jobData(['memberUserIds' => [11], 'name' => 'Messuvideo 2']), 10); + expect($this->events->dispatched)->toHaveCount($count); + + $this->update->execute($jobId, jobData(['memberUserIds' => [11], 'contactUserId' => 11]), 10); + expect(end($this->events->dispatched)->newRoles)->toBe([11 => ['contact']]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php index 5464c70..42b6b18 100644 --- a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -15,6 +15,7 @@ use App\Modules\Jobs\Application\UseCases\ScheduleTask; use App\Modules\Jobs\Application\UseCases\UpdateTask; use App\Modules\Jobs\Domain\Enums\JobStatus; use App\Modules\Jobs\Domain\Enums\TaskStatus; +use App\Modules\Jobs\Domain\Events\PeopleAddedToTask; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskReference; use App\Modules\Jobs\Domain\Exceptions\InvalidTaskTitle; use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart; @@ -26,6 +27,7 @@ use App\Modules\Shared\Application\UseCases\HolidayCalendar; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; use Tests\Fakes\FakeCustomerQueries; +use Tests\Fakes\FakeEventDispatcher; use Tests\Fakes\FakeSettings; use Tests\Fakes\FakeTaskImageFiles; use Tests\Fakes\FakeTaskUsage; @@ -38,6 +40,7 @@ use Tests\Fakes\InMemoryTaskImageRepository; use Tests\Fakes\InMemoryTaskRepository; beforeEach(function () { + $this->events = new FakeEventDispatcher; $this->jobs = new InMemoryCustomerJobRepository; $this->tasks = new InMemoryTaskRepository; $customers = new FakeCustomerQueries; @@ -55,16 +58,16 @@ beforeEach(function () { $this->users->addUser(10, 'Eero'); $this->users->addUser(12, 'Pois', active: false); - $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $this->catalog, $this->users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01'))); + $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $this->catalog, $this->users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01')), $this->events); $this->jobId = $createJob->execute(new CustomerJobData('Kampanja', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10); $this->tentativeJobId = $createJob->execute(new CustomerJobData('Alustava', 1, [1], 10, 'one_off', 'tentative', 'normal'), 10); $checker = new TaskReferenceChecker($this->catalog, $this->users); $this->bookings = new InMemoryTaskBookingRepository($this->tasks); $this->planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new FakeSettings); - $this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); - $this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); - $this->scheduleTask = new ScheduleTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions); + $this->addTask = new AddTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions, $this->events); + $this->updateTask = new UpdateTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions, $this->events); + $this->scheduleTask = new ScheduleTask($this->jobs, $this->tasks, $checker, $this->planner, $transactions, $this->events); $this->clearSchedule = new ClearTaskSchedule($this->tasks, $this->planner, $transactions); $this->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions); $this->usage = new FakeTaskUsage; @@ -112,7 +115,7 @@ it('rejects a work type of another unit and an inactive assignee or member', fun it('changes, moves through statuses and removes a task', function () { $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); - $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat ja banneri', 11, 'in_progress')); + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat ja banneri', 11, 'in_progress'), 10); $this->changeTaskStatus->execute($this->jobId, $taskId, TaskStatus::Done); $task = $this->tasks->findForJob($this->jobId, $taskId); @@ -127,7 +130,7 @@ it('can still change a task after the job moved back to an earlier status', func $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); $this->changeJobStatus->execute($this->jobId, JobStatus::Tentative, 10); - $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'in_review')); + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'in_review'), 10); expect($this->tasks->findForJob($this->jobId, $taskId)?->status())->toBe(TaskStatus::InReview); }); @@ -136,7 +139,7 @@ it('does not touch a task of another job', function (string $action) { $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting'), 10); match ($action) { - 'update' => $this->updateTask->execute($this->tentativeJobId, $taskId, new TaskData('X', 11, 'done')), + 'update' => $this->updateTask->execute($this->tentativeJobId, $taskId, new TaskData('X', 11, 'done'), 10), 'status' => $this->changeTaskStatus->execute($this->tentativeJobId, $taskId, TaskStatus::Done), 'remove' => $this->removeTask->execute($this->tentativeJobId, $taskId), }; @@ -165,7 +168,7 @@ it('moves what does not fit in a full day to the next working day', function () $this->addTask->execute($this->jobId, new TaskData('Kuvaus', 11, 'waiting', estimatedHours: '6', assigneeUserId: 10, plannedFrom: '2026-12-04'), 10); $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10), 10); - $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-04', '2026-12-04'); + $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-04', '2026-12-04', 10); expect($result->extended)->toBeTrue() ->and($result->plannedTo)->toBe('2026-12-07') @@ -184,7 +187,7 @@ it('moves a task to another person and gives it the days its estimate needs', fu $this->users->addUser(11, 'Aino'); $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '20', assigneeUserId: 10, plannedFrom: '2026-12-01'), 10); - $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-11', null); + $result = $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-11', null, 10); expect($this->tasks->findForJob($this->jobId, $taskId)?->assigneeUserId())->toBe(11) ->and($result->plannedFrom)->toBe('2026-12-11') @@ -197,8 +200,8 @@ it('moves a task to another person and gives it the days its estimate needs', fu it('rejects moving a task to an inactive person or ending it before it starts', function () { $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', assigneeUserId: 10), 10); - expect(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 12, '2026-12-07', '2026-12-07'))->toThrow(InvalidTaskReference::class) - ->and(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-07', '2026-12-04'))->toThrow(PlanEndsBeforeStart::class); + expect(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 12, '2026-12-07', '2026-12-07', 10))->toThrow(InvalidTaskReference::class) + ->and(fn () => $this->scheduleTask->execute($this->jobId, $taskId, 10, 10, '2026-12-07', '2026-12-04', 10))->toThrow(PlanEndsBeforeStart::class); }); it('takes a task out of the calendar', function () { @@ -225,7 +228,7 @@ it('moves a task to a member, who then is the assignee and no longer a member', $this->users->addUser(13, 'Ville'); $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '4', assigneeUserId: 10, memberUserIds: [11, 13], plannedFrom: '2026-12-07'), 10); - $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-07', '2026-12-07'); + $this->scheduleTask->execute($this->jobId, $taskId, 10, 11, '2026-12-07', '2026-12-07', 10); $task = $this->tasks->findForJob($this->jobId, $taskId); expect($task?->assigneeUserId())->toBe(11) @@ -240,3 +243,32 @@ it('books nothing for a task without an assignee', function () { expect($this->bookings->of($taskId, 10))->toBe([]) ->and($this->tasks->findForJob($this->jobId, $taskId)?->plannedTo()?->format('Y-m-d'))->toBe('2026-12-07'); }); + +it('publishes who was added to a task: the new assignee and new members, not those who already were', function () { + $this->users->addUser(11, 'Aino'); + $this->users->addUser(13, 'Ville'); + + $taskId = $this->addTask->execute($this->jobId, new TaskData('Mainoskuvat', 11, 'waiting', assigneeUserId: 10, memberUserIds: [11]), 10); + $added = end($this->events->dispatched); + + expect($added)->toBeInstanceOf(PeopleAddedToTask::class) + ->and($added->taskId)->toBe($taskId) + ->and($added->taskTitle)->toBe('Mainoskuvat') + ->and($added->jobName)->toBe('Kampanja') + ->and($added->newAssigneeId)->toBe(10) + ->and($added->newMemberIds)->toBe([11]) + ->and($added->actorUserId)->toBe(10); + + $count = count($this->events->dispatched); + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'waiting', assigneeUserId: 10, memberUserIds: [11]), 10); + expect($this->events->dispatched)->toHaveCount($count); + + $this->updateTask->execute($this->jobId, $taskId, new TaskData('Mainoskuvat', 11, 'waiting', assigneeUserId: 10, memberUserIds: [11, 13]), 11); + expect(end($this->events->dispatched)->newAssigneeId)->toBeNull() + ->and(end($this->events->dispatched)->newMemberIds)->toBe([13]) + ->and(end($this->events->dispatched)->actorUserId)->toBe(11); + + $this->scheduleTask->execute($this->jobId, $taskId, 10, 13, '2026-12-07', '2026-12-07', 10); + expect(end($this->events->dispatched)->newAssigneeId)->toBe(13) + ->and(end($this->events->dispatched)->newMemberIds)->toBe([]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php index 1045edf..06d9e67 100644 --- a/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php +++ b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php @@ -17,6 +17,7 @@ use App\Modules\Shared\Application\UseCases\HolidayCalendar; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; use Tests\Fakes\FakeCustomerQueries; +use Tests\Fakes\FakeEventDispatcher; use Tests\Fakes\FakeSettings; use Tests\Fakes\FakeTransactionManager; use Tests\Fakes\FakeUserAccountQueries; @@ -27,6 +28,7 @@ use Tests\Fakes\InMemoryTaskBookingRepository; use Tests\Fakes\InMemoryTaskRepository; beforeEach(function () { + $this->events = new FakeEventDispatcher; $this->jobs = new InMemoryCustomerJobRepository; $this->tasks = new InMemoryTaskRepository; $customers = new FakeCustomerQueries; @@ -47,7 +49,7 @@ beforeEach(function () { $users->addUser(11, 'Aino'); $users->addUser(12, 'Pois', active: false); - $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $catalog, $users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01'))); + $createJob = new CreateCustomerJob($this->jobs, $this->jobs, new JobDetailsFactory($customers, $catalog, $users), $transactions, new FakeClock(new DateTimeImmutable('2026-05-01')), $this->events); $this->jobId = $createJob->execute(new CustomerJobData('Video', 1, [1], 10, 'one_off', 'quote_request', 'normal'), 10); $this->tentativeJobId = $createJob->execute(new CustomerJobData('Alustava', 1, [1], 10, 'one_off', 'tentative', 'normal'), 10); @@ -58,7 +60,7 @@ beforeEach(function () { $this->bookings = new InMemoryTaskBookingRepository($this->tasks); $planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new FakeSettings); - $this->addTasks = new AddTasksFromWorkflowTemplate($this->jobs, $this->tasks, $this->templates, new TaskReferenceChecker($catalog, $users), $planner, new FakeClock(new DateTimeImmutable('2026-05-01')), $transactions); + $this->addTasks = new AddTasksFromWorkflowTemplate($this->jobs, $this->tasks, $this->templates, new TaskReferenceChecker($catalog, $users), $planner, new FakeClock(new DateTimeImmutable('2026-05-01')), $transactions, $this->events); }); it('adds a waiting task per step in order, with the step work type and the adder as assignee', function () { diff --git a/tests/Unit/Modules/Notifications/NotifyAddedPeopleTest.php b/tests/Unit/Modules/Notifications/NotifyAddedPeopleTest.php new file mode 100644 index 0000000..a979e0e --- /dev/null +++ b/tests/Unit/Modules/Notifications/NotifyAddedPeopleTest.php @@ -0,0 +1,46 @@ +notifications = new InMemoryNotificationRepository; + $this->notify = new NotifyAddedPeople($this->notifications, new FakeClock(new DateTimeImmutable('2026-11-25'))); +}); + +it('tells the new assignee and members of a task, but not the one who added them', function () { + $this->notify->forTask(new PeopleAddedToTask(7, 'Kuvauspäivä', 3, '2026-0042', 'Messuvideo', 10, [11, 12], 12)); + + $notifications = array_values($this->notifications->notifications); + + expect($notifications)->toHaveCount(2) + ->and($notifications[0]->userId)->toBe(10) + ->and($notifications[0]->type)->toBe(NotificationType::TaskAssigned) + ->and($notifications[0]->params)->toBe(['task_id' => 7, 'task_title' => 'Kuvauspäivä', 'job_id' => 3, 'job_number' => '2026-0042', 'job_name' => 'Messuvideo', 'role' => 'assignee']) + ->and($notifications[1]->userId)->toBe(11) + ->and($notifications[1]->params['role'])->toBe('member'); +}); + +it('tells each person about their new roles on a job, but not the one who gave them', function () { + $this->notify->forJob(new PeopleAddedToJob(3, '2026-0042', 'Messuvideo', [10 => ['responsible'], 11 => ['contact', 'member']], 10)); + + $notifications = array_values($this->notifications->notifications); + + expect($notifications)->toHaveCount(1) + ->and($notifications[0]->userId)->toBe(11) + ->and($notifications[0]->type)->toBe(NotificationType::JobAssigned) + ->and($notifications[0]->params['roles'])->toBe('contact,member'); +}); + +it('tells again when the same person is added again later', function () { + $event = new PeopleAddedToTask(7, 'Kuvauspäivä', 3, '2026-0042', 'Messuvideo', 10, [], 12); + + $this->notify->forTask($event); + $this->notify->forTask($event); + + expect($this->notifications->notifications)->toHaveCount(2); +}); diff --git a/tests/Unit/Modules/Notifications/NotifyTasksStartingSoonTest.php b/tests/Unit/Modules/Notifications/NotifyTasksStartingSoonTest.php new file mode 100644 index 0000000..449c439 --- /dev/null +++ b/tests/Unit/Modules/Notifications/NotifyTasksStartingSoonTest.php @@ -0,0 +1,90 @@ +tasks = new FakeUpcomingTasks; + $this->notifications = new InMemoryNotificationRepository; + $this->clock = new FakeClock(new DateTimeImmutable('2026-11-26')); + $this->notify = new NotifyTasksStartingSoon( + $this->tasks, + $this->notifications, + new WorkingDays(new HolidayCalendar(new InMemoryHolidayOverrides)), + new FakeTransactionManager, + $this->clock, + ); +}); + +function upcomingTask(int $id, string $startsOn, array $recipients = [10]): UpcomingTask +{ + return new UpcomingTask($id, 'Tehtävä '.$id, 5, '2026-0042', 'Messuvideo', $startsOn, $recipients); +} + +it('notifies on Thursday about tasks starting on Friday, not later ones or today\'s', function () { + $this->tasks->tasks = [upcomingTask(1, '2026-11-26'), upcomingTask(2, '2026-11-27'), upcomingTask(3, '2026-11-30')]; + + expect($this->notify->execute())->toBe(1) + ->and($this->notifications->recipients())->toBe(['10:2']); +}); + +it('notifies on Friday about tasks starting on Saturday to Monday', function () { + $this->clock->today = new DateTimeImmutable('2026-11-27'); + $this->tasks->tasks = [upcomingTask(1, '2026-11-28'), upcomingTask(2, '2026-11-30'), upcomingTask(3, '2026-12-01')]; + + $this->notify->execute(); + + expect($this->notifications->recipients())->toBe(['10:1', '10:2']); +}); + +it('skips holidays: before Christmas it notifies up to the next working day after them', function () { + $this->clock->today = new DateTimeImmutable('2026-12-23'); + $this->tasks->tasks = [upcomingTask(1, '2026-12-28'), upcomingTask(2, '2026-12-29')]; + + $this->notify->execute(); + + expect($this->notifications->recipients())->toBe(['10:1']); +}); + +it('notifies nobody on a day off', function () { + $this->clock->today = new DateTimeImmutable('2026-11-29'); + $this->tasks->tasks = [upcomingTask(1, '2026-11-30')]; + + expect($this->notify->execute())->toBe(0) + ->and($this->notifications->notifications)->toBe([]); +}); + +it('notifies each recipient once, also when run again', function () { + $this->tasks->tasks = [upcomingTask(1, '2026-11-27', [10, 12])]; + + expect($this->notify->execute())->toBe(2) + ->and($this->notify->execute())->toBe(0) + ->and($this->notifications->recipients())->toBe(['10:1', '12:1']); + + $notification = array_values($this->notifications->notifications)[0]; + expect($notification->params)->toBe([ + 'task_id' => 1, + 'task_title' => 'Tehtävä 1', + 'job_id' => 5, + 'job_number' => '2026-0042', + 'job_name' => 'Messuvideo', + 'starts_on' => '2026-11-27', + ]); +}); + +it('removes notifications older than a week', function () { + $this->notifications->addIfNew(NewNotification::taskStartsSoon(10, 1, '2026-11-18', ['task_id' => 1], new DateTimeImmutable('2026-11-17 14:00'))); + $this->notifications->addIfNew(NewNotification::taskStartsSoon(10, 2, '2026-11-20', ['task_id' => 2], new DateTimeImmutable('2026-11-19 14:00'))); + + $this->notify->execute(); + + expect($this->notifications->recipients())->toBe(['10:2']); +});