From eb9346d31c8779e864baf01df3770681edb36c76 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 12:10:43 +0200 Subject: [PATCH] Fill the task calendar's working days in order instead of evenly A task's estimate now takes each working day of its planned period up to the assignee's free capacity before the next day gets anything, so 9 h is booked as 7.5 h + 1.5 h rather than 4.5 h + 4.5 h. What does not fit in the period still moves past its end and makes the task end later. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 2 +- .../Jobs/Domain/Services/TaskScheduler.php | 52 ++++++------------- docs/maarittely.md | 2 +- .../Feature/Modules/Jobs/TaskCalendarTest.php | 2 +- .../Jobs/Application/TaskUseCasesTest.php | 4 +- .../Modules/Jobs/Domain/TaskSchedulerTest.php | 6 +-- 6 files changed, 23 insertions(+), 45 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 57748a3..3b9abfd 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 `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. +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, filling the working days in order up to the daily maximum (9 h → 7.5 h + 1.5 h) with the rest moved past the period's end; the daily maximum is `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/Domain/Services/TaskScheduler.php b/app/Modules/Jobs/Domain/Services/TaskScheduler.php index 9effd4c..b13291a 100644 --- a/app/Modules/Jobs/Domain/Services/TaskScheduler.php +++ b/app/Modules/Jobs/Domain/Services/TaskScheduler.php @@ -11,19 +11,16 @@ use DateTimeImmutable; /** * Books a task's estimated time from its assignee's days (spec 18.3). * - * The estimate is split evenly over the working days of the planned - * period (not Saturdays, Sundays or holidays); a period of only such days - * splits it over all its days. No day gets more than the assignee's free - * capacity (the daily maximum minus what other open tasks already book): - * what does not fit moves to the next day of the period, and past its - * end to the next working days, which makes the task end later. Other - * tasks' bookings never move. + * The estimate fills the working days of the planned period in order + * (not Saturdays, Sundays or holidays; a period of only such days uses + * all its days): each day gets the assignee's free capacity (the daily + * maximum minus what other open tasks already book) before the next day + * gets anything. What does not fit in the period moves to the next + * working days after it, which makes the task end later. Other tasks' + * bookings never move. */ final class TaskScheduler { - /** Bookings are made in quarter hours, like time entries. */ - private const int STEP_MINUTES = 15; - /** How far past the planned end the overflow may go. */ private const int MAX_EXTRA_DAYS = 366; @@ -51,14 +48,16 @@ final class TaskScheduler $targets = $days; } - $shares = self::split($minutes, count($targets)); $booked = []; - $carry = 0; + $carry = $minutes; - foreach ($targets as $index => $day) { - $wanted = $shares[$index] + $carry; - $booking = min($wanted, self::free($day, $otherMinutes, $capacityMinutes)); - $carry = $wanted - $booking; + foreach ($targets as $day) { + if ($carry === 0) { + break; + } + + $booking = min($carry, self::free($day, $otherMinutes, $capacityMinutes)); + $carry -= $booking; if ($booking > 0) { $booked[$day] = $booking; @@ -198,27 +197,6 @@ final class TaskScheduler return $days; } - /** - * Splits the minutes into equal quarter-hour shares; the first days get - * the remainder. Odd minutes go to the first day. - * - * @return list - */ - private static function split(int $minutes, int $parts): array - { - $steps = intdiv($minutes, self::STEP_MINUTES); - $odd = $minutes % self::STEP_MINUTES; - $shares = []; - - for ($index = 0; $index < $parts; $index++) { - $shares[] = (intdiv($steps, $parts) + ($index < $steps % $parts ? 1 : 0)) * self::STEP_MINUTES; - } - - $shares[0] += $odd; - - return $shares; - } - /** * Books the carried minutes on the working days after the day; what * finds no free time within MAX_EXTRA_DAYS goes on the last day tried. diff --git a/docs/maarittely.md b/docs/maarittely.md index 48723ee..5a6630f 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -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 (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. +- **Päiväkuorma:** tehtävän arvioitu aika varataan tekijältä (jäseniltä ei) jakson arkipäiville järjestyksessä: ensimmäinen päivä täytetään ennen seuraavaa (esim. 9 h → 7,5 h + 1,5 h). 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 varataan 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. Jos arvio ei mahdu jaksoon, loput varataan jakson jälkeisille arkipäiville 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/tests/Feature/Modules/Jobs/TaskCalendarTest.php b/tests/Feature/Modules/Jobs/TaskCalendarTest.php index 6965e2d..123b09e 100644 --- a/tests/Feature/Modules/Jobs/TaskCalendarTest.php +++ b/tests/Feature/Modules/Jobs/TaskCalendarTest.php @@ -55,7 +55,7 @@ it('moves a task to another person by dropping it and books their days', functio expect($task->refresh()->planned_from?->format('Y-m-d'))->toBe('2026-12-28') ->and($task->planned_to?->format('Y-m-d'))->toBe('2026-12-29') ->and($task->assignee_user_id)->toBe($this->other->id) - ->and(DB::table('task_bookings')->where('task_id', $task->id)->orderBy('day')->pluck('minutes', 'day')->all())->toBe(['2026-12-28' => 360, '2026-12-29' => 360]); + ->and(DB::table('task_bookings')->where('task_id', $task->id)->orderBy('day')->pluck('minutes', 'day')->all())->toBe(['2026-12-28' => 450, '2026-12-29' => 270]); }); it('continues a task on the next working day when the day is full', function () { diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php index f807f02..b67ecd6 100644 --- a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -156,11 +156,11 @@ it('does not remove a task with time entries', function () { ->and(JobStatus::OnHold->locksTime())->toBeFalse(); }); -it('books a scheduled task evenly from the working days of its period', function () { +it('books a scheduled task by filling the working days of its period in order', function () { $taskId = $this->addTask->execute($this->jobId, new TaskData('Taitto', 11, 'waiting', estimatedHours: '12', assigneeUserId: 10, plannedFrom: '2026-12-04', plannedTo: '2026-12-07'), 10); $oneDayId = $this->addTask->execute($this->jobId, new TaskData('Palaveri', 91, 'waiting', assigneeUserId: 10, plannedFrom: '2026-12-08'), 10); - expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 360, '2026-12-07' => 360]) + expect($this->bookings->of($taskId, 10))->toBe(['2026-12-04' => 480, '2026-12-07' => 240]) ->and($this->tasks->findForJob($this->jobId, $oneDayId)?->plannedTo()?->format('Y-m-d'))->toBe('2026-12-08') ->and($this->bookings->of($oneDayId, 10))->toBe([]); }); diff --git a/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php b/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php index 1a3424a..ab566ee 100644 --- a/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php +++ b/tests/Unit/Modules/Jobs/Domain/TaskSchedulerTest.php @@ -7,11 +7,11 @@ function scheduleDay(string $date): DateTimeImmutable return new DateTimeImmutable($date); } -it('splits the estimate evenly over the working days of the period', function () { +it('fills the working days of the period in order', function () { // Fri 4.12.2026 – Tue 8.12.2026; the weekend in between gets nothing. $schedule = TaskScheduler::schedule(scheduleDay('2026-12-04'), scheduleDay('2026-12-08'), 600, [], 480, []); - expect($schedule->minutesByDay)->toBe(['2026-12-04' => 210, '2026-12-07' => 195, '2026-12-08' => 195]) + expect($schedule->minutesByDay)->toBe(['2026-12-04' => 480, '2026-12-07' => 120]) ->and($schedule->end->format('Y-m-d'))->toBe('2026-12-08') ->and($schedule->extended)->toBeFalse(); }); @@ -21,7 +21,7 @@ it('skips holidays and uses weekend days when the period has nothing else', func $weekend = TaskScheduler::schedule(scheduleDay('2026-12-05'), scheduleDay('2026-12-06'), 300, [], 480, []); expect($overHolidays->minutesByDay)->toBe(['2026-12-28' => 240]) - ->and($weekend->minutesByDay)->toBe(['2026-12-05' => 150, '2026-12-06' => 150]); + ->and($weekend->minutesByDay)->toBe(['2026-12-05' => 300]); }); it('moves what does not fit to the next working days and ends later', function () {