From 32c33e2a64f0ffe454cd369484da02e0e92a1a03 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Sun, 29 Nov 2026 09:58:11 +0200 Subject: [PATCH] Give the machine console its own session with PIN sign-in, make counters cumulative The console under console/ has its own session cookie and console guard (UseConsoleSession), so signing out or changing user there leaves the normal interface alone. Links open it in a new window through a one-time handoff key; a signed-out console asks for a PIN code or password on its own login page. Users set their 4-6 digit PIN on the profile's PIN page, and the console's change user dialog takes it on a keypad; five wrong PINs lock PIN sign-in for 15 minutes. Machine counters are cumulative: users record how much a job used and it is added to the latest reading. A maintenance record restarts the whole counter interval from the reading at the record. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 2 +- app/Models/User.php | 2 +- .../Inventory/Presentation/Routes/web.php | 7 ++ .../UseCases/MachineMaintenance.php | 50 ++++----- .../Domain/Services/MaintenanceStatus.php | 3 +- .../Concerns/DescribesMaintenance.php | 15 +++ .../Presentation/Livewire/⚡console.blade.php | 86 ++++++++------- .../Presentation/Livewire/⚡index.blade.php | 2 +- .../Livewire/⚡maintenance.blade.php | 60 +++++------ .../Presentation/Livewire/⚡show.blade.php | 3 +- .../Machines/Presentation/Routes/web.php | 7 +- .../Presentation/Livewire/⚡orders.blade.php | 2 +- .../Application/Contracts/SecretHasher.php | 15 +++ .../Contracts/UserAccountQueries.php | 8 ++ .../Users/Application/UseCases/LoginPins.php | 79 ++++++++++++++ .../Users/Domain/Contracts/LoginSecrets.php | 20 ++++ .../Domain/Exceptions/InvalidLoginPin.php | 15 +++ .../Users/Domain/Exceptions/WrongPassword.php | 15 +++ .../Users/Domain/ValueObjects/LoginPin.php | 31 ++++++ .../Auth/LaravelSecretHasher.php | 19 ++++ .../Repositories/EloquentLoginSecrets.php | 28 +++++ .../EloquentUserAccountQueries.php | 20 ++++ .../Providers/UsersServiceProvider.php | 10 ++ .../Http/Controllers/ConsoleHandoff.php | 65 +++++++++++ .../Controllers/ConsoleLogoutController.php | 34 ++++++ .../Http/Middleware/EnsureAccountIsUsable.php | 2 +- .../Http/Middleware/UseConsoleSession.php | 78 ++++++++++++++ .../Livewire/Concerns/SignsInWithPassword.php | 74 +++++++++++++ .../Livewire/Concerns/SignsInWithPin.php | 84 +++++++++++++++ .../Livewire/⚡console-login.blade.php | 81 ++++++++++++++ .../Presentation/Livewire/⚡login.blade.php | 59 +--------- .../Livewire/⚡pin-switch.blade.php | 83 ++++++++++++++ .../Presentation/Livewire/⚡pin.blade.php | 101 ++++++++++++++++++ app/Modules/Users/Presentation/Routes/web.php | 11 ++ bootstrap/app.php | 6 +- config/auth.php | 7 ++ ..._29_071643_add_pin_hash_to_users_table.php | 26 +++++ docs/maarittely.md | 14 +-- lang/en/layout.php | 1 + lang/en/machines.php | 19 ++-- lang/en/users.php | 41 +++++++ lang/fi/layout.php | 1 + lang/fi/machines.php | 19 ++-- lang/fi/users.php | 41 +++++++ .../views/components/profile-menu.blade.php | 9 ++ .../components/users/pin-fields.blade.php | 40 +++++++ tests/Browser/MachinesAccessibilityTest.php | 69 ++++++++++++ .../QuickSaleOrdersAccessibilityTest.php | 2 + tests/Fakes/FakeUserAccountQueries.php | 5 + .../Feature/Modules/Machines/ConsoleTest.php | 81 +++++++++++++- .../Modules/Machines/MaintenanceTest.php | 46 ++++++-- .../Modules/Users/ConsoleSessionTest.php | 97 +++++++++++++++++ tests/Feature/Modules/Users/LoginPinTest.php | 60 +++++++++++ .../Users/Application/LoginPinsTest.php | 87 +++++++++++++++ .../Modules/Users/Domain/LoginPinTest.php | 12 +++ 55 files changed, 1660 insertions(+), 194 deletions(-) create mode 100644 app/Modules/Users/Application/Contracts/SecretHasher.php create mode 100644 app/Modules/Users/Application/UseCases/LoginPins.php create mode 100644 app/Modules/Users/Domain/Contracts/LoginSecrets.php create mode 100644 app/Modules/Users/Domain/Exceptions/InvalidLoginPin.php create mode 100644 app/Modules/Users/Domain/Exceptions/WrongPassword.php create mode 100644 app/Modules/Users/Domain/ValueObjects/LoginPin.php create mode 100644 app/Modules/Users/Infrastructure/Auth/LaravelSecretHasher.php create mode 100644 app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentLoginSecrets.php create mode 100644 app/Modules/Users/Presentation/Http/Controllers/ConsoleHandoff.php create mode 100644 app/Modules/Users/Presentation/Http/Controllers/ConsoleLogoutController.php create mode 100644 app/Modules/Users/Presentation/Http/Middleware/UseConsoleSession.php create mode 100644 app/Modules/Users/Presentation/Livewire/Concerns/SignsInWithPassword.php create mode 100644 app/Modules/Users/Presentation/Livewire/Concerns/SignsInWithPin.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡console-login.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡pin-switch.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡pin.blade.php create mode 100644 database/migrations/2026_11_29_071643_add_pin_hash_to_users_table.php create mode 100644 resources/views/components/users/pin-fields.blade.php create mode 100644 tests/Feature/Modules/Users/ConsoleSessionTest.php create mode 100644 tests/Feature/Modules/Users/LoginPinTest.php create mode 100644 tests/Unit/Modules/Users/Application/LoginPinsTest.php create mode 100644 tests/Unit/Modules/Users/Domain/LoginPinTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 18a5caf..31bc2b8 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, 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); a monthly fee job's billed periods (its `monthly_fee` billing lines on created materials, with the months still to bill up to now through `MonthlyBillingViews`) on `billing::job-months`, linked from the job page's payment basis for `billing.manage`; 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`; receipts can be emailed (`ReceiptMailer`, queued `SendQuickSaleReceipt`, address encrypted on the sale); a sale of a product with a production process becomes a `QuickSaleOrder` with the day's pickup number (`QuickSaleOrders`: send, complete a step with its materials and hours, pay as an ordinary sale, cancel while unpaid; `sales::orders` on the quick sale page) through its `ProductionProcesses`, `ProductionQueue` and `OrderMaterials` ports) `Inventory` (stock, spec 19.1–19.3: item groups, items with an optional image (`StockItemImages` on the private disk, via Shared's `ImageResizer`) and a moving average cost kept in hundredths of a cent per unit (`StockValuation`), movements whose sum is the balance (quantities in thousandths, `StockQuantity`; purchase, use, write-off, stock count correction, reversal; never changed or deleted, users reverse their own use of the day), `inventory::task-materials` (Used material in a job's task card, with a workflow step's default materials as suggestions from Jobs' `TaskMaterialsSuggested` event) and stock counts (`InventoryCounts`, CSV); a task with stock movements is kept like one with hours (`TaskUsageWithStock` decorates Jobs' `TaskUsage`); `StockQueries`/`StockReportQueries` are read by other modules) `Machines` (spec 19.4–19.7: machines in service units that use stock, their counters, the day-by-day work list `MachineWorkList` (`machine_queue_entries`: job tasks via `machines::task-machine` in the task card, or steps of quick sale order lines; a finished task row marks the task done through its `MachineTasks` port, and Jobs' `TaskCompleted` event closes the row), maintenance items with a counter interval and/or a time interval (`MaintenancePeriod` day/week/month/year × N, `MaintenanceStatus`), maintenance records and the daily `notifications:maintenance-due` requests to the machine's responsible person, the touch-screen `machines::console` (layout `layouts.console`, no main menu; Change user logs out with `return_to`), and products' production processes `production_steps`) 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; stock usage and stock value behind `reports.stock`, and stock used on jobs as a material cost in profitability through `ReportStock`)); `/` (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); a monthly fee job's billed periods (its `monthly_fee` billing lines on created materials, with the months still to bill up to now through `MonthlyBillingViews`) on `billing::job-months`, linked from the job page's payment basis for `billing.manage`; 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`; receipts can be emailed (`ReceiptMailer`, queued `SendQuickSaleReceipt`, address encrypted on the sale); a sale of a product with a production process becomes a `QuickSaleOrder` with the day's pickup number (`QuickSaleOrders`: send, complete a step with its materials and hours, pay as an ordinary sale, cancel while unpaid; `sales::orders` on the quick sale page) through its `ProductionProcesses`, `ProductionQueue` and `OrderMaterials` ports) `Inventory` (stock, spec 19.1–19.3: item groups, items with an optional image (`StockItemImages` on the private disk, via Shared's `ImageResizer`) and a moving average cost kept in hundredths of a cent per unit (`StockValuation`), movements whose sum is the balance (quantities in thousandths, `StockQuantity`; purchase, use, write-off, stock count correction, reversal; never changed or deleted, users reverse their own use of the day), `inventory::task-materials` (Used material in a job's task card, with a workflow step's default materials as suggestions from Jobs' `TaskMaterialsSuggested` event) and stock counts (`InventoryCounts`, CSV); a task with stock movements is kept like one with hours (`TaskUsageWithStock` decorates Jobs' `TaskUsage`); `StockQueries`/`StockReportQueries` are read by other modules) `Machines` (spec 19.4–19.7: machines in service units that use stock, their cumulative counters (users record a job's usage, `MachineMaintenance::recordUsage` adds it to the latest reading; the console suggests booked hours for `hour` counters), the day-by-day work list `MachineWorkList` (`machine_queue_entries`: job tasks via `machines::task-machine` in the task card, or steps of quick sale order lines; a finished task row marks the task done through its `MachineTasks` port, and Jobs' `TaskCompleted` event closes the row), maintenance items with a counter interval and/or a time interval (`MaintenancePeriod` day/week/month/year × N, `MaintenanceStatus`; a maintenance record resets the item: the counter interval counts down from the whole interval from the reading at the record, and the time interval restarts on the maintenance day), maintenance records and the daily `notifications:maintenance-due` requests to the machine's responsible person, the touch-screen `machines::console` at `/console/machines/{id}` (layout `layouts.console`, no main menu). The console has its own session: Users' `UseConsoleSession` (prepended to `web`) gives paths under `console/`, and Livewire requests whose snapshot `memo.path` is there, their own session cookie (`…_console`) and the `console` guard (`Auth::shouldUse`), so `auth()`, Gate and `can:` work unchanged; pages the console needs must live under `console/` (e.g. `inventory.items.console-image`). Links open it in a new window through `console.handoff` (a one-time cache key, 60 s); a signed-out console goes to `console.login` (`users::console-login`, PIN or password), `console.logout` signs out of the console only, and `/login` always signs in to the normal interface. Change user is `users::pin-switch` with the user's own console PIN code (`users.pin_hash`, set on `users::pin` at `/profile/pin`, `LoginPins`; traits `SignsInWithPin`, `SignsInWithPassword`). In tests, act on the console with `actingAs($user, 'console')`), and products' production processes `production_steps`) 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; stock usage and stock value behind `reports.stock`, and stock used on jobs as a material cost in profitability through `ReportStock`)); `/` (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/Models/User.php b/app/Models/User.php index 1cc5651..3f5b98d 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -33,7 +33,7 @@ use Illuminate\Support\Carbon; * @property-read UserMoneyPermissionsModel|null $moneyPermissions */ #[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id', 'locale'])] -#[Hidden(['password', 'remember_token'])] +#[Hidden(['password', 'remember_token', 'pin_hash'])] class User extends Authenticatable implements HasLocalePreference { /** @use HasFactory */ diff --git a/app/Modules/Inventory/Presentation/Routes/web.php b/app/Modules/Inventory/Presentation/Routes/web.php index 7926ccf..2a96138 100644 --- a/app/Modules/Inventory/Presentation/Routes/web.php +++ b/app/Modules/Inventory/Presentation/Routes/web.php @@ -4,6 +4,13 @@ use App\Modules\Inventory\Presentation\Http\Controllers\DownloadInventoryCount; use App\Modules\Inventory\Presentation\Http\Controllers\ShowStockItemImage; use Illuminate\Support\Facades\Route; +// Pictures on the machine console, which has its own session (paths under console/). +Route::middleware(['web', 'auth', 'can:inventory.view']) + ->get('/console/inventory/items/{item}/image/{size}', ShowStockItemImage::class) + ->whereNumber('item') + ->whereIn('size', ['full', 'thumbnail']) + ->name('inventory.items.console-image'); + Route::middleware(['web', 'auth', 'can:inventory.view']) ->prefix('inventory') ->name('inventory.') diff --git a/app/Modules/Machines/Application/UseCases/MachineMaintenance.php b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php index 86098dc..0a76b87 100644 --- a/app/Modules/Machines/Application/UseCases/MachineMaintenance.php +++ b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php @@ -24,7 +24,7 @@ use App\Modules\Users\Application\Contracts\Clock; /** * Machine maintenance (spec 19.5): maintenance items are kept by - * management; counter readings and maintenance done are recorded by + * management; counter usage and maintenance done are recorded by * anyone using the machine. A maintenance record starts the item's * intervals again and uses up its stock item; a mistaken record is * cancelled by management, never deleted. @@ -98,50 +98,52 @@ final class MachineMaintenance } /** - * Records a counter's reading, e.g. the machine's own total counter. + * Records how much of a counter one job used (spec 19.5): counters are + * cumulative, so the usage is added to the counter's latest reading. + * + * @return int The counter's new reading. * * @throws CounterNotFound * @throws InvalidReading */ - public function recordReading(int $counterId, string $reading, int $actorUserId): int + public function recordUsage(int $counterId, string $usage, int $actorUserId): int { - $milli = Reading::parse($reading) ?? throw new InvalidReading; + $usageMilli = Reading::parse($usage); - $this->transactions->run(function () use ($counterId, $milli, $actorUserId): void { + if ($usageMilli === null || $usageMilli <= 0) { + throw new InvalidReading; + } + + return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int { $this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound; - $this->maintenance->addReading($counterId, $milli, $actorUserId, $this->clock->now()); - }); + $reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli; + $this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now()); - return $milli; + return $reading; + }); } /** - * Records maintenance done (Huolto tehty) with the counter's reading - * (the latest one when not given) and uses up the item's stock item. + * Records maintenance done (Huolto tehty) at the counter's latest + * reading and uses up the item's stock item. This resets the item: the + * whole counter interval is left again, counted from this reading, and + * the time interval starts again from today. * * @return array{recordId: int, stockRecorded: bool} * * @throws MaintenanceItemNotFound - * @throws InvalidReading */ - public function recordMaintenance(int $itemId, int $actorUserId, string $reading = '', ?string $note = null): array + public function recordMaintenance(int $itemId, int $actorUserId, ?string $note = null): array { - $readingMilli = Reading::parse($reading); $note = $note === null ? '' : trim($note); - return $this->transactions->run(function () use ($itemId, $actorUserId, $readingMilli, $note): array { + return $this->transactions->run(function () use ($itemId, $actorUserId, $note): array { $item = $this->maintenance->findItem($itemId) ?? throw new MaintenanceItemNotFound; - $now = $this->clock->now(); + $readingMilli = $item->counterId() === null + ? null + : ($this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli()); - if ($item->counterId() !== null) { - if ($readingMilli !== null) { - $this->maintenance->addReading($item->counterId(), $readingMilli, $actorUserId, $now); - } else { - $readingMilli = $this->maintenance->latestReading($item->counterId()) ?? $item->baselineMilli(); - } - } - - $recordId = $this->maintenance->addRecord($itemId, $now, $actorUserId, $item->counterId() === null ? null : $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000)); + $recordId = $this->maintenance->addRecord($itemId, $this->clock->now(), $actorUserId, $readingMilli, $note === '' ? null : mb_substr($note, 0, 2000)); $stockRecorded = $item->stockItemId() === null || $this->materials->use($item->stockItemId(), (int) $item->stockQuantityMilli(), $item->machineId(), $recordId, $actorUserId); diff --git a/app/Modules/Machines/Domain/Services/MaintenanceStatus.php b/app/Modules/Machines/Domain/Services/MaintenanceStatus.php index e4b76bf..024e5a5 100644 --- a/app/Modules/Machines/Domain/Services/MaintenanceStatus.php +++ b/app/Modules/Machines/Domain/Services/MaintenanceStatus.php @@ -12,7 +12,8 @@ use DateTimeImmutable; /** * Works out a maintenance item's state from what has accumulated since its * last maintenance (spec 19.5). The counter interval counts the counter's - * latest reading minus its reading at the last maintenance; the time + * latest reading minus its reading at the last maintenance, so a + * maintenance starts the whole interval again; the time * interval counts calendar periods from the day of the last maintenance. * With both, maintenance is due when either is. The advance warning * applies to both, but not to daily maintenance. diff --git a/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php b/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php index 63fc52d..04e9161 100644 --- a/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php +++ b/app/Modules/Machines/Presentation/Livewire/Concerns/DescribesMaintenance.php @@ -2,7 +2,9 @@ namespace App\Modules\Machines\Presentation\Livewire\Concerns; +use App\Modules\Machines\Application\DTOs\CounterSummary; use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus; +use App\Modules\Machines\Domain\ValueObjects\Reading; /** * Texts of a maintenance item's state, shared by the machine page and the @@ -68,4 +70,17 @@ trait DescribesMaintenance return implode(__('machines.maintenance.or'), $parts); } + + /** + * E.g. "Laskuriin Tulosteet lisätty 350 kpl, laskuri nyt 20 350 kpl." + */ + public function usageSaved(CounterSummary $counter, string $usage, int $readingMilli): string + { + return __('machines.maintenance.usage_saved', [ + 'counter' => $counter->name, + 'usage' => $this->reading((int) Reading::parse($usage)), + 'reading' => $this->reading($readingMilli), + 'unit' => __('machines.counter_units.'.$counter->unit->value), + ]); + } } diff --git a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php index 1a6af6b..d1c5162 100644 --- a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php +++ b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php @@ -17,6 +17,8 @@ use App\Modules\Machines\Application\DTOs\MaintenanceItemStatus; use App\Modules\Machines\Application\DTOs\QueueRow; use App\Modules\Machines\Application\UseCases\MachineMaintenance; use App\Modules\Machines\Application\UseCases\MachineWorkList; +use App\Modules\Machines\Domain\Enums\CounterUnit; +use App\Modules\Machines\Domain\ValueObjects\Reading; use App\Modules\Machines\Presentation\Livewire\Concerns\DescribesMaintenance; use App\Modules\Sales\Application\Contracts\QuickSaleOrderQueries; use App\Modules\Sales\Application\DTOs\OrderLineSummary; @@ -36,8 +38,9 @@ use Livewire\Component; * for the tablet or touch screen next to a machine. It shows today's work * list (late rows of earlier days included; the next day can be viewed), * lets the user start and finish tasks, record the material used with - * large item buttons, frequent items first, record today's hours, counter - * readings and maintenance. Touch targets are at least 44 × 44 px. The + * large item buttons, frequent items first, record today's hours (which + * are suggested as the usage of the machine's hour counters), counter + * usage and maintenance. Touch targets are at least 44 × 44 px. The * view refreshes itself, and the Refresh button fetches the latest state * at once and tells what changed. */ @@ -85,15 +88,15 @@ new #[Layout('layouts.console')] class extends Component public string $hours = ''; /** + * Usage typed, by counter id. + * * @var array */ - public array $readings = []; + public array $usage = []; #[Locked] public ?int $recordingItemId = null; - public string $recordReading = ''; - #[Locked] public string $message = ''; @@ -487,35 +490,55 @@ new #[Layout('layouts.console')] class extends Component } $this->message = __('machines.console.hours_saved', ['hours' => $this->hours, 'title' => $task->title, 'total' => $total]); + $this->suggestHourCounters($this->hours); $this->hours = ''; } - public function saveReading(int $counterId, MachineMaintenance $maintenance): void + /** + * Hours just booked on the machine are suggested as the usage of its + * hour counters; nothing is recorded until the user saves the counter. + */ + private function suggestHourCounters(string $hours): void + { + $milli = Reading::parse($hours); + + if ($milli === null || $milli <= 0) { + return; + } + + foreach ($this->machine->counters as $counter) { + if ($counter->unit === CounterUnit::Hour) { + $this->usage[$counter->id] = str_replace("\u{00A0}", '', $this->reading($milli)); + $this->message .= ' '.__('machines.console.hour_suggestion', ['hours' => $this->reading($milli), 'counter' => $counter->name]); + } + } + } + + public function saveUsage(int $counterId, MachineMaintenance $maintenance): void { $this->authorize('machines.use'); - $this->resetErrorBag('readings.'.$counterId); + $this->resetErrorBag('usage.'.$counterId); $counter = collect($this->machine->counters)->firstWhere('id', $counterId) ?? abort(404); + $usage = $this->usage[$counterId] ?? ''; try { - $milli = $maintenance->recordReading($counterId, $this->readings[$counterId] ?? '', (int) auth()->id()); + $milli = $maintenance->recordUsage($counterId, $usage, (int) auth()->id()); } catch (DomainException) { - $this->addError('readings.'.$counterId, __('machines.maintenance.errors.reading')); + $this->addError('usage.'.$counterId, __('machines.maintenance.errors.usage')); return; } - $this->message = __('machines.maintenance.reading_saved', ['counter' => $counter->name, 'reading' => $this->reading($milli), 'unit' => __('machines.counter_units.'.$counter->unit->value)]); - unset($this->readings[$counterId], $this->machine, $this->maintenance); + $this->message = $this->usageSaved($counter, $usage, $milli); + unset($this->usage[$counterId], $this->machine, $this->maintenance); } public function startMaintenance(int $itemId): void { $this->authorize('machines.use'); - $item = collect($this->maintenance)->firstWhere('id', $itemId) ?? abort(404); - $this->recordingItemId = $itemId; - $this->recordReading = $item->readingMilli === null ? '' : str_replace("\u{00A0}", '', $this->reading($item->readingMilli)); + $this->recordingItemId = (collect($this->maintenance)->firstWhere('id', $itemId) ?? abort(404))->id; $this->js("setTimeout(() => document.getElementById('maintenance-confirm')?.focus())"); } @@ -526,11 +549,9 @@ new #[Layout('layouts.console')] class extends Component $item = collect($this->maintenance)->firstWhere('id', $this->recordingItemId) ?? abort(404); try { - $result = $maintenance->recordMaintenance($item->id, (int) auth()->id(), $item->counterId === null ? '' : $this->recordReading); + $result = $maintenance->recordMaintenance($item->id, (int) auth()->id()); } catch (DomainException) { - $this->addError('recordReading', __('machines.maintenance.errors.reading')); - - return; + abort(404); } $this->message = __('machines.maintenance.recorded', ['name' => $item->name]).($result['stockRecorded'] ? '' : ' '.__('machines.maintenance.stock_not_recorded')); @@ -612,14 +633,8 @@ new #[Layout('layouts.console')] class extends Component