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
@@ -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();
});
+43
View File
@@ -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);
});