Files
Toiminnanohjaus/tests/Feature/Modules/Billing/BillingExportTest.php
T
petriandClaude Opus 5.5 5f9423a3c3 Add monthly fee billing lines to the billing material
Jobs billed by a fixed monthly fee get a monthly fee field, kept behind
the quotes permission like the quoted amount. A billing material now has
a billing month: a new draft adds every monthly fee job with something
to bill, each on an invoice of its own, and bills one line for every
unbilled month from the job's start up to the billing month (or its end
or completion), so skipped months are caught up and no month is billed
twice. Their expenses are billed alongside, their hours are covered by
the fee and marked billed, and the job keeps running.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 13:23:46 +02:00

298 lines
15 KiB
PHP

<?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']);
it('bills every unbilled month of a monthly fee job on an invoice of its own and keeps the job running', function () {
$this->travelTo(now()->setDate(2026, 11, 20)->setTime(12, 0));
$maintenance = doneJob([
'name' => 'Ylläpito',
'status' => JobStatus::InProduction,
'payment_basis' => 'monthly_fee',
'monthly_fee_cents' => 9900,
'starts_on' => '2026-09-10',
], [$this->layout->id => 2]);
ExpenseModel::factory()->create(['customer_job_id' => $maintenance->id, 'description' => 'Lisenssi', 'billed_amount_cents' => 1500]);
$other = doneJob([], [$this->layout->id => 1]);
$exportId = openDraft();
$page = Livewire::test('billing::export', ['export' => $exportId])
->assertSee('9/2026')
->assertSee('Hyväksytyt tunnit 2 h kuuluvat kuukausihintaan')
->call('savePeriod', '2026-10')
->assertSet('statusMessage', 'Laskutuskuukausi on nyt 10/2026.')
->assertDontSee('11/2026')
->call('savePeriod', '2026-13')
->assertHasErrors(['period'])
->call('savePeriod', '2026-11')
->call('add', $other->id)
->set("moveTargets.{$other->id}", (string) $maintenance->id)
->call('move', $other->id)
->assertSet('errorMessage', 'Kuukausilaskutuksen työ laskutetaan omalla laskullaan.');
expect($page->get('export')->invoices)->toHaveCount(2)
->and($page->get('export')->invoices[0]->mergeTargets[$maintenance->id])->toBe([]);
$page->call('finalize')->assertSet('errorMessage', '');
$monthly = BillingLineModel::query()->where('customer_job_id', $maintenance->id)->orderBy('sort_order')->get();
expect($monthly->map->only(['kind', 'period', 'net_cents'])->all())->toBe([
['kind' => LineKind::MonthlyFee, 'period' => '2026-09', 'net_cents' => 9900],
['kind' => LineKind::MonthlyFee, 'period' => '2026-10', 'net_cents' => 9900],
['kind' => LineKind::MonthlyFee, 'period' => '2026-11', 'net_cents' => 9900],
['kind' => LineKind::Expense, 'period' => null, 'net_cents' => 1500],
])
->and($maintenance->refresh()->status)->toBe(JobStatus::InProduction)
->and($other->refresh()->status)->toBe(JobStatus::Invoiced)
->and(TimeEntryModel::query()->where('customer_job_id', $maintenance->id)->value('billing_export_id'))->toBe($exportId);
// The same month again bills nothing; the next month bills one row.
$next = openDraft();
expect(DB::table('billing_invoice_jobs')->count())->toBe(2);
$this->travelTo(now()->setDate(2026, 12, 5));
Livewire::test('billing::export', ['export' => $next])
->assertSee('Ei laskutettavaa')
->call('savePeriod', '2026-12')
->call('add', $maintenance->id)
->assertSet('errorMessage', '')
->call('finalize');
expect(BillingLineModel::query()->where('customer_job_id', $maintenance->id)->where('kind', LineKind::MonthlyFee)->pluck('period')->all())
->toBe(['2026-09', '2026-10', '2026-11', '2026-12']);
});
it('does not bill a monthly fee job without a monthly fee', function () {
$job = doneJob(['status' => JobStatus::InProduction, 'payment_basis' => 'monthly_fee']);
Livewire::test('billing::export', ['export' => openDraft()])
->assertSee('Kuukausilaskutuksen työltä puuttuu kuukausihinta.')
->call('add', $job->id)
->assertSet('errorMessage', fn (string $message) => str_contains($message, 'kuukausihinta'));
});