From 8aa62c8e02cf15253cae4006e091145a3e82fb99 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Wed, 25 Nov 2026 08:50:30 +0200 Subject: [PATCH] Add the profitability report and the internal hourly cost Profitability by job and service unit from a period's hours, expenses and the created billing materials of its months. Hours are costed at one internal hourly cost, set on the price list maintenance page; a job of several service units is shared evenly between them. Co-Authored-By: Claude Sonnet 5.5 --- .../Contracts/BilledRevenueQueries.php | 21 ++ .../Application/DTOs/BilledJobRevenue.php | 21 ++ .../EloquentBilledRevenueQueries.php | 49 ++++ .../Providers/BillingServiceProvider.php | 3 + .../Contracts/PriceListQueries.php | 5 + .../UseCases/SetInternalHourlyCost.php | 35 +++ .../Repositories/EloquentPriceListQueries.php | 8 + .../Presentation/Livewire/⚡prices.blade.php | 41 ++++ .../Application/Contracts/ReportCatalog.php | 5 + .../Application/Contracts/ReportRevenue.php | 22 ++ .../Reports/Application/DTOs/JobProfit.php | 18 ++ .../Reports/Application/DTOs/JobRevenue.php | 19 ++ .../Application/DTOs/ProfitabilityReport.php | 26 +++ .../Application/DTOs/ServiceUnitProfit.php | 21 ++ .../UseCases/ProfitabilityByJob.php | 102 ++++++++ .../Reports/Domain/ValueObjects/Profit.php | 116 ++++++++++ .../Adapters/CatalogForReports.php | 5 + .../Adapters/RevenueForReports.php | 27 +++ .../Providers/ReportsServiceProvider.php | 3 + .../Presentation/Csv/ProfitabilityCsv.php | 57 +++++ .../Http/Controllers/DownloadReport.php | 4 +- .../Livewire/⚡profitability.blade.php | 217 ++++++++++++++++++ .../Reports/Presentation/Routes/web.php | 1 + app/View/MainMenu.php | 1 + lang/en/catalog.php | 8 + lang/en/reports.php | 47 ++++ lang/fi/catalog.php | 8 + lang/fi/reports.php | 47 ++++ .../Feature/Modules/Catalog/PriceListTest.php | 21 ++ .../Reports/ProfitabilityReportTest.php | 110 +++++++++ tests/Unit/Modules/Reports/ProfitTest.php | 43 ++++ 31 files changed, 1110 insertions(+), 1 deletion(-) create mode 100644 app/Modules/Billing/Application/Contracts/BilledRevenueQueries.php create mode 100644 app/Modules/Billing/Application/DTOs/BilledJobRevenue.php create mode 100644 app/Modules/Billing/Infrastructure/Persistence/Repositories/EloquentBilledRevenueQueries.php create mode 100644 app/Modules/Catalog/Application/UseCases/SetInternalHourlyCost.php create mode 100644 app/Modules/Reports/Application/Contracts/ReportRevenue.php create mode 100644 app/Modules/Reports/Application/DTOs/JobProfit.php create mode 100644 app/Modules/Reports/Application/DTOs/JobRevenue.php create mode 100644 app/Modules/Reports/Application/DTOs/ProfitabilityReport.php create mode 100644 app/Modules/Reports/Application/DTOs/ServiceUnitProfit.php create mode 100644 app/Modules/Reports/Application/UseCases/ProfitabilityByJob.php create mode 100644 app/Modules/Reports/Domain/ValueObjects/Profit.php create mode 100644 app/Modules/Reports/Infrastructure/Adapters/RevenueForReports.php create mode 100644 app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php create mode 100644 app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php create mode 100644 tests/Feature/Modules/Reports/ProfitabilityReportTest.php create mode 100644 tests/Unit/Modules/Reports/ProfitTest.php diff --git a/app/Modules/Billing/Application/Contracts/BilledRevenueQueries.php b/app/Modules/Billing/Application/Contracts/BilledRevenueQueries.php new file mode 100644 index 0000000..b147b79 --- /dev/null +++ b/app/Modules/Billing/Application/Contracts/BilledRevenueQueries.php @@ -0,0 +1,21 @@ + Keyed by job id. + */ + public function byJob(string $fromMonth, string $toMonth): array; +} diff --git a/app/Modules/Billing/Application/DTOs/BilledJobRevenue.php b/app/Modules/Billing/Application/DTOs/BilledJobRevenue.php new file mode 100644 index 0000000..130b67e --- /dev/null +++ b/app/Modules/Billing/Application/DTOs/BilledJobRevenue.php @@ -0,0 +1,21 @@ +join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id') + ->join('billing_exports', 'billing_exports.id', '=', 'billing_invoices.billing_export_id') + ->where('billing_exports.status', ExportStatus::Created->value) + ->whereBetween('billing_exports.period', [$fromMonth, $toMonth]) + ->groupBy('billing_lines.customer_job_id') + ->select('billing_lines.customer_job_id') + ->selectRaw(self::sumOf(LineKind::Hours, 'net_cents').' as hours_cents') + ->selectRaw(self::sumOf(LineKind::FixedPrice, 'net_cents').' as fixed_cents') + ->selectRaw(self::sumOf(LineKind::MonthlyFee, 'net_cents').' as monthly_cents') + ->selectRaw(self::sumOf(LineKind::Expense, 'net_cents').' as expense_cents') + ->selectRaw(self::sumOf(LineKind::Hours, 'quantity_quarters').' as billed_quarters') + ->get(); + + $result = []; + foreach ($rows as $row) { + $jobId = (int) $row->customer_job_id; + $result[$jobId] = new BilledJobRevenue( + $jobId, + (int) $row->hours_cents, + (int) $row->fixed_cents, + (int) $row->monthly_cents, + (int) $row->expense_cents, + (int) $row->billed_quarters, + ); + } + + return $result; + } + + private static function sumOf(LineKind $kind, string $column): string + { + return "SUM(CASE WHEN billing_lines.kind = '{$kind->value}' THEN COALESCE(billing_lines.{$column}, 0) ELSE 0 END)"; + } +} diff --git a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php index 8ca48df..fc32bf7 100644 --- a/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php +++ b/app/Modules/Billing/Infrastructure/Providers/BillingServiceProvider.php @@ -3,6 +3,7 @@ namespace App\Modules\Billing\Infrastructure\Providers; use App\Models\User; +use App\Modules\Billing\Application\Contracts\BilledRevenueQueries; use App\Modules\Billing\Application\Contracts\BillingCustomers; use App\Modules\Billing\Application\Contracts\BillingExpenses; use App\Modules\Billing\Application\Contracts\BillingHours; @@ -15,6 +16,7 @@ use App\Modules\Billing\Infrastructure\CustomersForBilling; use App\Modules\Billing\Infrastructure\ExpensesForBilling; use App\Modules\Billing\Infrastructure\HoursForBilling; use App\Modules\Billing\Infrastructure\JobsForBilling; +use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBilledRevenueQueries; use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingExportRepository; use App\Modules\Billing\Infrastructure\Persistence\Repositories\EloquentBillingQueries; use App\Modules\Billing\Infrastructure\PricesForBilling; @@ -36,6 +38,7 @@ class BillingServiceProvider extends ServiceProvider public array $bindings = [ BillingExportRepository::class => EloquentBillingExportRepository::class, BillingQueries::class => EloquentBillingQueries::class, + BilledRevenueQueries::class => EloquentBilledRevenueQueries::class, BillingJobs::class => JobsForBilling::class, BillingHours::class => HoursForBilling::class, BillingExpenses::class => ExpensesForBilling::class, diff --git a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php index dcab407..821cb33 100644 --- a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php +++ b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php @@ -44,6 +44,11 @@ interface PriceListQueries */ public function mileageRateCents(): ?int; + /** + * The internal cost of an hour of work in cents (VAT 0), null when not set. + */ + public function internalHourlyCostCents(): ?int; + /** * Markup suggested for new purchase expenses, in hundredths of a percent (0 when not set). */ diff --git a/app/Modules/Catalog/Application/UseCases/SetInternalHourlyCost.php b/app/Modules/Catalog/Application/UseCases/SetInternalHourlyCost.php new file mode 100644 index 0000000..041819b --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetInternalHourlyCost.php @@ -0,0 +1,35 @@ +settings->put(self::SETTING_KEY, $cost === null ? null : (string) $cost->cents); + + return $cost; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php index 63a103a..d8bd403 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php @@ -11,6 +11,7 @@ use App\Modules\Catalog\Application\DTOs\ServiceUnitNode; use App\Modules\Catalog\Application\DTOs\VatRateSummary; use App\Modules\Catalog\Application\DTOs\WorkTypeSummary; use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup; +use App\Modules\Catalog\Application\UseCases\SetInternalHourlyCost; use App\Modules\Catalog\Application\UseCases\SetMileageRate; use App\Modules\Catalog\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; @@ -125,6 +126,13 @@ class EloquentPriceListQueries implements PriceListQueries return $value === null ? null : (int) $value; } + public function internalHourlyCostCents(): ?int + { + $value = $this->settings->get(SetInternalHourlyCost::SETTING_KEY); + + return $value === null ? null : (int) $value; + } + public function defaultExpenseMarkupBasisPoints(): int { return (int) ($this->settings->get(SetDefaultExpenseMarkup::SETTING_KEY) ?? 0); diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php index ca94bb4..90a2ad1 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php @@ -9,6 +9,7 @@ use App\Modules\Catalog\Application\UseCases\MoveProduct; use App\Modules\Catalog\Application\UseCases\MoveVatRate; use App\Modules\Catalog\Application\UseCases\SetDefaultExpenseMarkup; use App\Modules\Catalog\Application\UseCases\SetHourlyRate; +use App\Modules\Catalog\Application\UseCases\SetInternalHourlyCost; use App\Modules\Catalog\Application\UseCases\SetMileageRate; use App\Modules\Catalog\Application\UseCases\SetProductActive; use App\Modules\Catalog\Application\UseCases\SetVatRateActive; @@ -51,6 +52,8 @@ new class extends Component public string $expenseMarkup = ''; + public string $internalHourlyCost = ''; + protected PriceListQueries $priceList; public function boot(PriceListQueries $priceList): void @@ -63,6 +66,7 @@ new class extends Component $this->authorize('catalog.manage'); $this->mileageRate = $this->inputValue($this->priceList->mileageRateCents()); + $this->internalHourlyCost = $this->inputValue($this->priceList->internalHourlyCostCents()); $markup = $this->priceList->defaultExpenseMarkupBasisPoints(); $this->expenseMarkup = $markup === 0 ? '' : (new VatPercentage($markup))->inputValue(); } @@ -223,6 +227,26 @@ new class extends Component : __('catalog.mileage.saved', ['rate' => $rate->format()]); } + public function saveInternalHourlyCost(SetInternalHourlyCost $setInternalHourlyCost): void + { + $this->authorize('catalog.manage'); + + $this->resetErrorBag('internalHourlyCost'); + + try { + $cost = $setInternalHourlyCost->execute($this->internalHourlyCost); + } catch (InvalidMoneyAmount) { + $this->addError('internalHourlyCost', __('catalog.errors.invalid_price')); + + return; + } + + $this->internalHourlyCost = $cost?->inputValue() ?? ''; + $this->statusMessage = $cost === null + ? __('catalog.internal_cost.removed') + : __('catalog.internal_cost.saved', ['cost' => $cost->format()]); + } + /** * @return list */ @@ -527,4 +551,21 @@ new class extends Component + +
+

{{ __('catalog.internal_cost.section') }}

+ +
+
+ +
+ + +
diff --git a/app/Modules/Reports/Application/Contracts/ReportCatalog.php b/app/Modules/Reports/Application/Contracts/ReportCatalog.php index 2bb0081..6aa4c18 100644 --- a/app/Modules/Reports/Application/Contracts/ReportCatalog.php +++ b/app/Modules/Reports/Application/Contracts/ReportCatalog.php @@ -24,4 +24,9 @@ interface ReportCatalog * @return array */ public function serviceUnits(): array; + + /** + * The internal cost of an hour of work in cents (VAT 0), null when not set. + */ + public function internalHourlyCostCents(): ?int; } diff --git a/app/Modules/Reports/Application/Contracts/ReportRevenue.php b/app/Modules/Reports/Application/Contracts/ReportRevenue.php new file mode 100644 index 0000000..bf5bb8e --- /dev/null +++ b/app/Modules/Reports/Application/Contracts/ReportRevenue.php @@ -0,0 +1,22 @@ + Keyed by job id. + */ + public function byJob(ReportPeriod $period): array; +} diff --git a/app/Modules/Reports/Application/DTOs/JobProfit.php b/app/Modules/Reports/Application/DTOs/JobProfit.php new file mode 100644 index 0000000..6ba35ef --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/JobProfit.php @@ -0,0 +1,18 @@ + $jobs + * @param list $serviceUnits + */ + public function __construct( + public array $jobs, + public array $serviceUnits, + public Profit $total, + public ?int $hourlyCostCents, + ) {} +} diff --git a/app/Modules/Reports/Application/DTOs/ServiceUnitProfit.php b/app/Modules/Reports/Application/DTOs/ServiceUnitProfit.php new file mode 100644 index 0000000..27cc920 --- /dev/null +++ b/app/Modules/Reports/Application/DTOs/ServiceUnitProfit.php @@ -0,0 +1,21 @@ +hours->between($period) as $entry) { + $quarters[$entry->jobId] = ($quarters[$entry->jobId] ?? 0) + $entry->quarters; + } + + $expenseCosts = $this->expenses->costsByJob($period); + $revenue = $this->revenue->byJob($period); + $hourlyCost = $this->catalog->internalHourlyCostCents(); + + $jobIds = array_values(array_unique([...array_keys($quarters), ...array_keys($expenseCosts), ...array_keys($revenue)])); + $jobs = $this->jobs->infoOf($jobIds); + + $rows = []; + foreach ($jobs as $job) { + if ($job->isInternal && ! $includeInternal) { + continue; + } + + $billed = $revenue[$job->id] ?? null; + $rows[] = new JobProfit($job, Profit::of( + $quarters[$job->id] ?? 0, + $billed->billedQuarters ?? 0, + $billed->workCents ?? 0, + $billed->expenseCents ?? 0, + $expenseCosts[$job->id] ?? 0, + $hourlyCost, + )); + } + + usort($rows, fn (JobProfit $a, JobProfit $b): int => strcmp($a->job->number, $b->job->number)); + + $total = array_reduce($rows, fn (Profit $sum, JobProfit $row): Profit => $sum->plus($row->profit), Profit::of(0, 0, 0, 0, 0, $hourlyCost)); + + return new ProfitabilityReport($rows, $this->byServiceUnit($rows, $hourlyCost), $total, $hourlyCost); + } + + /** + * @param list $rows + * @return list + */ + private function byServiceUnit(array $rows, ?int $hourlyCost): array + { + $names = $this->catalog->serviceUnits(); + $profits = []; + $jobCounts = []; + + foreach ($rows as $row) { + $unitIds = $row->job->serviceUnitIds === [] ? [0] : $row->job->serviceUnitIds; + + foreach ($row->profit->split(count($unitIds)) as $index => $share) { + $unitId = $unitIds[$index]; + $profits[$unitId] = ($profits[$unitId] ?? Profit::of(0, 0, 0, 0, 0, $hourlyCost))->plus($share); + $jobCounts[$unitId] = ($jobCounts[$unitId] ?? 0) + 1; + } + } + + $result = []; + foreach ([...array_keys($names), 0] as $unitId) { + if (isset($profits[$unitId])) { + $result[] = new ServiceUnitProfit($unitId, $names[$unitId] ?? '', $jobCounts[$unitId], $profits[$unitId]); + } + } + + return $result; + } +} diff --git a/app/Modules/Reports/Domain/ValueObjects/Profit.php b/app/Modules/Reports/Domain/ValueObjects/Profit.php new file mode 100644 index 0000000..07a85a3 --- /dev/null +++ b/app/Modules/Reports/Domain/ValueObjects/Profit.php @@ -0,0 +1,116 @@ +workCents + $this->expenseRevenueCents; + } + + public function marginCents(): ?int + { + return $this->hourCostCents === null ? null : $this->revenueCents() - $this->expenseCostCents - $this->hourCostCents; + } + + /** + * The margin as a share of what was billed, null when nothing was billed. + */ + public function marginRatio(): ?float + { + $margin = $this->marginCents(); + + return $margin === null || $this->revenueCents() <= 0 ? null : $margin / $this->revenueCents(); + } + + /** + * What an hour worked brought in: billed for the work per hour worked. + */ + public function effectiveHourlyCents(): ?int + { + return $this->quarters === 0 ? null : (int) round($this->workCents * 4 / $this->quarters); + } + + public function plus(self $other): self + { + return new self( + $this->quarters + $other->quarters, + $this->billedQuarters + $other->billedQuarters, + $this->workCents + $other->workCents, + $this->expenseRevenueCents + $other->expenseRevenueCents, + $this->expenseCostCents + $other->expenseCostCents, + $this->hourCostCents === null || $other->hourCostCents === null ? null : $this->hourCostCents + $other->hourCostCents, + ); + } + + /** + * Splits the figures evenly into parts, e.g. for a job of several + * service units; the first parts take what does not divide evenly, so + * the parts add up to the whole. + * + * @return non-empty-list + */ + public function split(int $parts): array + { + $parts = max(1, $parts); + $result = []; + + for ($index = 0; $index < $parts; $index++) { + $result[] = new self( + self::share($this->quarters, $parts, $index), + self::share($this->billedQuarters, $parts, $index), + self::share($this->workCents, $parts, $index), + self::share($this->expenseRevenueCents, $parts, $index), + self::share($this->expenseCostCents, $parts, $index), + $this->hourCostCents === null ? null : self::share($this->hourCostCents, $parts, $index), + ); + } + + return $result; + } + + private static function share(int $value, int $parts, int $index): int + { + $base = intdiv($value, $parts); + $rest = $value - $base * $parts; + + return $base + ($index < abs($rest) ? ($rest <=> 0) : 0); + } +} diff --git a/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php b/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php index 278736c..e745d0b 100644 --- a/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php +++ b/app/Modules/Reports/Infrastructure/Adapters/CatalogForReports.php @@ -37,4 +37,9 @@ class CatalogForReports implements ReportCatalog return $units; } + + public function internalHourlyCostCents(): ?int + { + return $this->prices->internalHourlyCostCents(); + } } diff --git a/app/Modules/Reports/Infrastructure/Adapters/RevenueForReports.php b/app/Modules/Reports/Infrastructure/Adapters/RevenueForReports.php new file mode 100644 index 0000000..4d691fe --- /dev/null +++ b/app/Modules/Reports/Infrastructure/Adapters/RevenueForReports.php @@ -0,0 +1,27 @@ + new JobRevenue( + $revenue->jobId, + $revenue->hoursNetCents + $revenue->fixedPriceNetCents + $revenue->monthlyFeeNetCents, + $revenue->expenseNetCents, + $revenue->billedQuarters, + ), $this->queries->byJob($period->fromMonth(), $period->toMonth())); + } +} diff --git a/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php index 7796957..641ce58 100644 --- a/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php +++ b/app/Modules/Reports/Infrastructure/Providers/ReportsServiceProvider.php @@ -8,12 +8,14 @@ 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\ReportPeople; +use App\Modules\Reports\Application\Contracts\ReportRevenue; use App\Modules\Reports\Application\Contracts\ReportSales; use App\Modules\Reports\Infrastructure\Adapters\CatalogForReports; use App\Modules\Reports\Infrastructure\Adapters\ExpensesForReports; use App\Modules\Reports\Infrastructure\Adapters\HoursForReports; 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 Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; @@ -36,6 +38,7 @@ class ReportsServiceProvider extends ServiceProvider ReportPeople::class => PeopleForReports::class, ReportSales::class => SalesForReports::class, ReportExpenses::class => ExpensesForReports::class, + ReportRevenue::class => RevenueForReports::class, ]; public function boot(): void diff --git a/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php b/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php new file mode 100644 index 0000000..fa8eb8c --- /dev/null +++ b/app/Modules/Reports/Presentation/Csv/ProfitabilityCsv.php @@ -0,0 +1,57 @@ +from.'-'.$period->to; + } + + public function headers(): array + { + return array_values(__('reports.profitability.csv')); + } + + public function rows(Request $request): iterable + { + $report = $this->report->execute(CsvFilters::period($request), CsvFilters::flag($request, 'sisaiset')); + $serviceUnits = []; + + foreach ($report->serviceUnits as $unit) { + $serviceUnits[$unit->serviceUnitId] = $unit->name; + } + + foreach ($report->jobs as $row) { + $profit = $row->profit; + + yield [ + $row->job->number, + $row->job->name, + $row->job->customerName, + implode(', ', array_map(fn (int $id): string => $serviceUnits[$id] ?? '', $row->job->serviceUnitIds)), + $row->job->paymentBasis === null ? '' : __('jobs.payment_bases.'.$row->job->paymentBasis), + ReportFormat::csvHours($profit->quarters), + ReportFormat::csvHours($profit->billedQuarters), + $profit->workCents, + $profit->expenseRevenueCents, + $profit->expenseCostCents, + $profit->hourCostCents ?? '', + $profit->marginCents() ?? '', + ]; + } + } +} diff --git a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php index c267a76..bf0b0c7 100644 --- a/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php +++ b/app/Modules/Reports/Presentation/Http/Controllers/DownloadReport.php @@ -4,6 +4,7 @@ namespace App\Modules\Reports\Presentation\Http\Controllers; use App\Modules\Reports\Domain\Exceptions\InvalidReportPeriod; use App\Modules\Reports\Presentation\Csv\HoursCsv; +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; @@ -21,7 +22,7 @@ use Symfony\Component\HttpFoundation\StreamedResponse; class DownloadReport { /** The reports that have a CSV, by their URL key. */ - public const array REPORTS = ['hours', 'unbilled', 'sales', 'reimbursements']; + public const array REPORTS = ['hours', 'unbilled', 'profitability', 'sales', 'reimbursements']; public function __invoke(string $report, Request $request): StreamedResponse { @@ -75,6 +76,7 @@ class DownloadReport return match ($report) { 'hours' => app(HoursCsv::class), 'unbilled' => app(UnbilledCsv::class), + 'profitability' => app(ProfitabilityCsv::class), 'sales' => app(SalesCsv::class), 'reimbursements' => app(ReimbursementsCsv::class), default => abort(404), diff --git a/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php b/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php new file mode 100644 index 0000000..d271c7d --- /dev/null +++ b/app/Modules/Reports/Presentation/Livewire/⚡profitability.blade.php @@ -0,0 +1,217 @@ +startPeriod($clock, 'this_year'); + } + + #[Computed] + public function report(): ?ProfitabilityReport + { + $period = $this->period(); + + return $period === null ? null : app(ProfitabilityByJob::class)->execute($period, $this->includeInternal); + } + + public function updated(): void + { + $this->authorize('reports.view'); + unset($this->report); + } + + public function margin(Profit $profit): string + { + $margin = $profit->marginCents(); + + return $margin === null ? '–' : $this->money($margin); + } + + public function marginPercent(Profit $profit): string + { + $ratio = $profit->marginRatio(); + + return $ratio === null ? '–' : $this->percent($ratio); + } + + public function hourCost(Profit $profit): string + { + return $profit->hourCostCents === null ? '–' : $this->money($profit->hourCostCents); + } + + public function effectiveRate(Profit $profit): string + { + $cents = $profit->effectiveHourlyCents(); + + return $cents === null ? '–' : $this->money($cents); + } + + public function render(): mixed + { + return $this->view()->title(__('reports.profitability.title')); + } +}; +?> + +
+
+

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

+

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

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

{{ $this->periodLabel() }}

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

{{ __('reports.profitability.cost_used', ['cost' => $this->money($report->hourlyCostCents)]) }}

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

{{ __('reports.profitability.none') }}

+ @else +
+

{{ __('reports.profitability.by_service_unit') }}

+

{{ __('reports.profitability.split_note') }}

+ +
+ + + + + + + + + + + + + + + @foreach ($report->serviceUnits as $unit) + + + + + + + + + + @endforeach + +
{{ __('reports.profitability.units_table', ['period' => $this->periodLabel()]) }}
{{ __('reports.profitability.service_unit') }}{{ __('reports.profitability.jobs') }}{{ __('reports.profitability.hours') }}{{ __('reports.profitability.revenue') }}{{ __('reports.profitability.costs') }}{{ __('reports.profitability.margin') }}{{ __('reports.profitability.margin_percent') }}
{{ $unit->name !== '' ? $unit->name : __('reports.profitability.no_service_unit') }}{{ $unit->jobCount }}{{ $this->hours($unit->profit->quarters) }}{{ $this->money($unit->profit->revenueCents()) }}{{ $this->money($unit->profit->expenseCostCents + ($unit->profit->hourCostCents ?? 0)) }}{{ $this->margin($unit->profit) }}{{ $this->marginPercent($unit->profit) }}
+
+ + @if ($report->hourlyCostCents !== null) + + @endif +
+ +
+

{{ __('reports.profitability.by_job') }}

+ +
+ + + + + + + + + + + + + + + + + + @foreach ($report->jobs as $row) + + + + + + + + + + + + + @endforeach + + + + + + + + + + + + + + + +
{{ __('reports.profitability.jobs_table', ['period' => $this->periodLabel()]) }}
{{ __('reports.profitability.job') }}{{ __('reports.profitability.hours') }}{{ __('reports.profitability.billed_hours') }}{{ __('reports.profitability.work_revenue') }}{{ __('reports.profitability.expense_revenue') }}{{ __('reports.profitability.expense_cost') }}{{ __('reports.profitability.hour_cost') }}{{ __('reports.profitability.margin') }}{{ __('reports.profitability.margin_percent') }}{{ __('reports.profitability.effective_rate') }}
+ {{ $row->job->number }} {{ $row->job->name }} + + {{ $row->job->customerName }}@if ($row->job->paymentBasis !== null), {{ __('jobs.payment_bases.'.$row->job->paymentBasis) }}@endif + @if ($row->job->quotedAmountCents !== null), {{ __('reports.profitability.quoted', ['amount' => $this->money($row->job->quotedAmountCents)]) }}@endif + + {{ $this->hours($row->profit->quarters) }}{{ $this->hours($row->profit->billedQuarters) }}{{ $this->money($row->profit->workCents) }}{{ $this->money($row->profit->expenseRevenueCents) }}{{ $this->money($row->profit->expenseCostCents) }}{{ $this->hourCost($row->profit) }}{{ $this->margin($row->profit) }}{{ $this->marginPercent($row->profit) }}{{ $this->effectiveRate($row->profit) }}
{{ __('reports.total') }}{{ $this->hours($report->total->quarters) }}{{ $this->hours($report->total->billedQuarters) }}{{ $this->money($report->total->workCents) }}{{ $this->money($report->total->expenseRevenueCents) }}{{ $this->money($report->total->expenseCostCents) }}{{ $this->hourCost($report->total) }}{{ $this->margin($report->total) }}{{ $this->marginPercent($report->total) }}{{ $this->effectiveRate($report->total) }}
+
+
+ @endif + @endif +
diff --git a/app/Modules/Reports/Presentation/Routes/web.php b/app/Modules/Reports/Presentation/Routes/web.php index 0f54493..86936d6 100644 --- a/app/Modules/Reports/Presentation/Routes/web.php +++ b/app/Modules/Reports/Presentation/Routes/web.php @@ -9,6 +9,7 @@ Route::middleware(['web', 'auth', 'can:reports.view']) ->group(function () { Route::livewire('/hours', 'reports::hours')->name('hours'); Route::livewire('/unbilled', 'reports::unbilled')->name('unbilled'); + Route::livewire('/profitability', 'reports::profitability')->name('profitability'); Route::livewire('/sales', 'reports::sales')->name('sales'); Route::livewire('/reimbursements', 'reports::reimbursements')->name('reimbursements'); 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 cd0eb62..83cc43d 100644 --- a/app/View/MainMenu.php +++ b/app/View/MainMenu.php @@ -99,6 +99,7 @@ final class MainMenu 'items' => [ ['route' => 'reports.hours', 'pattern' => ['reports.hours'], 'label' => 'layout.report_hours', 'ability' => 'reports.view'], ['route' => 'reports.unbilled', 'pattern' => ['reports.unbilled'], 'label' => 'layout.report_unbilled', 'ability' => 'reports.view'], + ['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'], ], diff --git a/lang/en/catalog.php b/lang/en/catalog.php index d30f3e8..58e4457 100644 --- a/lang/en/catalog.php +++ b/lang/en/catalog.php @@ -210,6 +210,14 @@ return [ 'removed' => 'Mileage rate removed.', ], + 'internal_cost' => [ + 'section' => 'Internal hourly cost', + 'label' => 'Hourly cost (€/h, excl. VAT)', + 'help' => 'One shared cost of an hour of work (wages and overheads), e.g. 45. The profitability report uses it for the cost of the hours. An empty field removes it.', + 'saved' => 'Hourly cost :cost saved.', + 'removed' => 'Hourly cost removed.', + ], + 'fields' => [ 'name' => 'Name', 'service_unit' => 'Service unit', diff --git a/lang/en/reports.php b/lang/en/reports.php index 45116f4..e2552bc 100644 --- a/lang/en/reports.php +++ b/lang/en/reports.php @@ -162,4 +162,51 @@ return [ 'amount' => 'Amount VAT 0 (cents)', ], ], + + 'profitability' => [ + 'title' => 'Profitability', + 'file' => 'profitability', + 'intro' => 'From what happened in the period: the hours worked and expenses recorded in it, and what the created billing materials of its billing months billed. The margin is what was billed (work and expenses) less the expenses’ purchase costs and the cost of the hours. Amounts are without VAT (VAT 0).', + 'include_internal' => 'Also show internal jobs', + 'no_cost' => 'No internal hourly cost is set, so the cost of the hours and the margin are not calculated.', + 'set_cost' => 'Set the hourly cost in price list maintenance', + 'cost_used' => 'Hours are costed at the internal hourly cost of :cost / h.', + 'none' => 'There are no hours, expenses or billing in the period.', + 'by_service_unit' => 'By service unit', + 'split_note' => 'The figures of a job with several service units are shared evenly between them.', + 'units_table' => 'Profitability by service unit :period', + 'service_unit' => 'Service unit', + 'no_service_unit' => 'No service unit', + 'jobs' => 'Jobs', + 'hours' => 'Hours', + 'revenue' => 'Billed', + 'costs' => 'Costs', + 'margin' => 'Margin', + 'margin_percent' => 'Margin %', + 'chart' => 'Margin by service unit', + 'by_job' => 'By customer job', + 'jobs_table' => 'Profitability by customer job :period', + 'job' => 'Customer job', + 'billed_hours' => 'Billed hours', + 'work_revenue' => 'Billed work', + 'expense_revenue' => 'Billed expenses', + 'expense_cost' => 'Expense purchase cost', + 'hour_cost' => 'Cost of hours', + 'effective_rate' => 'Realised €/h', + 'quoted' => 'quote :amount', + 'csv' => [ + 'job_number' => 'Job number', + 'job' => 'Customer job', + 'customer' => 'Customer', + 'service_units' => 'Service units', + 'payment_basis' => 'Payment basis', + 'hours' => 'Hours', + 'billed_hours' => 'Billed hours', + 'work_revenue' => 'Billed work (cents)', + 'expense_revenue' => 'Billed expenses (cents)', + 'expense_cost' => 'Expense purchase cost (cents)', + 'hour_cost' => 'Cost of hours (cents)', + 'margin' => 'Margin (cents)', + ], + ], ]; diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index e92a42c..f08148e 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -210,6 +210,14 @@ return [ 'removed' => 'Km-hinta poistettu.', ], + 'internal_cost' => [ + 'section' => 'Sisäinen tuntikustannus', + 'label' => 'Tuntikustannus (€/h, ALV 0)', + 'help' => 'Yksi yhteinen hinta tehdyn työtunnin kustannukselle (palkka ja sivukulut), esim. 45. Kannattavuusraportti laskee sillä tuntien kustannuksen. Tyhjä kenttä poistaa hinnan.', + 'saved' => 'Tuntikustannus :cost tallennettu.', + 'removed' => 'Tuntikustannus poistettu.', + ], + 'fields' => [ 'name' => 'Nimi', 'service_unit' => 'Palveluyksikkö', diff --git a/lang/fi/reports.php b/lang/fi/reports.php index d34d034..00ff1d3 100644 --- a/lang/fi/reports.php +++ b/lang/fi/reports.php @@ -162,4 +162,51 @@ return [ 'amount' => 'Summa ALV 0 (snt)', ], ], + + 'profitability' => [ + 'title' => 'Kannattavuus', + 'file' => 'kannattavuus', + 'intro' => 'Aikavälin tapahtumista: siinä tehdyt tunnit ja kirjatut kulut sekä sen laskutuskuukausien luotujen laskuaineistojen laskutus. Kate on laskutus (työ ja kulut) vähennettynä kulujen hankintahinnalla ja tuntien kustannuksella. Summat ovat verottomia (ALV 0).', + 'include_internal' => 'Näytä myös sisäiset työt', + 'no_cost' => 'Sisäistä tuntikustannusta ei ole asetettu, joten tuntien kustannusta ja katetta ei lasketa.', + 'set_cost' => 'Aseta tuntikustannus hinnaston ylläpidossa', + 'cost_used' => 'Tuntien kustannus lasketaan sisäisellä tuntikustannuksella :cost / h.', + 'none' => 'Aikavälillä ei ole tunteja, kuluja eikä laskutusta.', + 'by_service_unit' => 'Palveluyksiköittäin', + 'split_note' => 'Usean palveluyksikön työn luvut jaetaan tasan sen palveluyksiköille.', + 'units_table' => 'Kannattavuus palveluyksiköittäin :period', + 'service_unit' => 'Palveluyksikkö', + 'no_service_unit' => 'Ei palveluyksikköä', + 'jobs' => 'Töitä', + 'hours' => 'Tunnit', + 'revenue' => 'Laskutettu', + 'costs' => 'Kustannukset', + 'margin' => 'Kate', + 'margin_percent' => 'Kate %', + 'chart' => 'Kate palveluyksiköittäin', + 'by_job' => 'Asiakastöittäin', + 'jobs_table' => 'Kannattavuus asiakastöittäin :period', + 'job' => 'Asiakastyö', + 'billed_hours' => 'Laskutetut tunnit', + 'work_revenue' => 'Laskutettu työ', + 'expense_revenue' => 'Laskutetut kulut', + 'expense_cost' => 'Kulujen hankintahinta', + 'hour_cost' => 'Tuntien kustannus', + 'effective_rate' => 'Toteutunut €/h', + 'quoted' => 'tarjous :amount', + 'csv' => [ + 'job_number' => 'Työn numero', + 'job' => 'Asiakastyö', + 'customer' => 'Asiakas', + 'service_units' => 'Palveluyksiköt', + 'payment_basis' => 'Maksuperuste', + 'hours' => 'Tunnit', + 'billed_hours' => 'Laskutetut tunnit', + 'work_revenue' => 'Laskutettu työ (snt)', + 'expense_revenue' => 'Laskutetut kulut (snt)', + 'expense_cost' => 'Kulujen hankintahinta (snt)', + 'hour_cost' => 'Tuntien kustannus (snt)', + 'margin' => 'Kate (snt)', + ], + ], ]; diff --git a/tests/Feature/Modules/Catalog/PriceListTest.php b/tests/Feature/Modules/Catalog/PriceListTest.php index b109ab7..d5da1af 100644 --- a/tests/Feature/Modules/Catalog/PriceListTest.php +++ b/tests/Feature/Modules/Catalog/PriceListTest.php @@ -182,6 +182,27 @@ it('saves the mileage rate', function () { ->assertHasErrors(['mileageRate']); }); +it('saves and removes the internal hourly cost', function () { + Livewire::test('catalog::prices') + ->set('internalHourlyCost', '45') + ->call('saveInternalHourlyCost') + ->assertHasNoErrors() + ->assertSet('statusMessage', "Tuntikustannus 45,00\u{00A0}€ tallennettu."); + + expect(app(PriceListQueries::class)->internalHourlyCostCents())->toBe(4500); + + Livewire::test('catalog::prices') + ->assertSet('internalHourlyCost', '45,00') + ->set('internalHourlyCost', 'abc') + ->call('saveInternalHourlyCost') + ->assertHasErrors(['internalHourlyCost']) + ->set('internalHourlyCost', '') + ->call('saveInternalHourlyCost') + ->assertSet('statusMessage', 'Tuntikustannus poistettu.'); + + expect(app(PriceListQueries::class)->internalHourlyCostCents())->toBeNull(); +}); + it('manages VAT rates and keeps one default', function () { $general = VatRateModel::query()->where('is_default', true)->sole(); diff --git a/tests/Feature/Modules/Reports/ProfitabilityReportTest.php b/tests/Feature/Modules/Reports/ProfitabilityReportTest.php new file mode 100644 index 0000000..5ed2651 --- /dev/null +++ b/tests/Feature/Modules/Reports/ProfitabilityReportTest.php @@ -0,0 +1,110 @@ +travelTo('2026-11-25 12:00'); + $this->manager = User::factory()->management()->create(); + $this->actingAs($this->manager); + $this->editing = WorkTypeModel::factory()->create(['name' => 'Editointi', 'hourly_rate_cents' => 8000]); + $this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']); + $this->video = ServiceUnitModel::factory()->create(['name' => 'Videotuotanto']); + $this->web = ServiceUnitModel::factory()->create(['name' => 'Verkkosivut']); +}); + +function profitJob(array $attributes, array $serviceUnitIds): CustomerJobModel +{ + $job = CustomerJobModel::factory()->create(array_merge(['customer_id' => test()->customer->id], $attributes)); + DB::table('customer_job_service_unit')->where('customer_job_id', $job->id)->delete(); + DB::table('customer_job_service_unit')->insert(array_map(fn (int $id): array => ['customer_job_id' => $job->id, 'service_unit_id' => $id], $serviceUnitIds)); + + return $job; +} + +function profitHours(CustomerJobModel $job, float $hours, string $day): void +{ + $task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => test()->editing->id]); + TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => $hours, 'worked_on' => $day]); +} + +it('reports billing, costs and margins by job and service unit', function () { + app(SetInternalHourlyCost::class)->execute('40'); + + $billed = profitJob(['name' => 'Mainosvideo', 'payment_basis' => 'hourly', 'status' => JobStatus::Done], [$this->video->id]); + profitHours($billed, 10, '2026-11-03'); + ExpenseModel::factory()->create(['customer_job_id' => $billed->id, 'spent_on' => '2026-11-04', 'cost_cents' => 10000, 'billed_amount_cents' => 12000]); + + $exportId = app(OpenBillingDraft::class)->execute($this->manager->id); + DB::table('billing_exports')->where('id', $exportId)->update(['period' => '2026-11']); + app(AddJobToDraft::class)->execute($exportId, $billed->id); + app(FinalizeBillingExport::class)->execute($exportId, $this->manager->id); + + $shared = profitJob(['name' => 'Sivusto ja video', 'payment_basis' => 'fixed_quote', 'quoted_amount_cents' => 500000], [$this->video->id, $this->web->id]); + profitHours($shared, 3, '2026-11-10'); + profitHours($shared, 50, '2026-10-10'); + + $internal = profitJob(['customer_id' => CustomerModel::query()->where('is_internal', true)->value('id'), 'name' => 'Hallinto'], [$this->web->id]); + profitHours($internal, 2, '2026-11-10'); + + $page = Livewire::withQueryParams(['alku' => '2026-11-01', 'loppu' => '2026-11-30']) + ->test('reports::profitability') + ->assertOk() + ->assertSee('Mainosvideo') + ->assertDontSee('Hallinto'); + + $report = $page->instance()->report(); + + expect(array_map(fn ($row) => $row->job->name, $report->jobs))->toBe(['Mainosvideo', 'Sivusto ja video']); + + $first = $report->jobs[0]->profit; + expect($first->quarters)->toBe(40) + ->and($first->billedQuarters)->toBe(40) + ->and($first->workCents)->toBe(80000) + ->and($first->expenseRevenueCents)->toBe(12000) + ->and($first->expenseCostCents)->toBe(10000) + ->and($first->hourCostCents)->toBe(40000) + ->and($first->marginCents())->toBe(42000); + + expect($report->jobs[1]->profit->marginCents())->toBe(-12000) + ->and(array_map(fn ($unit) => [$unit->name, $unit->jobCount, $unit->profit->quarters, $unit->profit->marginCents()], $report->serviceUnits)) + ->toContain(['Videotuotanto', 2, 46, 36000], ['Verkkosivut', 1, 6, -6000]) + ->and($report->total->marginCents())->toBe(30000); + + $page->set('includeInternal', true); + expect($page->instance()->report()->jobs)->toHaveCount(3); + + $response = $this->get(route('reports.csv', ['report' => 'profitability', 'alku' => '2026-11-01', 'loppu' => '2026-11-30'])) + ->assertOk() + ->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(';-12000'); +}); + +it('asks for the internal hourly cost before showing margins', function () { + profitHours(profitJob(['name' => 'Tuntityö', 'payment_basis' => 'hourly'], [$this->video->id]), 2, '2026-11-03'); + + $page = Livewire::withQueryParams(['alku' => '2026-11-01', 'loppu' => '2026-11-30']) + ->test('reports::profitability') + ->assertSee(__('reports.profitability.no_cost')); + + expect($page->instance()->report()->total->marginCents())->toBeNull(); +}); diff --git a/tests/Unit/Modules/Reports/ProfitTest.php b/tests/Unit/Modules/Reports/ProfitTest.php new file mode 100644 index 0000000..4b65c5c --- /dev/null +++ b/tests/Unit/Modules/Reports/ProfitTest.php @@ -0,0 +1,43 @@ +hourCostCents)->toBe(46125) + ->and($profit->revenueCents())->toBe(112000) + ->and($profit->marginCents())->toBe(55875) + ->and($profit->marginRatio())->toEqualWithDelta(0.4989, 0.0001) + ->and($profit->effectiveHourlyCents())->toBe(9756); +}); + +it('leaves the cost of the hours and the margin out without an hourly cost', function () { + $profit = Profit::of(8, 0, 50000, 0, 0, null); + + expect($profit->hourCostCents)->toBeNull() + ->and($profit->marginCents())->toBeNull() + ->and($profit->marginRatio())->toBeNull() + ->and($profit->effectiveHourlyCents())->toBe(25000) + ->and($profit->plus(Profit::of(4, 0, 0, 0, 0, 4500))->hourCostCents)->toBeNull(); +}); + +it('has no margin ratio or hourly yield when nothing was billed or worked', function () { + $profit = Profit::of(0, 0, 0, 0, 5000, 4500); + + expect($profit->marginCents())->toBe(-5000) + ->and($profit->marginRatio())->toBeNull() + ->and($profit->effectiveHourlyCents())->toBeNull(); +}); + +it('splits the figures evenly so that the parts add up to the whole', function () { + $profit = Profit::of(5, 4, 1001, 0, -7, 4500); + $parts = $profit->split(3); + + expect(array_map(fn (Profit $part): int => $part->quarters, $parts))->toBe([2, 2, 1]) + ->and(array_map(fn (Profit $part): int => $part->workCents, $parts))->toBe([334, 334, 333]) + ->and(array_map(fn (Profit $part): int => $part->expenseCostCents, $parts))->toBe([-3, -2, -2]) + ->and(array_sum(array_map(fn (Profit $part): int => (int) $part->hourCostCents, $parts)))->toBe($profit->hourCostCents) + ->and($parts[0]->plus($parts[1])->plus($parts[2]))->toEqual($profit); +});