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 <[email protected]>
This commit is contained in:
2026-11-25 08:50:30 +02:00
co-authored by Claude Sonnet 5.5
parent 8079c272d2
commit 8aa62c8e02
31 changed files with 1110 additions and 1 deletions
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\Contracts;
use App\Modules\Billing\Application\DTOs\BilledJobRevenue;
/**
* What created billing materials billed, for management's reports.
*/
interface BilledRevenueQueries
{
/**
* Invoice lines of the created billing materials of the billing months
* from the first to the last (Y-m, both included), summed by job.
*
* @return array<int, BilledJobRevenue> Keyed by job id.
*/
public function byJob(string $fromMonth, string $toMonth): array;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Billing\Application\DTOs;
/**
* A job's billed amounts without VAT in cents by line kind, and the hours
* billed on its hour lines in quarter hours.
*/
final readonly class BilledJobRevenue
{
public function __construct(
public int $jobId,
public int $hoursNetCents,
public int $fixedPriceNetCents,
public int $monthlyFeeNetCents,
public int $expenseNetCents,
public int $billedQuarters,
) {}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Modules\Billing\Infrastructure\Persistence\Repositories;
use App\Modules\Billing\Application\Contracts\BilledRevenueQueries;
use App\Modules\Billing\Application\DTOs\BilledJobRevenue;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use Illuminate\Support\Facades\DB;
class EloquentBilledRevenueQueries implements BilledRevenueQueries
{
public function byJob(string $fromMonth, string $toMonth): array
{
$rows = DB::table('billing_lines')
->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)";
}
}
@@ -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,
@@ -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).
*/
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* Sets the company's internal cost of an hour of work (wages and
* overheads, VAT 0), one rate for everyone, which the profitability report
* charges for the hours worked. An empty value removes it.
*/
final class SetInternalHourlyCost
{
public const string SETTING_KEY = 'catalog.internal_hourly_cost_cents';
public function __construct(private Settings $settings) {}
/**
* @return Money|null The stored cost.
*
* @throws InvalidMoneyAmount
*/
public function execute(string $hourlyCost): ?Money
{
$cost = Money::parse($hourlyCost);
$this->settings->put(self::SETTING_KEY, $cost === null ? null : (string) $cost->cents);
return $cost;
}
}
@@ -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);
@@ -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<array{index: string, label: string, sortable: bool, align?: string}>
*/
@@ -527,4 +551,21 @@ new class extends Component
<x-button submit :text="__('catalog.save')" />
</form>
</section>
<section aria-labelledby="internal-cost-heading" class="space-y-4">
<h2 id="internal-cost-heading" class="text-xl font-semibold">{{ __('catalog.internal_cost.section') }}</h2>
<form wire:submit="saveInternalHourlyCost" class="flex max-w-md flex-wrap items-end gap-3" novalidate>
<div class="min-w-40 flex-1">
<x-input
wire:model="internalHourlyCost"
:label="__('catalog.internal_cost.label')"
:hint="__('catalog.internal_cost.help')"
inputmode="decimal"
autocomplete="off"
/>
</div>
<x-button submit :text="__('catalog.save')" />
</form>
</section>
</div>
@@ -24,4 +24,9 @@ interface ReportCatalog
* @return array<int, string>
*/
public function serviceUnits(): array;
/**
* The internal cost of an hour of work in cents (VAT 0), null when not set.
*/
public function internalHourlyCostCents(): ?int;
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\Contracts;
use App\Modules\Reports\Application\DTOs\JobRevenue;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* What was billed, from the Billing module.
*/
interface ReportRevenue
{
/**
* Amounts billed by the created billing materials of the billing months
* the period touches, by job.
*
* @return array<int, JobRevenue> Keyed by job id.
*/
public function byJob(ReportPeriod $period): array;
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
use App\Modules\Reports\Domain\ValueObjects\Profit;
/**
* A job's profitability in the period.
*/
final readonly class JobProfit
{
public function __construct(
public ReportJob $job,
public Profit $profit,
) {}
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
/**
* A job's billed amounts without VAT in cents: for the work (hours, fixed
* price, monthly fees) and for expenses, and the billed hours in quarters.
*/
final readonly class JobRevenue
{
public function __construct(
public int $jobId,
public int $workCents,
public int $expenseCents,
public int $billedQuarters,
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
use App\Modules\Reports\Domain\ValueObjects\Profit;
/**
* Profitability by job (by job number) and by service unit (catalog
* order), the total, and the internal hourly cost used (null when not set,
* and then there are no hour costs or margins).
*/
final readonly class ProfitabilityReport
{
/**
* @param list<JobProfit> $jobs
* @param list<ServiceUnitProfit> $serviceUnits
*/
public function __construct(
public array $jobs,
public array $serviceUnits,
public Profit $total,
public ?int $hourlyCostCents,
) {}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\DTOs;
use App\Modules\Reports\Domain\ValueObjects\Profit;
/**
* A service unit's profitability in the period: its jobs' figures, a job
* of several service units shared evenly between them.
*/
final readonly class ServiceUnitProfit
{
public function __construct(
public int $serviceUnitId,
public string $name,
public int $jobCount,
public Profit $profit,
) {}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Application\UseCases;
use App\Modules\Reports\Application\Contracts\ReportCatalog;
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\DTOs\JobProfit;
use App\Modules\Reports\Application\DTOs\ProfitabilityReport;
use App\Modules\Reports\Application\DTOs\ServiceUnitProfit;
use App\Modules\Reports\Domain\ValueObjects\Profit;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Profitability by job and by service unit (spec 13) from what happened
* in a period: hours worked and expenses spent in it, and what the created
* billing materials of its billing months billed. Hours cost the company's
* one internal hourly cost. A job of several service units is shared
* evenly between them. Internal jobs are left out unless asked for.
*/
final readonly class ProfitabilityByJob
{
public function __construct(
private ReportHours $hours,
private ReportExpenses $expenses,
private ReportRevenue $revenue,
private ReportJobs $jobs,
private ReportCatalog $catalog,
) {}
public function execute(ReportPeriod $period, bool $includeInternal = false): ProfitabilityReport
{
$quarters = [];
foreach ($this->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<JobProfit> $rows
* @return list<ServiceUnitProfit>
*/
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;
}
}
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace App\Modules\Reports\Domain\ValueObjects;
/**
* The profitability of a job or a group of jobs in a period, without VAT,
* amounts in cents and hours in quarters:
*
* - 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 margin: everything billed less those costs (null without the hourly cost).
*/
final readonly class Profit
{
public function __construct(
public int $quarters = 0,
public int $billedQuarters = 0,
public int $workCents = 0,
public int $expenseRevenueCents = 0,
public int $expenseCostCents = 0,
public ?int $hourCostCents = 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
{
return new self(
$quarters,
$billedQuarters,
$workCents,
$expenseRevenueCents,
$expenseCostCents,
// Rounded half up to a cent.
$hourlyCostCents === null ? null : intdiv($quarters * $hourlyCostCents * 2 + 4, 8),
);
}
public function revenueCents(): int
{
return $this->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<self>
*/
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);
}
}
@@ -37,4 +37,9 @@ class CatalogForReports implements ReportCatalog
return $units;
}
public function internalHourlyCostCents(): ?int
{
return $this->prices->internalHourlyCostCents();
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Modules\Reports\Infrastructure\Adapters;
use App\Modules\Billing\Application\Contracts\BilledRevenueQueries;
use App\Modules\Billing\Application\DTOs\BilledJobRevenue;
use App\Modules\Reports\Application\Contracts\ReportRevenue;
use App\Modules\Reports\Application\DTOs\JobRevenue;
use App\Modules\Reports\Domain\ValueObjects\ReportPeriod;
/**
* Billed amounts for reports through the Billing module.
*/
class RevenueForReports implements ReportRevenue
{
public function __construct(private BilledRevenueQueries $queries) {}
public function byJob(ReportPeriod $period): array
{
return array_map(fn (BilledJobRevenue $revenue): JobRevenue => new JobRevenue(
$revenue->jobId,
$revenue->hoursNetCents + $revenue->fixedPriceNetCents + $revenue->monthlyFeeNetCents,
$revenue->expenseNetCents,
$revenue->billedQuarters,
), $this->queries->byJob($period->fromMonth(), $period->toMonth()));
}
}
@@ -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
@@ -0,0 +1,57 @@
<?php
namespace App\Modules\Reports\Presentation\Csv;
use App\Modules\Reports\Application\UseCases\ProfitabilityByJob;
use App\Modules\Reports\Presentation\ReportFormat;
use Illuminate\Http\Request;
/**
* Profitability as CSV: a row per job, amounts in cents (VAT 0); the hour
* cost and margin are empty when no internal hourly cost is set.
*/
class ProfitabilityCsv implements ReportCsv
{
public function __construct(private ProfitabilityByJob $report) {}
public function fileName(Request $request): string
{
$period = CsvFilters::period($request);
return __('reports.profitability.file').'-'.$period->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() ?? '',
];
}
}
}
@@ -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),
@@ -0,0 +1,217 @@
<?php
use App\Modules\Reports\Application\DTOs\ProfitabilityReport;
use App\Modules\Reports\Application\UseCases\ProfitabilityByJob;
use App\Modules\Reports\Domain\ValueObjects\Profit;
use App\Modules\Reports\Presentation\Livewire\Concerns\ReportPage;
use App\Modules\Users\Application\Contracts\Clock;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
/**
* Profitability by service unit and by job (spec 13) in a period: what
* was billed less the expenses' purchase costs and the hours at the
* internal hourly cost (set on the price list maintenance page).
*/
new class extends Component
{
use ReportPage;
#[Url(as: 'sisaiset', except: false)]
public bool $includeInternal = false;
public function mount(Clock $clock): void
{
$this->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'));
}
};
?>
<div class="mx-auto max-w-7xl space-y-6 p-4 sm:p-6">
<div class="space-y-2">
<h1 class="text-2xl font-semibold">{{ __('reports.profitability.title') }}</h1>
<p class="max-w-3xl text-sm">{{ __('reports.profitability.intro') }}</p>
</div>
<x-reports.period-filter :presets="$this->periodPresets()" :valid="$this->period !== null" />
<x-checkbox id="include-internal" wire:model.live="includeInternal" :label="__('reports.profitability.include_internal')" />
@php($report = $this->report)
@if ($report !== null)
<div class="flex flex-wrap items-center justify-between gap-3">
<h2 class="text-xl font-semibold" role="status" aria-live="polite">{{ $this->periodLabel() }}</h2>
<x-button :href="$this->csvUrl('profitability', ['sisaiset' => $includeInternal ? '1' : ''])" subtle color="black" icon="arrow-down-tray" :text="__('reports.download_csv')" />
</div>
@if ($report->hourlyCostCents === null)
<div class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
<p>
{{ __('reports.profitability.no_cost') }}
@can('catalog.manage')
<x-link :href="route('catalog.prices').'#internal-cost-heading'">{{ __('reports.profitability.set_cost') }}</x-link>
@endcan
</p>
</div>
@else
<p class="text-sm">{{ __('reports.profitability.cost_used', ['cost' => $this->money($report->hourlyCostCents)]) }}</p>
@endif
@if ($report->jobs === [])
<p>{{ __('reports.profitability.none') }}</p>
@else
<section aria-labelledby="units-heading" class="space-y-4">
<h2 id="units-heading" class="text-xl font-semibold">{{ __('reports.profitability.by_service_unit') }}</h2>
<p class="text-sm">{{ __('reports.profitability.split_note') }}</p>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('reports.profitability.units_table', ['period' => $this->periodLabel()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('reports.profitability.service_unit') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.jobs') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.hours') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.revenue') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.costs') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.margin') }}</th>
<th scope="col" class="py-2 text-right">{{ __('reports.profitability.margin_percent') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->serviceUnits as $unit)
<tr wire:key="unit-{{ $unit->serviceUnitId }}">
<th scope="row" class="py-2 pr-3 text-left font-normal">{{ $unit->name !== '' ? $unit->name : __('reports.profitability.no_service_unit') }}</th>
<td class="py-2 pr-3 text-right">{{ $unit->jobCount }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($unit->profit->quarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($unit->profit->revenueCents()) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($unit->profit->expenseCostCents + ($unit->profit->hourCostCents ?? 0)) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->margin($unit->profit) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->marginPercent($unit->profit) }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@if ($report->hourlyCostCents !== null)
<x-reports.chart
:title="__('reports.profitability.chart')"
:summary="implode(', ', array_map(fn ($unit) => $unit->name.' '.$this->margin($unit->profit), $report->serviceUnits))"
:labels="array_map(fn ($unit) => $unit->name, $report->serviceUnits)"
:values="array_map(fn ($unit) => ($unit->profit->marginCents() ?? 0) / 100, $report->serviceUnits)"
:formatter="fn (float $value) => number_format($value, 0, ',', ' ').' €'"
/>
@endif
</section>
<section aria-labelledby="jobs-heading" class="space-y-4">
<h2 id="jobs-heading" class="text-xl font-semibold">{{ __('reports.profitability.by_job') }}</h2>
<div class="overflow-x-auto">
<table class="w-full text-sm">
<caption class="sr-only">{{ __('reports.profitability.jobs_table', ['period' => $this->periodLabel()]) }}</caption>
<thead>
<tr class="border-b border-zinc-300 text-left align-bottom dark:border-zinc-600">
<th scope="col" class="py-2 pr-3">{{ __('reports.profitability.job') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.hours') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.billed_hours') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.work_revenue') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.expense_revenue') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.expense_cost') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.hour_cost') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.margin') }}</th>
<th scope="col" class="py-2 pr-3 text-right">{{ __('reports.profitability.margin_percent') }}</th>
<th scope="col" class="py-2 text-right">{{ __('reports.profitability.effective_rate') }}</th>
</tr>
</thead>
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
@foreach ($report->jobs as $row)
<tr wire:key="job-{{ $row->job->id }}" class="align-top">
<th scope="row" class="py-2 pr-3 text-left font-normal">
<x-link :href="route('jobs.show', $row->job->id)" navigate>{{ $row->job->number }} {{ $row->job->name }}</x-link>
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
{{ $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
</span>
</th>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($row->profit->quarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($row->profit->billedQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($row->profit->workCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($row->profit->expenseRevenueCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($row->profit->expenseCostCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hourCost($row->profit) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->margin($row->profit) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->marginPercent($row->profit) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->effectiveRate($row->profit) }}</td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr class="border-t-2 border-zinc-400 font-semibold dark:border-zinc-500">
<th scope="row" class="py-2 pr-3 text-left">{{ __('reports.total') }}</th>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->quarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hours($report->total->billedQuarters) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($report->total->workCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($report->total->expenseRevenueCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->money($report->total->expenseCostCents) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->hourCost($report->total) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->margin($report->total) }}</td>
<td class="py-2 pr-3 text-right whitespace-nowrap">{{ $this->marginPercent($report->total) }}</td>
<td class="py-2 text-right whitespace-nowrap">{{ $this->effectiveRate($report->total) }}</td>
</tr>
</tfoot>
</table>
</div>
</section>
@endif
@endif
</div>
@@ -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');
+1
View File
@@ -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'],
],