Add the billing material with drafts, combined invoices and billed marks

Management builds the monthly billing material (laskuaineisto) as a
draft: done jobs are added as invoices of their own, combined when the
customer, billing unit and reference allow it, and their billable hours
are set per work type. Creating the material checks the jobs again,
marks the approved hours and billable expenses billed, forms invoice
lines with price and VAT snapshots and moves the jobs to "Lasku luotu".
Fixed price jobs bill their quoted amount once. Billed hours keep their
approval and billed expenses can no longer change. The Fennoa export
and monthly fee lines come later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 13:08:24 +02:00
co-authored by Claude Opus 5.5
parent 6de5d9bef1
commit 97bd23bed5
98 changed files with 4887 additions and 22 deletions
@@ -0,0 +1,78 @@
<?php
use App\Models\User;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
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;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->manager = User::factory()->management()->create(['name' => 'Maija Johtaja']);
$this->actingAs($this->manager);
$layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8000]);
$customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']);
$this->jobs = [];
foreach (['Esite', 'Juliste'] as $name) {
$job = CustomerJobModel::factory()->create(['name' => $name, 'customer_id' => $customer->id, 'status' => JobStatus::Done, 'payment_basis' => 'hourly']);
$task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $layout->id]);
TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => 2.5]);
TimeEntryModel::factory()->create(['task_id' => TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $layout->id])->id, 'hours' => 1]);
$this->jobs[] = $job;
}
ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']);
$this->exportId = BillingExportModel::query()->create(['status' => 'draft', 'created_by' => $this->manager->id])->id;
});
it('has no accessibility issues on the billing pages', function (string $page, string $device, string $colorScheme) {
$url = $page === 'index' ? route('billing.index') : route('billing.export', $this->exportId);
$visit = visit($url);
$visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop();
$visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode();
$visit->assertSee($page === 'index' ? 'Jatka luonnosta' : 'Esite')
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['index', 'export'])->with([
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
]);
it('adds and combines jobs and creates the material', function () {
[$first, $second] = $this->jobs;
$page = visit(route('billing.export', $this->exportId));
$page->click('[wire\\:click="add('.$first->id.')"]')
->assertSee('lisätty aineistoon')
->click('[wire\\:click="add('.$second->id.')"]')
->assertSee('Lasku 2: Asiakas Oy')
->assertSee('Hyväksymättömiä tunteja 1 h')
->assertNoAccessibilityIssues(level: 2)
->select('[wire\\:model="moveTargets.'.$second->id.'"]', (string) $first->id)
->click('[wire\\:click="move('.$second->id.')"]')
->assertSee('siirretty laskulle')
->assertDontSee('Lasku 2: Asiakas Oy')
->click('Muodosta aineisto')
->assertSee('Muodostetaanko laskuaineisto?')
->assertNoAccessibilityIssues(level: 2)
->click('#finalize-dialog button:last-child')
->assertSee('Laskuaineisto muodostettu: 1 laskua.')
->assertSee('Laskutetut h')
->assertNoAccessibilityIssues(level: 2);
expect($first->refresh()->status)->toBe(JobStatus::Invoiced);
});
+15 -1
View File
@@ -20,7 +20,7 @@ class InMemoryExpenseRepository implements ExpenseRepository
public function save(Expense $expense): Expense
{
$id = $expense->id() ?? $this->nextId++;
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details());
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details(), $expense->billingExportId());
return clone $this->items[$id];
}
@@ -29,4 +29,18 @@ class InMemoryExpenseRepository implements ExpenseRepository
{
unset($this->items[$expense->id()]);
}
public function markBillableAsBilled(int $jobId, int $billingExportId): array
{
$ids = [];
foreach ($this->items as $id => $expense) {
if ($expense->jobId() === $jobId && $expense->details()->isBillable() && ! $expense->isBilled()) {
$this->items[$id] = Expense::reconstitute($id, $expense->jobId(), $expense->userId(), $expense->recordedBy(), $expense->details(), $billingExportId);
$ids[] = $id;
}
}
return $ids;
}
}
+8 -1
View File
@@ -34,7 +34,7 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository
public function save(TimeEntry $entry): TimeEntry
{
$id = $entry->id() ?? $this->nextId++;
$this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt());
$this->entries[$id] = TimeEntry::reconstitute($id, $entry->userId(), $entry->taskId(), $entry->jobId(), $entry->workTypeId(), $entry->workedOn(), $entry->hours(), $entry->note(), $entry->approvedBy(), $entry->approvedAt(), $entry->billingExportId());
return clone $this->entries[$id];
}
@@ -53,6 +53,13 @@ class InMemoryTimeEntryRepository implements TimeEntryRepository
unset($this->entries[$entry->id()]);
}
public function approvedUnbilledForJob(int $jobId): array
{
$found = array_filter($this->entries, fn (TimeEntry $entry): bool => $entry->jobId() === $jobId && $entry->isApproved() && ! $entry->isBilled());
return array_values(array_map(fn (TimeEntry $entry): TimeEntry => clone $entry, $found));
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{
$quarters = 0;
@@ -0,0 +1,227 @@
<?php
use App\Models\User;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingLineModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Expenses\Application\UseCases\RemoveExpense;
use App\Modules\Expenses\Domain\Exceptions\ExpenseLocked;
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\Application\UseCases\CancelWeekApproval;
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->manager = User::factory()->management()->create(['name' => 'Maija Johtaja']);
$this->actingAs($this->manager);
$this->layout = WorkTypeModel::factory()->create(['name' => 'Taitto', 'hourly_rate_cents' => 8000]);
$this->photo = WorkTypeModel::factory()->create(['name' => 'Kuvaus', 'hourly_rate_cents' => 10000]);
$this->customer = CustomerModel::factory()->company()->create(['name' => 'Asiakas Oy']);
});
/**
* A done job of the test customer with approved hours on the given work types.
*
* @param array<string, mixed> $attributes
* @param array<int, float> $approvedHours Hours keyed by work type id.
*/
function doneJob(array $attributes = [], array $approvedHours = []): CustomerJobModel
{
$job = CustomerJobModel::factory()->create(array_merge([
'customer_id' => test()->customer->id,
'status' => JobStatus::Done,
'payment_basis' => 'hourly',
], $attributes));
foreach ($approvedHours as $workTypeId => $hours) {
$task = TaskModel::factory()->create(['customer_job_id' => $job->id, 'work_type_id' => $workTypeId]);
TimeEntryModel::factory()->approved()->create(['task_id' => $task->id, 'hours' => $hours]);
}
return $job;
}
function openDraft(): int
{
Livewire::test('billing::index')->call('openDraftNow')->assertRedirect();
return (int) BillingExportModel::query()->where('status', ExportStatus::Draft)->value('id');
}
it('combines jobs of the same customer on one invoice and creates the billing material', function () {
$first = doneJob(['name' => 'Esite'], [$this->layout->id => 2.5, $this->photo->id => 1]);
$second = doneJob(['name' => 'Juliste', 'customer_reference' => 'PO-1'], [$this->layout->id => 1]);
$waiting = TimeEntryModel::factory()->create([
'task_id' => TaskModel::factory()->create(['customer_job_id' => $first->id, 'work_type_id' => $this->layout->id])->id,
'hours' => 3,
]);
$expense = ExpenseModel::factory()->create(['customer_job_id' => $first->id, 'description' => 'Paperi', 'billed_amount_cents' => 5000]);
ExpenseModel::factory()->notBillable()->create(['customer_job_id' => $first->id]);
$exportId = openDraft();
$page = Livewire::test('billing::export', ['export' => $exportId])
->call('add', $first->id)
->call('add', $second->id)
->assertSet('errorMessage', '')
->set("moveTargets.{$second->id}", (string) $first->id)
->call('move', $second->id)
->assertSet('errorMessage', '')
->call('saveHours', $first->id, $this->layout->id, '2')
->assertHasNoErrors();
$view = $page->get('export');
expect($view->invoices)->toHaveCount(1)
->and($view->invoices[0]->reference)->toBe('PO-1')
->and($view->invoices[0]->jobs[0]->unapprovedQuarters)->toBe(12)
->and($view->invoices[0]->totals->netCents)->toBe(2 * 8000 + 10000 + 5000 + 8000);
$page->call('finalize')->assertSet('errorMessage', '')->assertSet('statusMessage', 'Laskuaineisto muodostettu: 1 laskua.');
$export = BillingExportModel::query()->sole();
expect($export->status)->toBe(ExportStatus::Created)
->and($export->finalized_by)->toBe($this->manager->id);
$lines = BillingLineModel::query()->orderBy('sort_order')->get();
expect($lines->map->only(['customer_job_id', 'kind', 'description', 'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents'])->all())->toBe([
['customer_job_id' => $first->id, 'kind' => LineKind::Hours, 'description' => 'Kuvaus', 'recorded_quarters' => 4, 'quantity_quarters' => 4, 'unit_price_cents' => 10000, 'vat_basis_points' => 2550, 'net_cents' => 10000],
['customer_job_id' => $first->id, 'kind' => LineKind::Hours, 'description' => 'Taitto', 'recorded_quarters' => 10, 'quantity_quarters' => 8, 'unit_price_cents' => 8000, 'vat_basis_points' => 2550, 'net_cents' => 16000],
['customer_job_id' => $first->id, 'kind' => LineKind::Expense, 'description' => 'Tuotteet, tarvikkeet ja materiaalit '.$expense->spent_on->format('j.n.Y').': Paperi', 'recorded_quarters' => null, 'quantity_quarters' => null, 'unit_price_cents' => 5000, 'vat_basis_points' => 2550, 'net_cents' => 5000],
['customer_job_id' => $second->id, 'kind' => LineKind::Hours, 'description' => 'Taitto', 'recorded_quarters' => 4, 'quantity_quarters' => 4, 'unit_price_cents' => 8000, 'vat_basis_points' => 2550, 'net_cents' => 8000],
]);
expect(TimeEntryModel::query()->whereKeyNot($waiting->id)->pluck('billing_export_id')->unique()->all())->toBe([$export->id])
->and($waiting->refresh()->billing_export_id)->toBeNull()
->and($expense->refresh()->billing_export_id)->toBe($export->id)
->and(ExpenseModel::query()->where('is_billable', false)->value('billing_export_id'))->toBeNull()
->and($first->refresh()->status)->toBe(JobStatus::Invoiced)
->and($second->refresh()->status)->toBe(JobStatus::Invoiced)
->and(DB::table('customer_job_changes')->where('customer_job_id', $first->id)->where('field', 'status')->value('user_id'))->toBe($this->manager->id);
Livewire::test('billing::export', ['export' => $export->id])
->assertSee('Muodostettu')
->call('add', $first->id)
->assertSet('errorMessage', 'Aineisto on jo muodostettu, eikä sitä voi muuttaa.');
});
it('bills a fixed price job with its quoted amount once and marks its hours billed', function () {
$job = doneJob(['name' => 'Verkkosivut', 'payment_basis' => 'fixed_quote', 'quoted_amount_cents' => 250000], [$this->layout->id => 10]);
$exportId = openDraft();
Livewire::test('billing::export', ['export' => $exportId])
->call('add', $job->id)
->call('finalize')
->assertSet('errorMessage', '');
$line = BillingLineModel::query()->sole();
expect($line->kind)->toBe(LineKind::FixedPrice)
->and($line->net_cents)->toBe(250000)
->and($line->description)->toBe($job->number.' Verkkosivut')
->and(TimeEntryModel::query()->sole()->billing_export_id)->toBe($exportId);
// Moved back to done by mistake: the fixed price is not billed again.
$job->refresh()->update(['status' => JobStatus::Done]);
$next = openDraft();
Livewire::test('billing::export', ['export' => $next])
->assertSee('Ei laskutettavaa')
->call('add', $job->id)
->assertSet('errorMessage', fn (string $message) => str_contains($message, 'Ei laskutettavaa'));
});
it('does not add jobs that cannot be billed', function () {
$consumer = CustomerModel::factory()->consumer()->create();
$withoutCode = doneJob(['customer_id' => $consumer->id], [$this->layout->id => 1]);
$noRate = WorkTypeModel::factory()->create(['name' => 'Suunnittelu', 'hourly_rate_cents' => null]);
$withoutRate = doneJob([], [$noRate->id => 2]);
$notBillable = doneJob(['payment_basis' => 'not_billable'], [$this->layout->id => 1]);
$notDone = doneJob(['status' => JobStatus::InProduction], [$this->layout->id => 1]);
$page = Livewire::test('billing::export', ['export' => openDraft()])
->assertSee('Asiakkaan henkilötunnus puuttuu.')
->assertSee('Tuntihinta puuttuu: Suunnittelu')
->assertDontSee($notDone->name);
foreach ([$withoutCode, $withoutRate, $notBillable, $notDone] as $job) {
$page->call('add', $job->id)->assertSet('errorMessage', fn (string $message) => $message !== '');
}
expect(DB::table('billing_invoice_jobs')->count())->toBe(0);
});
it('keeps jobs with different customer references on separate invoices', function () {
$first = doneJob(['customer_reference' => 'PO-1'], [$this->layout->id => 1]);
$second = doneJob(['customer_reference' => 'PO-2'], [$this->layout->id => 1]);
Livewire::test('billing::export', ['export' => openDraft()])
->call('add', $first->id)
->call('add', $second->id)
->set("moveTargets.{$second->id}", (string) $first->id)
->call('move', $second->id)
->assertSet('errorMessage', 'Töillä on eri asiakkaan viite.');
expect(DB::table('billing_invoices')->count())->toBe(2);
});
it('rejects billable hours that are not in quarters of an hour', function () {
$job = doneJob([], [$this->layout->id => 1]);
Livewire::test('billing::export', ['export' => openDraft()])
->call('add', $job->id)
->call('saveHours', $job->id, $this->layout->id, '1,1')
->assertHasErrors(["hours.{$job->id}.{$this->layout->id}"])
->call('saveHours', $job->id, $this->layout->id, '0,75')
->assertHasNoErrors();
expect(DB::table('billing_job_hours')->value('billable_quarters'))->toBe(3);
});
it('keeps one draft at a time and discards it without billing anything', function () {
$job = doneJob([], [$this->layout->id => 1]);
$exportId = openDraft();
Livewire::test('billing::index')
->assertSee('Jatka luonnosta')
->call('openDraftNow')
->assertSet('statusMessage', 'Luonnos on jo auki. Jatka sitä.');
Livewire::test('billing::export', ['export' => $exportId])
->call('add', $job->id)
->call('discard')
->assertRedirect(route('billing.index'));
expect(BillingExportModel::query()->count())->toBe(0)
->and(TimeEntryModel::query()->sole()->billing_export_id)->toBeNull()
->and($job->refresh()->status)->toBe(JobStatus::Done);
});
it('keeps billed hours approved and billed expenses unchanged', function () {
$job = doneJob([], [$this->layout->id => 1]);
$expense = ExpenseModel::factory()->create(['customer_job_id' => $job->id]);
Livewire::test('billing::export', ['export' => openDraft()])->call('add', $job->id)->call('finalize');
$job->refresh()->update(['status' => JobStatus::InProduction]);
$entry = TimeEntryModel::query()->sole();
expect(app(CancelWeekApproval::class)->execute($entry->user_id, $entry->worked_on->startOfWeek()->toDateString()))->toBe(0)
->and($entry->refresh()->approved_at)->not->toBeNull();
app(RemoveExpense::class)->execute($expense->id);
})->throws(ExpenseLocked::class);
it('keeps everyone but management out', function (string $role) {
$this->actingAs(User::factory()->{$role}()->create());
$this->get(route('billing.index'))->assertForbidden();
})->with(['employee', 'intern', 'subcontractor']);
@@ -0,0 +1,177 @@
<?php
use App\Modules\Billing\Application\DTOs\BillableExpense;
use App\Modules\Billing\Application\DTOs\BillableJob;
use App\Modules\Billing\Application\DTOs\HourlyRate;
use App\Modules\Billing\Application\DTOs\JobHours;
use App\Modules\Billing\Application\Services\BillingRules;
use App\Modules\Billing\Domain\Entities\BillingExport;
use App\Modules\Billing\Domain\Enums\BillingMode;
use App\Modules\Billing\Domain\Enums\ExportStatus;
use App\Modules\Billing\Domain\Enums\LineKind;
use App\Modules\Billing\Domain\Enums\MergeRefusal;
use App\Modules\Billing\Domain\Enums\NotBillableReason;
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
function draft(): BillingExport
{
return BillingExport::startDraft(1, new DateTimeImmutable('2026-11-24 10:00'));
}
function billableJob(int $id, BillingMode $mode = BillingMode::Hours, array $overrides = []): BillableJob
{
$values = array_merge([
'id' => $id,
'number' => '2026-000'.$id,
'name' => 'Työ '.$id,
'customerId' => 1,
'customerName' => 'Asiakas Oy',
'isConsumer' => false,
'isInternal' => false,
'hasIdentityCode' => false,
'billingUnitId' => null,
'billingUnitName' => null,
'customerReference' => null,
'mode' => $mode,
'quotedAmountCents' => null,
'isDone' => true,
], $overrides);
return new BillableJob(...$values);
}
it('combines jobs of the same customer and billing unit when at most one has a reference', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, 5, null));
$export->addJob(new DraftJob(2, 10, 5, 'PO-1'));
$export->addJob(new DraftJob(3, 10, 5, null));
$export->moveJob(2, 1);
$export->moveJob(3, 1);
expect($export->invoices())->toHaveCount(1)
->and($export->invoices()[0]->reference())->toBe('PO-1')
->and($export->jobIds())->toBe([1, 2, 3]);
$export->separate(2);
expect($export->invoices())->toHaveCount(2)
->and($export->invoiceOf(2)?->key())->toBe(2);
});
it('refuses to combine jobs that must be billed apart', function (DraftJob $other, MergeRefusal $refusal) {
$export = draft();
$export->addJob(new DraftJob(1, 10, 5, 'PO-1'));
$export->addJob($other);
try {
$export->moveJob($other->jobId, 1);
$this->fail('The jobs were combined.');
} catch (InvoicesCannotMerge $exception) {
expect($exception->refusal)->toBe($refusal)
->and($export->invoices())->toHaveCount(2);
}
})->with([
'another customer' => [new DraftJob(2, 11, 5, null), MergeRefusal::DifferentCustomer],
'another billing unit' => [new DraftJob(2, 10, null, null), MergeRefusal::DifferentBillingUnit],
'another reference' => [new DraftJob(2, 10, 5, 'PO-2'), MergeRefusal::DifferentReference],
]);
it('drops an invoice left without jobs and does not add a job twice', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, null, null));
$export->addJob(new DraftJob(2, 10, null, null));
$export->moveJob(2, 1);
$export->removeJob(1);
expect($export->invoices())->toHaveCount(1)
->and($export->invoices()[0]->key())->toBe(2);
$export->addJob(new DraftJob(2, 10, null, null));
})->throws(JobAlreadyInDraft::class);
it('parses billable hours in quarters of an hour', function (string $value, ?int $quarters) {
expect(DraftJob::parseHours($value))->toBe($quarters);
})->with([
['12,5', 50],
['0,25', 1],
['3', 12],
['0', 0],
['', null],
]);
it('rejects billable hours that are not quarters of an hour', function (string $value) {
DraftJob::parseHours($value);
})->throws(InvalidBillableHours::class)->with(['1,1', '-1', 'abc', '10000']);
it('locks the material once it is created', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, null, null));
$export->finalize([1 => [InvoiceLine::fixedPrice(1, 'Työ', 1000, 2550)]], 2, new DateTimeImmutable('2026-11-24 12:00'));
expect($export->status())->toBe(ExportStatus::Created)
->and($export->invoices()[0]->totals()->netCents)->toBe(1000);
$export->addJob(new DraftJob(2, 10, null, null));
})->throws(ExportNotDraft::class);
it('does not create an empty material', function () {
draft()->finalize([], 1, new DateTimeImmutable);
})->throws(ExportEmpty::class);
it('prices hours by the quarter and rounds half up', function () {
expect(InvoiceLine::hours(1, 2, 'Taitto', 10, 9, 8050, 2550)->netCents)->toBe(18113)
->and(InvoiceLine::hours(1, 2, 'Taitto', 1, 1, 2, 2550)->netCents)->toBe(1)
->and(InvoiceLine::hours(1, 2, 'Taitto', 1, 1, 1, 2550)->netCents)->toBe(0);
});
it('counts the VAT from each rate total', function () {
$totals = InvoiceTotals::of([
InvoiceLine::fixedPrice(1, 'A', 3333, 2550),
InvoiceLine::fixedPrice(1, 'B', 3333, 2550),
InvoiceLine::expense(1, 9, 'C', 1000, 1350),
]);
expect($totals->netCents)->toBe(7666)
->and($totals->byVatRate)->toBe([2550 => ['net' => 6666, 'vat' => 1700], 1350 => ['net' => 1000, 'vat' => 135]])
->and($totals->grossCents())->toBe(7666 + 1835);
});
it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hours, array $expenses, bool $fixedBilled, ?NotBillableReason $reason) {
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Suunnittelu', null)];
expect((new BillingRules)->reasonNotBillable($job, $hours, $expenses, $fixedBilled, $rates))->toBe($reason);
})->with([
'billable hours' => [billableJob(1), new JobHours(1, [1 => 4]), [], false, null],
'not done' => [billableJob(1, overrides: ['isDone' => false]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::WrongStatus],
'billed monthly or not billable' => [billableJob(1, overrides: ['mode' => null]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
'internal customer' => [billableJob(1, overrides: ['isInternal' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
'consumer without a code' => [billableJob(1, overrides: ['isConsumer' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::MissingIdentityCode],
'consumer with a code' => [billableJob(1, overrides: ['isConsumer' => true, 'hasIdentityCode' => true]), new JobHours(1, [1 => 4]), [], false, null],
'work type without a rate' => [billableJob(1), new JobHours(1, [1 => 4, 2 => 1]), [], false, NotBillableReason::MissingHourlyRate],
'only unapproved hours' => [billableJob(1), new JobHours(1, [], 8), [], false, NotBillableReason::NothingToBill],
'only expenses' => [billableJob(1), new JobHours(1), [new BillableExpense(5, 1, 'Paperi', 500)], false, null],
'fixed price' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1), [], false, null],
'fixed price without a quote' => [billableJob(1, BillingMode::FixedPrice), new JobHours(1), [], false, NotBillableReason::MissingQuotedAmount],
'fixed price billed before' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1, [1 => 4]), [], true, NotBillableReason::NothingToBill],
]);
it('forms hour lines by work type name with the billable hours, then the expenses', function () {
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Kuvaus', 10000)];
$draftJob = (new DraftJob(1, 1, null, null))->withBillableQuarters(1, 6);
$lines = (new BillingRules)->lines(billableJob(1), $draftJob, [1 => 8, 2 => 2], [new BillableExpense(5, 1, 'Paperi', 500)], false, $rates, 2550);
expect(array_map(fn (InvoiceLine $line): array => [$line->kind, $line->description, $line->recordedQuarters, $line->quantityQuarters, $line->netCents], $lines))->toBe([
[LineKind::Hours, 'Kuvaus', 2, 2, 5000],
[LineKind::Hours, 'Taitto', 8, 6, 12000],
[LineKind::Expense, 'Paperi', null, null, 500],
]);
});