diff --git a/CLAUDE.md b/CLAUDE.md index b8f951c..e1f8a3d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), task images (`jobs::task-images`, same rules with `jobs.remove-any-task-image`; `GdTaskImageFiles` stores an upright, at most 2560 px JPEG without EXIF and a 400 px thumbnail under `task-images/` on the private `local` disk, served only through `ShowTaskImage` after `jobs.view-job`; `RemoveTask` also deletes the files), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`) and `Reports` (management's reports behind `reports.view`: hours by person, unbilled hours, profitability by job and service unit, quick sales and expense reimbursements, each a `reports::` page with a period in the URL (`ReportPage` trait, `alku`/`loppu`), tables, a `` (TallStackUI's server-side `` as one image) and a CSV from `DownloadReport`; it reads the other modules only through its ports `ReportHours`, `ReportJobs`, `ReportCatalog`, `ReportPeople`, `ReportSales`, `ReportExpenses` and `ReportRevenue`, whose adapters call those modules' report queries (`TimeReportQueries`, `CustomerJobQueries::reportInfoOf`, `QuickSaleReportQueries`, `ExpenseReportQueries`, `BilledRevenueQueries`); hours are costed at the one internal hourly cost `catalog.internal_hourly_cost_cents`, set on the Hinnasto maintenance page)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). +An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), task images (`jobs::task-images`, same rules with `jobs.remove-any-task-image`; `GdTaskImageFiles` stores an upright, at most 2560 px JPEG without EXIF and a 400 px thumbnail under `task-images/` on the private `local` disk, served only through `ShowTaskImage` after `jobs.view-job`; `RemoveTask` also deletes the files), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`) and `Reports` (management's reports behind `reports.view`: hours by person, unbilled hours, profitability by job and service unit, quick sales and expense reimbursements, each a `reports::` page with a period in the URL (`ReportPage` trait, `alku`/`loppu`), tables, a `` (TallStackUI's server-side `` as one image) and a CSV from `DownloadReport`; it reads the other modules only through its ports `ReportHours`, `ReportJobs`, `ReportCatalog`, `ReportPeople`, `ReportSales`, `ReportExpenses` and `ReportRevenue`, whose adapters call those modules' report queries (`TimeReportQueries`, `CustomerJobQueries::reportInfoOf`, `QuickSaleReportQueries`, `ExpenseReportQueries`, `BilledRevenueQueries`); hours are costed at the one internal hourly cost `catalog.internal_hourly_cost_cents`, set on the Hinnasto maintenance page)); `/` (route `home`) is the home page of the `Dashboard` module (`dashboard::home`: the user's open tasks on an agenda (late, today and tomorrow, this week), their open jobs, this week's hours and quick links; for admin and management also `dashboard::management`, loaded with `lazy="on-load"` behind `dashboard.management`: things to do, the month so far against the same days of the previous month through the Reports use cases, jobs by status and late work, and everyone's workload from the task calendar against `jobs.daily_capacity_hours` × working days; it reads the other modules through its ports `DashboardWork`, `DashboardTime`, `DashboardAdmin` and `DashboardFigures`, Jobs' `JobOverviewQueries` among them). The layout `resources/views/layouts/app.blade.php` has the main menu and logout for signed-in users. - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification 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. @@ -23,7 +23,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `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`, `reports.view`, 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]`. +- **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`, `reports.view`, `dashboard.management`, 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 (incl. the reports), 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`). diff --git a/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php b/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php new file mode 100644 index 0000000..425b14a --- /dev/null +++ b/app/Modules/Dashboard/Application/Contracts/DashboardAdmin.php @@ -0,0 +1,38 @@ + + */ + public function unclosedCashDaysBefore(string $day): array; + + /** + * Active users who do the work, subcontractors left out, by name. + * + * @return array + */ + public function staff(): array; + + /** + * Public holidays in use and company days off between the days. + * + * @return list + */ + public function holidaysBetween(string $from, string $to): array; +} diff --git a/app/Modules/Dashboard/Application/Contracts/DashboardFigures.php b/app/Modules/Dashboard/Application/Contracts/DashboardFigures.php new file mode 100644 index 0000000..5176997 --- /dev/null +++ b/app/Modules/Dashboard/Application/Contracts/DashboardFigures.php @@ -0,0 +1,24 @@ + + */ + public function pendingApprovals(): array; +} diff --git a/app/Modules/Dashboard/Application/Contracts/DashboardWork.php b/app/Modules/Dashboard/Application/Contracts/DashboardWork.php new file mode 100644 index 0000000..c9291c6 --- /dev/null +++ b/app/Modules/Dashboard/Application/Contracts/DashboardWork.php @@ -0,0 +1,52 @@ + + */ + public function openTasksOf(int $userId): array; + + /** + * @return list + */ + public function openJobsOf(int $userId): array; + + /** + * @return array Kanban status key => jobs. + */ + public function jobCountsByStatus(): array; + + public function overdueJobCount(string $today): int; + + public function overdueTaskCount(string $today): int; + + /** + * @return list + */ + public function oldestOverdueTasks(string $today, int $limit): array; + + /** + * The daily maximum a person's tasks may book, in minutes. + */ + public function dailyCapacityMinutes(): int; + + /** + * Minutes the open tasks book per person in the days. + * + * @param list $userIds + * @return array + */ + public function bookedMinutes(array $userIds, string $from, string $to): array; +} diff --git a/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php b/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php new file mode 100644 index 0000000..1711227 --- /dev/null +++ b/app/Modules/Dashboard/Application/DTOs/ManagementOverview.php @@ -0,0 +1,46 @@ + $pendingApprovals + * @param list $unclosedCashDays + * @param array $jobCounts + * @param list $oldestOverdueTasks + * @param list $workloads + */ + public function __construct( + public array $pendingApprovals, + public int $doneJobCount, + public ?int $draftExportId, + public array $unclosedCashDays, + public int $unbilledValueCents, + public string $monthFrom, + public string $monthTo, + public string $previousFrom, + public string $previousTo, + public PeriodFigures $month, + public PeriodFigures $previousMonth, + public array $jobCounts, + public int $overdueJobCount, + public int $overdueTaskCount, + public array $oldestOverdueTasks, + public string $thisMonday, + public string $nextMonday, + public array $workloads, + ) {} +} diff --git a/app/Modules/Dashboard/Application/DTOs/PendingApproval.php b/app/Modules/Dashboard/Application/DTOs/PendingApproval.php new file mode 100644 index 0000000..d3e4a13 --- /dev/null +++ b/app/Modules/Dashboard/Application/DTOs/PendingApproval.php @@ -0,0 +1,18 @@ + $overdue + * @param list $soon + * @param list $thisWeek + * @param list $jobs + */ + public function __construct( + public array $overdue, + public array $soon, + public array $thisWeek, + public int $laterCount, + public array $jobs, + public int $jobCount, + public WeekHours $week, + ) {} + + public function hasTasks(): bool + { + return $this->overdue !== [] || $this->soon !== [] || $this->thisWeek !== [] || $this->laterCount > 0; + } +} diff --git a/app/Modules/Dashboard/Application/DTOs/WeekHours.php b/app/Modules/Dashboard/Application/DTOs/WeekHours.php new file mode 100644 index 0000000..a3d1f2c --- /dev/null +++ b/app/Modules/Dashboard/Application/DTOs/WeekHours.php @@ -0,0 +1,22 @@ + $days + */ + public function __construct( + public string $monday, + public array $days, + public int $totalQuarters, + public int $unapprovedQuarters, + ) {} +} diff --git a/app/Modules/Dashboard/Application/DTOs/WorkJob.php b/app/Modules/Dashboard/Application/DTOs/WorkJob.php new file mode 100644 index 0000000..6d3f4f5 --- /dev/null +++ b/app/Modules/Dashboard/Application/DTOs/WorkJob.php @@ -0,0 +1,28 @@ +id, $this->number, $this->name, $this->customerName, $this->status, $this->priority, $this->dueOn, true); + } +} diff --git a/app/Modules/Dashboard/Application/DTOs/WorkTask.php b/app/Modules/Dashboard/Application/DTOs/WorkTask.php new file mode 100644 index 0000000..a2db77b --- /dev/null +++ b/app/Modules/Dashboard/Application/DTOs/WorkTask.php @@ -0,0 +1,31 @@ +taskId, $this->jobId, $this->jobNumber, $this->jobName, $this->title, $this->status, $this->dueOn, $this->plannedFrom, $this->plannedTo, $this->assigneeName, true); + } +} diff --git a/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php b/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php new file mode 100644 index 0000000..30e47ee --- /dev/null +++ b/app/Modules/Dashboard/Application/UseCases/ManagementOverviewQuery.php @@ -0,0 +1,98 @@ +format('Y-m-d'); + $monthFrom = $today->format('Y-m-01'); + $previousStart = $today->modify('first day of previous month'); + $previousFrom = $previousStart->format('Y-m-d'); + $previousTo = $previousStart->format('Y-m-').sprintf('%02d', min((int) $today->format('j'), (int) $previousStart->format('t'))); + + $jobCounts = $this->work->jobCountsByStatus(); + + $thisMonday = $today->modify('monday this week'); + $nextMonday = $thisMonday->modify('+7 days'); + + return new ManagementOverview( + $this->time->pendingApprovals(), + $jobCounts['done'] ?? 0, + $this->admin->openDraftId(), + $this->admin->unclosedCashDaysBefore($day), + $this->figures->unbilledValueCents($day), + $monthFrom, + $day, + $previousFrom, + $previousTo, + $this->figures->between($monthFrom, $day), + $this->figures->between($previousFrom, $previousTo), + $jobCounts, + $this->work->overdueJobCount($day), + $this->work->overdueTaskCount($day), + array_map(fn (WorkTask $task): WorkTask => $task->late(), $this->work->oldestOverdueTasks($day, self::OVERDUE_TASK_LIMIT)), + $thisMonday->format('Y-m-d'), + $nextMonday->format('Y-m-d'), + $this->workloads($thisMonday, $nextMonday), + ); + } + + /** + * @return list + */ + private function workloads(DateTimeImmutable $thisMonday, DateTimeImmutable $nextMonday): array + { + $staff = $this->admin->staff(); + $daily = $this->work->dailyCapacityMinutes(); + $weeks = []; + + foreach ([$thisMonday, $nextMonday] as $monday) { + $from = $monday->format('Y-m-d'); + $to = $monday->modify('+6 days')->format('Y-m-d'); + $weeks[] = [ + 'booked' => $this->work->bookedMinutes(array_keys($staff), $from, $to), + 'days' => Workload::workingDays($from, $to, $this->admin->holidaysBetween($from, $to)), + ]; + } + + $result = []; + foreach ($staff as $userId => $name) { + $result[] = new PersonLoad( + $userId, + $name, + Workload::of($weeks[0]['booked'][$userId] ?? 0, $daily, $weeks[0]['days']), + Workload::of($weeks[1]['booked'][$userId] ?? 0, $daily, $weeks[1]['days']), + ); + } + + return $result; + } +} diff --git a/app/Modules/Dashboard/Application/UseCases/PersonalOverviewQuery.php b/app/Modules/Dashboard/Application/UseCases/PersonalOverviewQuery.php new file mode 100644 index 0000000..df22f2f --- /dev/null +++ b/app/Modules/Dashboard/Application/UseCases/PersonalOverviewQuery.php @@ -0,0 +1,55 @@ +format('Y-m-d'); + $tomorrow = $today->modify('+1 day')->format('Y-m-d'); + $monday = $today->modify('monday this week'); + $sunday = $monday->modify('+6 days')->format('Y-m-d'); + + $buckets = ['overdue' => [], 'soon' => [], 'this_week' => [], 'later' => []]; + foreach ($this->work->openTasksOf($userId) as $task) { + $bucket = AgendaBucket::of($task->dueOn, $task->plannedFrom, $day, $tomorrow, $sunday); + $buckets[$bucket->value][] = $bucket === AgendaBucket::Overdue ? $task->late() : $task; + } + + $jobs = array_map( + fn (WorkJob $job): WorkJob => $job->dueOn !== null && $job->dueOn < $day ? $job->late() : $job, + $this->work->openJobsOf($userId), + ); + + return new PersonalOverview( + $buckets['overdue'], + $buckets['soon'], + $buckets['this_week'], + count($buckets['later']), + array_slice($jobs, 0, self::JOB_LIMIT), + count($jobs), + $this->time->week($userId, $monday->format('Y-m-d')), + ); + } +} diff --git a/app/Modules/Dashboard/Domain/Enums/AgendaBucket.php b/app/Modules/Dashboard/Domain/Enums/AgendaBucket.php new file mode 100644 index 0000000..7ce8d87 --- /dev/null +++ b/app/Modules/Dashboard/Domain/Enums/AgendaBucket.php @@ -0,0 +1,36 @@ + self::Soon, + $nearest <= $weekEnd => self::ThisWeek, + default => self::Later, + }; + } +} diff --git a/app/Modules/Dashboard/Domain/ValueObjects/Change.php b/app/Modules/Dashboard/Domain/ValueObjects/Change.php new file mode 100644 index 0000000..9fdd837 --- /dev/null +++ b/app/Modules/Dashboard/Domain/ValueObjects/Change.php @@ -0,0 +1,23 @@ +previous === 0 ? null : ($this->current - $this->previous) / abs($this->previous); + } +} diff --git a/app/Modules/Dashboard/Domain/ValueObjects/Workload.php b/app/Modules/Dashboard/Domain/ValueObjects/Workload.php new file mode 100644 index 0000000..d9ef8b5 --- /dev/null +++ b/app/Modules/Dashboard/Domain/ValueObjects/Workload.php @@ -0,0 +1,55 @@ +capacityMinutes === 0 ? null : $this->bookedMinutes / $this->capacityMinutes; + } + + public function isOverloaded(): bool + { + return $this->bookedMinutes > $this->capacityMinutes; + } + + /** + * Weekdays (Monday to Friday) between the days (Y-m-d, both included) + * that are not among the holidays. + * + * @param list $holidays + */ + public static function workingDays(string $from, string $to, array $holidays): int + { + $days = 0; + + for ($day = new \DateTimeImmutable($from); $day->format('Y-m-d') <= $to; $day = $day->modify('+1 day')) { + if ((int) $day->format('N') <= 5 && ! in_array($day->format('Y-m-d'), $holidays, true)) { + $days++; + } + } + + return $days; + } +} diff --git a/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php b/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php new file mode 100644 index 0000000..f8db49f --- /dev/null +++ b/app/Modules/Dashboard/Infrastructure/Adapters/AdminForDashboard.php @@ -0,0 +1,59 @@ +billing->exports() as $export) { + if ($export->status === ExportStatus::Draft) { + return $export->id; + } + } + + return null; + } + + public function unclosedCashDaysBefore(string $day): array + { + return $this->sales->unclosedDaysBefore($day); + } + + public function staff(): array + { + $staff = []; + + foreach ($this->users->activeUserOptions() as $user) { + if ($user->role !== Role::Subcontractor) { + $staff[$user->id] = $user->name; + } + } + + return $staff; + } + + public function holidaysBetween(string $from, string $to): array + { + return $this->holidays->activeDatesBetween($from, $to); + } +} diff --git a/app/Modules/Dashboard/Infrastructure/Adapters/FiguresForDashboard.php b/app/Modules/Dashboard/Infrastructure/Adapters/FiguresForDashboard.php new file mode 100644 index 0000000..b35e507 --- /dev/null +++ b/app/Modules/Dashboard/Infrastructure/Adapters/FiguresForDashboard.php @@ -0,0 +1,45 @@ +hours->execute($period)->total; + $profit = $this->profitability->execute($period)->total; + + return new PeriodFigures( + $hours->customerQuarters, + $hours->internalQuarters, + $profit->revenueCents(), + $profit->marginCents(), + $this->sales->execute($period)->totalCents(), + ); + } + + public function unbilledValueCents(string $day): int + { + return $this->unbilled->execute($day)->valueCents; + } +} diff --git a/app/Modules/Dashboard/Infrastructure/Adapters/TimeForDashboard.php b/app/Modules/Dashboard/Infrastructure/Adapters/TimeForDashboard.php new file mode 100644 index 0000000..ad6361b --- /dev/null +++ b/app/Modules/Dashboard/Infrastructure/Adapters/TimeForDashboard.php @@ -0,0 +1,38 @@ +entries->week($userId, $monday); + + return new WeekHours($monday, $sheet->dayTotals, $sheet->totalQuarters, $sheet->unapprovedQuarters); + } + + public function pendingApprovals(): array + { + $people = []; + + foreach ($this->entries->pendingWeeks() as $week) { + $current = $people[$week->userId] ?? new PendingApproval($week->userId, $week->userName, 0, 0); + $people[$week->userId] = new PendingApproval($week->userId, $week->userName, $current->quarters + $week->quarters, $current->weekCount + 1); + } + + $people = array_values($people); + usort($people, fn (PendingApproval $a, PendingApproval $b): int => strnatcasecmp($a->name, $b->name)); + + return $people; + } +} diff --git a/app/Modules/Dashboard/Infrastructure/Adapters/WorkForDashboard.php b/app/Modules/Dashboard/Infrastructure/Adapters/WorkForDashboard.php new file mode 100644 index 0000000..10c6c2e --- /dev/null +++ b/app/Modules/Dashboard/Infrastructure/Adapters/WorkForDashboard.php @@ -0,0 +1,88 @@ +overview->openTasksOf($userId)); + } + + public function openJobsOf(int $userId): array + { + return array_map(fn (CustomerJobSummary $job): WorkJob => new WorkJob( + $job->id, + $job->number, + $job->name, + $job->customerName, + $job->status->value, + $job->priority->value, + $job->dueOn, + ), $this->overview->openJobsOf($userId)); + } + + public function jobCountsByStatus(): array + { + return $this->overview->jobCountsByStatus(); + } + + public function overdueJobCount(string $today): int + { + return $this->overview->overdueJobCount($today); + } + + public function overdueTaskCount(string $today): int + { + return $this->overview->overdueTaskCount($today); + } + + public function oldestOverdueTasks(string $today, int $limit): array + { + return array_map(self::task(...), $this->overview->oldestOverdueTasks($today, $limit)); + } + + public function dailyCapacityMinutes(): int + { + return $this->planner->capacityMinutes(); + } + + public function bookedMinutes(array $userIds, string $from, string $to): array + { + return array_map(fn (array $days): int => array_sum($days), $this->calendar->openMinutesByUser($userIds, $from, $to)); + } + + private static function task(OpenTask $task): WorkTask + { + return new WorkTask( + $task->taskId, + $task->jobId, + $task->jobNumber, + $task->jobName, + $task->title, + $task->status->value, + $task->dueOn, + $task->plannedFrom, + $task->plannedTo, + $task->assigneeName, + ); + } +} diff --git a/app/Modules/Dashboard/Infrastructure/Providers/DashboardServiceProvider.php b/app/Modules/Dashboard/Infrastructure/Providers/DashboardServiceProvider.php new file mode 100644 index 0000000..06fa966 --- /dev/null +++ b/app/Modules/Dashboard/Infrastructure/Providers/DashboardServiceProvider.php @@ -0,0 +1,48 @@ + + */ + public array $bindings = [ + DashboardWork::class => WorkForDashboard::class, + DashboardTime::class => TimeForDashboard::class, + DashboardAdmin::class => AdminForDashboard::class, + DashboardFigures::class => FiguresForDashboard::class, + ]; + + public function boot(): void + { + $presentationPath = dirname(__DIR__, 2).'/Presentation'; + + Livewire::addNamespace('dashboard', viewPath: $presentationPath.'/Livewire'); + + if (! $this->app->routesAreCached()) { + $this->loadRoutesFrom($presentationPath.'/Routes/web.php'); + } + + // The management panel of the home page: admin and management. + Gate::define('dashboard.management', fn (User $user): bool => $user->role->seesAllMoney()); + } +} diff --git a/app/Modules/Dashboard/Presentation/Livewire/Concerns/FormatsDashboard.php b/app/Modules/Dashboard/Presentation/Livewire/Concerns/FormatsDashboard.php new file mode 100644 index 0000000..5040db5 --- /dev/null +++ b/app/Modules/Dashboard/Presentation/Livewire/Concerns/FormatsDashboard.php @@ -0,0 +1,39 @@ +format(); + } + + /** + * E.g. 6 quarters → "1,5". + */ + public function hours(int $quarters): string + { + return rtrim(rtrim(number_format($quarters / 4, 2, ',', "\u{00A0}"), '0'), ','); + } + + /** + * E.g. 0.125 → "12,5 %". + */ + public function percent(float $ratio): string + { + return number_format($ratio * 100, 1, ',', "\u{00A0}")."\u{00A0}%"; + } + + public function dateLabel(string $day): string + { + return (new DateTimeImmutable($day))->format('j.n.Y'); + } +} diff --git a/app/Modules/Dashboard/Presentation/Livewire/⚡home.blade.php b/app/Modules/Dashboard/Presentation/Livewire/⚡home.blade.php new file mode 100644 index 0000000..98b08f7 --- /dev/null +++ b/app/Modules/Dashboard/Presentation/Livewire/⚡home.blade.php @@ -0,0 +1,195 @@ +execute((int) auth()->id(), app(Clock::class)->today()); + } + + /** + * @return list + */ + public function quickLinks(): array + { + $links = [ + ['route' => 'jobs.quick', 'label' => __('dashboard.links.quick_intake'), 'icon' => 'bolt', 'ability' => 'jobs.manage'], + ['route' => 'jobs.create', 'label' => __('dashboard.links.new_job'), 'icon' => 'plus', 'ability' => 'jobs.manage'], + ['route' => 'time.week', 'label' => __('dashboard.links.time'), 'icon' => 'clock', 'ability' => 'time.use'], + ['route' => 'sales.sell', 'label' => __('dashboard.links.quick_sale'), 'icon' => 'shopping-cart', 'ability' => 'sales.use'], + ['route' => 'jobs.calendar', 'label' => __('dashboard.links.calendar'), 'icon' => 'calendar-days', 'ability' => 'jobs.view'], + ]; + + return array_values(array_map( + fn (array $link): array => ['route' => $link['route'], 'label' => $link['label'], 'icon' => $link['icon']], + array_filter($links, fn (array $link): bool => Gate::allows($link['ability'])), + )); + } + + public function dayName(string $day): string + { + return __('time.days')[(int) (new DateTimeImmutable($day))->format('N') - 1]; + } + + public function render(): mixed + { + return $this->view()->title(__('dashboard.title')); + } +}; +?> + +
+

{{ __('dashboard.greeting', ['name' => auth()->user()->name]) }}

+ + @php($overview = $this->overview) + + + +
+
+

{{ __('dashboard.tasks.title') }}

+ + @if (! $overview->hasTasks()) +

{{ __('dashboard.tasks.none') }}

+ @endif + + @foreach (['overdue' => $overview->overdue, 'soon' => $overview->soon, 'this_week' => $overview->thisWeek] as $group => $tasks) + @if ($tasks !== []) +
+

+ @if ($group === 'overdue') +

+
    + @foreach ($tasks as $task) +
  • + {{ $task->title }} + {{ $task->jobNumber }} {{ $task->jobName }} + + {{ __('jobs.tasks.statuses.'.$task->status) }} + @if ($task->dueOn !== null) + {{ __('dashboard.tasks.due', ['date' => $this->dateLabel($task->dueOn)]) }} + @endif + @if ($task->plannedFrom !== null) + {{ __('dashboard.tasks.starts', ['date' => $this->dateLabel($task->plannedFrom)]) }} + @endif + @if ($task->isLate) + + + @endif + +
  • + @endforeach +
+
+ @endif + @endforeach + + @if ($overview->laterCount > 0) +

{{ trans_choice('dashboard.tasks.later', $overview->laterCount, ['count' => $overview->laterCount]) }}

+

{{ __('dashboard.tasks.to_calendar') }}

+ @endif +
+ +
+
+

{{ __('dashboard.week.title') }}

+ + + + + + @foreach (array_keys($overview->week->days) as $day) + + @endforeach + + + + + @foreach ($overview->week->days as $quarters) + + @endforeach + + +
{{ __('dashboard.week.caption', ['from' => $this->dateLabel($overview->week->monday)]) }}
+ {{ $this->dayName($day) }} + {{ (new DateTimeImmutable($day))->format('j.n.') }} +
{{ $this->hours($quarters) }}
+ +

+ {{ __('dashboard.week.total', ['hours' => $this->hours($overview->week->totalQuarters)]) }} + @if ($overview->week->unapprovedQuarters > 0) + + + @endif +

+

{{ __('dashboard.week.open') }}

+
+ +
+

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

+ + @if ($overview->jobs === []) +

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

+ @else +
    + @foreach ($overview->jobs as $job) +
  • + {{ $job->number }} {{ $job->name }} + {{ $job->customerName }} + + {{ __('jobs.statuses.'.$job->status) }} + + @if ($job->dueOn !== null) + {{ __('dashboard.jobs.due', ['date' => $this->dateLabel($job->dueOn)]) }} + @endif + @if ($job->isLate) + + + @endif + +
  • + @endforeach +
+ @endif + +

+ {{ trans_choice('dashboard.jobs.all', $overview->jobCount, ['count' => $overview->jobCount]) }} +

+
+
+
+ + @can('dashboard.management') + {{-- Loaded right after the page, not only when scrolled to. --}} + + @endcan +
diff --git a/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php b/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php new file mode 100644 index 0000000..d3f9700 --- /dev/null +++ b/app/Modules/Dashboard/Presentation/Livewire/⚡management.blade.php @@ -0,0 +1,244 @@ +authorize('dashboard.management'); + } + + #[Computed] + public function overview(): ManagementOverview + { + return app(ManagementOverviewQuery::class)->execute(app(Clock::class)->today()); + } + + public function placeholder(): string + { + return '

'.e(__('dashboard.management.loading')).'

'; + } + + /** + * E.g. "+12,5 % edelliseen", or "ei vertailukohtaa" when the earlier value was zero. + */ + public function change(int $current, int $previous): string + { + $ratio = (new Change($current, $previous))->ratio(); + + if ($ratio === null) { + return __('dashboard.management.no_comparison'); + } + + return __('dashboard.management.change', ['change' => ($ratio > 0 ? '+' : ($ratio < 0 ? '−' : '±')).$this->percent(abs($ratio))]); + } + + public function load(Workload $load): string + { + $ratio = $load->ratio(); + + return $ratio === null ? '–' : $this->percent($ratio); + } + + public function render(): mixed + { + return $this->view(); + } +}; +?> + +
+ @php($overview = $this->overview) + +

{{ __('dashboard.management.title') }}

+ +
+
+

{{ __('dashboard.todo.title') }}

+ +
    + @can('time.approve-others') +
  • + + {{ trans_choice('dashboard.todo.approvals', count($overview->pendingApprovals), ['count' => count($overview->pendingApprovals)]) }} + + @if ($overview->pendingApprovals !== []) +
      + @foreach ($overview->pendingApprovals as $pending) +
    • {{ __('dashboard.todo.approval_line', ['name' => $pending->name, 'hours' => $this->hours($pending->quarters), 'weeks' => $pending->weekCount]) }}
    • + @endforeach +
    + @endif +
  • + @endcan + @can('billing.manage') +
  • + {{ trans_choice('dashboard.todo.done_jobs', $overview->doneJobCount, ['count' => $overview->doneJobCount]) }} +
  • + @if ($overview->draftExportId !== null) +
  • {{ __('dashboard.todo.draft') }}
  • + @endif + @endcan + @can('sales.close-day') + @if ($overview->unclosedCashDays !== []) +
  • + + {{ trans_choice('dashboard.todo.cash_days', count($overview->unclosedCashDays), ['count' => count($overview->unclosedCashDays), 'first' => $this->dateLabel($overview->unclosedCashDays[0])]) }} + +
  • + @endif + @endcan + @can('reports.view') +
  • + {{ __('dashboard.todo.unbilled', ['amount' => $this->money($overview->unbilledValueCents)]) }} +
  • + @endcan +
+
+ + @can('reports.view') +
+

{{ __('dashboard.month.title') }}

+

+ {{ __('dashboard.month.period', [ + 'from' => $this->dateLabel($overview->monthFrom), 'to' => $this->dateLabel($overview->monthTo), + 'previous_from' => $this->dateLabel($overview->previousFrom), 'previous_to' => $this->dateLabel($overview->previousTo), + ]) }} +

+ + @php($month = $overview->month) + @php($previous = $overview->previousMonth) +
+ @foreach ([ + ['label' => 'customer_hours', 'value' => $this->hours($month->customerQuarters).' h', 'current' => $month->customerQuarters, 'previous' => $previous->customerQuarters, 'route' => 'reports.hours'], + ['label' => 'internal_hours', 'value' => $this->hours($month->internalQuarters).' h', 'current' => $month->internalQuarters, 'previous' => $previous->internalQuarters, 'route' => 'reports.hours'], + ['label' => 'billed', 'value' => $this->money($month->billedCents), 'current' => $month->billedCents, 'previous' => $previous->billedCents, 'route' => 'reports.profitability'], + ['label' => 'margin', 'value' => $month->marginCents === null ? __('dashboard.month.no_cost') : $this->money($month->marginCents), 'current' => $month->marginCents, 'previous' => $previous->marginCents, 'route' => 'reports.profitability'], + ['label' => 'sales', 'value' => $this->money($month->salesCents), 'current' => $month->salesCents, 'previous' => $previous->salesCents, 'route' => 'reports.sales'], + ] as $figure) +
+
+ {{ __('dashboard.month.'.$figure['label']) }} +
+
{{ $figure['value'] }}
+ @if ($figure['current'] !== null && $figure['previous'] !== null) +
{{ $this->change($figure['current'], $figure['previous']) }}
+ @endif +
+ @endforeach +
+

{{ __('dashboard.month.billing_note') }}

+
+ @endcan +
+ +
+
+

{{ __('dashboard.stock.title') }}

+ + + + + + + + + + + @foreach ($overview->jobCounts as $status => $count) + + + + + @endforeach + +
{{ __('dashboard.stock.caption') }}
{{ __('dashboard.stock.status') }}{{ __('dashboard.stock.count') }}
+ {{ __('jobs.statuses.'.$status) }} + {{ $count }}
+ +

+ @if ($overview->overdueJobCount > 0) +

+

+ @if ($overview->overdueTaskCount > 0) +

+ + @if ($overview->oldestOverdueTasks !== []) +

{{ __('dashboard.stock.oldest_overdue') }}

+
    + @foreach ($overview->oldestOverdueTasks as $task) +
  • + {{ $task->title }} + + {{ $task->jobNumber }} {{ $task->jobName }} · {{ $task->assigneeName ?? __('dashboard.stock.no_assignee') }} + · {{ __('dashboard.tasks.due', ['date' => $this->dateLabel((string) $task->dueOn)]) }} + +
  • + @endforeach +
+ @endif +
+ +
+

{{ __('dashboard.load.title') }}

+ + @if ($overview->workloads === []) +

{{ __('dashboard.load.none') }}

+ @else +
+ + + + + + + + + + + @foreach ($overview->workloads as $person) + + + @foreach ([$person->thisWeek, $person->nextWeek] as $index => $load) + + @endforeach + + @endforeach + +
{{ __('dashboard.load.caption') }}
{{ __('dashboard.load.person') }}{{ __('dashboard.load.week', ['from' => $this->dateLabel($overview->thisMonday)]) }}{{ __('dashboard.load.week', ['from' => $this->dateLabel($overview->nextMonday)]) }}
{{ $person->name }} + {{ __('dashboard.load.value', ['booked' => $this->hours(intdiv($load->bookedMinutes, 15)), 'capacity' => $this->hours(intdiv($load->capacityMinutes, 15)), 'ratio' => $this->load($load)]) }} + @if ($load->isOverloaded()) + + + @endif +
+
+

{{ __('dashboard.load.note') }}

+

{{ __('dashboard.load.to_calendar') }}

+ @endif +
+
+
diff --git a/app/Modules/Dashboard/Presentation/Routes/web.php b/app/Modules/Dashboard/Presentation/Routes/web.php new file mode 100644 index 0000000..31a8992 --- /dev/null +++ b/app/Modules/Dashboard/Presentation/Routes/web.php @@ -0,0 +1,7 @@ +group(function () { + Route::livewire('/', 'dashboard::home')->name('home'); +}); diff --git a/app/Modules/Jobs/Application/Contracts/JobOverviewQueries.php b/app/Modules/Jobs/Application/Contracts/JobOverviewQueries.php new file mode 100644 index 0000000..c9457e6 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/JobOverviewQueries.php @@ -0,0 +1,55 @@ + + */ + public function openTasksOf(int $userId): array; + + /** + * The user's own jobs (5.6) that are still open (before done), by due + * date (none last), then newest first. + * + * @return list + */ + public function openJobsOf(int $userId): array; + + /** + * Jobs by Kanban status key (archived left out), every status included. + * + * @return array + */ + public function jobCountsByStatus(): array; + + /** + * Open jobs (before done) whose due date is before the day. + */ + public function overdueJobCount(string $today): int; + + /** + * Open tasks whose due date is before the day. + */ + public function overdueTaskCount(string $today): int; + + /** + * The open tasks that have been late the longest. + * + * @return list + */ + public function oldestOverdueTasks(string $today, int $limit): array; +} diff --git a/app/Modules/Jobs/Application/DTOs/OpenTask.php b/app/Modules/Jobs/Application/DTOs/OpenTask.php new file mode 100644 index 0000000..54b1824 --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/OpenTask.php @@ -0,0 +1,28 @@ +locksTime(); + } + + /** + * @return list + */ + public static function openStatuses(): array + { + return array_values(array_filter(self::cases(), fn (self $status): bool => $status->isOpen())); + } + /** * Whether moving from this status to $to opens the lock on hours and expenses. */ diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentJobOverviewQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentJobOverviewQueries.php new file mode 100644 index 0000000..d9ad451 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentJobOverviewQueries.php @@ -0,0 +1,137 @@ +openTasks() + ->where(fn (Builder $query) => $query + ->where('tasks.assignee_user_id', $userId) + ->orWhereIn('tasks.id', DB::table('task_members')->select('task_id')->where('user_id', $userId))) + ->orderByRaw('tasks.due_on IS NULL') + ->orderBy('tasks.due_on') + ->orderByRaw('tasks.planned_from IS NULL') + ->orderBy('tasks.planned_from') + ->orderBy('tasks.id'); + + return $this->toOpenTasks($query); + } + + public function openJobsOf(int $userId): array + { + $query = DB::table('customer_jobs') + ->whereIn('status', array_map(fn (JobStatus $status): string => $status->value, JobStatus::openStatuses())) + ->whereNull('quick_sale_year'); + JobInvolvement::restrict($query, $userId); + + $ids = $query->orderByRaw('due_on IS NULL')->orderBy('due_on')->orderByDesc('id') + ->pluck('id')->map(fn ($id): int => (int) $id)->all(); + $summaries = $this->jobs->summariesByIds($ids); + + return array_values(array_filter(array_map(fn (int $id): ?CustomerJobSummary => $summaries[$id] ?? null, $ids))); + } + + public function jobCountsByStatus(): array + { + $counts = DB::table('customer_jobs') + ->where('status', '!=', JobStatus::Archived->value) + ->groupBy('status') + ->selectRaw('status, COUNT(*) as job_count') + ->pluck('job_count', 'status'); + + $result = []; + foreach (JobStatus::kanbanStatuses() as $status) { + $result[$status->value] = (int) ($counts[$status->value] ?? 0); + } + + return $result; + } + + public function overdueJobCount(string $today): int + { + return DB::table('customer_jobs') + ->whereIn('status', array_map(fn (JobStatus $status): string => $status->value, JobStatus::openStatuses())) + ->whereNull('quick_sale_year') + ->whereNotNull('due_on') + ->where('due_on', '<', $today) + ->count(); + } + + public function overdueTaskCount(string $today): int + { + return $this->overdueTasks($today)->count(); + } + + public function oldestOverdueTasks(string $today, int $limit): array + { + return $this->toOpenTasks($this->overdueTasks($today)->orderBy('tasks.due_on')->orderBy('tasks.id')->limit($limit)); + } + + private function overdueTasks(string $today): Builder + { + return $this->openTasks()->whereNotNull('tasks.due_on')->where('tasks.due_on', '<', $today); + } + + private function openTasks(): Builder + { + return DB::table('tasks') + ->join('customer_jobs', 'customer_jobs.id', '=', 'tasks.customer_job_id') + ->where('tasks.status', '!=', TaskStatus::Done->value) + ->where('customer_jobs.status', '!=', JobStatus::Archived->value) + ->whereNull('customer_jobs.quick_sale_year'); + } + + /** + * @return list + */ + private function toOpenTasks(Builder $query): array + { + $rows = $query->get([ + 'tasks.id', 'tasks.customer_job_id', 'tasks.title', 'tasks.status', 'tasks.due_on', 'tasks.planned_from', 'tasks.planned_to', 'tasks.assignee_user_id', + 'customer_jobs.number', 'customer_jobs.name', + ]); + + $assigneeIds = $rows->pluck('assignee_user_id')->filter()->map(fn ($id): int => (int) $id)->unique()->values()->all(); + $names = $assigneeIds === [] ? [] : $this->users->namesByIds($assigneeIds); + + return $rows->map(fn (object $row): OpenTask => new OpenTask( + (int) $row->id, + (int) $row->customer_job_id, + (string) $row->number, + (string) $row->name, + (string) $row->title, + TaskStatus::from((string) $row->status), + self::day($row->due_on), + self::day($row->planned_from), + self::day($row->planned_to), + $row->assignee_user_id === null ? null : (int) $row->assignee_user_id, + $row->assignee_user_id === null ? null : ($names[(int) $row->assignee_user_id] ?? null), + ))->values()->all(); + } + + private static function day(mixed $value): ?string + { + return $value === null ? null : substr((string) $value, 0, 10); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index f7bc221..7c93aff 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -7,6 +7,7 @@ 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\JobOverviewQueries; use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries; use App\Modules\Jobs\Application\Contracts\TaskCommentQueries; use App\Modules\Jobs\Application\Contracts\TaskImageFiles; @@ -30,6 +31,7 @@ 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\EloquentJobOverviewQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBookingRepository; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCommentQueries; @@ -62,6 +64,7 @@ class JobsServiceProvider extends ServiceProvider TaskQueries::class => EloquentTaskQueries::class, TaskBookingRepository::class => EloquentTaskBookingRepository::class, TaskCalendarQueries::class => EloquentTaskCalendarQueries::class, + JobOverviewQueries::class => EloquentJobOverviewQueries::class, ChecklistItemRepository::class => EloquentChecklistItemRepository::class, ChecklistQueries::class => EloquentChecklistQueries::class, TaskCommentRepository::class => EloquentTaskCommentRepository::class, diff --git a/bootstrap/providers.php b/bootstrap/providers.php index e75f79a..eca145e 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -3,6 +3,7 @@ use App\Modules\Billing\Infrastructure\Providers\BillingServiceProvider; use App\Modules\Catalog\Infrastructure\Providers\CatalogServiceProvider; use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider; +use App\Modules\Dashboard\Infrastructure\Providers\DashboardServiceProvider; use App\Modules\Expenses\Infrastructure\Providers\ExpensesServiceProvider; use App\Modules\Jobs\Infrastructure\Providers\JobsServiceProvider; use App\Modules\Notifications\Infrastructure\Providers\NotificationsServiceProvider; @@ -28,4 +29,5 @@ return [ BillingServiceProvider::class, NotificationsServiceProvider::class, ReportsServiceProvider::class, + DashboardServiceProvider::class, ]; diff --git a/config/livewire.php b/config/livewire.php index 1f586b3..42f6199 100644 --- a/config/livewire.php +++ b/config/livewire.php @@ -31,7 +31,6 @@ return [ 'component_namespaces' => [ 'layouts' => resource_path('views/layouts'), - 'pages' => resource_path('views/pages'), ], /* diff --git a/docs/maarittely.md b/docs/maarittely.md index 6aa425f..b45a277 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -328,7 +328,11 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. - **CSV-lataus** *(valmis)*: muodostetun aineiston saa ladattua CSV-tiedostona (Excel-yhteensopiva: puolipiste, UTF-8 BOM; rahasummat kokonaisina sentteinä, esim. 400,00 € = 40000, ALV-kanta promilleina, esim. 10 % = 100 ja 25,5 % = 255, tunnit desimaalipilkulla). Jokainen laskurivi on oma rivinsä, ja siinä on laskun numero aineistossa, asiakas, asiakastyyppi, Y-tunnus, kuluttajan henkilötunnus, laskutusyksikkö, laskutusosoite, verkkolaskuosoite ja välittäjä, viite (laskun tai laskutusyksikön), työ, rivin laji, kuvaus, kirjatut tunnit, määrä ja yksikkö (h, kk, kpl), à-hinta, ALV-kanta, veroton, ALV ja verollinen (summat sentteinä, kanta promilleina). Rivin ALV lasketaan riviltä, joten laskun ALV-summa voi erota sivun kannoittaisesta summasta sentillä. Henkilötunnus kirjoitetaan vain, jos lataajalla on oikeus nähdä se; tiedostoa ei välimuisteta, ja kaavaksi tulkittavat solut saavat eteensä heittomerkin. Sarakkeet sovitetaan Fennoan tuontimuotoon, kun esimerkki saadaan (avoin kysymys 4). - Laskutetut tunnit pysyvät hyväksyttyinä (hyväksynnän peruminen ohittaa ne), eikä laskutettua kulua voi muuttaa tai poistaa *(valmis)*. -## 13. Ilmoitukset ja raportit *(K52, K53)* +## 13. Etusivu, ilmoitukset ja raportit *(K52, K53)* + +- **Etusivu** *(valmis)*: kirjautuneen käyttäjän työpöytä. + - Kaikille: pikalinkit oikeuksien mukaan (pikavastaanotto, uusi työ, tuntikirjaus, pikamyynti, kalenteri); omat avoimet tehtävät (tekijänä tai jäsenenä, ei pikamyyntitöiden) ryhmissä *Myöhässä* (määräpäivä ohi), *Tänään ja huomenna* ja *Myöhemmin tällä viikolla* (lähin päivä: määräpäivä tai suunniteltu alku) sekä myöhempien määrä; omat avoimet asiakastyöt (5.6, tila ennen Valmis) määräajan mukaan, 10 ensimmäistä; tämän viikon kirjatut tunnit päivittäin, yhteensä ja hyväksymättä. Myöhässä näytetään aina tekstinä ja kuvakkeena. + - Pääkäyttäjälle ja johdolle lisäksi **johtajapaneeli** (ladataan sivun jälkeen): *Vaatii toimia* (hyväksymättömät tunnit henkilöittäin, valmiit työt laskuttamatta, kesken oleva laskuaineistoluonnos, päättämättömät kassapäivät, laskuttamattomien tuntien arvo), *Kuukausi tähän mennessä* verrattuna edellisen kuukauden samoihin päiviin (asiakas- ja sisäisen työn tunnit, laskutettu, kate, pikamyynnit; samat luvut kuin raporteissa), *Työkanta* (työt tiloittain, myöhässä olevat työt ja tehtävät, viisi pisimpään myöhässä ollutta tehtävää) ja *Henkilöiden kuormitus* (aktiiviset käyttäjät ilman alihankkijoita: tehtäväkalenterin varaukset tällä ja ensi viikolla suhteessa työaikaan = päiväkatto × työpäivät ilman arkipyhiä ja vapaapäiviä; yli 100 % on "Ylikuormitettu"). - 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. diff --git a/lang/en/dashboard.php b/lang/en/dashboard.php new file mode 100644 index 0000000..c228524 --- /dev/null +++ b/lang/en/dashboard.php @@ -0,0 +1,96 @@ + 'Home', + 'greeting' => 'Hello, :name', + + 'links' => [ + 'title' => 'Quick links', + 'quick_intake' => 'Quick intake', + 'new_job' => 'New job', + 'time' => 'Time entry', + 'quick_sale' => 'Quick sale', + 'calendar' => 'Calendar', + ], + + 'tasks' => [ + 'title' => 'My tasks', + 'none' => 'You have no open tasks.', + 'groups' => [ + 'overdue' => 'Late (:count)', + 'soon' => 'Today and tomorrow (:count)', + 'this_week' => 'Later this week (:count)', + ], + 'due' => 'due :date', + 'starts' => 'starts :date', + 'later' => '{1} One more task later.|[2,*] :count more tasks later.', + 'to_calendar' => 'Open the calendar', + ], + + 'week' => [ + 'title' => 'Hours this week', + 'caption' => 'Recorded hours by day in the week starting :from', + 'total' => 'Total :hours h.', + 'unapproved' => 'Not approved :hours h.', + 'open' => 'Open the weekly view', + ], + + 'jobs' => [ + 'title' => 'My customer jobs', + 'none' => 'You have no open customer jobs.', + 'due' => 'due :date', + 'all' => '{0} Customer job list|{1} All my jobs (1 open)|[2,*] All my jobs (:count open)', + ], + + 'management' => [ + 'title' => 'Management panel', + 'loading' => 'Loading the management panel…', + 'change' => ':change on the previous month', + 'no_comparison' => 'Nothing to compare with in the previous month', + ], + + 'todo' => [ + 'title' => 'To do', + 'approvals' => '{0} No hours waiting for approval|{1} One person has hours waiting for approval|[2,*] :count people have hours waiting for approval', + 'approval_line' => ':name: :hours h over :weeks weeks', + 'done_jobs' => '{0} No done jobs waiting for billing|{1} One done job is waiting for billing|[2,*] :count done jobs are waiting for billing', + 'draft' => 'A billing material draft is in progress', + 'cash_days' => '{1} Cash day :first is not closed|[2,*] :count cash days are not closed, the oldest :first', + 'unbilled' => 'Value of unbilled hours :amount', + ], + + 'month' => [ + 'title' => 'Month so far', + 'period' => ':from–:to compared with :previous_from–:previous_to.', + 'customer_hours' => 'Customer work hours', + 'internal_hours' => 'Internal work hours', + 'billed' => 'Billed (VAT 0)', + 'margin' => 'Margin (VAT 0)', + 'no_cost' => 'No hourly cost set', + 'sales' => 'Quick sales (with VAT)', + 'billing_note' => 'Billing and margin come from the billing materials created for the month.', + ], + + 'stock' => [ + 'title' => 'Jobs', + 'caption' => 'Customer jobs by status', + 'status' => 'Status', + 'count' => 'Jobs', + 'overdue_jobs' => '{0} No late jobs.|{1} One job is late.|[2,*] :count jobs are late.', + 'overdue_tasks' => '{0} No late tasks.|{1} One task is late.|[2,*] :count tasks are late.', + 'oldest_overdue' => 'Tasks late the longest', + 'no_assignee' => 'no assignee', + ], + + 'load' => [ + 'title' => 'Workload', + 'none' => 'No active users.', + 'caption' => 'Task calendar bookings against working time', + 'person' => 'Person', + 'week' => 'Week of :from', + 'value' => ':booked / :capacity h (:ratio)', + 'overloaded' => 'Overloaded', + 'note' => 'Bookings are the estimates of open tasks in the task calendar; working time is the daily maximum times the working days.', + 'to_calendar' => 'Open the calendar', + ], +]; diff --git a/lang/en/layout.php b/lang/en/layout.php index c82461d..09e3182 100644 --- a/lang/en/layout.php +++ b/lang/en/layout.php @@ -51,10 +51,4 @@ return [ 'theme_system' => 'System default', 'selected' => '(selected)', ], - 'demo' => [ - 'title' => 'Toiminnanohjaus', - 'intro' => 'Livewire and TallStackUI are working. This is a temporary test page.', - 'add_click' => 'Add click', - 'clicked' => 'Clicked :count times', - ], ]; diff --git a/lang/fi/dashboard.php b/lang/fi/dashboard.php new file mode 100644 index 0000000..47a990d --- /dev/null +++ b/lang/fi/dashboard.php @@ -0,0 +1,96 @@ + 'Etusivu', + 'greeting' => 'Hei, :name', + + 'links' => [ + 'title' => 'Pikalinkit', + 'quick_intake' => 'Pikavastaanotto', + 'new_job' => 'Uusi työ', + 'time' => 'Tuntikirjaus', + 'quick_sale' => 'Pikamyynti', + 'calendar' => 'Kalenteri', + ], + + 'tasks' => [ + 'title' => 'Omat tehtävät', + 'none' => 'Sinulla ei ole avoimia tehtäviä.', + 'groups' => [ + 'overdue' => 'Myöhässä (:count)', + 'soon' => 'Tänään ja huomenna (:count)', + 'this_week' => 'Myöhemmin tällä viikolla (:count)', + ], + 'due' => 'määräpäivä :date', + 'starts' => 'alkaa :date', + 'later' => '{1} Lisäksi yksi tehtävä myöhemmin.|[2,*] Lisäksi :count tehtävää myöhemmin.', + 'to_calendar' => 'Avaa kalenteri', + ], + + 'week' => [ + 'title' => 'Tämän viikon tunnit', + 'caption' => 'Kirjatut tunnit päivittäin viikolla, joka alkaa :from', + 'total' => 'Yhteensä :hours h.', + 'unapproved' => 'Hyväksymättä :hours h.', + 'open' => 'Avaa viikkonäkymä', + ], + + 'jobs' => [ + 'title' => 'Omat asiakastyöt', + 'none' => 'Sinulla ei ole avoimia asiakastöitä.', + 'due' => 'määräaika :date', + 'all' => '{0} Asiakastyölista|{1} Kaikki omat työt (1 avoin)|[2,*] Kaikki omat työt (:count avointa)', + ], + + 'management' => [ + 'title' => 'Johtajapaneeli', + 'loading' => 'Ladataan johtajapaneelia…', + 'change' => ':change edelliseen kuukauteen', + 'no_comparison' => 'Ei vertailukohtaa edellisessä kuukaudessa', + ], + + 'todo' => [ + 'title' => 'Vaatii toimia', + 'approvals' => '{0} Ei hyväksymättömiä tunteja|{1} Yhdellä henkilöllä hyväksymättömiä tunteja|[2,*] :count henkilöllä hyväksymättömiä tunteja', + 'approval_line' => ':name: :hours h, :weeks viikolta', + 'done_jobs' => '{0} Ei valmiita töitä laskuttamatta|{1} Yksi valmis työ odottaa laskutusta|[2,*] :count valmista työtä odottaa laskutusta', + 'draft' => 'Laskuaineiston luonnos on kesken', + 'cash_days' => '{1} Kassapäivä :first on päättämättä|[2,*] :count kassapäivää päättämättä, vanhin :first', + 'unbilled' => 'Laskuttamattomien tuntien arvo :amount', + ], + + 'month' => [ + 'title' => 'Kuukausi tähän mennessä', + 'period' => ':from–:to verrattuna jaksoon :previous_from–:previous_to.', + 'customer_hours' => 'Asiakastyön tunnit', + 'internal_hours' => 'Sisäisen työn tunnit', + 'billed' => 'Laskutettu (ALV 0)', + 'margin' => 'Kate (ALV 0)', + 'no_cost' => 'Tuntikustannus puuttuu', + 'sales' => 'Pikamyynnit (verollinen)', + 'billing_note' => 'Laskutus ja kate tulevat kuukauden luoduista laskuaineistoista.', + ], + + 'stock' => [ + 'title' => 'Työkanta', + 'caption' => 'Asiakastyöt tiloittain', + 'status' => 'Tila', + 'count' => 'Töitä', + 'overdue_jobs' => '{0} Ei myöhässä olevia töitä.|{1} Yksi työ on myöhässä.|[2,*] :count työtä on myöhässä.', + 'overdue_tasks' => '{0} Ei myöhässä olevia tehtäviä.|{1} Yksi tehtävä on myöhässä.|[2,*] :count tehtävää on myöhässä.', + 'oldest_overdue' => 'Pisimpään myöhässä olleet tehtävät', + 'no_assignee' => 'ei tekijää', + ], + + 'load' => [ + 'title' => 'Henkilöiden kuormitus', + 'none' => 'Ei aktiivisia käyttäjiä.', + 'caption' => 'Tehtäväkalenterin varaukset suhteessa työaikaan', + 'person' => 'Henkilö', + 'week' => 'Viikko :from', + 'value' => ':booked / :capacity h (:ratio)', + 'overloaded' => 'Ylikuormitettu', + 'note' => 'Varaukset ovat avoimien tehtävien arvioita tehtäväkalenterissa; työaika on päiväkatto kertaa työpäivät.', + 'to_calendar' => 'Avaa kalenteri', + ], +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index 26a91f0..e0fe33c 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -51,10 +51,4 @@ return [ 'theme_system' => 'Järjestelmän mukainen', 'selected' => '(valittu)', ], - 'demo' => [ - 'title' => 'Toiminnanohjaus', - 'intro' => 'Livewire ja TallStackUI toimivat. Tämä on väliaikainen kokeilusivu.', - 'add_click' => 'Lisää klikkaus', - 'clicked' => 'Klikattu :count kertaa', - ], ]; diff --git a/resources/views/pages/⚡home.blade.php b/resources/views/pages/⚡home.blade.php deleted file mode 100644 index 65cf36d..0000000 --- a/resources/views/pages/⚡home.blade.php +++ /dev/null @@ -1,31 +0,0 @@ -clickCount++; - } - - public function render(): mixed - { - return $this->view()->title(__('layout.demo.title')); - } -}; -?> - -
-

{{ __('layout.demo.title') }}

- -

{{ __('layout.demo.intro') }}

- - - -

- {{ __('layout.demo.clicked', ['count' => $clickCount]) }} -

-
diff --git a/routes/web.php b/routes/web.php index df4abcd..b88e1dd 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,5 +1,3 @@ middleware('auth')->name('home'); +// Module routes live in each module's Presentation/Routes/web.php (the home page in Dashboard). diff --git a/tests/Browser/AccessibilityTest.php b/tests/Browser/AccessibilityTest.php index 3cb4196..2259918 100644 --- a/tests/Browser/AccessibilityTest.php +++ b/tests/Browser/AccessibilityTest.php @@ -32,9 +32,7 @@ it('can be operated with the keyboard alone', function () { ->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön') ->keys('a[href="#main-content"]', 'Enter') ->keys('#main-content', 'Tab') - ->assertScript('document.activeElement.textContent.trim()', 'Lisää klikkaus') - ->keys('#main-content button', 'Enter') - ->assertSeeIn('[role="status"]', 'Klikattu 1 kertaa'); + ->assertScript('document.activeElement.textContent.trim()', 'Pikavastaanotto'); }); it('reaches the main menu with the keyboard', function () { diff --git a/tests/Browser/DashboardAccessibilityTest.php b/tests/Browser/DashboardAccessibilityTest.php new file mode 100644 index 0000000..229a6ed --- /dev/null +++ b/tests/Browser/DashboardAccessibilityTest.php @@ -0,0 +1,45 @@ +worker = User::factory()->employee()->create(['name' => 'Aino Tekijä']); + $job = CustomerJobModel::factory()->create([ + 'name' => 'Mainosvideo', + 'customer_id' => CustomerModel::factory()->company()->create()->id, + 'status' => JobStatus::InProduction, + 'responsible_user_id' => $this->worker->id, + 'due_on' => now()->subDays(3)->toDateString(), + ]); + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'title' => 'Leikkaus', 'assignee_user_id' => $this->worker->id, 'due_on' => now()->subDay()->toDateString()]); + TaskModel::factory()->create(['customer_job_id' => $job->id, 'title' => 'Värimäärittely', 'assignee_user_id' => $this->worker->id, 'due_on' => now()->toDateString()]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => $task->id, 'worked_on' => now()->toDateString(), 'hours' => 2]); +}); + +it('has no accessibility issues on the home page', function (string $role, string $device, string $colorScheme) { + $this->actingAs($role === 'management' ? User::factory()->management()->create(['name' => 'Maija Johtaja']) : $this->worker); + + $visit = visit(route('home')); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $role === 'management' + ? $visit->assertSee('Henkilöiden kuormitus')->assertSee('Leikkaus') + : $visit->assertSee('Leikkaus')->assertSee('Värimäärittely')->assertDontSee('Johtajapaneeli'); + + $visit->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with(['employee', 'management'])->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Feature/HomePageTest.php b/tests/Feature/HomePageTest.php index 0cb2049..7ae784e 100644 --- a/tests/Feature/HomePageTest.php +++ b/tests/Feature/HomePageTest.php @@ -2,7 +2,6 @@ use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; -use Livewire\Livewire; uses(RefreshDatabase::class); @@ -14,17 +13,10 @@ it('renders the home page with the main menu', function () { $this->get(route('home')) ->assertOk() ->assertSee('Toiminnanohjaus') + ->assertSee('Hei, Eero Esimerkki') ->assertSee('Siirry pääsisältöön') ->assertSee('id="main-content"', false) ->assertSee('aria-label="Päävalikko"', false) ->assertSee('aria-label="Profiili: Eero Esimerkki"', false) ->assertSee('Kirjaudu ulos'); }); - -it('increments the click count', function () { - Livewire::test('pages::home') - ->assertSet('clickCount', 0) - ->call('incrementClickCount') - ->assertSet('clickCount', 1) - ->assertSee('Klikattu 1 kertaa'); -}); diff --git a/tests/Feature/Modules/Dashboard/DashboardTest.php b/tests/Feature/Modules/Dashboard/DashboardTest.php new file mode 100644 index 0000000..5a19419 --- /dev/null +++ b/tests/Feature/Modules/Dashboard/DashboardTest.php @@ -0,0 +1,112 @@ +travelTo('2026-11-25 12:00'); + $this->worker = User::factory()->employee()->create(['name' => 'Aino Tekijä']); + $this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']); + $this->job = CustomerJobModel::factory()->create([ + 'name' => 'Mainosvideo', 'customer_id' => $this->customer->id, 'status' => JobStatus::InProduction, + 'responsible_user_id' => $this->worker->id, 'due_on' => '2026-11-20', + ]); +}); + +function homeTask(array $attributes, array $memberIds = []): TaskModel +{ + $task = TaskModel::factory()->create(array_merge(['customer_job_id' => test()->job->id], $attributes)); + foreach ($memberIds as $userId) { + DB::table('task_members')->insert(['task_id' => $task->id, 'user_id' => $userId]); + } + + return $task; +} + +it('shows the user their tasks on an agenda, their open jobs and the week', function () { + homeTask(['title' => 'Myöhästynyt', 'assignee_user_id' => $this->worker->id, 'due_on' => '2026-11-24']); + homeTask(['title' => 'Huomenna', 'due_on' => '2026-11-26'], [$this->worker->id]); + homeTask(['title' => 'Perjantaina', 'assignee_user_id' => $this->worker->id, 'planned_from' => '2026-11-27', 'planned_to' => '2026-11-27']); + homeTask(['title' => 'Ensi kuussa', 'assignee_user_id' => $this->worker->id, 'due_on' => '2026-12-15']); + homeTask(['title' => 'Valmis', 'assignee_user_id' => $this->worker->id, 'status' => TaskStatus::Done, 'due_on' => '2026-11-24']); + homeTask(['title' => 'Jonkun muun', 'due_on' => '2026-11-24']); + CustomerJobModel::factory()->create(['name' => 'Valmistunut', 'customer_id' => $this->customer->id, 'status' => JobStatus::Done, 'responsible_user_id' => $this->worker->id]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => TaskModel::factory()->create(['customer_job_id' => $this->job->id])->id, 'worked_on' => '2026-11-23', 'hours' => 2.5]); + + $this->actingAs($this->worker); + + $page = Livewire::test('dashboard::home') + ->assertOk() + ->assertSee('Hei, Aino Tekijä') + ->assertSee('Myöhässä (1)') + ->assertSee('Mainosvideo') + ->assertDontSee('Valmistunut') + ->assertDontSee('Jonkun muun') + ->assertDontSee('Johtajapaneeli') + ->assertSee('Lisäksi yksi tehtävä myöhemmin.'); + + $overview = $page->instance()->overview(); + + expect(array_map(fn ($task) => $task->title, $overview->overdue))->toBe(['Myöhästynyt']) + ->and($overview->overdue[0]->isLate)->toBeTrue() + ->and(array_map(fn ($task) => $task->title, $overview->soon))->toBe(['Huomenna']) + ->and(array_map(fn ($task) => $task->title, $overview->thisWeek))->toBe(['Perjantaina']) + ->and($overview->laterCount)->toBe(1) + ->and(array_map(fn ($job) => $job->name, $overview->jobs))->toBe(['Mainosvideo']) + ->and($overview->jobs[0]->isLate)->toBeTrue() + ->and($overview->week->monday)->toBe('2026-11-23') + ->and($overview->week->totalQuarters)->toBe(10) + ->and($overview->week->unapprovedQuarters)->toBe(10); +}); + +it('gives admin and management the management panel', function () { + $manager = User::factory()->management()->create(['name' => 'Maija Johtaja']); + WorkTypeModel::factory()->create(['hourly_rate_cents' => 8000]); + homeTask(['title' => 'Myöhässä oleva', 'assignee_user_id' => $this->worker->id, 'due_on' => '2026-11-20', 'estimated_hours' => 30, 'planned_from' => '2026-11-23', 'planned_to' => '2026-11-27']); + DB::table('task_bookings')->insert(['task_id' => TaskModel::query()->where('title', 'Myöhässä oleva')->value('id'), 'user_id' => $this->worker->id, 'day' => '2026-11-26', 'minutes' => 45 * 60]); + TimeEntryModel::factory()->create(['user_id' => $this->worker->id, 'task_id' => TaskModel::factory()->create(['customer_job_id' => $this->job->id])->id, 'worked_on' => '2026-11-03', 'hours' => 4]); + TimeEntryModel::factory()->approved()->create(['user_id' => $this->worker->id, 'task_id' => TaskModel::factory()->create(['customer_job_id' => $this->job->id])->id, 'worked_on' => '2026-10-03', 'hours' => 2]); + + $this->actingAs($manager); + $this->get(route('home'))->assertOk()->assertSee('Hei, Maija Johtaja'); + + $panel = Livewire::test('dashboard::management') + ->assertOk() + ->assertSee('Johtajapaneeli') + ->assertSee('Yhdellä henkilöllä hyväksymättömiä tunteja') + ->assertSee('Aino Tekijä: 4 h, 1 viikolta') + ->assertSee('Yksi työ on myöhässä.') + ->assertSee('Myöhässä oleva') + ->assertSee('Ylikuormitettu') + ->assertSee("+100,0\u{00A0}% edelliseen kuukauteen"); + + $overview = $panel->instance()->overview(); + expect($overview->previousFrom)->toBe('2026-10-01') + ->and($overview->previousTo)->toBe('2026-10-25') + ->and($overview->month->customerQuarters)->toBe(16) + ->and($overview->jobCounts['in_production'])->toBe(1) + ->and($overview->overdueTaskCount)->toBe(1); + + $load = collect($overview->workloads)->firstWhere('userId', $this->worker->id); + expect($load->thisWeek->bookedMinutes)->toBe(2700) + ->and($load->thisWeek->capacityMinutes)->toBe(5 * 8 * 60) + ->and(collect($overview->workloads)->pluck('userId'))->toContain($manager->id); +}); + +it('keeps the management panel from employees', function () { + $this->actingAs($this->worker); + + Livewire::test('dashboard::management')->assertForbidden(); +}); diff --git a/tests/Unit/Modules/Dashboard/DashboardRulesTest.php b/tests/Unit/Modules/Dashboard/DashboardRulesTest.php new file mode 100644 index 0000000..8421c1f --- /dev/null +++ b/tests/Unit/Modules/Dashboard/DashboardRulesTest.php @@ -0,0 +1,41 @@ +toBe($bucket); +})->with([ + 'due yesterday' => ['2026-11-24', null, AgendaBucket::Overdue], + 'due yesterday, started earlier' => ['2026-11-24', '2026-11-01', AgendaBucket::Overdue], + 'due today' => ['2026-11-25', null, AgendaBucket::Soon], + 'under way since Monday' => ['2026-12-10', '2026-11-23', AgendaBucket::Soon], + 'starts tomorrow' => [null, '2026-11-26', AgendaBucket::Soon], + 'due on Sunday' => ['2026-11-29', null, AgendaBucket::ThisWeek], + 'starts next week' => [null, '2026-11-30', AgendaBucket::Later], + 'no dates' => [null, null, AgendaBucket::Later], +]); + +it('counts working days without weekends and holidays', function () { + expect(Workload::workingDays('2026-12-21', '2026-12-27', ['2026-12-24', '2026-12-25', '2026-12-26']))->toBe(3) + ->and(Workload::workingDays('2026-11-23', '2026-11-29', []))->toBe(5); +}); + +it('compares the workload with the capacity', function () { + $load = Workload::of(2700, 480, 5); + + expect($load->capacityMinutes)->toBe(2400) + ->and($load->ratio())->toBe(1.125) + ->and($load->isOverloaded())->toBeTrue() + ->and(Workload::of(0, 480, 0)->ratio())->toBeNull() + ->and(Workload::of(2400, 480, 5)->isOverloaded())->toBeFalse(); +}); + +it('gives the change from the earlier value, none from zero', function () { + expect((new Change(150, 100))->ratio())->toBe(0.5) + ->and((new Change(50, 100))->ratio())->toBe(-0.5) + ->and((new Change(-50, -100))->ratio())->toBe(0.5) + ->and((new Change(10, 0))->ratio())->toBeNull(); +});