diff --git a/CLAUDE.md b/CLAUDE.md index 31bc2b8..146e42b 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 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. +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), which returns to the console page that asked or else to the console's machine list `machines::console-picker` (`/console/machines`), `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/Modules/Machines/Application/UseCases/MachineMaintenance.php b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php index 0a76b87..87cb655 100644 --- a/app/Modules/Machines/Application/UseCases/MachineMaintenance.php +++ b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php @@ -115,7 +115,10 @@ final class MachineMaintenance } return $this->transactions->run(function () use ($counterId, $usageMilli, $actorUserId): int { - $this->maintenance->machineOfCounter($counterId) ?? throw new CounterNotFound; + if (! $this->maintenance->lockCounter($counterId)) { + throw new CounterNotFound; + } + $reading = ($this->maintenance->latestReading($counterId) ?? 0) + $usageMilli; $this->maintenance->addReading($counterId, $reading, $actorUserId, $this->clock->now()); diff --git a/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php b/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php index f7532bd..c1a81c6 100644 --- a/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php +++ b/app/Modules/Machines/Domain/Contracts/MaintenanceRepository.php @@ -21,6 +21,14 @@ interface MaintenanceRepository */ public function machineOfCounter(int $counterId): ?int; + /** + * Locks the counter until the transaction ends, so usage recorded at + * the same time is added one after the other. + * + * @return bool Whether the counter exists. + */ + public function lockCounter(int $counterId): bool; + public function latestReading(int $counterId): ?int; public function addReading(int $counterId, int $readingMilli, int $userId, DateTimeImmutable $at): void; diff --git a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php index 40a8284..aad43a8 100644 --- a/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php +++ b/app/Modules/Machines/Infrastructure/Persistence/Repositories/EloquentMaintenanceRepository.php @@ -64,6 +64,11 @@ class EloquentMaintenanceRepository implements MaintenanceRepository return $machineId === null ? null : (int) $machineId; } + public function lockCounter(int $counterId): bool + { + return MachineCounterModel::query()->whereKey($counterId)->lockForUpdate()->exists(); + } + public function latestReading(int $counterId): ?int { $reading = MachineCounterReadingModel::query() diff --git a/app/Modules/Machines/Presentation/Livewire/⚡console-picker.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡console-picker.blade.php new file mode 100644 index 0000000..3edfcfb --- /dev/null +++ b/app/Modules/Machines/Presentation/Livewire/⚡console-picker.blade.php @@ -0,0 +1,62 @@ +authorize('machines.use'); + } + + /** + * @return list + */ + #[Computed] + public function machines(): array + { + return app(MachineQueries::class)->machines(false); + } + + public function render(): mixed + { + return $this->view()->title(__('machines.console_picker.title')); + } +}; +?> + +
+

{{ __('machines.console_picker.title') }}

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

{{ __('machines.console_picker.empty') }}

+ @else +

{{ __('machines.console_picker.intro') }}

+ + + @endif +
diff --git a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php index d1c5162..a11e46c 100644 --- a/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php +++ b/app/Modules/Machines/Presentation/Livewire/⚡console.blade.php @@ -500,7 +500,12 @@ new #[Layout('layouts.console')] class extends Component */ private function suggestHourCounters(string $hours): void { - $milli = Reading::parse($hours); + // The hours are already saved; hours Reading does not read (",5") get no suggestion. + try { + $milli = Reading::parse($hours); + } catch (DomainException) { + return; + } if ($milli === null || $milli <= 0) { return; diff --git a/app/Modules/Machines/Presentation/Routes/web.php b/app/Modules/Machines/Presentation/Routes/web.php index 1e5f918..6945b1d 100644 --- a/app/Modules/Machines/Presentation/Routes/web.php +++ b/app/Modules/Machines/Presentation/Routes/web.php @@ -19,7 +19,7 @@ Route::middleware(['web', 'auth', 'can:machines.use']) }); // The console has its own session (Users' UseConsoleSession: paths under console/). -Route::livewire('/console/machines/{machine}', 'machines::console') - ->middleware(['web', 'auth', 'can:machines.use']) - ->whereNumber('machine') - ->name('machines.console'); +Route::middleware(['web', 'auth', 'can:machines.use'])->group(function () { + Route::livewire('/console/machines', 'machines::console-picker')->name('machines.console-picker'); + Route::livewire('/console/machines/{machine}', 'machines::console')->whereNumber('machine')->name('machines.console'); +}); diff --git a/app/Modules/Users/Presentation/Livewire/⚡console-login.blade.php b/app/Modules/Users/Presentation/Livewire/⚡console-login.blade.php index 9e24c97..ef624d9 100644 --- a/app/Modules/Users/Presentation/Livewire/⚡console-login.blade.php +++ b/app/Modules/Users/Presentation/Livewire/⚡console-login.blade.php @@ -27,7 +27,7 @@ new #[Layout('layouts.console')] class extends Component public function loginWithPin(LoginPins $pins): void { if ($this->signInWithPin($pins)) { - $this->redirectIntended(route('machines.index')); + $this->redirectIntended(route('machines.console-picker')); } } @@ -35,7 +35,7 @@ new #[Layout('layouts.console')] class extends Component { $this->signInWithPassword($checkLoginAllowed); - $this->redirectIntended(route('machines.index')); + $this->redirectIntended(route('machines.console-picker')); } public function render(): mixed diff --git a/bootstrap/app.php b/bootstrap/app.php index c30641e..df34f94 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -15,7 +15,7 @@ return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware): void { // The machine console has its own session and sign-in page. $middleware->redirectGuestsTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('console.login') : route('login')); - $middleware->redirectUsersTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('machines.index') : route('home')); + $middleware->redirectUsersTo(fn (Request $request) => UseConsoleSession::isConsole($request) ? route('machines.console-picker') : route('home')); }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->shouldRenderJsonWhen( diff --git a/lang/en/machines.php b/lang/en/machines.php index a526309..c61829c 100644 --- a/lang/en/machines.php +++ b/lang/en/machines.php @@ -220,6 +220,11 @@ return [ 'usage' => 'Enter the amount the job used as a number greater than zero, e.g. 350, at most three decimals.', ], ], + 'console_picker' => [ + 'title' => 'Machine console', + 'intro' => 'Choose the machine you are working at.', + 'empty' => 'There are no machines in use.', + ], 'console' => [ 'ordered_at' => 'ordered at :time', 'order_step' => 'step :step/:steps', diff --git a/lang/fi/machines.php b/lang/fi/machines.php index 13bb756..fc83683 100644 --- a/lang/fi/machines.php +++ b/lang/fi/machines.php @@ -220,6 +220,11 @@ return [ 'usage' => 'Anna työn kulutus nollaa suurempana lukuna, esim. 350, enintään kolme desimaalia.', ], ], + 'console_picker' => [ + 'title' => 'Konekäyttöliittymä', + 'intro' => 'Valitse kone, jonka vieressä olet.', + 'empty' => 'Käytössä olevia koneita ei ole.', + ], 'console' => [ 'ordered_at' => 'tilattu klo :time', 'order_step' => 'vaihe :step/:steps', diff --git a/tests/Browser/MachinesAccessibilityTest.php b/tests/Browser/MachinesAccessibilityTest.php index 0d7e8b6..41f2162 100644 --- a/tests/Browser/MachinesAccessibilityTest.php +++ b/tests/Browser/MachinesAccessibilityTest.php @@ -51,6 +51,7 @@ it('has no accessibility issues on the machine pages', function (string $page, s 'form' => route('machines.edit', $this->machine->id), 'job' => route('jobs.show', $this->job->id).'#task-'.$this->task->id, 'maintenance' => route('machines.maintenance.create', $this->machine->id), + 'console picker' => route('machines.console-picker'), }; $visit = visit($url); @@ -64,7 +65,7 @@ it('has no accessibility issues on the machine pages', function (string $page, s $visit->assertSee($page === 'form' ? __('machines.form.edit_title') : 'Suurkuvatulostin') ->assertNoJavaScriptErrors() ->assertNoAccessibilityIssues(level: 2); -})->with(['index', 'show', 'form', 'job', 'maintenance'])->with([ +})->with(['index', 'show', 'form', 'job', 'maintenance', 'console picker'])->with([ 'desktop, light' => ['desktop', 'light'], 'desktop, dark' => ['desktop', 'dark'], 'mobile, light' => ['mobile', 'light'], diff --git a/tests/Feature/Modules/Machines/ConsoleTest.php b/tests/Feature/Modules/Machines/ConsoleTest.php index 8b32ecd..23d8e7f 100644 --- a/tests/Feature/Modules/Machines/ConsoleTest.php +++ b/tests/Feature/Modules/Machines/ConsoleTest.php @@ -155,6 +155,21 @@ it('suggests the hours booked as the usage of the machine\'s hour counter and le expect(MachineCounterReadingModel::query()->sole()->reading_milli)->toBe(1_500); }); +it('saves hours written as ",5" without a counter suggestion it cannot read', function () { + $hours = MachineCounterModel::query()->create(['machine_id' => $this->machine->id, 'name' => 'Käyttötunnit', 'unit' => 'hour', 'sort_order' => 1]); + + console($this) + ->call('selectRow', MachineQueueEntryModel::query()->sole()->id) + ->set('hours', ',5') + ->call('saveHours') + ->assertHasNoErrors() + ->assertSet('hours', '') + ->assertSet('usage', []); + + expect(TimeEntryModel::query()->sole()->hours)->toEqual(0.5) + ->and(MachineCounterReadingModel::query()->where('machine_counter_id', $hours->id)->exists())->toBeFalse(); +}); + it('changes the console\'s user with a PIN code', function () { $console = route('machines.console', $this->machine->id); $other = User::factory()->employee()->create(['name' => 'Olli Operaattori', 'pin_hash' => Hash::make('2468')]); diff --git a/tests/Feature/Modules/Users/ConsoleSessionTest.php b/tests/Feature/Modules/Users/ConsoleSessionTest.php index dfcef0e..3b36051 100644 --- a/tests/Feature/Modules/Users/ConsoleSessionTest.php +++ b/tests/Feature/Modules/Users/ConsoleSessionTest.php @@ -49,7 +49,7 @@ it('asks a signed-out console to sign in on the console\'s own page and keeps /l $this->actingAs($this->user, 'console'); $this->get(route('login'))->assertOk(); - $this->get(route('console.login'))->assertRedirect(route('machines.index')); + $this->get(route('console.login'))->assertRedirect(route('machines.console-picker')); }); it('signs out of the console without signing out of the normal user interface', function () { @@ -83,6 +83,24 @@ it('signs in to the console with a PIN code or a password', function () { ->assertRedirect($this->console); }); +it('goes to the console\'s machine list, in the console\'s own session, when no machine asked for the sign-in', function () { + $this->user->forceFill(['pin_hash' => Hash::make('2468')])->save(); + + Livewire::test('users::console-login') + ->set('userId', (string) $this->user->id) + ->set('pin', '2468') + ->call('loginWithPin') + ->assertRedirect(route('machines.console-picker')); + + expect(UseConsoleSession::isConsoleUrl(route('machines.console-picker')))->toBeTrue(); + + $this->actingAs($this->user, 'console') + ->get(route('machines.console-picker')) + ->assertOk() + ->assertSee('Suurkuvatulostin') + ->assertSee($this->console); +}); + it('tells console requests by their path or by where their Livewire component was rendered', function () { $livewire = fn (string $path): Request => tap( Request::create('/livewire-1234/update', 'POST', ['components' => [['snapshot' => json_encode(['memo' => ['path' => $path]])]]]),