diff --git a/CLAUDE.md b/CLAUDE.md index df961e5..b7563ec 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), 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. +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); the Kanban `jobs::board` (docs/ui-kanban-board.md): `BoardView`/`BoardColumn` columns placed by `BoardLayout` (virtual urgent lane by each user's `UrgentThreshold`, the `ongoing` status's own column, tasks of continuing jobs pinned as cards via `tasks.is_pinned_to_board`), drag order in `board_position` through `MoveBoardCard`, per-user `job_board_preferences` (`BoardPreferences`: density, threshold, column colours and sorts), cards from `JobBoardQueries` with logged hours through the `LoggedJobHours` port (TimeTracking binds it); the board's job editor `jobs::job-editor` (traits `EditsJobDetails`, `DescribesJobHistory`, embeds `time::job-quick-hours` and `expenses::job-quick-expense`) and `jobs::quick` as a dialog (`inDialog`)) `TimeTracking` (hours on tasks: the weekly time sheet `time::week` (docs/ui-timesheet.md) with "Aikataulutettu" and "Lukitut työt" (`time_pinned_tasks`, `PinTimesheetTasks`) grouped by `TimesheetLayout`, H:MM cells (`WorkedHours::parseFlexible`), the entry's `EntryBillingModel`, billing note (`note`, required by `ApproveWeek`) and internal comment (`DescribeTimeEntry`), and a browser timer; and the 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. @@ -31,6 +31,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Company details** (name, business ID, address, phone, email) are kept by `Shared\Application\UseCases\CompanyDetailsStore` in the settings (`shared.company_*`) and edited by the admin on `shared::company` (`/settings/company`, gate `settings.manage`). `BusinessId` (Y-tunnus with check digit) is a Shared value object. The name at the left of the main menu is the optional "Valikon nimi" (`shared.company_menu_name`), read with `CompanyDetailsStore::menuName()` (falls back to `config('app.name')`). - **PDFs** use `barryvdh/laravel-dompdf` with a plain Blade view (no Tailwind; DejaVu Sans), streamed inline: see the quick sale receipt `Sales\Presentation\Http\Controllers\ShowReceipt` and `Sales/Presentation/Views/receipt.blade.php` (view namespace `sales-views`). - **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`. +- **Colours**: `Shared\Domain\ValueObjects\HexColor` (text colour by the higher contrast, `mixedInto` for tints); customers have `customers.header_color` (`ChangeCustomerHeaderColor`), shown on Kanban cards and time sheet rows. One `` per page, opened with `$dispatch('color-picker:open', {id, title, color, method, args, resettable})`. Large modal work areas use `` (native ``, optional `locked` Alpine expression). The dark canvas is `#5a5e60`: text placed directly on it needs zinc-100/200 or primary-100. - Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - Generate module files with Artisan, then edit them: `php artisan make:class Modules////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. diff --git a/app/Modules/Jobs/Application/UseCases/MoveBoardCard.php b/app/Modules/Jobs/Application/UseCases/MoveBoardCard.php index 9c9c9b1..b934282 100644 --- a/app/Modules/Jobs/Application/UseCases/MoveBoardCard.php +++ b/app/Modules/Jobs/Application/UseCases/MoveBoardCard.php @@ -125,7 +125,7 @@ final class MoveBoardCard $jobPositions = []; $taskPositions = []; - foreach (array_values($orderedKeys) as $index => $key) { + foreach ($orderedKeys as $index => $key) { if (preg_match('/^(job|task)-(\d+)$/', $key, $matches) !== 1) { continue; }