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:
@@ -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,
|
||||
) {}
|
||||
}
|
||||
+49
@@ -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;
|
||||
}
|
||||
}
|
||||
+8
@@ -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');
|
||||
|
||||
@@ -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'],
|
||||
],
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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)',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -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ö',
|
||||
|
||||
@@ -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)',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Billing\Application\UseCases\AddJobToDraft;
|
||||
use App\Modules\Billing\Application\UseCases\FinalizeBillingExport;
|
||||
use App\Modules\Billing\Application\UseCases\OpenBillingDraft;
|
||||
use App\Modules\Catalog\Application\UseCases\SetInternalHourlyCost;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
|
||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
|
||||
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
|
||||
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
||||
use App\Modules\Jobs\Domain\Enums\JobStatus;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
|
||||
use App\Modules\TimeTracking\Infrastructure\Persistence\Eloquent\TimeEntryModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->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();
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Reports\Domain\ValueObjects\Profit;
|
||||
|
||||
it('charges the hours at the internal hourly cost and subtracts the costs from what was billed', function () {
|
||||
// 10,25 h at 45 €/h, 1 000 € billed for work and 120 € for expenses that cost 100 €.
|
||||
$profit = Profit::of(41, 40, 100000, 12000, 10000, 4500);
|
||||
|
||||
expect($profit->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);
|
||||
});
|
||||
Reference in New Issue
Block a user