Files
Toiminnanohjaus/tests/Feature/Modules/Catalog/PriceListTest.php
petriandClaude Sonnet 5.5 8aa62c8e02 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]>
2026-11-25 08:50:30 +02:00

268 lines
11 KiB
PHP

<?php
use App\Models\User;
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\VatRateModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->management()->create());
$this->workType = fn (string $name) => WorkTypeModel::query()->where('name', $name)->firstOrFail();
});
it('shows the price list pages to admins and management only', function (string $role, int $status) {
$product = ProductModel::factory()->create();
$user = User::factory()->{$role}()->create();
foreach ([route('catalog.prices'), route('catalog.products.create'), route('catalog.products.edit', $product->id)] as $url) {
$this->actingAs($user)->get($url)->assertStatus($status);
}
})->with([
'admin' => ['admin', 200],
'management' => ['management', 200],
'employee' => ['employee', 403],
'intern' => ['intern', 403],
'subcontractor' => ['subcontractor', 403],
]);
it('links the menu to the management page or the read-only price list by role', function () {
$this->get(route('customers.index'))->assertSee(route('catalog.prices'), false);
$this->actingAs(User::factory()->employee()->create())->get(route('customers.index'))
->assertSee(route('catalog.price-list'), false)
->assertDontSee(route('catalog.prices'), false);
});
it('saves and removes hourly rates from the grid', function () {
$programming = ($this->workType)('ohjelmointityö');
Livewire::test('catalog::prices')
->call('saveRate', $programming->id, '85,50')
->assertHasNoErrors()
->assertSet('statusMessage', "ohjelmointityö: tuntihinta 85,50\u{00A0}€ tallennettu.");
expect($programming->refresh()->hourly_rate_cents)->toBe(8550);
Livewire::test('catalog::prices')
->assertSee('value="85,50"', false)
->call('saveRate', $programming->id, '')
->assertSet('statusMessage', 'ohjelmointityö: tuntihinta poistettu.');
expect($programming->refresh()->hourly_rate_cents)->toBeNull();
});
it('shows an invalid hourly rate as a cell error and keeps the typed value', function () {
$editing = WorkTypeModel::factory()->create(['name' => 'leikkaus', 'hourly_rate_cents' => 5000]);
Livewire::test('catalog::prices')
->call('saveRate', $editing->id, '50,123')
->assertHasErrors("rates.{$editing->id}")
->assertSet('errorMessage', 'leikkaus: '.__('catalog.errors.invalid_price'))
->assertSee('value="50,123"', false);
expect($editing->refresh()->hourly_rate_cents)->toBe(5000);
});
it('does not let others save prices through the page actions', function () {
$component = Livewire::test('catalog::prices');
$programming = ($this->workType)('ohjelmointityö');
$this->actingAs(User::factory()->create());
$component->call('saveRate', $programming->id, '85')->assertForbidden();
expect($programming->refresh()->hourly_rate_cents)->toBeNull();
});
it('sets the hourly rate on the work type form', function () {
$programming = ($this->workType)('ohjelmointityö');
Livewire::test('catalog::work-type-form', ['workType' => $programming->id])
->set('form.hourly_rate', '110')
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.index'));
expect($programming->refresh()->hourly_rate_cents)->toBe(11000);
Livewire::test('catalog::work-type-form', ['workType' => $programming->id])
->assertSet('form.hourly_rate', '110,00')
->set('form.hourly_rate', 'paljon')
->call('save')
->assertHasErrors(['form.hourly_rate']);
});
it('adds and edits a product with automatic hours', function () {
$passPhotos = ($this->workType)('passikuvat');
Livewire::test('catalog::product-form')
->set('form.name', 'Passikuvat (4 kpl)')
->set('form.unit', 'package')
->set('form.price', '18,50')
->set('form.is_consumer_product', true)
->set('form.duration', '0,25')
->set('form.work_type_id', (string) $passPhotos->id)
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.prices'));
$product = ProductModel::query()->sole();
expect($product->only(['name', 'unit', 'price_cents', 'is_consumer_product', 'work_type_id']))->toBe([
'name' => 'Passikuvat (4 kpl)',
'unit' => 'package',
'price_cents' => 1850,
'is_consumer_product' => true,
'work_type_id' => $passPhotos->id,
])->and((float) $product->auto_hours)->toBe(0.25);
Livewire::test('catalog::product-form', ['product' => $product->id])
->assertSet('form.price', '18,50')
->assertSet('form.duration', '0,25')
->set('form.price', '20')
->set('form.duration', '')
->set('form.work_type_id', '')
->call('save')
->assertHasNoErrors();
expect($product->refresh()->price_cents)->toBe(2000)
->and($product->work_type_id)->toBeNull();
});
it('shows product rule violations as Finnish field errors', function (array $fields, string $field, string $message) {
ProductModel::factory()->create(['name' => 'Tuloste A4']);
$component = Livewire::test('catalog::product-form')
->set('form.name', 'Tuloste A3')
->set('form.price', '2');
foreach ($fields as $name => $value) {
$component->set("form.{$name}", $value);
}
$component->call('save')->assertHasErrors(["form.{$field}" => [__($message)]]);
})->with([
'name taken' => [['name' => 'tuloste a4'], 'name', 'catalog.errors.product_name_taken'],
'invalid price' => [['price' => '2,555'], 'price', 'catalog.errors.invalid_price'],
'missing price' => [['price' => ''], 'price', 'catalog.errors.price_required'],
'unknown unit' => [['unit' => 'litre'], 'unit', 'catalog.errors.invalid_unit'],
'duration without work type' => [['duration' => '1'], 'work_type_id', 'catalog.errors.work_type_required'],
'invalid duration' => [['duration' => '25'], 'duration', 'catalog.errors.invalid_duration'],
]);
it('moves and deactivates products on the price list page', function () {
$first = ProductModel::factory()->create(['name' => 'Passikuvat', 'sort_order' => 1]);
$second = ProductModel::factory()->create(['name' => 'Tuloste', 'sort_order' => 2]);
Livewire::test('catalog::prices')
->call('move', 'product', $second->id, 'up')
->assertSet('statusMessage', 'Tuloste siirretty ylöspäin.')
->call('toggleActive', 'product', $first->id)
->assertSet('statusMessage', 'Passikuvat poistettu käytöstä. Sitä ei voi enää myydä.');
expect(array_map(fn ($product) => [$product->name, $product->isActive], app(PriceListQueries::class)->products()))
->toBe([['Tuloste', true], ['Passikuvat', false]]);
});
it('saves the mileage rate', function () {
Livewire::test('catalog::prices')
->set('mileageRate', '0,59')
->call('saveMileageRate')
->assertHasNoErrors()
->assertSet('statusMessage', "Km-hinta 0,59\u{00A0}€ tallennettu.");
expect(app(PriceListQueries::class)->mileageRateCents())->toBe(59);
Livewire::test('catalog::prices')
->assertSet('mileageRate', '0,59')
->set('mileageRate', '-1')
->call('saveMileageRate')
->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();
Livewire::test('catalog::vat-rate-form')
->set('name', 'Alennettu 14 %')
->set('percentage', '14')
->set('makeDefault', true)
->call('save')
->assertHasNoErrors()
->assertRedirect(route('catalog.prices'));
$new = VatRateModel::query()->where('name', 'Alennettu 14 %')->sole();
expect($new->basis_points)->toBe(1400)
->and($new->is_default)->toBeTrue()
->and($general->refresh()->is_default)->toBeFalse();
Livewire::test('catalog::vat-rate-form', ['vatRate' => $general->id])
->assertSet('percentage', '25,5')
->set('percentage', '101')
->call('save')
->assertHasErrors(['percentage' => [__('catalog.errors.invalid_vat_percentage')]]);
});
it('does not take the default VAT rate out of use', function () {
$general = VatRateModel::query()->where('is_default', true)->sole();
Livewire::test('catalog::prices')
->call('toggleActive', 'vat_rate', $general->id)
->assertSet('errorMessage', __('catalog.errors.default_vat_rate_active', ['name' => 'Yleinen']));
expect($general->refresh()->is_active)->toBeTrue();
});
it('stores a consumer price with VAT and shows both prices', function () {
$reduced = VatRateModel::query()->where('basis_points', 1000)->sole();
Livewire::test('catalog::product-form')
->assertSet('form.vat_rate_id', (string) VatRateModel::query()->where('is_default', true)->value('id'))
->set('form.name', 'Passikuvat')
->set('form.is_consumer_product', true)
->assertSee('Hinta sis. ALV')
->set('form.price', '18')
->assertSee("Veroton hinta: 14,34\u{00A0}€")
->set('form.vat_rate_id', (string) $reduced->id)
->call('save')
->assertHasNoErrors();
$product = app(PriceListQueries::class)->findProduct(ProductModel::query()->sole()->id);
expect([$product->priceCents, $product->grossCents, $product->netCents, $product->vatBasisPoints])->toBe([1800, 1800, 1636, 1000]);
});
it('does not let an inactive VAT rate be chosen for a product', function () {
$inactive = VatRateModel::factory()->inactive()->create();
Livewire::test('catalog::product-form')
->set('form.name', 'Tuloste')
->set('form.price', '2')
->set('form.vat_rate_id', (string) $inactive->id)
->call('save')
->assertHasErrors(['form.vat_rate_id' => [__('catalog.errors.vat_rate_unavailable')]]);
});