diff --git a/CLAUDE.md b/CLAUDE.md index aed56cb..18a5caf 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`) 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); 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. - **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. @@ -23,7 +23,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `jobs.remove-any-task-comment`, `jobs.remove-any-task-image`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, `reports.view`, `dashboard.management`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. +- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `jobs.remove-any-task-comment`, `jobs.remove-any-task-image`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, `reports.view`, `reports.stock`, `dashboard.management`, `inventory.view`, `inventory.record-use`, `inventory.count`, `inventory.manage`, `inventory.manage-counts`, `inventory.reverse-any`, `inventory.see-value`, `inventory.menu`, `machines.use`, `machines.manage`, `machines.menu`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Main menu**: the layout renders the groups of `App\View\MainMenu` (Työt, Oma kirjaus, Asiakkaat ja myynti, Hallinto (incl. the reports), Ylläpito) as disclosure popovers (`resources/views/components/nav-group.blade.php`). A new page is added to `MainMenu::definition()` with the Gate ability of its route; groups with no allowed links disappear. - **Notifications** are their own module (`Notifications`): the header's bell `notifications::bell` (beside the profile menu) shows the unseen count and the last 7 days of `user_notifications`, and opening it marks them seen. Texts are made at display time from `NotificationType` and its `params` (`lang/*/notifications.php`). `NotifyTasksStartingSoon` (`notifications:task-starts`, scheduled daily at 14.00 business time in `routes/console.php`) notifies the assignee and members of tasks starting by the next working day through Jobs' `UpcomingTasks` port; `dedupe_key` keeps reruns from notifying twice. Jobs' use cases publish `PeopleAddedToTask` and `PeopleAddedToJob` (Domain events, after commit) when someone else is made a task's assignee or member or gets a role on a job; `NotifyAddedPeople` turns them into notifications at once, never for the actor's own changes. The scheduler needs `php artisan schedule:run` every minute (cron / Windows Task Scheduler; locally `php artisan schedule:work`). diff --git a/app/Modules/Inventory/Application/Contracts/StockReportQueries.php b/app/Modules/Inventory/Application/Contracts/StockReportQueries.php new file mode 100644 index 0000000..3a2e5fd --- /dev/null +++ b/app/Modules/Inventory/Application/Contracts/StockReportQueries.php @@ -0,0 +1,36 @@ + + */ + public function usage(string $from, string $to): array; + + /** + * Every item with movements up to the day, or in use, in group order. + * + * @return list + */ + public function valueOn(string $day): array; + + /** + * The value of the stock used and written off on jobs' tasks between + * the days, by job id (spec 19.8: material cost in profitability). + * + * @return array + */ + public function materialCostsByJob(string $from, string $to): array; +} diff --git a/app/Modules/Inventory/Application/DTOs/StockUsageEntry.php b/app/Modules/Inventory/Application/DTOs/StockUsageEntry.php new file mode 100644 index 0000000..2e9bd78 --- /dev/null +++ b/app/Modules/Inventory/Application/DTOs/StockUsageEntry.php @@ -0,0 +1,27 @@ +reorderLevelMilli !== null && $this->balanceMilli <= $this->reorderLevelMilli; + } +} diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockReportQueries.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockReportQueries.php new file mode 100644 index 0000000..b456c63 --- /dev/null +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockReportQueries.php @@ -0,0 +1,94 @@ +leftJoin('stock_movements as o', 'o.id', '=', 'm.reverses_movement_id') + ->join('stock_items as i', 'i.id', '=', 'm.stock_item_id') + ->join('stock_item_groups as g', 'g.id', '=', 'i.stock_item_group_id') + ->whereDate('m.occurred_on', '>=', $from) + ->whereDate('m.occurred_on', '<=', $to) + ->where(fn (Builder $query) => $query + ->whereIn('m.kind', ['consumption', 'write_off', 'adjustment']) + ->orWhere(fn (Builder $query) => $query->where('m.kind', 'reversal')->whereIn('o.kind', ['consumption', 'write_off']))) + ->selectRaw("i.id as item_id, i.name as item_name, g.name as group_name, i.unit as unit, CASE WHEN m.kind = 'reversal' THEN o.kind ELSE m.kind END as kind, m.machine_id, m.customer_job_id, SUM(m.quantity_milli) as quantity, SUM(m.value_cents) as value") + ->groupBy('i.id', 'i.name', 'g.name', 'i.unit', DB::raw("CASE WHEN m.kind = 'reversal' THEN o.kind ELSE m.kind END"), 'm.machine_id', 'm.customer_job_id') + ->orderBy('g.name') + ->orderBy('i.name') + ->get(); + + return $rows + ->map(fn (object $row): StockUsageEntry => new StockUsageEntry( + (int) $row->item_id, + (string) $row->item_name, + (string) $row->group_name, + (string) $row->unit, + (string) $row->kind, + $row->machine_id === null ? null : (int) $row->machine_id, + $row->customer_job_id === null ? null : (int) $row->customer_job_id, + -(int) $row->quantity, + -(int) $row->value, + )) + ->filter(fn (StockUsageEntry $entry): bool => $entry->quantityMilli !== 0 || $entry->valueCents !== 0) + ->values() + ->all(); + } + + public function valueOn(string $day): array + { + $sums = DB::table('stock_movements') + ->whereDate('occurred_on', '<=', $day) + ->groupBy('stock_item_id') + ->selectRaw('stock_item_id, SUM(quantity_milli) as quantity, SUM(value_cents) as value') + ->get() + ->keyBy('stock_item_id'); + + return DB::table('stock_items as i') + ->join('stock_item_groups as g', 'g.id', '=', 'i.stock_item_group_id') + ->orderBy('g.sort_order') + ->orderBy('i.name') + ->get(['i.id', 'i.name', 'i.unit', 'i.reorder_level_milli', 'i.is_active', 'g.name as group_name']) + ->filter(fn (object $item): bool => (bool) $item->is_active || $sums->has($item->id)) + ->map(fn (object $item): StockValueEntry => new StockValueEntry( + (int) $item->id, + (string) $item->name, + (string) $item->group_name, + (string) $item->unit, + (int) ($sums->get($item->id)->quantity ?? 0), + (int) ($sums->get($item->id)->value ?? 0), + $item->reorder_level_milli === null ? null : (int) $item->reorder_level_milli, + (bool) $item->is_active, + )) + ->values() + ->all(); + } + + public function materialCostsByJob(string $from, string $to): array + { + return DB::table('stock_movements') + ->whereNotNull('customer_job_id') + ->whereIn('kind', ['consumption', 'write_off', 'reversal']) + ->whereDate('occurred_on', '>=', $from) + ->whereDate('occurred_on', '<=', $to) + ->groupBy('customer_job_id') + ->selectRaw('customer_job_id, SUM(value_cents) as value') + ->pluck('value', 'customer_job_id') + ->map(fn ($value): int => -(int) $value) + ->filter(fn (int $value): bool => $value !== 0) + ->all(); + } +} diff --git a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php index 7a0fadc..4d3e186 100644 --- a/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php +++ b/app/Modules/Inventory/Infrastructure/Providers/InventoryServiceProvider.php @@ -7,6 +7,7 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Inventory\Application\Contracts\InventoryCountQueries; use App\Modules\Inventory\Application\Contracts\StockItemImages; use App\Modules\Inventory\Application\Contracts\StockQueries; +use App\Modules\Inventory\Application\Contracts\StockReportQueries; use App\Modules\Inventory\Application\Contracts\StockTasks; use App\Modules\Inventory\Application\UseCases\TaskMaterials; use App\Modules\Inventory\Domain\Contracts\InventoryCountRepository; @@ -23,6 +24,7 @@ use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockI use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockItemRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockMovementRepository; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockQueries; +use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentStockReportQueries; use App\Modules\Inventory\Infrastructure\Persistence\Repositories\EloquentTaskMaterialSuggestionRepository; use App\Modules\Jobs\Application\Contracts\TaskUsage; use App\Modules\Jobs\Domain\Events\TaskMaterialsSuggested; @@ -52,6 +54,7 @@ class InventoryServiceProvider extends ServiceProvider StockTasks::class => TasksForStock::class, InventoryCountRepository::class => EloquentInventoryCountRepository::class, InventoryCountQueries::class => EloquentInventoryCountQueries::class, + StockReportQueries::class => EloquentStockReportQueries::class, ]; public function register(): void diff --git a/app/Modules/Reports/Application/Contracts/ReportStock.php b/app/Modules/Reports/Application/Contracts/ReportStock.php new file mode 100644 index 0000000..ba85036 --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportStock.php @@ -0,0 +1,39 @@ + + */ + public function usage(ReportPeriod $period): array; + + /** + * @return list + */ + public function valueOn(string $day): array; + + /** + * The value of stock used on each job's tasks, by job id. + * + * @return array + */ + public function materialCostsByJob(ReportPeriod $period): array; + + /** + * @param list $ids + * @return array + */ + public function machineNames(array $ids): array; +} diff --git a/app/Modules/Reports/Application/DTOs/StockUsageReportData.php b/app/Modules/Reports/Application/DTOs/StockUsageReportData.php new file mode 100644 index 0000000..b9c55df --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/StockUsageReportData.php @@ -0,0 +1,25 @@ + $items + * @param list $groups + * @param list $machines + * @param list $jobs + */ + public function __construct( + public array $items, + public array $groups, + public array $machines, + public array $jobs, + public StockUsageRow $total, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/StockUsageRow.php b/app/Modules/Reports/Application/DTOs/StockUsageRow.php new file mode 100644 index 0000000..57ebd26 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/StockUsageRow.php @@ -0,0 +1,31 @@ +usedCents + $this->writtenOffCents + $this->adjustedCents; + } +} diff --git a/app/Modules/Reports/Application/DTOs/StockValueReportData.php b/app/Modules/Reports/Application/DTOs/StockValueReportData.php new file mode 100644 index 0000000..cedeef3 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/StockValueReportData.php @@ -0,0 +1,24 @@ + $items + * @param list $toOrder + */ + public function __construct( + public array $items, + public int $totalCents, + public array $toOrder, + ) {} +} diff --git a/app/Modules/Reports/Application/UseCases/ProfitabilityByJob.php b/app/Modules/Reports/Application/UseCases/ProfitabilityByJob.php index fb3c541..5901fc4 100644 --- a/app/Modules/Reports/Application/UseCases/ProfitabilityByJob.php +++ b/app/Modules/Reports/Application/UseCases/ProfitabilityByJob.php @@ -9,6 +9,7 @@ use App\Modules\Reports\Application\Contracts\ReportExpenses; use App\Modules\Reports\Application\Contracts\ReportHours; use App\Modules\Reports\Application\Contracts\ReportJobs; use App\Modules\Reports\Application\Contracts\ReportRevenue; +use App\Modules\Reports\Application\Contracts\ReportStock; use App\Modules\Reports\Application\DTOs\JobProfit; use App\Modules\Reports\Application\DTOs\ProfitabilityReport; use App\Modules\Reports\Application\DTOs\ServiceUnitProfit; @@ -30,6 +31,7 @@ final readonly class ProfitabilityByJob private ReportRevenue $revenue, private ReportJobs $jobs, private ReportCatalog $catalog, + private ReportStock $stock, ) {} public function execute(ReportPeriod $period, bool $includeInternal = false): ProfitabilityReport @@ -40,10 +42,11 @@ final readonly class ProfitabilityByJob } $expenseCosts = $this->expenses->costsByJob($period); + $materialCosts = $this->stock->materialCostsByJob($period); $revenue = $this->revenue->byJob($period); $hourlyCost = $this->catalog->internalHourlyCostCents(); - $jobIds = array_values(array_unique([...array_keys($quarters), ...array_keys($expenseCosts), ...array_keys($revenue)])); + $jobIds = array_values(array_unique([...array_keys($quarters), ...array_keys($expenseCosts), ...array_keys($materialCosts), ...array_keys($revenue)])); $jobs = $this->jobs->infoOf($jobIds); $rows = []; @@ -60,6 +63,7 @@ final readonly class ProfitabilityByJob $billed->expenseCents ?? 0, $expenseCosts[$job->id] ?? 0, $hourlyCost, + $materialCosts[$job->id] ?? 0, )); } diff --git a/app/Modules/Reports/Application/UseCases/StockUsageReport.php b/app/Modules/Reports/Application/UseCases/StockUsageReport.php new file mode 100644 index 0000000..60a36e3 --- /dev/null +++ b/app/Modules/Reports/Application/UseCases/StockUsageReport.php @@ -0,0 +1,96 @@ +stock->usage($period); + + $machineIds = array_values(array_unique(array_filter(array_map(fn (StockUsageEntry $entry): ?int => $entry->machineId, $entries)))); + $jobIds = array_values(array_unique(array_filter(array_map(fn (StockUsageEntry $entry): ?int => $entry->jobId, $entries)))); + $machineNames = $this->stock->machineNames($machineIds); + $jobs = $this->jobs->infoOf($jobIds); + + $items = $this->sum($entries, fn (StockUsageEntry $entry): string => $entry->groupName."\0".$entry->itemName."\0".$entry->unit, true); + $groups = $this->sum($entries, fn (StockUsageEntry $entry): string => $entry->groupName); + $machines = $this->sum($entries, fn (StockUsageEntry $entry): string => $entry->machineId === null ? $noneLabel : ($machineNames[$entry->machineId] ?? '')); + $jobRows = $this->sum($entries, function (StockUsageEntry $entry) use ($jobs, $noneLabel): string { + $job = $entry->jobId === null ? null : ($jobs[$entry->jobId] ?? null); + + return $job === null ? $noneLabel : $job->number.' '.$job->name; + }); + + $total = $this->sum($entries, fn (): string => '')[0] ?? new StockUsageRow('', null, null, 0, 0, 0, 0, 0, 0); + + return new StockUsageReportData($items, $groups, $machines, $jobRows, $total); + } + + /** + * @param list $entries + * @param callable(StockUsageEntry): string $key + * @return list + */ + private function sum(array $entries, callable $key, bool $byItem = false): array + { + /** @var array $sums */ + $sums = []; + /** @var array $firsts */ + $firsts = []; + + foreach ($entries as $entry) { + $k = $key($entry); + $firsts[$k] ??= $entry; + $sum = $sums[$k] ?? ['used' => [0, 0], 'write_off' => [0, 0], 'adjustment' => [0, 0]]; + $kind = match ($entry->kind) { + 'consumption' => 'used', + 'write_off' => 'write_off', + default => 'adjustment', + }; + $sum[$kind][0] += $entry->quantityMilli; + $sum[$kind][1] += $entry->valueCents; + $sums[$k] = $sum; + } + + ksort($sums, SORT_NATURAL | SORT_FLAG_CASE); + $rows = []; + + foreach ($sums as $k => $sum) { + $first = $firsts[$k]; + $rows[] = new StockUsageRow( + $byItem ? $first->itemName : (string) $k, + $byItem ? $first->groupName : null, + $byItem ? $first->unit : null, + $sum['used'][0], + $sum['used'][1], + $sum['write_off'][0], + $sum['write_off'][1], + $sum['adjustment'][0], + $sum['adjustment'][1], + ); + } + + return $rows; + } +} diff --git a/app/Modules/Reports/Application/UseCases/StockValueReport.php b/app/Modules/Reports/Application/UseCases/StockValueReport.php new file mode 100644 index 0000000..17e782e --- /dev/null +++ b/app/Modules/Reports/Application/UseCases/StockValueReport.php @@ -0,0 +1,29 @@ +stock->valueOn($day); + + return new StockValueReportData( + $items, + array_sum(array_map(fn (StockValueEntry $item): int => $item->valueCents, $items)), + array_values(array_filter($items, fn (StockValueEntry $item): bool => $item->isActive && $item->needsReorder())), + ); + } +} diff --git a/app/Modules/Reports/Domain/ValueObjects/Profit.php b/app/Modules/Reports/Domain/ValueObjects/Profit.php index 07a85a3..9b5c999 100644 --- a/app/Modules/Reports/Domain/ValueObjects/Profit.php +++ b/app/Modules/Reports/Domain/ValueObjects/Profit.php @@ -11,6 +11,8 @@ namespace App\Modules\Reports\Domain\ValueObjects; * - billed for the work (hours, fixed price, monthly fees) and for expenses; * - the purchase cost of the expenses and the cost of the hours worked at * the company's one internal hourly cost (null when it is not set); + * - the cost of the stock used on the job (material, spec 19.8), which is + * not billed separately; * - the margin: everything billed less those costs (null without the hourly cost). */ final readonly class Profit @@ -22,12 +24,13 @@ final readonly class Profit public int $expenseRevenueCents = 0, public int $expenseCostCents = 0, public ?int $hourCostCents = 0, + public int $materialCostCents = 0, ) {} /** * @param int|null $hourlyCostCents The internal cost of an hour, null when not set. */ - public static function of(int $quarters, int $billedQuarters, int $workCents, int $expenseRevenueCents, int $expenseCostCents, ?int $hourlyCostCents): self + public static function of(int $quarters, int $billedQuarters, int $workCents, int $expenseRevenueCents, int $expenseCostCents, ?int $hourlyCostCents, int $materialCostCents = 0): self { return new self( $quarters, @@ -37,6 +40,7 @@ final readonly class Profit $expenseCostCents, // Rounded half up to a cent. $hourlyCostCents === null ? null : intdiv($quarters * $hourlyCostCents * 2 + 4, 8), + $materialCostCents, ); } @@ -47,7 +51,7 @@ final readonly class Profit public function marginCents(): ?int { - return $this->hourCostCents === null ? null : $this->revenueCents() - $this->expenseCostCents - $this->hourCostCents; + return $this->hourCostCents === null ? null : $this->revenueCents() - $this->expenseCostCents - $this->materialCostCents - $this->hourCostCents; } /** @@ -77,6 +81,7 @@ final readonly class Profit $this->expenseRevenueCents + $other->expenseRevenueCents, $this->expenseCostCents + $other->expenseCostCents, $this->hourCostCents === null || $other->hourCostCents === null ? null : $this->hourCostCents + $other->hourCostCents, + $this->materialCostCents + $other->materialCostCents, ); } @@ -100,6 +105,7 @@ final readonly class Profit self::share($this->expenseRevenueCents, $parts, $index), self::share($this->expenseCostCents, $parts, $index), $this->hourCostCents === null ? null : self::share($this->hourCostCents, $parts, $index), + self::share($this->materialCostCents, $parts, $index), ); } diff --git a/app/Modules/Reports/Infrastructure/Adapters/StockForReports.php b/app/Modules/Reports/Infrastructure/Adapters/StockForReports.php new file mode 100644 index 0000000..b913cf9 --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/StockForReports.php @@ -0,0 +1,47 @@ +stock->usage($period->from, $period->to); + } + + public function valueOn(string $day): array + { + return $this->stock->valueOn($day); + } + + public function materialCostsByJob(ReportPeriod $period): array + { + return $this->stock->materialCostsByJob($period->from, $period->to); + } + + public function machineNames(array $ids): array + { + $names = []; + + foreach ($this->machines->machines(includeInactive: true) as $machine) { + if (in_array($machine->id, $ids, true)) { + $names[$machine->id] = $machine->name; + } + } + + return $names; + } +} diff --git a/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php index 641ce58..c1a2c50 100644 --- a/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php +++ b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php @@ -3,6 +3,7 @@ namespace App\Modules\Reports\Infrastructure\Providers; use App\Models\User; +use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Reports\Application\Contracts\ReportCatalog; use App\Modules\Reports\Application\Contracts\ReportExpenses; use App\Modules\Reports\Application\Contracts\ReportHours; @@ -10,6 +11,7 @@ use App\Modules\Reports\Application\Contracts\ReportJobs; use App\Modules\Reports\Application\Contracts\ReportPeople; use App\Modules\Reports\Application\Contracts\ReportRevenue; use App\Modules\Reports\Application\Contracts\ReportSales; +use App\Modules\Reports\Application\Contracts\ReportStock; use App\Modules\Reports\Infrastructure\Adapters\CatalogForReports; use App\Modules\Reports\Infrastructure\Adapters\ExpensesForReports; use App\Modules\Reports\Infrastructure\Adapters\HoursForReports; @@ -17,6 +19,7 @@ use App\Modules\Reports\Infrastructure\Adapters\JobsForReports; use App\Modules\Reports\Infrastructure\Adapters\PeopleForReports; use App\Modules\Reports\Infrastructure\Adapters\RevenueForReports; use App\Modules\Reports\Infrastructure\Adapters\SalesForReports; +use App\Modules\Reports\Infrastructure\Adapters\StockForReports; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Livewire\Livewire; @@ -37,6 +40,7 @@ class ReportsServiceProvider extends ServiceProvider ReportCatalog::class => CatalogForReports::class, ReportPeople::class => PeopleForReports::class, ReportSales::class => SalesForReports::class, + ReportStock::class => StockForReports::class, ReportExpenses::class => ExpensesForReports::class, ReportRevenue::class => RevenueForReports::class, ]; @@ -52,6 +56,8 @@ class ReportsServiceProvider extends ServiceProvider } // Reports are for admin and management (spec 2.4). + Gate::define('reports.stock', fn (User $user): bool => $user->role->seesAllMoney() && app(CatalogQueries::class)->stockServiceUnitIds() !== []); + Gate::define('reports.view', fn (User $user): bool => $user->role->seesAllMoney()); } } diff --git a/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php b/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php index fa8eb8c..13e8de3 100644 --- a/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php +++ b/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php @@ -49,6 +49,7 @@ class ProfitabilityCsv implements ReportCsv $profit->workCents, $profit->expenseRevenueCents, $profit->expenseCostCents, + $profit->materialCostCents, $profit->hourCostCents ?? '', $profit->marginCents() ?? '', ]; diff --git a/app/Modules/Reports/Presentation/Csv/StockUsageCsv.php b/app/Modules/Reports/Presentation/Csv/StockUsageCsv.php new file mode 100644 index 0000000..309e659 --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/StockUsageCsv.php @@ -0,0 +1,46 @@ +from.'-'.$period->to; + } + + public function headers(): array + { + return array_values(__('reports.stock_usage.csv')); + } + + public function rows(Request $request): iterable + { + foreach ($this->report->execute(CsvFilters::period($request))->items as $row) { + yield [ + $row->label, + (string) $row->group, + __('inventory.units.'.$row->unit), + StockQuantity::inputValue($row->usedMilli), + $row->usedCents, + StockQuantity::inputValue($row->writtenOffMilli), + $row->writtenOffCents, + StockQuantity::inputValue($row->adjustedMilli), + $row->adjustedCents, + $row->totalCents(), + ]; + } + } +} diff --git a/app/Modules/Reports/Presentation/Csv/StockValueCsv.php b/app/Modules/Reports/Presentation/Csv/StockValueCsv.php new file mode 100644 index 0000000..f58500d --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/StockValueCsv.php @@ -0,0 +1,40 @@ +report->execute(CsvFilters::day($request, 'paiva'))->items as $item) { + yield [ + $item->itemName, + $item->groupName, + __('inventory.units.'.$item->unit), + StockQuantity::inputValue($item->balanceMilli), + $item->valueCents, + $item->needsReorder() ? __('inventory.status.reorder') : '', + ]; + } + } +} diff --git a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php index bf0b0c7..e822046 100644 --- a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php +++ b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php @@ -8,6 +8,8 @@ use App\Modules\Reports\Presentation\Csv\ProfitabilityCsv; use App\Modules\Reports\Presentation\Csv\ReimbursementsCsv; use App\Modules\Reports\Presentation\Csv\ReportCsv; use App\Modules\Reports\Presentation\Csv\SalesCsv; +use App\Modules\Reports\Presentation\Csv\StockUsageCsv; +use App\Modules\Reports\Presentation\Csv\StockValueCsv; use App\Modules\Reports\Presentation\Csv\UnbilledCsv; use Illuminate\Http\Request; use Illuminate\Support\Facades\Gate; @@ -22,7 +24,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse; class DownloadReport { /** The reports that have a CSV, by their URL key. */ - public const array REPORTS = ['hours', 'unbilled', 'profitability', 'sales', 'reimbursements']; + public const array REPORTS = ['hours', 'unbilled', 'profitability', 'sales', 'reimbursements', 'stock-usage', 'stock-value']; public function __invoke(string $report, Request $request): StreamedResponse { @@ -79,6 +81,8 @@ class DownloadReport 'profitability' => app(ProfitabilityCsv::class), 'sales' => app(SalesCsv::class), 'reimbursements' => app(ReimbursementsCsv::class), + 'stock-usage' => app(StockUsageCsv::class), + 'stock-value' => app(StockValueCsv::class), default => abort(404), }; } diff --git a/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php b/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php index 274844d..0aee95e 100644 --- a/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php +++ b/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php @@ -133,7 +133,7 @@ new class extends Component {{ $unit->jobCount }} {{ $this->hours($unit->profit->quarters) }} {{ $this->money($unit->profit->revenueCents()) }} - {{ $this->money($unit->profit->expenseCostCents + ($unit->profit->hourCostCents ?? 0)) }} + {{ $this->money($unit->profit->expenseCostCents + $unit->profit->materialCostCents + ($unit->profit->hourCostCents ?? 0)) }} {{ $this->margin($unit->profit) }} {{ $this->marginPercent($unit->profit) }} @@ -167,6 +167,7 @@ new class extends Component {{ __('reports.profitability.work_revenue') }} {{ __('reports.profitability.expense_revenue') }} {{ __('reports.profitability.expense_cost') }} + {{ __('reports.profitability.material_cost') }} {{ __('reports.profitability.hour_cost') }} {{ __('reports.profitability.margin') }} {{ __('reports.profitability.margin_percent') }} @@ -188,6 +189,7 @@ new class extends Component {{ $this->money($row->profit->workCents) }} {{ $this->money($row->profit->expenseRevenueCents) }} {{ $this->money($row->profit->expenseCostCents) }} + {{ $this->money($row->profit->materialCostCents) }} {{ $this->hourCost($row->profit) }} {{ $this->margin($row->profit) }} {{ $this->marginPercent($row->profit) }} @@ -203,6 +205,7 @@ new class extends Component {{ $this->money($report->total->workCents) }} {{ $this->money($report->total->expenseRevenueCents) }} {{ $this->money($report->total->expenseCostCents) }} + {{ $this->money($report->total->materialCostCents) }} {{ $this->hourCost($report->total) }} {{ $this->margin($report->total) }} {{ $this->marginPercent($report->total) }} diff --git a/app/Modules/Reports/Presentation/Livewire/⚡stock-usage.blade.php b/app/Modules/Reports/Presentation/Livewire/⚡stock-usage.blade.php new file mode 100644 index 0000000..a0fb643 --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/⚡stock-usage.blade.php @@ -0,0 +1,153 @@ +startPeriod($clock, 'this_month'); + } + + #[Computed] + public function report(): ?StockUsageReportData + { + $period = $this->period(); + + return $period === null ? null : app(StockUsageReport::class)->execute($period, __('reports.stock_usage.none_target')); + } + + public function updated(): void + { + $this->authorize('reports.view'); + unset($this->report); + } + + public function quantity(int $milli, ?string $unit): string + { + return StockQuantity::format($milli).($unit === null ? '' : "\u{00A0}".__('inventory.units.'.$unit)); + } + + public function signedMoney(int $cents): string + { + return ($cents < 0 ? '-' : '').$this->money(abs($cents)); + } + + /** + * @return list}> + */ + public function summaries(StockUsageReportData $report): array + { + return [ + ['key' => 'groups', 'rows' => $report->groups], + ['key' => 'machines', 'rows' => $report->machines], + ['key' => 'jobs', 'rows' => $report->jobs], + ]; + } + + public function render(): mixed + { + return $this->view()->title(__('reports.stock_usage.title')); + } +}; +?> + +
+
+

{{ __('reports.stock_usage.title') }}

+

{{ __('reports.stock_usage.intro') }}

+
+ + + + @php($report = $this->report) + + @if ($report !== null) +
+

{{ $this->periodLabel() }}

+ +
+ + @if ($report->items === []) +

{{ __('reports.stock_usage.empty') }}

+ @else +

{{ __('reports.stock_usage.total', ['amount' => $this->signedMoney($report->total->totalCents())]) }}

+ +
+

{{ __('reports.stock_usage.by_item') }}

+
+ + + + + + + + + + + + + + @foreach ($report->items as $index => $row) + + + + + + + + + @endforeach + +
{{ __('reports.stock_usage.by_item') }}, {{ $this->periodLabel() }}
{{ __('reports.stock_usage.item') }}{{ __('reports.stock_usage.group') }}{{ __('reports.stock_usage.used') }}{{ __('reports.stock_usage.written_off') }}{{ __('reports.stock_usage.adjusted') }}{{ __('reports.stock_usage.value') }}
{{ $row->label }}{{ $row->group }}{{ $this->quantity($row->usedMilli, $row->unit) }}{{ $this->quantity($row->writtenOffMilli, $row->unit) }}{{ $this->quantity($row->adjustedMilli, $row->unit) }}{{ $this->signedMoney($row->totalCents()) }}
+
+
+ + @foreach ($this->summaries($report) as $summary) +
+

{{ __('reports.stock_usage.by_'.$summary['key']) }}

+
+ + + + + + + + + + + + + @foreach ($summary['rows'] as $index => $row) + + + + + + + + @endforeach + +
{{ __('reports.stock_usage.by_'.$summary['key']) }}, {{ $this->periodLabel() }}
{{ __('reports.stock_usage.'.$summary['key'].'_column') }}{{ __('reports.stock_usage.used_value') }}{{ __('reports.stock_usage.written_off_value') }}{{ __('reports.stock_usage.adjusted_value') }}{{ __('reports.stock_usage.value') }}
{{ $row->label }}{{ $this->signedMoney($row->usedCents) }}{{ $this->signedMoney($row->writtenOffCents) }}{{ $this->signedMoney($row->adjustedCents) }}{{ $this->signedMoney($row->totalCents()) }}
+
+
+ @endforeach + @endif + @endif +
diff --git a/app/Modules/Reports/Presentation/Livewire/⚡stock-value.blade.php b/app/Modules/Reports/Presentation/Livewire/⚡stock-value.blade.php new file mode 100644 index 0000000..15d290d --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/⚡stock-value.blade.php @@ -0,0 +1,143 @@ +authorize('reports.view'); + + if ($this->validDay() === null) { + $this->day = $clock->today()->format('Y-m-d'); + } + } + + #[Computed] + public function report(): ?StockValueReportData + { + $day = $this->validDay(); + + return $day === null ? null : app(StockValueReport::class)->execute($day); + } + + public function updatedDay(): void + { + $this->authorize('reports.view'); + unset($this->report); + } + + public function quantity(int $milli, string $unit): string + { + return StockQuantity::format($milli)."\u{00A0}".__('inventory.units.'.$unit); + } + + public function signedMoney(int $cents): string + { + return ($cents < 0 ? '-' : '').$this->money(abs($cents)); + } + + public function render(): mixed + { + return $this->view()->title(__('reports.stock_value.title')); + } + + private function validDay(): ?string + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $this->day) !== 1) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $this->day); + + return $date !== null && $date->format('Y-m-d') === $this->day ? $this->day : null; + } +}; +?> + +
+
+

{{ __('reports.stock_value.title') }}

+

{{ __('reports.stock_value.intro') }}

+
+ +
+ +
+ + @php($report = $this->report) + + @if ($report === null) + + @else +
+

{{ __('reports.stock_value.total', ['date' => $this->dateLabel($day), 'amount' => $this->signedMoney($report->totalCents)]) }}

+ +
+ + @if ($report->toOrder !== []) +
+

+

+
    + @foreach ($report->toOrder as $item) +
  • {{ $item->itemName }}: {{ $this->quantity($item->balanceMilli, $item->unit) }}
  • + @endforeach +
+
+ @endif + + @if ($report->items === []) +

{{ __('reports.stock_value.empty') }}

+ @else +
+ + + + + + + + + + + + @foreach ($report->items as $item) + + + + + + + @endforeach + +
{{ __('reports.stock_value.table', ['date' => $this->dateLabel($day)]) }}
{{ __('reports.stock_usage.item') }}{{ __('reports.stock_usage.group') }}{{ __('inventory.columns.balance') }}{{ __('inventory.columns.value') }}
+ {{ $item->itemName }} + @if ($item->needsReorder()) + {{ __('inventory.status.reorder') }} + @endif + {{ $item->groupName }}{{ $this->quantity($item->balanceMilli, $item->unit) }}{{ $this->signedMoney($item->valueCents) }}
+
+ @endif + @endif +
diff --git a/app/Modules/Reports/Presentation/Routes/web.php b/app/Modules/Reports/Presentation/Routes/web.php index 86936d6..b45188b 100644 --- a/app/Modules/Reports/Presentation/Routes/web.php +++ b/app/Modules/Reports/Presentation/Routes/web.php @@ -12,5 +12,7 @@ Route::middleware(['web', 'auth', 'can:reports.view']) Route::livewire('/profitability', 'reports::profitability')->name('profitability'); Route::livewire('/sales', 'reports::sales')->name('sales'); Route::livewire('/reimbursements', 'reports::reimbursements')->name('reimbursements'); + Route::livewire('/stock-usage', 'reports::stock-usage')->middleware('can:reports.stock')->name('stock-usage'); + Route::livewire('/stock-value', 'reports::stock-value')->middleware('can:reports.stock')->name('stock-value'); Route::get('/{report}/csv', DownloadReport::class)->whereIn('report', DownloadReport::REPORTS)->name('csv'); }); diff --git a/app/View/MainMenu.php b/app/View/MainMenu.php index c20df03..d889ed8 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -98,6 +98,8 @@ final class MainMenu ['route' => 'reports.profitability', 'pattern' => ['reports.profitability'], 'label' => 'layout.report_profitability', 'ability' => 'reports.view'], ['route' => 'reports.sales', 'pattern' => ['reports.sales'], 'label' => 'layout.report_sales', 'ability' => 'reports.view'], ['route' => 'reports.reimbursements', 'pattern' => ['reports.reimbursements'], 'label' => 'layout.report_reimbursements', 'ability' => 'reports.view'], + ['route' => 'reports.stock-usage', 'pattern' => ['reports.stock-usage'], 'label' => 'layout.report_stock_usage', 'ability' => 'reports.stock'], + ['route' => 'reports.stock-value', 'pattern' => ['reports.stock-value'], 'label' => 'layout.report_stock_value', 'ability' => 'reports.stock'], ], ], 'maintenance' => [ diff --git a/docs/maarittely.md b/docs/maarittely.md index babf692..1713d80 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -227,7 +227,7 @@ Kevyt käteis- ja pankkikorttimyynti kuluttajille ilman täyttä asiakastyötä - Myyntiä ei poisteta. Virhe korjataan **hyvityksellä** (hyvityslaskumenettely): uusi myynti, joka viittaa alkuperäiseen, samat rivit miinusmerkkisinä ja sama maksutapa. Hyvitys kirjataan kuluvalle kassapäivälle, myynnin voi hyvittää vain kerran, ja hyvittää voi myyjä itse tai johto. Hyvitys ei muuta tunteja. - **Kassapäivä**: päivän myynnit kirjataan yksitellen, ja kassapäivä päätetään. Päättämisestä muodostuu päivän saldo: myyntien määrä, summat maksutavoittain ja ALV-kannoittain (verollinen, veroton, vero; vero lasketaan kannan päiväsummasta). Päätettyyn päivään ei voi kirjata myyntejä. Päivän voi päättää kuka tahansa pikamyyntiä käyttävä (myös unohtuneen aiemman päivän), ja avata uudelleen vain johto, jolloin saldo muodostetaan uudelleen seuraavassa päättämisessä. Laskettua käteistä tai kassaeroa ei kirjata. - Myynnit tallentuvat laskuaineistosta erillisinä käteismyynteinä (raportit). -- Vaiheessa 5 koneella valmistettavat tuotteet myydään tilauksena: tilaus koneen työlistalle, valmistuksen kuittaus koneelta ja sen jälkeen maksu (19.7). +- Vaiheessa 5 koneella valmistettavat tuotteet myydään tilauksena: tilaus koneen työlistalle, valmistuksen kuittaus koneelta ja sen jälkeen maksu (19.7) *(valmis)*. ## 8. Tehtävät ja Kanban @@ -431,7 +431,7 @@ Tarkistuslistat *(valmis)*, kommentit *(valmis)*, kuvat *(valmis)*, työnkulkupo **Vaihe 4 – laajennukset** Alihankkijoiden näkymät ja rajaukset, raportit *(valmis)*, ilmoitukset *(osittain: kello ja tehtävän alku)*, Fennoa-rajapinta, PWA, kenttien yksinkertaistus palveluyksiköittäin *(K31; siirretty vaiheesta 3)*. -**Vaihe 5 – varasto ja koneet** (luku 19) +**Vaihe 5 – varasto ja koneet** (luku 19) *(valmis)* Varastokirjanpito (nimikkeet, hankinnat hankintahintoineen, käyttö, inventaario), koneet ja niiden työlistat, koneiden huoltokohteet ja huoltohistoria sekä koneen kosketusnäyttökäyttöliittymä, jolla kirjataan työt, käytetty materiaali ja huollot; pikamyyntituotteiden valmistus koneella tilauksena ennen maksua. ## 16. Vaiheen 1 tarkka sisältö @@ -554,7 +554,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - Valikon varasto- ja konesivut näkyvät, kun ainakin yhdellä palveluyksiköllä asetus on päällä. Asetuksen poisto piilottaa toiminnot, mutta kirjatut tapahtumat ja työlistat säilyvät, ja aiemmin kirjattu käyttö näkyy tehtävällä edelleen lukutilassa. - Asetus on ensimmäinen palveluyksikkökohtainen kenttävalinta; kenttien yksinkertaistus palveluyksiköittäin (K31, vaihe 4) laajentaa samaa mallia. -### 19.1 Varastonimikkeet +### 19.1 Varastonimikkeet *(valmis)* - **Nimike** (materiaali): nimi, nimikeryhmä (esim. paperit ja kartongit, tulostusmediat, musteet ja värijauheet, passikuvatarvikkeet, viimeistely), yksikkö (kpl, arkki, rulla, m, m², l, pakkaus), vapaaehtoinen tuotekoodi tai viivakoodi, vapaaehtoinen toimittaja, hälytysraja (saldo, jonka alittuessa nimike näytetään tilattavana) ja käytössä-tieto. Nimikkeelle voi lisätä kuvan, joka helpottaa tunnistamista kosketusnäytöllä. - Nimikeryhmiä ylläpidetään varaston pohjatiedoissa (lisäys, nimeäminen, järjestys, käytöstä poisto). @@ -562,7 +562,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - Nimikkeitä ei poisteta, vaan ne poistetaan käytöstä; käytöstä poistettua ei voi kirjata käytetyksi, mutta sen tapahtumat säilyvät. - Varastolista: haku (nimi, koodi), suodattimet ryhmä ja "vain tilattavat" (saldo hälytysrajalla tai alle), sarakkeet saldo yksikköineen ja hälytysraja; johdolle lisäksi keskihinta ja varaston arvo. Tilattava nimike näytetään tekstillä ja kuvakkeella, ei pelkällä värillä. -### 19.2 Varastotapahtumat ja hankintahinta +### 19.2 Varastotapahtumat ja hankintahinta *(valmis)* - Saldo on nimikkeen tapahtumien summa. Tapahtumalajit: - **Hankinta** (saapuminen): päivä, määrä, hankintahinta yhteensä tai yksikköhinta (ALV 0), toimittaja ja vapaaehtoinen ostolaskun tai kuitin numero. @@ -574,7 +574,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - Käyttöä ei estetä, vaikka saldo menisi negatiiviseksi (kone ei saa pysähtyä kirjaukseen). Negatiivinen saldo näytetään varoituksena tekstillä ja kuvakkeella, ja se korjataan hankinnalla tai inventaariolla. - Nimikkeen sivulla on tapahtumahistoria (aika, laji, määrä, saldo tapahtuman jälkeen, kirjaaja, kohde; johdolle arvo). -### 19.3 Inventaario +### 19.3 Inventaario *(valmis)* - Johto aloittaa inventaarion koko varastolle tai valituille nimikeryhmille. Inventaariolla on päivä, tila (kesken / vahvistettu) ja aloittaja; kerrallaan voi olla kesken yksi inventaario. - Laskentalista näyttää nimikkeet ryhmittäin. Laskija syöttää lasketun määrän; samalla tallennetaan nimikkeen kirjanpitosaldo laskentahetkellä, joten inventaarion aikana kirjatut käytöt eivät vääristä eroa. Laskennan voi tehdä useampi henkilö ja useassa osassa (myös tabletilla), ja laskematta olevat nimikkeet näytetään. @@ -582,7 +582,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - Johto vahvistaa inventaarion vahvistusdialogissa: jokaisesta erosta syntyy inventaariokorjaus, ja inventaarioon tallennetaan varaston arvo ennen ja jälkeen korjausten. Laskemattomat nimikkeet jätetään ennalleen (niistä kerrotaan ennen vahvistusta). Vahvistettua inventaariota ei muuteta. - Inventaariot säilyvät listana, ja vahvistetusta voi ladata CSV:n (nimike, yksikkö, saldo, laskettu, ero, keskihinta, arvot) kirjanpitoa varten. -### 19.4 Koneet ja koneen työlista +### 19.4 Koneet ja koneen työlista *(valmis)* - Koneita on useita ja erityyppisiä: painomustetta käyttäviä tulostus- ja painokoneita (esim. suurkuvatulostimet) sekä tarraleikkureita. Kullakin koneella on oma työlistansa, laskurinsa, huoltokohteensa ja konekäyttöliittymänsä. - **Kone**: nimi, konetyyppi (painokone / tarraleikkuri / muu), kuvaus, palveluyksiköt (pakollinen, yksi tai useampi; eri palveluyksiköillä on eri koneita, ja yhteiskäyttöinen kone, esim. valokuvatulostin Painotuotannossa ja Kuluttajapalveluissa, kuuluu molempiin), vastuuhenkilö (saa huoltoilmoitukset), laskurit (19.5) ja käytössä-tieto. Koneita ylläpitävät pääkäyttäjä ja johto; käytöstä poistettu kone ei näy valinnoissa, mutta sen historia säilyy. @@ -597,17 +597,18 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - Työnkulkupohjan vaiheelle (8.3, 18.2) voi määritellä **oletusmateriaalit** (nimike ja määrä): ne esitäytetään tehtävän Käytetty materiaali -osioon kirjattaviksi, mutta kirjataan vasta, kun tekijä vahvistaa ne (määrää voi muuttaa). Esim. pohja "Ikkunateippaus" = 1) tulostus ja leikkaus koneella, 2) asennus, jonka oletusmateriaali on siirtotarrapaperi. - Koneen päivä on tehtävän aikataulusta (18.3) erillinen tieto: koneelle ajoitus ei muuta tehtävän aikataulua eikä tekijän varauksia, mutta jos päivä on tehtävän aikataulun ulkopuolella tai määräpäivän jälkeen, siitä näytetään huomautus tekstinä. -### 19.5 Huoltokohteet ja huoltohistoria +### 19.5 Huoltokohteet ja huoltohistoria *(valmis)* -- Koneella on **laskureita**, joilla huollon tarve mitataan, esim. tulosteet (kpl), arkit, tulostettu pinta-ala (m²), musteen kulutus (ml), leikattu matka (m) tai käyttötunnit. Konetyypin mukaan uudelle koneelle ehdotetaan tavalliset laskurit: painokoneelle tulosteet ja m², tarraleikkurille leikattu matka. Laskurin lukema kirjataan konekäyttöliittymästä (esim. koneen oma kokonaislaskuri) tai se kasvaa kirjatuista töistä. Lisäksi huoltoväli voi olla aikaan perustuva (päivät). -- **Huoltokohde**: kone, nimi (painokoneella esim. jätemustesäiliön tai värijauhetankin tyhjennys, tulostuspään puhdistus, pyyhkimen vaihto; tarraleikkurilla esim. terän vaihto, leikkuualustan tai -nauhan vaihto, puhdistus), laskuri tai aikaväli, huoltoväli (esim. 20 000 tulostetta tai 30 päivää), ennakkovaroitus (esim. 90 % välistä) ja vapaaehtoinen ohje. Huoltokohteelle voi liittää varastonimikkeen (esim. vaihtorumpu), joka kirjataan käytetyksi huollon yhteydessä. +- Koneella on **laskureita**, joilla huollon tarve mitataan, esim. tulosteet (kpl), arkit, tulostettu pinta-ala (m²), musteen kulutus (ml), leikattu matka (m) tai käyttötunnit. Konetyypin mukaan uudelle koneelle ehdotetaan tavalliset laskurit: painokoneelle tulosteet ja m², tarraleikkurille leikattu matka. Laskurin lukema kirjataan käsin konekäyttöliittymästä tai koneen sivulta (esim. koneen oma kokonaislaskuri); laskuri ei kasva kirjatuista töistä. +- **Huoltokohde**: kone, nimi (painokoneella esim. jätemustesäiliön tai värijauhetankin tyhjennys, tulostuspään puhdistus, pyyhkimen vaihto; tarraleikkurilla esim. terän vaihto, leikkuualustan tai -nauhan vaihto, puhdistus), huoltoväli: **laskuriväli** (laskuri ja määrä, esim. 20 000 tulostetta), **aikaväli** (päivähuolto, viikkohuolto, kuukausihuolto tai vuosihuolto, joka N. jakso, esim. joka 2. viikko) tai molemmat, jolloin huolto erääntyy kumman tahansa täyttyessä ensin; aikavälin käyttö ei ole pakollista, ja koneella voi olla useita eri välein huollettavia kohteita yhtä aikaa (esim. päivittäinen puhdistus, viikoittainen tarkistus ja vuosihuolto), ennakkovaroitus (päivähuollolla ei ennakkovaroitusta) (esim. 90 % välistä) ja vapaaehtoinen ohje. Huoltokohteelle voi liittää varastonimikkeen (esim. vaihtorumpu), joka kirjataan käytetyksi huollon yhteydessä. +- Erääntynyt huolto on **huoltopyyntö**: se näkyy tilassa *Huolto myöhässä* ja ilmoitetaan, ja se kuittautuu huoltokirjauksella. Aikaväli lasketaan kalenterijaksoina viimeisen huollon päivästä (kuukauden loppu rajataan, esim. 31.1. → 28.2.). - Huoltokohteen tila lasketaan viimeisestä huollosta kertyneestä määrästä: *Kunnossa*, *Huolto lähestyy* tai *Huolto myöhässä*; tila näytetään aina tekstinä ja kuvakkeena sekä jäljellä olevana määränä (esim. "jäljellä 1 200 tulostetta"). - Huollon tekee ja kuittaa koneen käyttäjä (kuka tahansa konekäyttöliittymää käyttävä, 19.9); erillistä huolto-oikeutta ei ole. - **Huoltokirjaus**: huoltokohde, aika, tekijä, laskurin lukema huoltohetkellä, vapaaehtoinen huomautus ja käytetyt varaosat/materiaalit varastosta. Kirjaus nollaa kohteen kertymän. Kirjauksia ei poisteta; virheellisen kirjauksen johto merkitsee perutuksi. - Koneen sivulla on huoltokohteet tiloineen ja huoltohistoria (suodatus huoltokohteella ja aikavälillä). - Lähestyvät ja myöhässä olevat huollot näytetään konekäyttöliittymässä, johdon etusivun *Vaatii toimia* -osassa ja ilmoituksina (luku 13) koneen vastuuhenkilölle; samasta huoltotarpeesta ei ilmoiteta kahdesti. -### 19.6 Konekäyttöliittymä (kosketusnäyttö) +### 19.6 Konekäyttöliittymä (kosketusnäyttö) *(valmis)* - Jokaisella koneella on oma koko näytön näkymä (`/machines/{kone}/console`) koneen vieressä olevalle tabletille tai kosketusnäytölle. Näkymässä ei ole päävalikkoa, vain koneen nimi, käyttäjä, **Päivitä**, Vaihda käyttäjä ja paluu tavalliseen käyttöliittymään. - **Päivitä**-painike (iso, aina näkyvissä yläreunassa) lataa työlistan, tilausten tilat, saldot ja huoltojen tilat uudelleen palvelimelta. Näkymä päivittyy myös itsestään, mutta painikkeella saa heti ajantasaisen tilanteen, kun samaa asiaa on käsitelty toisella laitteella: esim. pikamyyntitilaus aloitetaan puhelimella, valmistetaan tabletilla konekäyttöliittymässä ja maksetaan lopuksi kassakoneella, josta kuitti tulostetaan. Päivityksen jälkeen ilmoitus (`role="status"`) kertoo päivitysajan ja uusien rivien määrän, ja fokus pysyy painikkeessa. @@ -621,7 +622,7 @@ Päätetty: hankintahinta liukuvana keskihintana, negatiivinen saldo sallitaan v - **Laskurit ja huollot**: laskurin lukeman kirjaus numeronäppäimistöllä; huoltokohteet tiloineen ja huoltokirjaus (Huolto tehty, lukema esitäytettynä, käytetyt osat). Myöhässä olevat huollot näkyvät näkymän yläosassa tekstinä ja kuvakkeena. - Tehtävän tunnit kirjataan tavalliseen tapaan (luku 9); konekäyttöliittymässä on pikakirjaus valitun tehtävän tämän päivän tunneille. -### 19.7 Pikamyyntituotteiden valmistus +### 19.7 Pikamyyntituotteiden valmistus *(valmis)* Kuluttajatuote (esim. passikuvat, tuloste, tarra), jolla on valmistusprosessi, valmistetaan koneella ennen kuin myynti maksetaan. Myynnin on oltava myyjälle mahdollisimman helppo: tuotteet valitaan, tilaus lähtee koneelle, kone kuittaa tuotteen valmiiksi ja myyjä ottaa maksun. @@ -634,7 +635,7 @@ Kuluttajatuote (esim. passikuvat, tuloste, tarra), jolla on valmistusprosessi, v - **Kassapäivä**: päivän voi päättää, vaikka tilauksia on maksamatta; päättäminen kertoo maksamattomat tilaukset, ja ne jäävät avoimiksi seuraavalle päivälle. Maksamaton tilaus ei ole myyntiä eikä näy kassapäivän saldossa. - Pikamyynnin tuotteiden materiaalit kirjautuvat varastosta vain valmistusprosessin kautta; prosessittomien tuotteiden materiaalia ei kirjata automaattisesti. -### 19.8 Laskutus ja kustannukset +### 19.8 Laskutus ja kustannukset *(valmis)* - Painotyöt ja niiden materiaali laskutetaan tarjoushinnan mukaan (maksuperuste kiinteä tarjous, 5.5). Varaston käyttö ei siksi ole asiakastyön kulu (luku 10), eikä se tule laskuaineistoon. - Varaston käyttö hankintahinnalla on kustannustietoa: johdon raportteihin (luku 13) tulevat **Varaston käyttö** (aikavälin käyttö, hävikki ja korjaukset nimikkeittäin, ryhmittäin, koneittain ja asiakastöittäin, määrät ja arvot) ja **Varaston arvo** (saldot ja arvo valittuna päivänä, tilattavat nimikkeet). Kannattavuusraporttiin lisätään asiakastyön materiaalikustannus omana sarakkeenaan (avoin kysymys 6). @@ -665,7 +666,7 @@ Kuluttajatuote (esim. passikuvat, tuloste, tarra), jolla on valmistusprosessi, v - `stock_movements`: `stock_item_id`, `kind` (`purchase`/`consumption`/`write_off`/`adjustment`/`reversal`), `quantity_milli` (etumerkillinen), `unit_cost_cents`, `value_cents`, `occurred_on`, `user_id`, `task_id`, `customer_job_id`, `machine_id`, `quick_sale_id`, `inventory_count_id`, `maintenance_record_id`, `quick_sale_order_line_id`, `reverses_movement_id`, `reason`, `supplier`, `document_number` - `inventory_counts`: `counted_on`, `status`, `started_by`, `confirmed_by`, `confirmed_at`, `value_before_cents`, `value_after_cents`; `inventory_count_lines`: `stock_item_id`, `book_quantity_milli`, `counted_quantity_milli`, `counted_by`, `counted_at` - `machines`: `name`, `type` (`printer`/`cutter`/`other`), `description`, `responsible_user_id`, `is_active`; `machine_service_units`: `machine_id`, `service_unit_id` (vähintään yksi per kone); `machine_counters`: `machine_id`, `name`, `unit`, `current_reading`; `machine_counter_readings`: `machine_counter_id`, `reading`, `user_id`, `read_at` -- `maintenance_items`: `machine_id`, `name`, `machine_counter_id` tai `interval_days`, `interval_amount`, `warning_percent`, `instructions`, `stock_item_id`, `is_active`; `maintenance_records`: `maintenance_item_id`, `performed_at`, `user_id`, `counter_reading`, `note`, `cancelled_at`, `cancelled_by` +- `maintenance_items`: `machine_id`, `name`, `machine_counter_id` ja `interval_milli` (laskuriväli, `counter_baseline_milli` lukema lisättäessä), `period` (`day`/`week`/`month`/`year`) ja `period_count` (aikaväli), `starts_on`, `warning_percent`, `instructions`, `stock_item_id`, `stock_quantity_milli`, `is_active`; `maintenance_records`: `maintenance_item_id`, `performed_at`, `user_id`, `counter_reading`, `note`, `cancelled_at`, `cancelled_by` - `workflow_template_step_materials`: `workflow_template_step_id`, `stock_item_id`, `quantity_milli` (oletusmateriaalit) - `machine_queue_entries`: `machine_id`, `planned_on` (valmistuspäivä), `position` (järjestys päivän sisällä), `task_id` tai `quick_sale_order_line_id` + `production_step_position`, `completed_at`, `completed_by` (korvaa tehtävien sarakkeet `machine_id` ja `machine_queue_position`) - `production_steps`: `product_id`, `sort_order`, `machine_id` (tyhjä = koneeton vaihe), `duration_quarters`, `work_type_id`; `production_step_materials`: `production_step_id`, `stock_item_id`, `quantity_milli` (kappaletta kohden) @@ -681,10 +682,10 @@ Kuluttajatuote (esim. passikuvat, tuloste, tarra), jolla on valmistusprosessi, v 5. **Inventaarion tiheys** (19.3): kuinka usein inventaario tehdään (esim. tilinpäätös, kuukausittain)? (Arvostus on päätetty: liukuva keskihinta, 19.2.) 6. **Materiaalikustannus kannattavuudessa** (19.8): näytetäänkö asiakastyön varaston käyttö kannattavuusraportissa kustannuksena, vaikka sitä ei laskuteta erikseen? 7. ~~**Pikamyynnin materiaalit**~~: ratkaistu – materiaalit kirjautuvat tuotteen valmistusprosessin mukaan, kun kone kuittaa vaiheen valmiiksi (19.7). -8. **Koneet ja laskurit** (19.4–19.5): mitkä painokoneet ja tarraleikkurit (merkit ja mallit) sekä niiden huoltokohteet ja -välit otetaan käyttöön, ja tarvitaanko muita konetyyppejä, ja luetaanko laskurit koneilta käsin vai automaattisesti (esim. tulostimen verkkoliittymä, myöhemmin)? Kasvaako laskuri kirjatuista töistä vai vain luetuista lukemista? -9. **Konekäyttöliittymän kirjautuminen** (19.6): kirjautuuko jokainen käyttäjä tabletille omilla tunnuksillaan, vai tarvitaanko koneen yhteinen istunto, jossa käyttäjä valitaan (esim. PIN-koodilla)? Kuinka pitkä istunto saa olla? +8. **Koneet ja laskurit** (19.4–19.5): mitkä painokoneet ja tarraleikkurit (merkit ja mallit) sekä niiden huoltokohteet ja -välit otetaan käyttöön, ja tarvitaanko muita konetyyppejä? Laskurit luetaan toistaiseksi käsin; automaattinen luku (esim. tulostimen verkkoliittymä) myöhemmin. ~~Kasvaako laskuri kirjatuista töistä?~~ Ratkaistu: vain luetuista lukemista. +9. ~~**Konekäyttöliittymän kirjautuminen**~~: ratkaistu – jokainen kirjautuu omilla tunnuksillaan; Vaihda käyttäjä kirjaa ulos ja palauttaa kirjautumisen jälkeen konekäyttöliittymään (19.6). 10. **Ostot** (19.2): riittääkö saapumisten kirjaus, vai tarvitaanko ostotilaukset ja tilausehdotus hälytysrajoista? 11. **Tiedostot koneelle** (19.7): miten tulostettava kuva (esim. passikuva kamerasta) siirtyy koneelle? Ehdotus: järjestelmän ulkopuolella, ja tilaus tunnistetaan noutonumerolla. -12. **Vaiheen kone** (19.7): määritelläänkö valmistusvaiheelle tietty kone vai konetyyppi (mikä tahansa vapaa painokone)? Ehdotus: tietty kone, jolta rivin voi siirtää toiselle samantyyppiselle. +12. ~~**Vaiheen kone**~~: ratkaistu – vaiheelle valitaan tietty kone, ja rivin voi siirtää konekäyttöliittymässä toiselle samantyyppiselle koneelle (19.7). 13. **Kuitin sähköpostiosoitteen säilytys** (luku 7): kuinka kauan myyntiin tallennettu osoite säilytetään (esim. 12 kk, jonka jälkeen se poistetaan), ja tarvitaanko kuittiviestiin muuta tekstiä kuin yrityksen tiedot? 14. ~~**Usean päivän konetyö**~~: ratkaistu – yksi päivä per rivi; keskeneräinen rivi siirtyy seuraavalle päivälle myöhässä-merkinnällä (19.4). diff --git a/lang/en/layout.php b/lang/en/layout.php index 3995e79..7eac316 100644 --- a/lang/en/layout.php +++ b/lang/en/layout.php @@ -35,6 +35,8 @@ return [ 'report_profitability' => 'Profitability', 'report_sales' => 'Quick sales', 'report_reimbursements' => 'Expense reimbursements', + 'report_stock_usage' => 'Stock usage', + 'report_stock_value' => 'Stock value', 'new_job' => 'New job', 'sales_list' => 'Quick sales and cash days', 'workflow_templates' => 'Workflow templates', diff --git a/lang/en/reports.php b/lang/en/reports.php index e2552bc..64e311e 100644 --- a/lang/en/reports.php +++ b/lang/en/reports.php @@ -191,6 +191,7 @@ return [ 'work_revenue' => 'Billed work', 'expense_revenue' => 'Billed expenses', 'expense_cost' => 'Expense purchase cost', + 'material_cost' => 'Materials', 'hour_cost' => 'Cost of hours', 'effective_rate' => 'Realised €/h', 'quoted' => 'quote :amount', @@ -205,8 +206,63 @@ return [ 'work_revenue' => 'Billed work (cents)', 'expense_revenue' => 'Billed expenses (cents)', 'expense_cost' => 'Expense purchase cost (cents)', + 'material_cost' => 'Material cost (cents)', 'hour_cost' => 'Cost of hours (cents)', 'margin' => 'Margin (cents)', ], ], + 'stock_usage' => [ + 'title' => 'Stock usage', + 'intro' => 'Stock used, written off and corrected in stock counts in a period at cost (VAT 0), by item, group, machine and job. Stock use is not an expense of a job and is not billed.', + 'empty' => 'No stock movements in the period.', + 'total' => 'Total :amount', + 'none_target' => 'None', + 'by_item' => 'By item', + 'by_groups' => 'By group', + 'by_machines' => 'By machine', + 'by_jobs' => 'By job', + 'groups_column' => 'Group', + 'machines_column' => 'Machine', + 'jobs_column' => 'Job', + 'item' => 'Item', + 'group' => 'Group', + 'used' => 'Use', + 'written_off' => 'Write-off', + 'adjusted' => 'Stock count correction', + 'used_value' => 'Use (€)', + 'written_off_value' => 'Write-off (€)', + 'adjusted_value' => 'Corrections (€)', + 'value' => 'Total value', + 'file' => 'stock-usage', + 'csv' => [ + 'item' => 'Item', + 'group' => 'Group', + 'unit' => 'Unit', + 'used' => 'Use', + 'used_value' => 'Use value (cents)', + 'written_off' => 'Write-off', + 'written_off_value' => 'Write-off value (cents)', + 'adjusted' => 'Stock count correction', + 'adjusted_value' => 'Correction value (cents)', + 'value' => 'Total value (cents)', + ], + ], + 'stock_value' => [ + 'title' => 'Stock value', + 'intro' => 'Balances and book value (at cost, VAT 0) of the items at the end of the chosen day, and the items to order.', + 'day' => 'Day', + 'total' => 'Stock value :date: :amount', + 'to_order' => 'Items to order', + 'empty' => 'No items.', + 'table' => 'Stock value :date', + 'file' => 'stock-value', + 'csv' => [ + 'item' => 'Item', + 'group' => 'Group', + 'unit' => 'Unit', + 'balance' => 'Balance', + 'value' => 'Value (cents)', + 'reorder' => 'To order', + ], + ], ]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php index b5f5606..cdbd9a4 100644 --- a/lang/fi/layout.php +++ b/lang/fi/layout.php @@ -35,6 +35,8 @@ return [ 'report_profitability' => 'Kannattavuus', 'report_sales' => 'Pikamyynnit', 'report_reimbursements' => 'Kulukorvaukset', + 'report_stock_usage' => 'Varaston käyttö', + 'report_stock_value' => 'Varaston arvo', 'new_job' => 'Uusi työ', 'sales_list' => 'Pikamyynnit ja kassapäivät', 'workflow_templates' => 'Työnkulkupohjat', diff --git a/lang/fi/reports.php b/lang/fi/reports.php index 00ff1d3..e0663f0 100644 --- a/lang/fi/reports.php +++ b/lang/fi/reports.php @@ -191,6 +191,7 @@ return [ 'work_revenue' => 'Laskutettu työ', 'expense_revenue' => 'Laskutetut kulut', 'expense_cost' => 'Kulujen hankintahinta', + 'material_cost' => 'Materiaalit', 'hour_cost' => 'Tuntien kustannus', 'effective_rate' => 'Toteutunut €/h', 'quoted' => 'tarjous :amount', @@ -205,8 +206,63 @@ return [ 'work_revenue' => 'Laskutettu työ (snt)', 'expense_revenue' => 'Laskutetut kulut (snt)', 'expense_cost' => 'Kulujen hankintahinta (snt)', + 'material_cost' => 'Materiaalikustannus (snt)', 'hour_cost' => 'Tuntien kustannus (snt)', 'margin' => 'Kate (snt)', ], ], + 'stock_usage' => [ + 'title' => 'Varaston käyttö', + 'intro' => 'Aikavälin varaston käyttö, hävikki ja inventaariokorjaukset hankintahinnalla (ALV 0) nimikkeittäin, ryhmittäin, koneittain ja asiakastöittäin. Varaston käyttö ei ole asiakastyön kulu eikä tule laskuaineistoon.', + 'empty' => 'Ei varastotapahtumia aikavälillä.', + 'total' => 'Yhteensä :amount', + 'none_target' => 'Ei kohdetta', + 'by_item' => 'Nimikkeittäin', + 'by_groups' => 'Ryhmittäin', + 'by_machines' => 'Koneittain', + 'by_jobs' => 'Asiakastöittäin', + 'groups_column' => 'Ryhmä', + 'machines_column' => 'Kone', + 'jobs_column' => 'Asiakastyö', + 'item' => 'Nimike', + 'group' => 'Ryhmä', + 'used' => 'Käyttö', + 'written_off' => 'Hävikki', + 'adjusted' => 'Inventaariokorjaus', + 'used_value' => 'Käyttö (€)', + 'written_off_value' => 'Hävikki (€)', + 'adjusted_value' => 'Korjaukset (€)', + 'value' => 'Arvo yhteensä', + 'file' => 'varaston-kaytto', + 'csv' => [ + 'item' => 'Nimike', + 'group' => 'Ryhmä', + 'unit' => 'Yksikkö', + 'used' => 'Käyttö', + 'used_value' => 'Käytön arvo (snt)', + 'written_off' => 'Hävikki', + 'written_off_value' => 'Hävikin arvo (snt)', + 'adjusted' => 'Inventaariokorjaus', + 'adjusted_value' => 'Korjausten arvo (snt)', + 'value' => 'Arvo yhteensä (snt)', + ], + ], + 'stock_value' => [ + 'title' => 'Varaston arvo', + 'intro' => 'Nimikkeiden saldot ja kirjanpitoarvo (hankintahinnalla, ALV 0) valitun päivän lopussa sekä tilattavat nimikkeet.', + 'day' => 'Päivä', + 'total' => 'Varaston arvo :date: :amount', + 'to_order' => 'Tilattavat nimikkeet', + 'empty' => 'Ei nimikkeitä.', + 'table' => 'Varaston arvo :date', + 'file' => 'varaston-arvo', + 'csv' => [ + 'item' => 'Nimike', + 'group' => 'Ryhmä', + 'unit' => 'Yksikkö', + 'balance' => 'Saldo', + 'value' => 'Arvo (snt)', + 'reorder' => 'Tilattava', + ], + ], ]; diff --git a/phpunit.xml b/phpunit.xml index 899aa8d..5ee0067 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -21,6 +21,8 @@ + + diff --git a/tests/Browser/StockReportsAccessibilityTest.php b/tests/Browser/StockReportsAccessibilityTest.php new file mode 100644 index 0000000..694d013 --- /dev/null +++ b/tests/Browser/StockReportsAccessibilityTest.php @@ -0,0 +1,38 @@ +user = User::factory()->management()->create(); + $this->actingAs($this->user); + ServiceUnitModel::query()->where('name', 'Painotuotanto')->update(['uses_stock' => true]); + + $item = StockItemModel::factory()->create(['name' => 'Valokuvapaperi', 'unit' => 'sheet', 'reorder_level_milli' => 200_000]); + foreach ([['purchase', 100_000, 5_000], ['consumption', -20_000, -1_000]] as [$kind, $milli, $value]) { + StockMovementModel::query()->create([ + 'stock_item_id' => $item->id, 'kind' => $kind, 'quantity_milli' => $milli, 'unit_cost_hundredths' => 5_000, + 'value_cents' => $value, 'occurred_on' => now()->toDateString(), 'recorded_at' => now(), 'user_id' => $this->user->id, 'reason' => 'Koeajo', + ]); + } +}); + +it('has no accessibility issues on the stock reports', function (string $page, string $device, string $colorScheme) { + $visit = visit(route('reports.'.$page)); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee('Valokuvapaperi') + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with(['stock-usage', 'stock-value'])->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Feature/Modules/Reports/ProfitabilityReportTest.php b/tests/Feature/Modules/Reports/ProfitabilityReportTest.php index 30a5f9d..090be8d 100644 --- a/tests/Feature/Modules/Reports/ProfitabilityReportTest.php +++ b/tests/Feature/Modules/Reports/ProfitabilityReportTest.php @@ -95,7 +95,7 @@ it('reports billing, costs and margins by job and service unit', function () { ->assertDownload('kannattavuus-2026-11-01-2026-11-30.csv'); expect($response->streamedContent()) - ->toContain($billed->number.';Mainosvideo;"Asiakas Oy";Videotuotanto;Tuntityö;10;10;80000;12000;10000;40000;42000') + ->toContain($billed->number.';Mainosvideo;"Asiakas Oy";Videotuotanto;Tuntityö;10;10;80000;12000;10000;0;40000;42000') ->toContain(';-12000'); }); diff --git a/tests/Feature/Modules/Reports/StockReportsTest.php b/tests/Feature/Modules/Reports/StockReportsTest.php new file mode 100644 index 0000000..a395a31 --- /dev/null +++ b/tests/Feature/Modules/Reports/StockReportsTest.php @@ -0,0 +1,75 @@ +manager = User::factory()->management()->create(); + $this->actingAs($this->manager); + ServiceUnitModel::query()->where('name', 'Painotuotanto')->update(['uses_stock' => true]); + + $this->machine = MachineModel::factory()->create(['name' => 'Suurkuvatulostin']); + $this->job = CustomerJobModel::factory()->create(['name' => 'Messut', 'number' => '2026-0042']); + $papers = StockItemGroupModel::factory()->create(['name' => 'Paperit']); + $this->paper = StockItemModel::factory()->create(['stock_item_group_id' => $papers->id, 'name' => 'Valokuvapaperi', 'unit' => 'sheet', 'reorder_level_milli' => 50_000]); + + $move = fn (string $kind, int $milli, int $value, string $day, array $extra = []) => StockMovementModel::query()->create([ + 'stock_item_id' => $this->paper->id, 'kind' => $kind, 'quantity_milli' => $milli, 'unit_cost_hundredths' => 5_000, + 'value_cents' => $value, 'occurred_on' => $day, 'recorded_at' => now(), 'user_id' => $this->manager->id, ...$extra, + ]); + + $move('purchase', 100_000, 5_000, '2026-10-15'); + $move('consumption', -20_000, -1_000, '2026-11-05', ['machine_id' => $this->machine->id, 'customer_job_id' => $this->job->id, 'reason' => null]); + $use = $move('consumption', -10_000, -500, '2026-11-10', ['reason' => 'Koeajo']); + $move('reversal', 10_000, 500, '2026-11-10', ['reverses_movement_id' => $use->id, 'reason' => 'Koeajo']); + $move('write_off', -5_000, -250, '2026-11-30', ['reason' => 'Vaurioitunut']); +}); + +it('reports stock usage by item, machine and job with reversals netted', function () { + Livewire::test('reports::stock-usage') + ->set('from', '2026-11-01') + ->set('to', '2026-11-30') + ->assertSee('Yhteensä 12,50') + ->assertSee('Valokuvapaperi') + ->assertSee('Suurkuvatulostin') + ->assertSee('2026-0042 Messut'); + + $csv = $this->get(route('reports.csv', ['report' => 'stock-usage', 'alku' => '2026-11-01', 'loppu' => '2026-11-30']))->assertOk()->streamedContent(); + + expect($csv)->toContain('Valokuvapaperi;Paperit;arkki;20;1000;5;250;0;0;1250'); +}); + +it('reports the stock value at the end of a day and the items to order', function () { + Livewire::test('reports::stock-value') + ->set('day', '2026-11-05') + ->assertSee("Varaston arvo 5.11.2026: 40,00\u{00A0}€", false) + ->set('day', '2026-11-30') + ->assertSee("37,50\u{00A0}€", false) + ->assertDontSee(__('reports.stock_value.to_order')); + + $this->get(route('reports.csv', ['report' => 'stock-value', 'paiva' => '2026-11-30'])) + ->assertOk() + ->assertDownload('varaston-arvo-2026-11-30.csv'); +}); + +it('adds the job\'s material cost to its profitability', function () { + $report = app(ProfitabilityByJob::class)->execute(new ReportPeriod('2026-11-01', '2026-11-30'), true); + + expect(collect($report->jobs)->firstWhere('job.id', $this->job->id)->profit->materialCostCents)->toBe(1_000); +}); + +it('shows stock reports only to management when stock is used', function () { + $this->actingAs(User::factory()->employee()->create()); + $this->get(route('reports.stock-usage'))->assertForbidden(); +});