Files
Toiminnanohjaus/tests/Unit/Modules/Billing/BillingDraftTest.php
petriandClaude Sonnet 5.5 7d7b72989d Add an editable menu name and reserve billing material numbers on creation
- Company details get an optional "Valikon nimi", shown at the left of the
  main menu; it falls back to the application name when empty.
- A billing material gets its running number (billing_exports.number) only
  when it is created, so discarded drafts leave no gaps. Drafts have no
  number; existing created materials are numbered by the migration, and the
  CSV file name uses the number.
- TaskAssigneeMigrationTest rolls back from its own migration onward instead
  of assuming it is the last one.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-24 19:41:57 +02:00

234 lines
11 KiB
PHP

<?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\BillingMonths;
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,
'inBillableStatus' => true,
'monthlyFeeCents' => null,
'billingStartsOn' => '2026-09-15',
'billingEndsOn' => null,
], $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));
expect($export->number())->toBeNull();
$export->finalize([1 => [InvoiceLine::fixedPrice(1, 'Työ', 1000, 2550)]], 7, 2, new DateTimeImmutable('2026-11-24 12:00'));
expect($export->status())->toBe(ExportStatus::Created)
->and($export->number())->toBe(7)
->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, 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: ['inBillableStatus' => 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('tells why a monthly fee job cannot be billed', function (array $overrides, array $months, array $expenses, ?NotBillableReason $reason) {
$job = billableJob(1, BillingMode::MonthlyFee, $overrides);
expect((new BillingRules)->reasonNotBillable($job, new JobHours(1, [2 => 8]), $expenses, false, [], $months))->toBe($reason);
})->with([
'months to bill' => [['monthlyFeeCents' => 9900], ['2026-11'], [], null],
'no monthly fee' => [[], ['2026-11'], [], NotBillableReason::MissingMonthlyFee],
'every month billed' => [['monthlyFeeCents' => 9900], [], [], NotBillableReason::NothingToBill],
'only expenses' => [['monthlyFeeCents' => 9900], [], [new BillableExpense(5, 1, 'Paperi', 500)], null],
'not running' => [['monthlyFeeCents' => 9900, 'inBillableStatus' => false], ['2026-11'], [], NotBillableReason::WrongStatus],
]);
it('bills every unbilled month of a monthly fee job and its expenses, not its hours', function () {
$job = billableJob(1, BillingMode::MonthlyFee, ['name' => 'Ylläpito', 'monthlyFeeCents' => 9900]);
$lines = (new BillingRules)->lines($job, $job->toDraftJob(), [1 => 8], [new BillableExpense(5, 1, 'Paperi', 500)], false, [1 => new HourlyRate(1, 'Taitto', 8000)], 2550, ['2026-10', '2026-11']);
expect(array_map(fn (InvoiceLine $line): array => [$line->kind, $line->period, $line->description, $line->netCents], $lines))->toBe([
[LineKind::MonthlyFee, '2026-10', '10/2026 2026-0001 Ylläpito', 9900],
[LineKind::MonthlyFee, '2026-11', '11/2026 2026-0001 Ylläpito', 9900],
[LineKind::Expense, null, 'Paperi', 500],
]);
});
it('counts the months from the start to the material, the last day or completion, leaving out billed ones', function (?string $endsOn, string $period, array $billed, array $months) {
expect(BillingMonths::unbilled('2026-09-15', $endsOn, $period, $billed))->toBe($months);
})->with([
'up to the material' => [null, '2026-11', [], ['2026-09', '2026-10', '2026-11']],
'billed months left out' => [null, '2026-11', ['2026-09', '2026-10'], ['2026-11']],
'ends before the material' => ['2026-10-31', '2026-12', [], ['2026-09', '2026-10']],
'over the year end' => [null, '2027-01', ['2026-09', '2026-10'], ['2026-11', '2026-12', '2027-01']],
'material before the start' => [null, '2026-08', [], []],
]);
it('keeps a monthly fee job on an invoice of its own', function () {
$export = draft();
$export->addJob(new DraftJob(1, 10, null, null));
$export->addJob(new DraftJob(2, 10, null, null, [], ownInvoice: true));
try {
$export->moveJob(2, 1);
$this->fail('The jobs were combined.');
} catch (InvoicesCannotMerge $exception) {
expect($exception->refusal)->toBe(MergeRefusal::MonthlyFeeAlone);
}
$export->moveJob(1, 2);
})->throws(InvoicesCannotMerge::class);
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],
]);
});