diff --git a/CLAUDE.md b/CLAUDE.md index e1f8a3d..57748a3 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)); `/` (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. +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 `shared.daily_capacity_hours` (Shared's `DailyCapacity`, set on the company details page, 7.5 h when empty)) `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 the daily capacity × 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. diff --git a/app/Modules/Jobs/Application/Services/TaskPlanner.php b/app/Modules/Jobs/Application/Services/TaskPlanner.php index e7d5308..da362a7 100644 --- a/app/Modules/Jobs/Application/Services/TaskPlanner.php +++ b/app/Modules/Jobs/Application/Services/TaskPlanner.php @@ -7,7 +7,7 @@ namespace App\Modules\Jobs\Application\Services; use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository; use App\Modules\Jobs\Domain\Entities\Task; use App\Modules\Jobs\Domain\Services\TaskScheduler; -use App\Modules\Shared\Application\Contracts\Settings; +use App\Modules\Shared\Application\UseCases\DailyCapacity; use App\Modules\Shared\Application\UseCases\HolidayCalendar; use DateInterval; use DateTimeImmutable; @@ -15,29 +15,23 @@ use DateTimeImmutable; /** * Books a saved task's estimate from its assignee's days with the * TaskScheduler, using the holidays in use and the daily maximum - * (setting `jobs.daily_capacity_hours`, 8 h by default). When the days - * are full, the task's planned end moves later. + * (Shared's DailyCapacity, set in the company details, 7.5 h by default). + * When the days are full, the task's planned end moves later. */ final class TaskPlanner { - public const string CAPACITY_KEY = 'jobs.daily_capacity_hours'; - - private const int DEFAULT_CAPACITY_HOURS = 8; - /** Days past the start in which holidays and other bookings are looked up. */ private const int LOOKAHEAD_DAYS = 400; public function __construct( private TaskBookingRepository $bookings, private HolidayCalendar $holidays, - private Settings $settings, + private DailyCapacity $capacity, ) {} public function capacityMinutes(): int { - $hours = (float) str_replace(',', '.', $this->settings->get(self::CAPACITY_KEY) ?? ''); - - return (int) round(($hours > 0 && $hours <= 24 ? $hours : self::DEFAULT_CAPACITY_HOURS) * 60); + return $this->capacity->minutes(); } /** diff --git a/app/Modules/Shared/Application/UseCases/DailyCapacity.php b/app/Modules/Shared/Application/UseCases/DailyCapacity.php new file mode 100644 index 0000000..a2e1e13 --- /dev/null +++ b/app/Modules/Shared/Application/UseCases/DailyCapacity.php @@ -0,0 +1,83 @@ +settings->get(self::KEY)) ?? self::DEFAULT_MINUTES; + } + + /** + * The saved hours in Finnish form (e.g. "7,5"), or null when not set. + */ + public function hours(): ?string + { + $minutes = self::minutesOf($this->settings->get(self::KEY)); + + return $minutes === null ? null : self::format($minutes); + } + + /** + * Saves the hours ("7,5" or "7.5"); empty removes the setting. + * + * @throws InvalidDailyCapacity + */ + public function save(?string $hours): void + { + $hours = trim((string) $hours); + + if ($hours === '') { + $this->settings->put(self::KEY, null); + + return; + } + + $minutes = self::minutesOf($hours) ?? throw new InvalidDailyCapacity; + + $this->settings->put(self::KEY, str_replace(',', '.', self::format($minutes))); + } + + /** + * Whether save() accepts the hours: empty, or more than 0 and at most 24. + */ + public static function isValid(?string $hours): bool + { + return trim((string) $hours) === '' || self::minutesOf($hours) !== null; + } + + private static function minutesOf(?string $hours): ?int + { + $hours = str_replace(',', '.', trim((string) $hours)); + + if (! is_numeric($hours)) { + return null; + } + + $minutes = (int) round((float) $hours * 60); + + return $minutes > 0 && $minutes <= 24 * 60 ? $minutes : null; + } + + private static function format(int $minutes): string + { + return str_replace('.', ',', rtrim(rtrim(number_format($minutes / 60, 2, '.', ''), '0'), '.')); + } +} diff --git a/app/Modules/Shared/Domain/Exceptions/InvalidDailyCapacity.php b/app/Modules/Shared/Domain/Exceptions/InvalidDailyCapacity.php new file mode 100644 index 0000000..1bd1402 --- /dev/null +++ b/app/Modules/Shared/Domain/Exceptions/InvalidDailyCapacity.php @@ -0,0 +1,13 @@ +authorize('settings.manage'); + $this->daily_capacity_hours = $capacity->hours() ?? ''; + $details = $store->get(); if ($details !== null) { @@ -45,7 +52,7 @@ new class extends Component } } - public function save(CompanyDetailsStore $store): void + public function save(CompanyDetailsStore $store, DailyCapacity $capacity): void { $this->authorize('settings.manage'); $this->statusMessage = ''; @@ -57,6 +64,7 @@ new class extends Component 'address' => ['nullable', 'string', 'max:500'], 'phone' => ['nullable', 'string', 'max:50'], 'email' => ['nullable', 'string', 'max:255'], + 'daily_capacity_hours' => ['nullable', 'string', 'max:10'], ], [ 'name.required' => __('company.errors.name'), 'name.max' => __('company.errors.name'), @@ -66,10 +74,22 @@ new class extends Component 'address.max' => __('company.errors.address'), 'phone.max' => __('company.errors.phone'), 'email.max' => __('company.errors.email'), + 'daily_capacity_hours.max' => __('company.errors.daily_capacity_hours'), ]); + if (! DailyCapacity::isValid($this->daily_capacity_hours)) { + $this->addError('daily_capacity_hours', __('company.errors.daily_capacity_hours')); + + return; + } + try { $store->save(new CompanyDetails($this->name, $this->business_id, $this->address, $this->phone, $this->email, $this->menu_name)); + $capacity->save($this->daily_capacity_hours); + } catch (InvalidDailyCapacity) { + $this->addError('daily_capacity_hours', __('company.errors.daily_capacity_hours')); + + return; } catch (CompanyNameRequired) { $this->addError('name', __('company.errors.name')); @@ -85,6 +105,7 @@ new class extends Component } $this->business_id = (string) $store->get()?->businessId; + $this->daily_capacity_hours = $capacity->hours() ?? ''; $this->statusMessage = __('company.saved'); } @@ -111,6 +132,9 @@ new class extends Component +

{{ __('company.calendar_heading') }}

+ + diff --git a/database/migrations/2026_11_25_084434_move_daily_capacity_setting_to_shared.php b/database/migrations/2026_11_25_084434_move_daily_capacity_setting_to_shared.php new file mode 100644 index 0000000..de90c85 --- /dev/null +++ b/database/migrations/2026_11_25_084434_move_daily_capacity_setting_to_shared.php @@ -0,0 +1,20 @@ +where('key', 'jobs.daily_capacity_hours')->update(['key' => 'shared.daily_capacity_hours']); + } + + public function down(): void + { + DB::table('settings')->where('key', 'shared.daily_capacity_hours')->update(['key' => 'jobs.daily_capacity_hours']); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index b45a277..48723ee 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -366,7 +366,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `vat_rates` *(V2, olemassa)*: `name`, `basis_points` (sadasosaprosentteina, 2550 = 25,5 %), `is_default`, `is_active`, `sort_order` - `products` *(V2, olemassa)*: `name`, `unit` (`piece`/`page`/`square_metre`/`metre`/`hour`/`package`), `price_cents` (kuluttajatuotteella verollinen, muuten veroton), `vat_rate_id`, `is_consumer_product`, `auto_hours`, `work_type_id` (nullable, pakollinen jos `auto_hours` > 0), `is_active`, `sort_order` - `workflow_templates` *(V3, olemassa)*: `work_type_id`, `name` (yksilöllinen työtehtävän sisällä), `is_active`; `workflow_template_steps`: `workflow_template_id`, `work_type_id` (nullable = pohjan työtehtävä), `title`, `description`, `sort_order` -- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, `catalog.internal_hourly_cost_cents` = sisäinen tuntikustannus kannattavuusraporttiin *(V4)*, työajanseuranta päällä, `jobs.daily_capacity_hours` = päiväkatto tunteina, oletus 8) +- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, `catalog.internal_hourly_cost_cents` = sisäinen tuntikustannus kannattavuusraporttiin *(V4)*, työajanseuranta päällä, `shared.daily_capacity_hours` = päiväkatto tunteina, pääkäyttäjä asettaa Yritystiedoissa, tyhjä = 7,5) - `holiday_overrides` *(V3, olemassa)*: `date` (uniikki), `is_holiday` (false = laskettu arkipyhä poistettu käytöstä, true = yrityksen oma vapaapäivä), `name` (oman päivän nimi) **Jobs** (asiakastyöt) @@ -527,7 +527,7 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t ### 18.3 Tehtäväkalenteri *(valmis)* - Valikon Kalenteri (`/jobs/calendar`, kaikki kirjautuneet): rullaava kaksi viikkoa tästä päivästä, painikkeet Edelliset 2 viikkoa / Tänään / Seuraavat 2 viikkoa. Rivi jokaiselle aktiiviselle käyttäjälle (oma rivi ensin) ja rivi Ei tekijää; suodattimet palveluyksikkö ja Vain oma rivi. Alihankkija näkee vain oman rivinsä ja liitettyjen töidensä tehtävät, ja hän voi vaihtaa vain tilaa. - Tehtävällä on aikataulu (suunniteltu alku ja loppu), joka näkyy palkkina tekijän rivillä (jäsenten riveillä ei). Päällekkäiset tehtävät pinotaan omille kaistoilleen, joten samalle päivälle voi asettaa useita lyhyitä tehtäviä. Palkissa näkyvät nimi, työn numero, tila tekstinä ja tunnit; jos aikataulu päättyy määräpäivän jälkeen, palkissa on "Myöhässä" kuvakkeineen. -- **Päiväkuorma:** tehtävän arvioitu aika varataan tekijältä (jäseniltä ei) ja jaetaan tasan jakson arkipäiville; arkipäiviä eivät ole la, su eivätkä käytössä olevat arkipyhät. Jos jaksossa on vain viikonloppu- tai pyhäpäiviä, arvio jaetaan niille. Henkilön päivään varataan enintään päiväkatto (8 h, asetus `jobs.daily_capacity_hours`) miinus muiden avoimien tehtävien varaukset; ylittävä osa siirtyy seuraavalle arkipäivälle, ja tehtävän loppu siirtyy myöhemmäksi (ilmoitetaan). Muiden tehtävien varaukset eivät muutu. Valmiit tehtävät eivät vie kapasiteettia. Päivän solussa näkyy kuorma, esim. "6 / 8 h". Ilman arviota tehtävä ei kuormita. +- **Päiväkuorma:** tehtävän arvioitu aika varataan tekijältä (jäseniltä ei) ja jaetaan tasan jakson arkipäiville; arkipäiviä eivät ole la, su eivätkä käytössä olevat arkipyhät. Jos jaksossa on vain viikonloppu- tai pyhäpäiviä, arvio jaetaan niille. Henkilön päivään varataan enintään päiväkatto (Yritystiedoissa, oletus 7,5 h, asetus `shared.daily_capacity_hours`) miinus muiden avoimien tehtävien varaukset; ylittävä osa siirtyy seuraavalle arkipäivälle, ja tehtävän loppu siirtyy myöhemmäksi (ilmoitetaan). Muiden tehtävien varaukset eivät muutu. Valmiit tehtävät eivät vie kapasiteettia. Päivän solussa näkyy kuorma, esim. "6 / 8 h". Ilman arviota tehtävä ei kuormita. - **Muutokset hiirellä:** palkin rungosta vetämällä tehtävä siirtyy ajassa ja toisen henkilön riville (uuden rivin henkilöstä tulee tekijä, jäsenet säilyvät); reunoista vetämällä muuttuu alku tai loppu. Aikatauluttamattomat avoimet tehtävät listataan kalenterin alla, ja ne voi vetää päivälle; ilman loppua tehtävä saa niin monta arkipäivää kuin arvio päiväkatolla vaatii. - **Näppäimistöllä:** jokainen palkki on painike, joka avaa dialogin: alkaa, päättyy, tekijä, tila, linkit työhön ja tehtävän muokkaukseen sekä Poista aikataulu. Muutos ilmoitetaan `aria-live`-alueella ja fokus palaa palkkiin. Puhelimella ja kapeassa ikkunassa ruudukon sijaan näytetään lista henkilöittäin samoin dialogein. - Tehtävän lomakkeella on kentät Aikataulu alkaa ja Aikataulu päättyy, ja työn sivun tehtäväkortissa näkyy aikataulu. diff --git a/lang/en/company.php b/lang/en/company.php index 58c658c..4ab0151 100644 --- a/lang/en/company.php +++ b/lang/en/company.php @@ -2,7 +2,8 @@ return [ 'title' => 'Company details', - 'intro' => 'The company details are printed on receipts, and the menu name is shown at the left edge of the main menu. The VAT number is formed from the business ID.', + 'intro' => 'The company details are printed on receipts, and the menu name is shown at the left edge of the main menu. The VAT number is formed from the business ID. The daily capacity limits the bookings in the task calendar.', + 'calendar_heading' => 'Task calendar', 'fields' => [ 'name' => 'Company name', 'menu_name' => 'Menu name', @@ -13,6 +14,8 @@ return [ 'address_hint' => 'Street address, postcode and town on separate lines.', 'phone' => 'Phone', 'email' => 'Email', + 'daily_capacity_hours' => 'Daily capacity (h)', + 'daily_capacity_hours_hint' => 'The task calendar books at most this many hours per person per working day, e.g. 7,5. If left empty, the limit is 7,5 h.', ], 'save' => 'Save', 'saved' => 'Company details saved.', @@ -23,5 +26,6 @@ return [ 'address' => 'The address may be at most 500 characters.', 'phone' => 'The phone number may be at most 50 characters.', 'email' => 'Enter a valid email address.', + 'daily_capacity_hours' => 'Enter more than 0 and at most 24 hours, e.g. 7,5.', ], ]; diff --git a/lang/fi/company.php b/lang/fi/company.php index 0e53897..e1a2090 100644 --- a/lang/fi/company.php +++ b/lang/fi/company.php @@ -2,7 +2,8 @@ return [ 'title' => 'Yritystiedot', - 'intro' => 'Yrityksen tiedot tulostuvat kuitteihin, ja valikon nimi näkyy päävalikon vasemmassa reunassa. Arvonlisäverotunnus muodostetaan Y-tunnuksesta.', + 'intro' => 'Yrityksen tiedot tulostuvat kuitteihin, ja valikon nimi näkyy päävalikon vasemmassa reunassa. Arvonlisäverotunnus muodostetaan Y-tunnuksesta. Päivän kuormitusraja ohjaa tehtäväkalenterin varauksia.', + 'calendar_heading' => 'Tehtäväkalenteri', 'fields' => [ 'name' => 'Yrityksen nimi', 'menu_name' => 'Valikon nimi', @@ -13,6 +14,8 @@ return [ 'address_hint' => 'Katuosoite, postinumero ja -toimipaikka omille riveilleen.', 'phone' => 'Puhelin', 'email' => 'Sähköposti', + 'daily_capacity_hours' => 'Päivän kuormitusraja (h)', + 'daily_capacity_hours_hint' => 'Tehtäväkalenteri varaa kullekin enintään näin monta tuntia työpäivää kohden, esim. 7,5. Jos kenttä on tyhjä, raja on 7,5 h.', ], 'save' => 'Tallenna', 'saved' => 'Yritystiedot tallennettu.', @@ -23,5 +26,6 @@ return [ 'address' => 'Osoite saa olla enintään 500 merkkiä.', 'phone' => 'Puhelinnumero saa olla enintään 50 merkkiä.', 'email' => 'Anna kelvollinen sähköpostiosoite.', + 'daily_capacity_hours' => 'Anna tuntimäärä, joka on yli 0 ja enintään 24, esim. 7,5.', ], ]; diff --git a/tests/Feature/Modules/Dashboard/DashboardTest.php b/tests/Feature/Modules/Dashboard/DashboardTest.php index 5a19419..50c3e11 100644 --- a/tests/Feature/Modules/Dashboard/DashboardTest.php +++ b/tests/Feature/Modules/Dashboard/DashboardTest.php @@ -101,7 +101,7 @@ it('gives admin and management the management panel', function () { $load = collect($overview->workloads)->firstWhere('userId', $this->worker->id); expect($load->thisWeek->bookedMinutes)->toBe(2700) - ->and($load->thisWeek->capacityMinutes)->toBe(5 * 8 * 60) + ->and($load->thisWeek->capacityMinutes)->toBe(5 * 450) ->and(collect($overview->workloads)->pluck('userId'))->toContain($manager->id); }); diff --git a/tests/Feature/Modules/Jobs/TaskCalendarTest.php b/tests/Feature/Modules/Jobs/TaskCalendarTest.php index 9d4a59d..e2ad263 100644 --- a/tests/Feature/Modules/Jobs/TaskCalendarTest.php +++ b/tests/Feature/Modules/Jobs/TaskCalendarTest.php @@ -68,7 +68,7 @@ it('continues a task on the next working day when the day is full', function () Livewire::test('jobs::calendar') ->call('reschedule', $task->id, $this->job->id, $this->employee->id, $this->employee->id, '2026-12-23', '2026-12-23') ->assertSee('Päivät olivat täynnä, joten tehtävä jatkuu 28.12.2026 asti.') - ->assertSee('8 / 8 h'); + ->assertSee('7,5 / 7,5 h'); expect($task->refresh()->planned_to?->format('Y-m-d'))->toBe('2026-12-28'); }); diff --git a/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php b/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php index 888e294..5cd010d 100644 --- a/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php +++ b/tests/Feature/Modules/Jobs/TasksFromTemplateTest.php @@ -9,6 +9,8 @@ use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel; use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel; +use App\Modules\Shared\Application\Contracts\Settings; +use App\Modules\Shared\Application\UseCases\DailyCapacity; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\DB; use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException; @@ -17,6 +19,7 @@ use Livewire\Livewire; uses(RefreshDatabase::class); beforeEach(function () { + app(Settings::class)->put(DailyCapacity::KEY, '8'); $this->employee = User::factory()->create(['name' => 'Eero Työntekijä']); $this->actingAs($this->employee); $this->marketing = ServiceUnitModel::query()->where('name', 'Markkinointi')->sole(); diff --git a/tests/Feature/Modules/Shared/CompanyDetailsTest.php b/tests/Feature/Modules/Shared/CompanyDetailsTest.php index 64c6d00..7706688 100644 --- a/tests/Feature/Modules/Shared/CompanyDetailsTest.php +++ b/tests/Feature/Modules/Shared/CompanyDetailsTest.php @@ -1,7 +1,9 @@ and($store->menuName())->toBe(config('app.name')); }); +it('saves the calendar daily capacity, 7.5 hours when empty', function () { + $this->actingAs(User::factory()->admin()->create()); + $capacity = app(DailyCapacity::class); + + Livewire::test('shared::company') + ->assertSet('daily_capacity_hours', '') + ->set('name', 'Mediatalo Oy') + ->set('business_id', '0737546-2') + ->set('daily_capacity_hours', '6,5') + ->call('save') + ->assertHasNoErrors(); + + expect($capacity->minutes())->toBe(390) + ->and(app(TaskPlanner::class)->capacityMinutes())->toBe(390); + + Livewire::test('shared::company') + ->assertSet('daily_capacity_hours', '6,5') + ->set('daily_capacity_hours', '') + ->call('save') + ->assertHasNoErrors(); + + expect($capacity->minutes())->toBe(450); +}); + +it('rejects an invalid daily capacity without saving anything', function () { + $this->actingAs(User::factory()->admin()->create()); + + Livewire::test('shared::company') + ->set('name', 'Mediatalo Oy') + ->set('business_id', '0737546-2') + ->set('daily_capacity_hours', '25') + ->call('save') + ->assertHasErrors(['daily_capacity_hours' => [__('company.errors.daily_capacity_hours')]]); + + expect(app(CompanyDetailsStore::class)->get())->toBeNull() + ->and(app(DailyCapacity::class)->hours())->toBeNull(); +}); + it('rejects a menu name over 100 characters', function () { $this->actingAs(User::factory()->admin()->create()); diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php index 42b6b18..f807f02 100644 --- a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -23,6 +23,7 @@ use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries; use App\Modules\Jobs\Domain\Exceptions\TaskNotFound; use App\Modules\Jobs\Domain\Exceptions\TasksNotAllowedYet; use App\Modules\Jobs\Domain\ValueObjects\TaskTitle; +use App\Modules\Shared\Application\UseCases\DailyCapacity; use App\Modules\Shared\Application\UseCases\HolidayCalendar; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; @@ -64,7 +65,7 @@ beforeEach(function () { $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->planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new DailyCapacity(tap(new FakeSettings, fn (FakeSettings $settings) => $settings->put(DailyCapacity::KEY, '8')))); $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); diff --git a/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php index 06d9e67..c0855f4 100644 --- a/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php +++ b/tests/Unit/Modules/Jobs/Application/TasksFromTemplateTest.php @@ -13,6 +13,7 @@ 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\Shared\Application\UseCases\DailyCapacity; use App\Modules\Shared\Application\UseCases\HolidayCalendar; use Tests\Fakes\FakeCatalogQueries; use Tests\Fakes\FakeClock; @@ -59,7 +60,7 @@ beforeEach(function () { $this->templates->addTemplate(4, 'Rikki', 11, 1, [['Painatus', 21]]); $this->bookings = new InMemoryTaskBookingRepository($this->tasks); - $planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new FakeSettings); + $planner = new TaskPlanner($this->bookings, new HolidayCalendar(new InMemoryHolidayOverrides), new DailyCapacity(tap(new FakeSettings, fn (FakeSettings $settings) => $settings->put(DailyCapacity::KEY, '8')))); $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); }); diff --git a/tests/Unit/Modules/Shared/DailyCapacityTest.php b/tests/Unit/Modules/Shared/DailyCapacityTest.php new file mode 100644 index 0000000..f6ae9d6 --- /dev/null +++ b/tests/Unit/Modules/Shared/DailyCapacityTest.php @@ -0,0 +1,35 @@ +minutes())->toBe(450) + ->and($capacity->hours())->toBeNull(); +}); + +it('saves hours with a comma or a point and clears them when empty', function () { + $settings = new FakeSettings; + $capacity = new DailyCapacity($settings); + + $capacity->save(' 6,5 '); + expect($capacity->minutes())->toBe(390) + ->and($capacity->hours())->toBe('6,5') + ->and($settings->get(DailyCapacity::KEY))->toBe('6.5'); + + $capacity->save('8.0'); + expect($capacity->minutes())->toBe(480) + ->and($capacity->hours())->toBe('8'); + + $capacity->save(''); + expect($capacity->minutes())->toBe(450) + ->and($settings->get(DailyCapacity::KEY))->toBeNull(); +}); + +it('rejects hours that are not more than 0 and at most 24', function (string $hours) { + expect(DailyCapacity::isValid($hours))->toBeFalse() + ->and(fn () => (new DailyCapacity(new FakeSettings))->save($hours))->toThrow(InvalidDailyCapacity::class); +})->with(['0', '-1', '24,5', 'abc', '7,5 h']);