From bdd8d446d8935932bd864fe9e95eff17d8191e58 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Tue, 24 Nov 2026 07:51:19 +0200 Subject: [PATCH] Add money permissions, a read-only price list and VAT rates - Admins give employees and interns personal money permissions (prices, expenses, quotes, billing) on the user form. Other modules check them through the money.* abilities; admins and management see all amounts, subcontractors none. - Employees and interns get a read-only price list: consumer products with VAT always, hourly rates, other products and the mileage rate only with the price permission. Subcontractors cannot open it. - VAT rates are maintained on the price list page, with one default rate that always stays in use. Products get a VAT rate; changing a rate's percentage applies to every product using it. - Consumer product prices are entered and stored with VAT, so cash prices stay round; the price without VAT is calculated. The product form shows the other price as you type. - Shared VatPercentage value object and Money::addVat()/removeVat(), rounding half up to the cent in integer arithmetic. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- app/Models/User.php | 26 ++ .../Contracts/PriceListQueries.php | 17 ++ .../Catalog/Application/DTOs/ProductInput.php | 4 +- .../Application/DTOs/ProductSummary.php | 10 +- .../Application/DTOs/VatRateSummary.php | 19 ++ .../Application/UseCases/AddProduct.php | 6 + .../Application/UseCases/AddVatRate.php | 52 ++++ .../Application/UseCases/DefaultVatRate.php | 28 +++ .../Application/UseCases/MoveVatRate.php | 44 ++++ .../Application/UseCases/ProductFields.php | 18 ++ .../Application/UseCases/SetVatRateActive.php | 36 +++ .../Application/UseCases/UpdateProduct.php | 12 +- .../Application/UseCases/UpdateVatRate.php | 56 +++++ .../Domain/Contracts/VatRateRepository.php | 35 +++ .../Catalog/Domain/Entities/Product.php | 33 ++- .../Catalog/Domain/Entities/VatRate.php | 80 ++++++ .../Exceptions/DefaultVatRateMustBeActive.php | 15 ++ .../Domain/Exceptions/VatRateNameTaken.php | 15 ++ .../Domain/Exceptions/VatRateNotFound.php | 15 ++ .../Persistence/Eloquent/ProductModel.php | 13 +- .../Persistence/Eloquent/VatRateModel.php | 42 ++++ .../Repositories/EloquentPriceListQueries.php | 60 ++++- .../EloquentProductRepository.php | 2 + .../EloquentVatRateRepository.php | 77 ++++++ .../Providers/CatalogServiceProvider.php | 7 + .../Livewire/Forms/ProductForm.php | 11 +- .../Livewire/⚡price-list.blade.php | 231 ++++++++++++++++++ .../Presentation/Livewire/⚡prices.blade.php | 146 ++++++++++- .../Livewire/⚡product-form.blade.php | 87 ++++++- .../Livewire/⚡vat-rate-form.blade.php | 138 +++++++++++ .../Catalog/Presentation/Routes/web.php | 11 + .../Exceptions/InvalidVatPercentage.php | 13 + .../Shared/Domain/ValueObjects/Money.php | 18 ++ .../Domain/ValueObjects/VatPercentage.php | 59 +++++ .../Application/DTOs/UserAccountData.php | 6 +- .../Users/Application/DTOs/UserSummary.php | 3 + .../UseCases/CreateUserAccount.php | 1 + .../UseCases/UpdateUserAccount.php | 2 +- .../Users/Domain/Entities/UserAccount.php | 34 ++- .../Users/Domain/Enums/MoneyPermission.php | 36 +++ app/Modules/Users/Domain/Enums/Role.php | 16 ++ .../Eloquent/UserMoneyPermissionsModel.php | 70 ++++++ .../EloquentUserAccountQueries.php | 3 +- .../EloquentUserAccountRepository.php | 8 + .../Providers/UsersServiceProvider.php | 7 + .../Presentation/Livewire/Forms/UserForm.php | 28 +++ .../Presentation/Livewire/⚡form.blade.php | 15 ++ database/factories/ProductFactory.php | 2 + database/factories/UserFactory.php | 15 ++ database/factories/VatRateFactory.php | 33 +++ ...26_11_24_053556_create_vat_rates_table.php | 47 ++++ ..._053557_add_vat_rate_to_products_table.php | 31 +++ ...58_create_user_money_permissions_table.php | 30 +++ docs/maarittely.md | 17 +- lang/fi/catalog.php | 51 +++- lang/fi/users.php | 14 ++ resources/views/layouts/app.blade.php | 4 +- tests/Browser/CatalogAccessibilityTest.php | 23 +- tests/Fakes/InMemoryProductRepository.php | 1 + tests/Fakes/InMemoryUserAccountRepository.php | 1 + tests/Fakes/InMemoryVatRateRepository.php | 68 ++++++ .../Feature/Modules/Catalog/PriceListTest.php | 72 +++++- .../Modules/Catalog/PriceListViewTest.php | 55 +++++ .../Modules/Users/MoneyPermissionsTest.php | 59 +++++ .../Application/PriceListUseCasesTest.php | 55 ++++- tests/Unit/Modules/Shared/MoneyTest.php | 28 +++ .../Modules/Users/Domain/UserAccountTest.php | 11 + 68 files changed, 2222 insertions(+), 64 deletions(-) create mode 100644 app/Modules/Catalog/Application/DTOs/VatRateSummary.php create mode 100644 app/Modules/Catalog/Application/UseCases/AddVatRate.php create mode 100644 app/Modules/Catalog/Application/UseCases/DefaultVatRate.php create mode 100644 app/Modules/Catalog/Application/UseCases/MoveVatRate.php create mode 100644 app/Modules/Catalog/Application/UseCases/SetVatRateActive.php create mode 100644 app/Modules/Catalog/Application/UseCases/UpdateVatRate.php create mode 100644 app/Modules/Catalog/Domain/Contracts/VatRateRepository.php create mode 100644 app/Modules/Catalog/Domain/Entities/VatRate.php create mode 100644 app/Modules/Catalog/Domain/Exceptions/DefaultVatRateMustBeActive.php create mode 100644 app/Modules/Catalog/Domain/Exceptions/VatRateNameTaken.php create mode 100644 app/Modules/Catalog/Domain/Exceptions/VatRateNotFound.php create mode 100644 app/Modules/Catalog/Infrastructure/Persistence/Eloquent/VatRateModel.php create mode 100644 app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentVatRateRepository.php create mode 100644 app/Modules/Catalog/Presentation/Livewire/⚡price-list.blade.php create mode 100644 app/Modules/Catalog/Presentation/Livewire/⚡vat-rate-form.blade.php create mode 100644 app/Modules/Shared/Domain/Exceptions/InvalidVatPercentage.php create mode 100644 app/Modules/Shared/Domain/ValueObjects/VatPercentage.php create mode 100644 app/Modules/Users/Domain/Enums/MoneyPermission.php create mode 100644 app/Modules/Users/Infrastructure/Persistence/Eloquent/UserMoneyPermissionsModel.php create mode 100644 database/factories/VatRateFactory.php create mode 100644 database/migrations/2026_11_24_053556_create_vat_rates_table.php create mode 100644 database/migrations/2026_11_24_053557_add_vat_rate_to_products_table.php create mode 100644 database/migrations/2026_11_24_053558_create_user_money_permissions_table.php create mode 100644 tests/Fakes/InMemoryVatRateRepository.php create mode 100644 tests/Feature/Modules/Catalog/PriceListViewTest.php create mode 100644 tests/Feature/Modules/Users/MoneyPermissionsTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 5b551a9..220749a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,10 +22,10 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. +- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `time.use`, `time.book`, `catalog.view-prices`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Security headers** (`X-Frame-Options`, `frame-ancestors`, `nosniff`, `Referrer-Policy`, HSTS over HTTPS) come from the global `Shared\Presentation\Http\Middleware\SetSecurityHeaders`, pushed in `SharedServiceProvider`. No full CSP: Alpine/Livewire need `unsafe-eval`. -- Money is `Shared\Domain\ValueObjects\Money` (whole cents, VAT 0, `parse()` accepts "85,50", `format()` gives "85,50 €"); store it in `*_cents` integer columns. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. +- Money is `Shared\Domain\ValueObjects\Money` (whole cents, `parse()` accepts "85,50", `format()` gives "85,50 €", `addVat()`/`removeVat()` with a `VatPercentage` round half up); store it in `*_cents` integer columns. Prices are without VAT except consumer product prices, which are stored with VAT. Show other than consumer prices only behind `money.prices` and keep amounts out of public Livewire properties. App-wide settings go through `Shared\Application\Contracts\Settings` (`settings` table) with keys prefixed by the owning module. - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - Generate module files with Artisan, then edit them: `php artisan make:class Modules////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. - When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool. diff --git a/app/Models/User.php b/app/Models/User.php index 38fc83e..2d18d18 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,12 +3,15 @@ namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; +use App\Modules\Users\Infrastructure\Persistence\Eloquent\UserMoneyPermissionsModel; use Database\Factories\UserFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasOne; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Carbon; @@ -24,6 +27,7 @@ use Illuminate\Support\Carbon; * @property bool $is_active * @property Carbon|null $employment_ends_on * @property int|null $supervisor_id + * @property-read UserMoneyPermissionsModel|null $moneyPermissions */ #[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id'])] #[Hidden(['password', 'remember_token'])] @@ -40,6 +44,28 @@ class User extends Authenticatable return $this->belongsTo(User::class, 'supervisor_id'); } + /** + * @return HasOne + */ + public function moneyPermissions(): HasOne + { + return $this->hasOne(UserMoneyPermissionsModel::class); + } + + /** + * Whether the user may see the given kind of money amounts: admins and + * management always, employees and interns with a personal permission. + */ + public function canSeeMoney(MoneyPermission $permission): bool + { + if ($this->role->seesAllMoney()) { + return true; + } + + return $this->role->hasPersonalMoneyPermissions() + && ($this->moneyPermissions?->allows($permission) ?? false); + } + /** * Get the attributes that should be cast. * diff --git a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php index 5e4ca6a..e2bf2e3 100644 --- a/app/Modules/Catalog/Application/Contracts/PriceListQueries.php +++ b/app/Modules/Catalog/Application/Contracts/PriceListQueries.php @@ -6,6 +6,7 @@ namespace App\Modules\Catalog\Application\Contracts; use App\Modules\Catalog\Application\DTOs\HourlyRateGroup; use App\Modules\Catalog\Application\DTOs\ProductSummary; +use App\Modules\Catalog\Application\DTOs\VatRateSummary; /** * Read side of the price list: hourly rates, products and the mileage rate. @@ -31,8 +32,24 @@ interface PriceListQueries public function findProduct(int $id): ?ProductSummary; + /** + * Active consumer products, whose prices with VAT every user may see. + * + * @return list + */ + public function consumerProducts(): array; + /** * Price of a driven kilometre in cents (VAT 0), null when not set. */ public function mileageRateCents(): ?int; + + /** + * @return list + */ + public function vatRates(bool $includeInactive = true): array; + + public function findVatRate(int $id): ?VatRateSummary; + + public function defaultVatRate(): ?VatRateSummary; } diff --git a/app/Modules/Catalog/Application/DTOs/ProductInput.php b/app/Modules/Catalog/Application/DTOs/ProductInput.php index 117be7e..6fd3037 100644 --- a/app/Modules/Catalog/Application/DTOs/ProductInput.php +++ b/app/Modules/Catalog/Application/DTOs/ProductInput.php @@ -7,7 +7,8 @@ namespace App\Modules\Catalog\Application\DTOs; use App\Modules\Catalog\Domain\Enums\ProductUnit; /** - * A product's fields as the user typed them: price "12,50", duration "0,25". + * A product's fields as the user typed them: price "12,50" (with VAT for a + * consumer product, otherwise without), duration "0,25". */ final readonly class ProductInput { @@ -15,6 +16,7 @@ final readonly class ProductInput public string $name, public ProductUnit $unit, public string $price, + public int $vatRateId, public bool $isConsumerProduct, public string $duration = '', public ?int $workTypeId = null, diff --git a/app/Modules/Catalog/Application/DTOs/ProductSummary.php b/app/Modules/Catalog/Application/DTOs/ProductSummary.php index 2bd023e..feb85bf 100644 --- a/app/Modules/Catalog/Application/DTOs/ProductSummary.php +++ b/app/Modules/Catalog/Application/DTOs/ProductSummary.php @@ -7,7 +7,10 @@ namespace App\Modules\Catalog\Application\DTOs; use App\Modules\Catalog\Domain\Enums\ProductUnit; /** - * A product with its price in cents (VAT 0) and the hours its sale books. + * A product with its prices in cents and the hours its sale books. + * $priceCents is the price as entered: with VAT when $priceIncludesVat + * (consumer products), otherwise without. $netCents and $grossCents are + * both, one of them calculated with the product's VAT rate. */ final readonly class ProductSummary { @@ -16,6 +19,11 @@ final readonly class ProductSummary public string $name, public ProductUnit $unit, public int $priceCents, + public bool $priceIncludesVat, + public int $netCents, + public int $grossCents, + public int $vatRateId, + public int $vatBasisPoints, public bool $isConsumerProduct, public int $durationQuarters, public ?int $workTypeId, diff --git a/app/Modules/Catalog/Application/DTOs/VatRateSummary.php b/app/Modules/Catalog/Application/DTOs/VatRateSummary.php new file mode 100644 index 0000000..b9546d0 --- /dev/null +++ b/app/Modules/Catalog/Application/DTOs/VatRateSummary.php @@ -0,0 +1,19 @@ +transactions->run(function () use ($fields): int { $fields->ensureWorkTypeIsUsable($this->workTypes); + $fields->ensureVatRateIsUsable($this->vatRates); if ($this->products->isNameTaken($fields->name->value)) { throw new ProductNameTaken; @@ -52,6 +57,7 @@ final class AddProduct $fields->name, $fields->unit, $fields->price, + $fields->vatRateId, $fields->isConsumerProduct, $fields->duration, $fields->workTypeId, diff --git a/app/Modules/Catalog/Application/UseCases/AddVatRate.php b/app/Modules/Catalog/Application/UseCases/AddVatRate.php new file mode 100644 index 0000000..2a92d21 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/AddVatRate.php @@ -0,0 +1,52 @@ +transactions->run(function () use ($name, $percentage, $makeDefault): int { + if ($this->vatRates->isNameTaken($name->value)) { + throw new VatRateNameTaken; + } + + $vatRate = VatRate::create($name, $percentage, $this->vatRates->nextSortOrder()); + + if ($makeDefault) { + DefaultVatRate::moveTo($vatRate, $this->vatRates); + } + + return (int) $this->vatRates->save($vatRate)->id(); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/DefaultVatRate.php b/app/Modules/Catalog/Application/UseCases/DefaultVatRate.php new file mode 100644 index 0000000..9b72748 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/DefaultVatRate.php @@ -0,0 +1,28 @@ +findDefault(); + + if ($current !== null && $current->id() !== $vatRate->id()) { + $current->clearDefault(); + $vatRates->save($current); + } + + $vatRate->makeDefault(); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/MoveVatRate.php b/app/Modules/Catalog/Application/UseCases/MoveVatRate.php new file mode 100644 index 0000000..dc3d41b --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/MoveVatRate.php @@ -0,0 +1,44 @@ +transactions->run(function () use ($vatRateId, $direction): bool { + $vatRate = $this->vatRates->findById($vatRateId) ?? throw new VatRateNotFound($vatRateId); + $neighbour = $this->vatRates->neighbour($vatRate, $direction); + + if ($neighbour === null) { + return false; + } + + $vatRate->swapOrderWith($neighbour); + $this->vatRates->save($vatRate); + $this->vatRates->save($neighbour); + + return true; + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/ProductFields.php b/app/Modules/Catalog/Application/UseCases/ProductFields.php index b35fb0e..410dc96 100644 --- a/app/Modules/Catalog/Application/UseCases/ProductFields.php +++ b/app/Modules/Catalog/Application/UseCases/ProductFields.php @@ -5,12 +5,14 @@ declare(strict_types=1); namespace App\Modules\Catalog\Application\UseCases; use App\Modules\Catalog\Application\DTOs\ProductInput; +use App\Modules\Catalog\Domain\Contracts\VatRateRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Domain\Enums\CatalogLevel; use App\Modules\Catalog\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName; use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration; +use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound; use App\Modules\Catalog\Domain\ValueObjects\CatalogName; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; @@ -27,6 +29,7 @@ final readonly class ProductFields public CatalogName $name, public ProductUnit $unit, public Money $price, + public int $vatRateId, public bool $isConsumerProduct, public ProductDuration $duration, public ?int $workTypeId, @@ -43,12 +46,27 @@ final readonly class ProductFields new CatalogName($input->name), $input->unit, Money::parse($input->price) ?? throw new InvalidMoneyAmount, + $input->vatRateId, $input->isConsumerProduct, ProductDuration::parse($input->duration), $input->workTypeId, ); } + /** + * A newly chosen VAT rate must exist and be in use. + * + * @throws VatRateNotFound + */ + public function ensureVatRateIsUsable(VatRateRepository $vatRates): void + { + $vatRate = $vatRates->findById($this->vatRateId); + + if ($vatRate === null || ! $vatRate->isActive()) { + throw new VatRateNotFound($this->vatRateId); + } + } + /** * A newly chosen work type must exist and be in use. * diff --git a/app/Modules/Catalog/Application/UseCases/SetVatRateActive.php b/app/Modules/Catalog/Application/UseCases/SetVatRateActive.php new file mode 100644 index 0000000..2f564f8 --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/SetVatRateActive.php @@ -0,0 +1,36 @@ +transactions->run(function () use ($vatRateId, $active): void { + $vatRate = $this->vatRates->findById($vatRateId) ?? throw new VatRateNotFound($vatRateId); + + $active ? $vatRate->activate() : $vatRate->deactivate(); + $this->vatRates->save($vatRate); + }); + } +} diff --git a/app/Modules/Catalog/Application/UseCases/UpdateProduct.php b/app/Modules/Catalog/Application/UseCases/UpdateProduct.php index d4b0bd2..f00e9cf 100644 --- a/app/Modules/Catalog/Application/UseCases/UpdateProduct.php +++ b/app/Modules/Catalog/Application/UseCases/UpdateProduct.php @@ -6,6 +6,7 @@ namespace App\Modules\Catalog\Application\UseCases; use App\Modules\Catalog\Application\DTOs\ProductInput; use App\Modules\Catalog\Domain\Contracts\ProductRepository; +use App\Modules\Catalog\Domain\Contracts\VatRateRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName; @@ -13,6 +14,7 @@ use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration; use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken; use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType; use App\Modules\Catalog\Domain\Exceptions\ProductNotFound; +use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound; use App\Modules\Shared\Application\Contracts\TransactionManager; use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; @@ -25,6 +27,7 @@ final class UpdateProduct public function __construct( private ProductRepository $products, private WorkTypeRepository $workTypes, + private VatRateRepository $vatRates, private TransactionManager $transactions, ) {} @@ -35,6 +38,7 @@ final class UpdateProduct * @throws InvalidProductDuration * @throws ProductNameTaken * @throws ProductNeedsWorkType + * @throws VatRateNotFound * @throws ProductNotFound */ public function execute(int $productId, ProductInput $input): void @@ -44,16 +48,20 @@ final class UpdateProduct $this->transactions->run(function () use ($productId, $fields): void { $product = $this->products->findById($productId) ?? throw new ProductNotFound($productId); - // An inactive work type may stay, but it cannot be newly chosen. + // An inactive work type or VAT rate may stay, but it cannot be newly chosen. if ($fields->workTypeId !== $product->workTypeId()) { $fields->ensureWorkTypeIsUsable($this->workTypes); } + if ($fields->vatRateId !== $product->vatRateId()) { + $fields->ensureVatRateIsUsable($this->vatRates); + } + if ($this->products->isNameTaken($fields->name->value, $productId)) { throw new ProductNameTaken; } - $product->update($fields->name, $fields->unit, $fields->price, $fields->isConsumerProduct, $fields->duration, $fields->workTypeId); + $product->update($fields->name, $fields->unit, $fields->price, $fields->vatRateId, $fields->isConsumerProduct, $fields->duration, $fields->workTypeId); $this->products->save($product); }); } diff --git a/app/Modules/Catalog/Application/UseCases/UpdateVatRate.php b/app/Modules/Catalog/Application/UseCases/UpdateVatRate.php new file mode 100644 index 0000000..eb2c0bb --- /dev/null +++ b/app/Modules/Catalog/Application/UseCases/UpdateVatRate.php @@ -0,0 +1,56 @@ +transactions->run(function () use ($vatRateId, $name, $percentage, $makeDefault): void { + $vatRate = $this->vatRates->findById($vatRateId) ?? throw new VatRateNotFound($vatRateId); + + if ($this->vatRates->isNameTaken($name->value, $vatRateId)) { + throw new VatRateNameTaken; + } + + $vatRate->rename($name); + $vatRate->changePercentage($percentage); + + if ($makeDefault) { + DefaultVatRate::moveTo($vatRate, $this->vatRates); + } + + $this->vatRates->save($vatRate); + }); + } +} diff --git a/app/Modules/Catalog/Domain/Contracts/VatRateRepository.php b/app/Modules/Catalog/Domain/Contracts/VatRateRepository.php new file mode 100644 index 0000000..baa0ff7 --- /dev/null +++ b/app/Modules/Catalog/Domain/Contracts/VatRateRepository.php @@ -0,0 +1,35 @@ +name = $name; $this->unit = $unit; $this->price = $price; + $this->vatRateId = $vatRateId; $this->consumerProduct = $consumerProduct; $this->duration = $duration; $this->workTypeId = $workTypeId; @@ -71,11 +75,24 @@ final class Product extends CatalogItem return $this->price; } + public function vatRateId(): int + { + return $this->vatRateId; + } + public function isConsumerProduct(): bool { return $this->consumerProduct; } + /** + * Whether price() includes VAT, which is so for consumer products. + */ + public function priceIncludesVat(): bool + { + return $this->consumerProduct; + } + public function duration(): ProductDuration { return $this->duration; diff --git a/app/Modules/Catalog/Domain/Entities/VatRate.php b/app/Modules/Catalog/Domain/Entities/VatRate.php new file mode 100644 index 0000000..7bac45b --- /dev/null +++ b/app/Modules/Catalog/Domain/Entities/VatRate.php @@ -0,0 +1,80 @@ +percentage = $percentage; + } + + /** + * Makes this the default rate; also puts it back in use. + */ + public function makeDefault(): void + { + $this->default = true; + $this->active = true; + } + + public function clearDefault(): void + { + $this->default = false; + } + + /** + * @throws DefaultVatRateMustBeActive + */ + public function deactivate(): void + { + if ($this->default) { + throw new DefaultVatRateMustBeActive; + } + + parent::deactivate(); + } + + public function percentage(): VatPercentage + { + return $this->percentage; + } + + public function isDefault(): bool + { + return $this->default; + } +} diff --git a/app/Modules/Catalog/Domain/Exceptions/DefaultVatRateMustBeActive.php b/app/Modules/Catalog/Domain/Exceptions/DefaultVatRateMustBeActive.php new file mode 100644 index 0000000..89ca4fc --- /dev/null +++ b/app/Modules/Catalog/Domain/Exceptions/DefaultVatRateMustBeActive.php @@ -0,0 +1,15 @@ +belongsTo(WorkTypeModel::class, 'work_type_id'); } + /** + * @return BelongsTo + */ + public function vatRate(): BelongsTo + { + return $this->belongsTo(VatRateModel::class, 'vat_rate_id'); + } + /** * @return array */ @@ -47,6 +57,7 @@ class ProductModel extends Model { return [ 'price_cents' => 'integer', + 'vat_rate_id' => 'integer', 'is_consumer_product' => 'boolean', 'auto_hours' => 'decimal:2', 'work_type_id' => 'integer', diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/VatRateModel.php b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/VatRateModel.php new file mode 100644 index 0000000..8894e10 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Eloquent/VatRateModel.php @@ -0,0 +1,42 @@ + */ + use HasFactory; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'basis_points' => 'integer', + 'is_default' => 'boolean', + 'is_active' => 'boolean', + 'sort_order' => 'integer', + ]; + } +} diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php index f49962a..dc77959 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentPriceListQueries.php @@ -8,13 +8,17 @@ use App\Modules\Catalog\Application\DTOs\HourlyRateGroup; use App\Modules\Catalog\Application\DTOs\HourlyRateRow; use App\Modules\Catalog\Application\DTOs\ProductSummary; use App\Modules\Catalog\Application\DTOs\ServiceUnitNode; +use App\Modules\Catalog\Application\DTOs\VatRateSummary; use App\Modules\Catalog\Application\DTOs\WorkTypeSummary; use App\Modules\Catalog\Application\UseCases\SetMileageRate; use App\Modules\Catalog\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; 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 App\Modules\Shared\Application\Contracts\Settings; +use App\Modules\Shared\Domain\ValueObjects\Money; +use App\Modules\Shared\Domain\ValueObjects\VatPercentage; class EloquentPriceListQueries implements PriceListQueries { @@ -59,7 +63,7 @@ class EloquentPriceListQueries implements PriceListQueries public function products(bool $includeInactive = true): array { return ProductModel::query() - ->with('workType') + ->with(['workType', 'vatRate']) ->when(! $includeInactive, fn ($query) => $query->where('is_active', true)) ->orderBy('sort_order') ->get() @@ -70,11 +74,49 @@ class EloquentPriceListQueries implements PriceListQueries public function findProduct(int $id): ?ProductSummary { - $model = ProductModel::query()->with('workType')->find($id); + $model = ProductModel::query()->with(['workType', 'vatRate'])->find($id); return $model === null ? null : $this->toSummary($model); } + public function consumerProducts(): array + { + return ProductModel::query() + ->with(['workType', 'vatRate']) + ->where('is_active', true) + ->where('is_consumer_product', true) + ->orderBy('sort_order') + ->get() + ->map(fn (ProductModel $model): ProductSummary => $this->toSummary($model)) + ->values() + ->all(); + } + + public function vatRates(bool $includeInactive = true): array + { + return VatRateModel::query() + ->when(! $includeInactive, fn ($query) => $query->where('is_active', true)) + ->orderBy('sort_order') + ->get() + ->map(fn (VatRateModel $model): VatRateSummary => $this->toVatRateSummary($model)) + ->values() + ->all(); + } + + public function findVatRate(int $id): ?VatRateSummary + { + $model = VatRateModel::query()->find($id); + + return $model === null ? null : $this->toVatRateSummary($model); + } + + public function defaultVatRate(): ?VatRateSummary + { + $model = VatRateModel::query()->where('is_default', true)->first(); + + return $model === null ? null : $this->toVatRateSummary($model); + } + public function mileageRateCents(): ?int { $value = $this->settings->get(SetMileageRate::SETTING_KEY); @@ -82,13 +124,27 @@ class EloquentPriceListQueries implements PriceListQueries return $value === null ? null : (int) $value; } + private function toVatRateSummary(VatRateModel $model): VatRateSummary + { + return new VatRateSummary($model->id, $model->name, $model->basis_points, $model->is_default, $model->is_active); + } + private function toSummary(ProductModel $model): ProductSummary { + $price = Money::fromCents($model->price_cents); + $vat = new VatPercentage($model->vatRate->basis_points ?? 0); + $includesVat = $model->is_consumer_product; + return new ProductSummary( $model->id, $model->name, ProductUnit::from($model->unit), $model->price_cents, + $includesVat, + $includesVat ? $price->removeVat($vat)->cents : $price->cents, + $includesVat ? $price->cents : $price->addVat($vat)->cents, + (int) $model->vat_rate_id, + $vat->basisPoints, $model->is_consumer_product, ProductDuration::fromDecimal((float) $model->auto_hours)->quarters, $model->work_type_id, diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php index 8fcac0a..990728d 100644 --- a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentProductRepository.php @@ -28,6 +28,7 @@ class EloquentProductRepository implements ProductRepository 'name' => $product->name()->value, 'unit' => $product->unit()->value, 'price_cents' => $product->price()->cents, + 'vat_rate_id' => $product->vatRateId(), 'is_consumer_product' => $product->isConsumerProduct(), 'auto_hours' => $product->duration()->decimal(), 'work_type_id' => $product->workTypeId(), @@ -68,6 +69,7 @@ class EloquentProductRepository implements ProductRepository new CatalogName($model->name), ProductUnit::from($model->unit), Money::fromCents($model->price_cents), + (int) $model->vat_rate_id, $model->is_consumer_product, ProductDuration::fromDecimal((float) $model->auto_hours), $model->work_type_id, diff --git a/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentVatRateRepository.php b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentVatRateRepository.php new file mode 100644 index 0000000..5fa7ef6 --- /dev/null +++ b/app/Modules/Catalog/Infrastructure/Persistence/Repositories/EloquentVatRateRepository.php @@ -0,0 +1,77 @@ +find($id); + + return $model === null ? null : $this->toEntity($model); + } + + public function findDefault(): ?VatRate + { + $model = VatRateModel::query()->where('is_default', true)->lockForUpdate()->first(); + + return $model === null ? null : $this->toEntity($model); + } + + public function save(VatRate $vatRate): VatRate + { + $model = $vatRate->id() === null ? new VatRateModel : VatRateModel::query()->findOrFail($vatRate->id()); + + $model->fill([ + 'name' => $vatRate->name()->value, + 'basis_points' => $vatRate->percentage()->basisPoints, + 'is_default' => $vatRate->isDefault(), + 'is_active' => $vatRate->isActive(), + 'sort_order' => $vatRate->sortOrder(), + ])->save(); + + return $this->toEntity($model); + } + + public function isNameTaken(string $name, ?int $exceptId = null): bool + { + return VatRateModel::query() + ->whereRaw('LOWER(name) = ?', [mb_strtolower($name)]) + ->when($exceptId !== null, fn ($query) => $query->whereKeyNot($exceptId)) + ->exists(); + } + + public function nextSortOrder(): int + { + return (int) VatRateModel::query()->max('sort_order') + 1; + } + + public function neighbour(VatRate $vatRate, MoveDirection $direction): ?VatRate + { + $model = VatRateModel::query() + ->where('sort_order', $direction === MoveDirection::Up ? '<' : '>', $vatRate->sortOrder()) + ->orderBy('sort_order', $direction === MoveDirection::Up ? 'desc' : 'asc') + ->first(); + + return $model === null ? null : $this->toEntity($model); + } + + private function toEntity(VatRateModel $model): VatRate + { + return VatRate::reconstitute( + $model->id, + new CatalogName($model->name), + new VatPercentage($model->basis_points), + $model->is_default, + $model->is_active, + $model->sort_order, + ); + } +} diff --git a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php index 36fb3fd..697a659 100644 --- a/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php +++ b/app/Modules/Catalog/Infrastructure/Providers/CatalogServiceProvider.php @@ -8,12 +8,14 @@ use App\Modules\Catalog\Application\Contracts\PriceListQueries; use App\Modules\Catalog\Domain\Contracts\ProductRepository; use App\Modules\Catalog\Domain\Contracts\ServiceRepository; use App\Modules\Catalog\Domain\Contracts\ServiceUnitRepository; +use App\Modules\Catalog\Domain\Contracts\VatRateRepository; use App\Modules\Catalog\Domain\Contracts\WorkTypeRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentCatalogQueries; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentPriceListQueries; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentProductRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentServiceUnitRepository; +use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentVatRateRepository; use App\Modules\Catalog\Infrastructure\Persistence\Repositories\EloquentWorkTypeRepository; use App\Modules\Users\Domain\Enums\Role; use Illuminate\Support\Facades\Gate; @@ -37,6 +39,7 @@ class CatalogServiceProvider extends ServiceProvider CatalogQueries::class => EloquentCatalogQueries::class, ProductRepository::class => EloquentProductRepository::class, PriceListQueries::class => EloquentPriceListQueries::class, + VatRateRepository::class => EloquentVatRateRepository::class, ]; public function boot(): void @@ -51,5 +54,9 @@ class CatalogServiceProvider extends ServiceProvider // Catalog data (pohjatiedot) and the price list are managed by admins and management. Gate::define('catalog.manage', fn (User $user): bool => in_array($user->role, [Role::Admin, Role::Management], true)); + + // The read-only price list: consumer product prices for everyone but + // subcontractors; other prices also need the `money.prices` ability. + Gate::define('catalog.view-prices', fn (User $user): bool => $user->role !== Role::Subcontractor); } } diff --git a/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php b/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php index d0d8d60..9640e7f 100644 --- a/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php +++ b/app/Modules/Catalog/Presentation/Livewire/Forms/ProductForm.php @@ -10,6 +10,7 @@ use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName; use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration; use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken; use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType; +use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; use App\Modules\Shared\Domain\Exceptions\DomainException; use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; @@ -19,7 +20,7 @@ use Livewire\Form; /** * Fields of a product. Price and duration are kept as typed ("12,50") and - * parsed by the use case. + * parsed by the use case. The price includes VAT for a consumer product. */ class ProductForm extends Form { @@ -29,6 +30,8 @@ class ProductForm extends Form public string $price = ''; + public string $vat_rate_id = ''; + public bool $is_consumer_product = false; public string $duration = ''; @@ -43,6 +46,7 @@ class ProductForm extends Form $this->name = $product->name; $this->unit = $product->unit->value; $this->price = Money::fromCents($product->priceCents)->inputValue(); + $this->vat_rate_id = (string) $product->vatRateId; $this->is_consumer_product = $product->isConsumerProduct; $this->duration = $product->durationQuarters === 0 ? '' : (new ProductDuration($product->durationQuarters))->format(); $this->work_type_id = $product->workTypeId === null ? '' : (string) $product->workTypeId; @@ -56,6 +60,7 @@ class ProductForm extends Form $this->name, ProductUnit::from($this->unit), $this->price, + (int) $this->vat_rate_id, $this->is_consumer_product, $this->duration, $this->work_type_id === '' ? null : (int) $this->work_type_id, @@ -74,6 +79,7 @@ class ProductForm extends Form InvalidProductDuration::class => ['duration', 'catalog.errors.invalid_duration'], ProductNeedsWorkType::class => ['work_type_id', 'catalog.errors.work_type_required'], CatalogItemNotFound::class => ['work_type_id', 'catalog.errors.work_type_unavailable'], + VatRateNotFound::class => ['vat_rate_id', 'catalog.errors.vat_rate_unavailable'], default => throw $exception, }; @@ -89,6 +95,7 @@ class ProductForm extends Form 'name' => ['required', 'string', 'max:100'], 'unit' => ['required', Rule::enum(ProductUnit::class)], 'price' => ['required', 'string', 'max:20'], + 'vat_rate_id' => ['required', 'integer'], 'is_consumer_product' => ['boolean'], 'duration' => ['nullable', 'string', 'max:10'], 'work_type_id' => ['nullable', 'integer'], @@ -107,6 +114,8 @@ class ProductForm extends Form 'unit.enum' => __('catalog.errors.invalid_unit'), 'price.required' => __('catalog.errors.price_required'), 'price.max' => __('catalog.errors.invalid_price'), + 'vat_rate_id.required' => __('catalog.errors.vat_rate_unavailable'), + 'vat_rate_id.integer' => __('catalog.errors.vat_rate_unavailable'), 'duration.max' => __('catalog.errors.invalid_duration'), 'work_type_id.integer' => __('catalog.errors.work_type_unavailable'), ]; diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡price-list.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡price-list.blade.php new file mode 100644 index 0000000..aa0d492 --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡price-list.blade.php @@ -0,0 +1,231 @@ +authorize('catalog.view-prices'); + } + + #[Computed] + public function canSeePrices(): bool + { + return auth()->user()?->can('money.prices') ?? false; + } + + /** + * @return list + */ + #[Computed] + public function consumerProducts(): array + { + return app(PriceListQueries::class)->consumerProducts(); + } + + /** + * Active products that are not consumer products; only with the price permission. + * + * @return list + */ + #[Computed] + public function otherProducts(): array + { + if (! $this->canSeePrices) { + return []; + } + + return array_values(array_filter( + app(PriceListQueries::class)->products(includeInactive: false), + fn (ProductSummary $product): bool => ! $product->isConsumerProduct, + )); + } + + /** + * @return list + */ + #[Computed] + public function hourlyRates(): array + { + if (! $this->canSeePrices) { + return []; + } + + return array_values(array_filter( + app(PriceListQueries::class)->hourlyRates(includeInactive: false), + fn (HourlyRateGroup $group): bool => $group->rows !== [], + )); + } + + #[Computed] + public function mileageRateCents(): ?int + { + return $this->canSeePrices ? app(PriceListQueries::class)->mileageRateCents() : null; + } + + /** + * @return list + */ + public function consumerHeaders(): array + { + return [ + ['index' => 'name', 'label' => __('catalog.price_list.product'), 'sortable' => false], + ['index' => 'unit', 'label' => __('catalog.products.unit'), 'sortable' => false], + ['index' => 'gross', 'label' => __('catalog.products.gross_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'vat', 'label' => __('catalog.products.vat_column'), 'sortable' => false], + ]; + } + + /** + * @return list + */ + public function otherHeaders(): array + { + return [ + ['index' => 'name', 'label' => __('catalog.price_list.product'), 'sortable' => false], + ['index' => 'unit', 'label' => __('catalog.products.unit'), 'sortable' => false], + ['index' => 'net', 'label' => __('catalog.products.net_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'gross', 'label' => __('catalog.products.gross_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'vat', 'label' => __('catalog.products.vat_column'), 'sortable' => false], + ]; + } + + public function money(int $cents): string + { + return Money::fromCents($cents)->format(); + } + + public function percentage(int $basisPoints): string + { + return (new VatPercentage($basisPoints))->format(); + } + + public function render(): mixed + { + return $this->view()->title(__('catalog.prices.title')); + } +}; +?> + +
+

{{ __('catalog.prices.title') }}

+ +
+
+

{{ __('catalog.price_list.consumer_products') }}

+

{{ __('catalog.price_list.consumer_help') }}

+
+ + @if ($this->consumerProducts === []) +

{{ __('catalog.products.none') }}

+ @else + + @interact('column_name', $product) + {{ $product->name }} + @endinteract + + @interact('column_unit', $product) + {{ __('catalog.units.'.$product->unit->value) }} + @endinteract + + @interact('column_gross', $product) + {{ $this->money($product->grossCents) }} + @endinteract + + @interact('column_vat', $product) + {{ $this->percentage($product->vatBasisPoints) }} + @endinteract + + @endif +
+ + @if ($this->canSeePrices) +
+
+

{{ __('catalog.prices.hourly_rates') }}

+

{{ __('catalog.price_list.hourly_help') }}

+
+ + @foreach ($this->hourlyRates as $group) + + + + + + + + + + @foreach ($group->rows as $row) + + + + + @endforeach + +
{{ $group->serviceUnitName }}
{{ __('catalog.prices.work_type') }}{{ __('catalog.prices.hourly_rate') }}
+ @if ($row->serviceName !== null) + {{ $row->serviceName }}: + @endif + {{ $row->name }} + + {{ $row->hourlyRateCents === null ? __('catalog.price_list.no_price') : $this->money($row->hourlyRateCents) }} +
+ @endforeach +
+ +
+

{{ __('catalog.price_list.other_products') }}

+ + @if ($this->otherProducts === []) +

{{ __('catalog.products.none') }}

+ @else + + @interact('column_name', $product) + {{ $product->name }} + @endinteract + + @interact('column_unit', $product) + {{ __('catalog.units.'.$product->unit->value) }} + @endinteract + + @interact('column_net', $product) + {{ $this->money($product->netCents) }} + @endinteract + + @interact('column_gross', $product) + {{ $this->money($product->grossCents) }} + @endinteract + + @interact('column_vat', $product) + {{ $this->percentage($product->vatBasisPoints) }} + @endinteract + + @endif +
+ +
+

{{ __('catalog.mileage.title') }}

+

+ {{ $this->mileageRateCents === null + ? __('catalog.price_list.no_price') + : __('catalog.price_list.mileage_value', ['rate' => $this->money($this->mileageRateCents)]) }} +

+
+ @else +

{{ __('catalog.price_list.no_permission') }}

+ @endif +
diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php index a2ec4df..00cf078 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡prices.blade.php @@ -4,23 +4,30 @@ use App\Modules\Catalog\Application\Contracts\PriceListQueries; use App\Modules\Catalog\Application\DTOs\HourlyRateGroup; use App\Modules\Catalog\Application\DTOs\HourlyRateRow; use App\Modules\Catalog\Application\DTOs\ProductSummary; +use App\Modules\Catalog\Application\DTOs\VatRateSummary; use App\Modules\Catalog\Application\UseCases\MoveProduct; +use App\Modules\Catalog\Application\UseCases\MoveVatRate; use App\Modules\Catalog\Application\UseCases\SetHourlyRate; use App\Modules\Catalog\Application\UseCases\SetMileageRate; use App\Modules\Catalog\Application\UseCases\SetProductActive; +use App\Modules\Catalog\Application\UseCases\SetVatRateActive; use App\Modules\Catalog\Domain\Enums\MoveDirection; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; +use App\Modules\Catalog\Domain\Exceptions\DefaultVatRateMustBeActive; use App\Modules\Catalog\Domain\Exceptions\ProductNotFound; +use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound; use App\Modules\Catalog\Domain\ValueObjects\ProductDuration; use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; use App\Modules\Shared\Domain\ValueObjects\Money; +use App\Modules\Shared\Domain\ValueObjects\VatPercentage; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Component; /** - * Price list (hinnasto): hourly rates of work types, products and the - * mileage rate. All prices are without VAT. + * Price list management (hinnasto): hourly rates of work types, products, + * the mileage rate and VAT rates. Prices are without VAT, except consumer + * product prices, which are entered with VAT. */ new class extends Component { @@ -105,24 +112,34 @@ new class extends Component } /** - * Called by the row actions shared with the catalog page, so the level is always "product". + * @return list */ - public function move(string $level, int $id, string $direction, MoveProduct $moveProduct): void + #[Computed] + public function vatRates(): array + { + return $this->priceList->vatRates($this->showInactive); + } + + /** + * Called by the row actions shared with the catalog page; the level is "product" or "vat_rate". + */ + public function move(string $level, int $id, string $direction, MoveProduct $moveProduct, MoveVatRate $moveVatRate): void { $this->authorize('catalog.manage'); $moveDirection = MoveDirection::from($direction); - $name = $this->priceList->findProduct($id)?->name ?? ''; + $isVatRate = $level === 'vat_rate'; + $name = ($isVatRate ? $this->priceList->findVatRate($id)?->name : $this->priceList->findProduct($id)?->name) ?? ''; try { - $moved = $moveProduct->execute($id, $moveDirection); - } catch (ProductNotFound) { + $moved = $isVatRate ? $moveVatRate->execute($id, $moveDirection) : $moveProduct->execute($id, $moveDirection); + } catch (ProductNotFound|VatRateNotFound) { $this->statusMessage = __('catalog.status.not_found'); return; } - unset($this->products); + unset($this->products, $this->vatRates); $this->statusMessage = __(match (true) { $moved && $moveDirection === MoveDirection::Up => 'catalog.status.moved_up', @@ -132,13 +149,20 @@ new class extends Component }, ['name' => $name]); // The row moved in the DOM: keep focus on the same button. - $this->js("document.getElementById('move-{$moveDirection->value}-product-{$id}')?.focus()"); + $level = $isVatRate ? 'vat_rate' : 'product'; + $this->js("document.getElementById('move-{$moveDirection->value}-{$level}-{$id}')?.focus()"); } - public function toggleActive(string $level, int $id, SetProductActive $setActive): void + public function toggleActive(string $level, int $id, SetProductActive $setActive, SetVatRateActive $setVatRateActive): void { $this->authorize('catalog.manage'); + if ($level === 'vat_rate') { + $this->toggleVatRate($id, $setVatRateActive); + + return; + } + $product = $this->priceList->findProduct($id); if ($product === null) { @@ -181,13 +205,33 @@ new class extends Component return [ ['index' => 'name', 'label' => __('catalog.fields.name'), 'sortable' => false], ['index' => 'unit', 'label' => __('catalog.products.unit'), 'sortable' => false], - ['index' => 'price', 'label' => __('catalog.products.price_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'net', 'label' => __('catalog.products.net_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'gross', 'label' => __('catalog.products.gross_column'), 'sortable' => false, 'align' => 'right'], + ['index' => 'vat', 'label' => __('catalog.products.vat_column'), 'sortable' => false], ['index' => 'consumer', 'label' => __('catalog.products.consumer_column'), 'sortable' => false], ['index' => 'duration', 'label' => __('catalog.products.duration_column'), 'sortable' => false], ['index' => 'actions', 'label' => __('catalog.products.actions'), 'sortable' => false], ]; } + /** + * @return list + */ + public function vatRateHeaders(): array + { + return [ + ['index' => 'name', 'label' => __('catalog.fields.name'), 'sortable' => false], + ['index' => 'percentage', 'label' => __('catalog.vat_rates.percentage_column'), 'sortable' => false], + ['index' => 'default', 'label' => __('catalog.vat_rates.default_column'), 'sortable' => false], + ['index' => 'actions', 'label' => __('catalog.products.actions'), 'sortable' => false], + ]; + } + + public function percentage(int $basisPoints): string + { + return (new VatPercentage($basisPoints))->format(); + } + public function money(?int $cents): string { return $cents === null ? '' : Money::fromCents($cents)->format(); @@ -208,6 +252,33 @@ new class extends Component return $this->view()->title(__('catalog.prices.title')); } + private function toggleVatRate(int $id, SetVatRateActive $setActive): void + { + $vatRate = $this->priceList->findVatRate($id); + $this->errorMessage = ''; + + if ($vatRate === null) { + $this->statusMessage = __('catalog.status.not_found'); + + return; + } + + try { + $setActive->execute($id, ! $vatRate->isActive); + } catch (DefaultVatRateMustBeActive) { + $this->errorMessage = __('catalog.errors.default_vat_rate_active', ['name' => $vatRate->name]); + // The checkbox was unticked in the browser: render it ticked again. + unset($this->vatRates); + $this->js("document.getElementById('active-vat_rate-{$id}').checked = true"); + + return; + } + + unset($this->vatRates, $this->products); + + $this->statusMessage = __($vatRate->isActive ? 'catalog.vat_rates.deactivated' : 'catalog.status.activated', ['name' => $vatRate->name]); + } + private function rateRow(int $workTypeId): ?HourlyRateRow { foreach ($this->priceList->hourlyRates() as $group) { @@ -320,8 +391,22 @@ new class extends Component {{ __('catalog.units.'.$product->unit->value) }} @endinteract - @interact('column_price', $product) - {{ $this->money($product->priceCents) }} + @interact('column_net', $product) + {{ $this->money($product->netCents) }} + @unless ($product->priceIncludesVat) + {{ __('catalog.products.entered') }} + @endunless + @endinteract + + @interact('column_gross', $product) + {{ $this->money($product->grossCents) }} + @if ($product->priceIncludesVat) + {{ __('catalog.products.entered') }} + @endif + @endinteract + + @interact('column_vat', $product) + {{ $this->percentage($product->vatBasisPoints) }} @endinteract @interact('column_consumer', $product) @@ -352,6 +437,41 @@ new class extends Component @endif +
+
+

{{ __('catalog.vat_rates.title') }}

+ +
+

{{ __('catalog.vat_rates.help') }}

+ + + @interact('column_name', $vatRate) + {{ $vatRate->name }} + @unless ($vatRate->isActive) + ({{ __('catalog.inactive') }}) + @endunless + @endinteract + + @interact('column_percentage', $vatRate) + {{ $this->percentage($vatRate->basisPoints) }} + @endinteract + + @interact('column_default', $vatRate) + {{ $vatRate->isDefault ? __('catalog.vat_rates.is_default') : '' }} + @endinteract + + @interact('column_actions', $vatRate) + + @endinteract + +
+

{{ __('catalog.mileage.title') }}

diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php index c3497fa..efed271 100644 --- a/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php +++ b/app/Modules/Catalog/Presentation/Livewire/⚡product-form.blade.php @@ -2,6 +2,7 @@ use App\Modules\Catalog\Application\Contracts\CatalogQueries; use App\Modules\Catalog\Application\Contracts\PriceListQueries; +use App\Modules\Catalog\Application\DTOs\VatRateSummary; use App\Modules\Catalog\Application\DTOs\WorkTypeSummary; use App\Modules\Catalog\Application\UseCases\AddProduct; use App\Modules\Catalog\Application\UseCases\UpdateProduct; @@ -9,6 +10,9 @@ use App\Modules\Catalog\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\Exceptions\ProductNotFound; use App\Modules\Catalog\Presentation\Livewire\Forms\ProductForm; use App\Modules\Shared\Domain\Exceptions\DomainException; +use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; +use App\Modules\Shared\Domain\ValueObjects\Money; +use App\Modules\Shared\Domain\ValueObjects\VatPercentage; use Livewire\Attributes\Computed; use Livewire\Attributes\Locked; use Livewire\Component; @@ -27,6 +31,12 @@ new class extends Component #[Locked] public ?int $storedWorkTypeId = null; + /** + * The stored VAT rate, listed even when it is no longer in use. + */ + #[Locked] + public ?int $storedVatRateId = null; + public ProductForm $form; public function mount(PriceListQueries $priceList, ?int $product = null): void @@ -40,8 +50,54 @@ new class extends Component $this->productId = $summary->id; $this->storedWorkTypeId = $summary->workTypeId; + $this->storedVatRateId = $summary->vatRateId; $this->form->fillFrom($summary); + + return; } + + $this->form->vat_rate_id = (string) ($priceList->defaultVatRate()?->id ?? ''); + } + + /** + * Active VAT rates, plus the stored one if it is no longer in use. + * + * @return list + */ + #[Computed] + public function vatRates(): array + { + $priceList = app(PriceListQueries::class); + + return array_values(array_filter( + $priceList->vatRates(), + fn (VatRateSummary $vatRate): bool => $vatRate->isActive || $vatRate->id === $this->storedVatRateId, + )); + } + + /** + * The price on the other side of VAT, e.g. "14,34 € ALV 0" for a consumer + * price of 18,00 €; empty while the price or rate is not valid. + */ + public function otherPrice(): string + { + $vatRate = collect($this->vatRates)->first(fn (VatRateSummary $rate): bool => (string) $rate->id === $this->form->vat_rate_id); + + try { + $price = Money::parse($this->form->price); + } catch (InvalidMoneyAmount) { + return ''; + } + + if ($price === null || $vatRate === null) { + return ''; + } + + $vat = new VatPercentage($vatRate->basisPoints); + + return $this->form->is_consumer_product + ? __('catalog.products.net_equivalent', ['price' => $price->removeVat($vat)->format()]) + : __('catalog.products.gross_equivalent', ['price' => $price->addVat($vat)->format()]); } /** @@ -135,18 +191,29 @@ new class extends Component @endforeach - +
+ +

{{ __('catalog.products.consumer_help') }}

+
+ + + @foreach ($this->vatRates as $vatRate) + + @endforeach +
- -

{{ __('catalog.products.consumer_help') }}

+ +

{{ $this->otherPrice() }}

diff --git a/app/Modules/Catalog/Presentation/Livewire/⚡vat-rate-form.blade.php b/app/Modules/Catalog/Presentation/Livewire/⚡vat-rate-form.blade.php new file mode 100644 index 0000000..39907fd --- /dev/null +++ b/app/Modules/Catalog/Presentation/Livewire/⚡vat-rate-form.blade.php @@ -0,0 +1,138 @@ +authorize('catalog.manage'); + + if ($vatRate === null) { + return; + } + + $summary = $priceList->findVatRate($vatRate); + + abort_if($summary === null, 404); + + $this->vatRateId = $summary->id; + $this->isDefault = $summary->isDefault; + $this->name = $summary->name; + $this->percentage = (new VatPercentage($summary->basisPoints))->inputValue(); + } + + public function save(AddVatRate $addVatRate, UpdateVatRate $updateVatRate): void + { + $this->authorize('catalog.manage'); + + $this->validate( + ['name' => ['required', 'string', 'max:100'], 'percentage' => ['required', 'string', 'max:10'], 'makeDefault' => ['boolean']], + [ + 'name.required' => __('catalog.errors.name_required'), + 'name.max' => __('catalog.errors.invalid_name'), + 'percentage.required' => __('catalog.errors.vat_percentage_required'), + 'percentage.max' => __('catalog.errors.invalid_vat_percentage'), + ], + ); + + try { + if ($this->vatRateId === null) { + $addVatRate->execute($this->name, $this->percentage, $this->makeDefault); + session()->flash('status', __('catalog.status.created', ['name' => trim($this->name)])); + } else { + $updateVatRate->execute($this->vatRateId, $this->name, $this->percentage, $this->makeDefault); + session()->flash('status', __('catalog.status.updated', ['name' => trim($this->name)])); + } + } catch (VatRateNotFound) { + abort(404); + } catch (InvalidCatalogName) { + $this->addError('name', __('catalog.errors.invalid_name')); + + return; + } catch (VatRateNameTaken) { + $this->addError('name', __('catalog.errors.vat_rate_name_taken')); + + return; + } catch (InvalidVatPercentage) { + $this->addError('percentage', __('catalog.errors.invalid_vat_percentage')); + + return; + } + + $this->redirectRoute('catalog.prices', navigate: true); + } + + public function heading(): string + { + return __($this->vatRateId === null ? 'catalog.vat_rates.create_title' : 'catalog.vat_rates.edit_title'); + } + + public function render(): mixed + { + return $this->view()->title($this->heading()); + } +}; +?> + +
+

{{ $this->heading() }}

+ + @if ($vatRateId !== null) +

{{ __('catalog.vat_rates.change_help') }}

+ @endif + +
+ + + + + @if ($isDefault) +

{{ __('catalog.vat_rates.is_default_help') }}

+ @else +
+ +

{{ __('catalog.vat_rates.make_default_help') }}

+
+ @endif + +
+ + +
+ +
diff --git a/app/Modules/Catalog/Presentation/Routes/web.php b/app/Modules/Catalog/Presentation/Routes/web.php index a72dc4d..3c81239 100644 --- a/app/Modules/Catalog/Presentation/Routes/web.php +++ b/app/Modules/Catalog/Presentation/Routes/web.php @@ -32,4 +32,15 @@ Route::middleware(['web', 'auth', 'can:catalog.manage']) Route::livewire('/products/{product}/edit', 'catalog::product-form') ->whereNumber('product') ->name('products.edit'); + Route::livewire('/vat-rates/create', 'catalog::vat-rate-form')->name('vat-rates.create'); + Route::livewire('/vat-rates/{vatRate}/edit', 'catalog::vat-rate-form') + ->whereNumber('vatRate') + ->name('vat-rates.edit'); + }); + +Route::middleware(['web', 'auth', 'can:catalog.view-prices']) + ->prefix('catalog') + ->name('catalog.') + ->group(function () { + Route::livewire('/price-list', 'catalog::price-list')->name('price-list'); }); diff --git a/app/Modules/Shared/Domain/Exceptions/InvalidVatPercentage.php b/app/Modules/Shared/Domain/Exceptions/InvalidVatPercentage.php new file mode 100644 index 0000000..ff0a8d2 --- /dev/null +++ b/app/Modules/Shared/Domain/Exceptions/InvalidVatPercentage.php @@ -0,0 +1,13 @@ +cents * (10_000 + $vat->basisPoints) * 2 + 10_000, 20_000)); + } + + /** + * The amount without VAT when this amount includes it, rounded half up to the cent. + */ + public function removeVat(VatPercentage $vat): self + { + $divisor = 10_000 + $vat->basisPoints; + + return new self(intdiv($this->cents * 10_000 * 2 + $divisor, $divisor * 2)); + } + /** * Finnish notation with the currency, e.g. "1 200,50 €". */ diff --git a/app/Modules/Shared/Domain/ValueObjects/VatPercentage.php b/app/Modules/Shared/Domain/ValueObjects/VatPercentage.php new file mode 100644 index 0000000..37582a4 --- /dev/null +++ b/app/Modules/Shared/Domain/ValueObjects/VatPercentage.php @@ -0,0 +1,59 @@ + self::MAX_BASIS_POINTS) { + throw new InvalidVatPercentage; + } + + $this->basisPoints = $basisPoints; + } + + /** + * Parses "25,5", "25.5", "0" or "25,5 %". + * + * @throws InvalidVatPercentage + */ + public static function parse(string $value): self + { + $value = str_replace(',', '.', preg_replace('/[\s\x{00A0}%]+/u', '', $value) ?? ''); + + if (preg_match('/^(\d{1,3})(?:\.(\d{1,2}))?$/', $value, $matches) !== 1) { + throw new InvalidVatPercentage; + } + + return new self((int) $matches[1] * 100 + (int) str_pad($matches[2] ?? '', 2, '0')); + } + + /** + * Finnish notation without trailing zeros, e.g. "25,5 %" or "0 %". + */ + public function format(): string + { + return $this->inputValue()."\u{00A0}%"; + } + + /** + * The percentage for an input field, e.g. "25,5". + */ + public function inputValue(): string + { + return str_replace('.', ',', rtrim(rtrim(number_format($this->basisPoints / 100, 2, '.', ''), '0'), '.')); + } +} diff --git a/app/Modules/Users/Application/DTOs/UserAccountData.php b/app/Modules/Users/Application/DTOs/UserAccountData.php index 834d484..9bac03f 100644 --- a/app/Modules/Users/Application/DTOs/UserAccountData.php +++ b/app/Modules/Users/Application/DTOs/UserAccountData.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Modules\Users\Application\DTOs; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; /** @@ -13,6 +14,7 @@ final readonly class UserAccountData { /** * @param string|null $employmentEndsOn Date as Y-m-d. + * @param list $moneyPermissions Only for employees and interns. */ public function __construct( public string $name, @@ -21,10 +23,11 @@ final readonly class UserAccountData public bool $active = true, public ?string $employmentEndsOn = null, public ?int $supervisorId = null, + public array $moneyPermissions = [], ) {} /** - * @param array{name: string, email: string, role: string|Role, active?: bool, employment_ends_on?: string|null, supervisor_id?: int|string|null} $data + * @param array{name: string, email: string, role: string|Role, active?: bool, employment_ends_on?: string|null, supervisor_id?: int|string|null, money_permissions?: list} $data */ public static function fromArray(array $data): self { @@ -38,6 +41,7 @@ final readonly class UserAccountData active: $data['active'] ?? true, employmentEndsOn: $endsOn === '' ? null : $endsOn, supervisorId: $supervisorId === null || $supervisorId === '' ? null : (int) $supervisorId, + moneyPermissions: MoneyPermission::listFrom($data['money_permissions'] ?? []), ); } } diff --git a/app/Modules/Users/Application/DTOs/UserSummary.php b/app/Modules/Users/Application/DTOs/UserSummary.php index f667eaa..4ed9376 100644 --- a/app/Modules/Users/Application/DTOs/UserSummary.php +++ b/app/Modules/Users/Application/DTOs/UserSummary.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Modules\Users\Application\DTOs; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; /** @@ -13,6 +14,7 @@ final readonly class UserSummary { /** * @param string|null $employmentEndsOn Date as Y-m-d. + * @param list $moneyPermissions */ public function __construct( public int $id, @@ -23,5 +25,6 @@ final readonly class UserSummary public ?string $employmentEndsOn, public ?int $supervisorId, public ?string $supervisorName, + public array $moneyPermissions = [], ) {} } diff --git a/app/Modules/Users/Application/UseCases/CreateUserAccount.php b/app/Modules/Users/Application/UseCases/CreateUserAccount.php index f508a28..17b4d70 100644 --- a/app/Modules/Users/Application/UseCases/CreateUserAccount.php +++ b/app/Modules/Users/Application/UseCases/CreateUserAccount.php @@ -42,6 +42,7 @@ final class CreateUserAccount $data->role, EmploymentEndDate::parse($data->employmentEndsOn), $data->supervisorId, + $data->moneyPermissions, ); $userId = $this->transactions->run(function () use ($user): int { diff --git a/app/Modules/Users/Application/UseCases/UpdateUserAccount.php b/app/Modules/Users/Application/UseCases/UpdateUserAccount.php index dcb50ef..b4d57df 100644 --- a/app/Modules/Users/Application/UseCases/UpdateUserAccount.php +++ b/app/Modules/Users/Application/UseCases/UpdateUserAccount.php @@ -46,7 +46,7 @@ final class UpdateUserAccount throw new EmailAlreadyInUse; } - $user->changeDetails($name, $email, $data->role, $data->active, $endsOn, $data->supervisorId); + $user->changeDetails($name, $email, $data->role, $data->active, $endsOn, $data->supervisorId, $data->moneyPermissions); if ($wasActiveAdmin && ! $user->isActiveAdmin() && $this->users->countActiveAdmins($userId) === 0) { throw new LastAdminCannotBeRemoved; diff --git a/app/Modules/Users/Domain/Entities/UserAccount.php b/app/Modules/Users/Domain/Entities/UserAccount.php index 3bc2129..21a935d 100644 --- a/app/Modules/Users/Domain/Entities/UserAccount.php +++ b/app/Modules/Users/Domain/Entities/UserAccount.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Modules\Users\Domain\Entities; use App\Modules\Shared\Domain\ValueObjects\EmailAddress; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor; use App\Modules\Users\Domain\Exceptions\InvalidSupervisor; @@ -16,9 +17,14 @@ use DateTimeImmutable; * * Interns have an employment end date (their last day with access) and a * supervisor. Other roles have neither: they are cleared on a role change. + * Employees and interns may have personal money permissions; other roles + * see money by role, so theirs are cleared. */ final class UserAccount { + /** + * @param list $moneyPermissions + */ private function __construct( private ?int $id, private PersonName $name, @@ -27,10 +33,13 @@ final class UserAccount private bool $active, private ?DateTimeImmutable $employmentEndsOn, private ?int $supervisorId, + private array $moneyPermissions = [], ) {} /** * A new, active user that is not stored yet, so it has no id. + * + * @param list $moneyPermissions */ public static function register( PersonName $name, @@ -38,8 +47,9 @@ final class UserAccount Role $role, ?DateTimeImmutable $employmentEndsOn = null, ?int $supervisorId = null, + array $moneyPermissions = [], ): self { - $user = new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId); + $user = new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId, MoneyPermission::listFrom($moneyPermissions)); $user->applyRoleRules(); return $user; @@ -52,6 +62,8 @@ final class UserAccount * intern whose supervisor was deleted, say) must still load, so the user * can be signed in or out and an admin can correct it. The rules apply * again on the next changeDetails(). + * + * @param list $moneyPermissions */ public static function reconstitute( int $id, @@ -61,10 +73,14 @@ final class UserAccount bool $active, ?DateTimeImmutable $employmentEndsOn, ?int $supervisorId, + array $moneyPermissions = [], ): self { - return new self($id, $name, $email, $role, $active, $employmentEndsOn, $supervisorId); + return new self($id, $name, $email, $role, $active, $employmentEndsOn, $supervisorId, MoneyPermission::listFrom($moneyPermissions)); } + /** + * @param list $moneyPermissions + */ public function changeDetails( PersonName $name, EmailAddress $email, @@ -72,6 +88,7 @@ final class UserAccount bool $active, ?DateTimeImmutable $employmentEndsOn, ?int $supervisorId, + array $moneyPermissions = [], ): void { $changed = clone $this; $changed->name = $name; @@ -80,6 +97,7 @@ final class UserAccount $changed->active = $active; $changed->employmentEndsOn = $employmentEndsOn; $changed->supervisorId = $supervisorId; + $changed->moneyPermissions = MoneyPermission::listFrom($moneyPermissions); $changed->applyRoleRules(); foreach (get_object_vars($changed) as $property => $value) { @@ -150,8 +168,20 @@ final class UserAccount return $this->supervisorId; } + /** + * @return list + */ + public function moneyPermissions(): array + { + return $this->moneyPermissions; + } + private function applyRoleRules(): void { + if (! $this->role->hasPersonalMoneyPermissions()) { + $this->moneyPermissions = []; + } + if ($this->role !== Role::Intern) { $this->employmentEndsOn = null; $this->supervisorId = null; diff --git a/app/Modules/Users/Domain/Enums/MoneyPermission.php b/app/Modules/Users/Domain/Enums/MoneyPermission.php new file mode 100644 index 0000000..53df4dd --- /dev/null +++ b/app/Modules/Users/Domain/Enums/MoneyPermission.php @@ -0,0 +1,36 @@ +` abilities. + */ +enum MoneyPermission: string +{ + /** Hourly rates and other than consumer product prices. */ + case Prices = 'prices'; + + /** Amounts of expenses. */ + case Expenses = 'expenses'; + + /** Budgets and quoted amounts. */ + case Quotes = 'quotes'; + + /** Billing material and billed amounts. */ + case Billing = 'billing'; + + /** + * @param list $values + * @return list + */ + public static function listFrom(array $values): array + { + $permissions = array_map(fn (self|string $value): self => $value instanceof self ? $value : self::from($value), $values); + + return array_values(array_filter(self::cases(), fn (self $case): bool => in_array($case, $permissions, true))); + } +} diff --git a/app/Modules/Users/Domain/Enums/Role.php b/app/Modules/Users/Domain/Enums/Role.php index f879b83..a216b18 100644 --- a/app/Modules/Users/Domain/Enums/Role.php +++ b/app/Modules/Users/Domain/Enums/Role.php @@ -21,6 +21,22 @@ enum Role: string return $this === self::Admin; } + /** + * Whether the role sees every money amount without personal permissions. + */ + public function seesAllMoney(): bool + { + return $this === self::Admin || $this === self::Management; + } + + /** + * Whether personal money permissions apply to the role. + */ + public function hasPersonalMoneyPermissions(): bool + { + return $this === self::Employee || $this === self::Intern; + } + /** * Whether a user with this role can be an intern's supervisor. */ diff --git a/app/Modules/Users/Infrastructure/Persistence/Eloquent/UserMoneyPermissionsModel.php b/app/Modules/Users/Infrastructure/Persistence/Eloquent/UserMoneyPermissionsModel.php new file mode 100644 index 0000000..ae0195e --- /dev/null +++ b/app/Modules/Users/Infrastructure/Persistence/Eloquent/UserMoneyPermissionsModel.php @@ -0,0 +1,70 @@ +value; + } + + /** + * @param list $permissions + * @return array + */ + public static function columnsFor(array $permissions): array + { + $columns = []; + + foreach (MoneyPermission::cases() as $permission) { + $columns[self::column($permission)] = in_array($permission, $permissions, true); + } + + return $columns; + } + + public function allows(MoneyPermission $permission): bool + { + return (bool) $this->getAttribute(self::column($permission)); + } + + /** + * @return list + */ + public function permissions(): array + { + return array_values(array_filter(MoneyPermission::cases(), fn (MoneyPermission $permission): bool => $this->allows($permission))); + } + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'user_id' => 'integer', + 'can_see_prices' => 'boolean', + 'can_see_expenses' => 'boolean', + 'can_see_quotes' => 'boolean', + 'can_see_billing' => 'boolean', + ]; + } +} diff --git a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php index 0008042..ec32b6b 100644 --- a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php +++ b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php @@ -14,7 +14,7 @@ class EloquentUserAccountQueries implements UserAccountQueries { public function findSummary(int $id): ?UserSummary { - $model = User::query()->with('supervisor:id,name')->find($id); + $model = User::query()->with(['supervisor:id,name', 'moneyPermissions'])->find($id); return $model === null ? null : $this->toSummary($model); } @@ -77,6 +77,7 @@ class EloquentUserAccountQueries implements UserAccountQueries employmentEndsOn: $model->employment_ends_on?->toDateString(), supervisorId: $model->supervisor_id, supervisorName: $model->supervisor?->name, + moneyPermissions: $model->moneyPermissions?->permissions() ?? [], ); } } diff --git a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php index 7310505..08af7a8 100644 --- a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php +++ b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php @@ -8,6 +8,7 @@ use App\Modules\Users\Domain\Contracts\UserAccountRepository; use App\Modules\Users\Domain\Entities\UserAccount; use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\ValueObjects\PersonName; +use App\Modules\Users\Infrastructure\Persistence\Eloquent\UserMoneyPermissionsModel; use DateTimeImmutable; use Illuminate\Support\Str; @@ -46,6 +47,12 @@ class EloquentUserAccountRepository implements UserAccountRepository 'supervisor_id' => $user->supervisorId(), ])->save(); + UserMoneyPermissionsModel::query()->updateOrCreate( + ['user_id' => $model->id], + UserMoneyPermissionsModel::columnsFor($user->moneyPermissions()), + ); + $model->unsetRelation('moneyPermissions'); + return $this->toEntity($model->refresh()); } @@ -90,6 +97,7 @@ class EloquentUserAccountRepository implements UserAccountRepository $model->is_active, $model->employment_ends_on === null ? null : DateTimeImmutable::createFromInterface($model->employment_ends_on), $model->supervisor_id, + $model->moneyPermissions?->permissions() ?? [], ); } } diff --git a/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php index 578cc6f..7f94b36 100644 --- a/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php +++ b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php @@ -7,6 +7,7 @@ use App\Modules\Users\Application\Contracts\Clock; use App\Modules\Users\Application\Contracts\PasswordLinkSender; use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Domain\Contracts\UserAccountRepository; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Infrastructure\Auth\LaravelPasswordLinkSender; use App\Modules\Users\Infrastructure\Auth\PasswordLinkMail; use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountQueries; @@ -65,6 +66,12 @@ class UsersServiceProvider extends ServiceProvider Gate::define('users.manage', fn (User $user): bool => $user->role->canManageUsers()); + // money.prices, money.expenses, money.quotes, money.billing: whether the + // user may see that kind of money amounts (specification 2.3). + foreach (MoneyPermission::cases() as $permission) { + Gate::define('money.'.$permission->value, fn (User $user): bool => $user->canSeeMoney($permission)); + } + Password::defaults(fn () => Password::min(12)->mixedCase()->numbers()->symbols()); ResetPassword::toMailUsing(fn (CanResetPassword $notifiable, string $token): MailMessage => PasswordLinkMail::build( diff --git a/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php b/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php index f0307a4..45dd20a 100644 --- a/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php +++ b/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php @@ -6,6 +6,7 @@ use App\Modules\Shared\Domain\Exceptions\DomainException; use App\Modules\Shared\Domain\Exceptions\InvalidEmailAddress; use App\Modules\Users\Application\DTOs\UserAccountData; use App\Modules\Users\Application\DTOs\UserSummary; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse; use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor; @@ -13,6 +14,7 @@ use App\Modules\Users\Domain\Exceptions\InvalidPersonName; use App\Modules\Users\Domain\Exceptions\InvalidSupervisor; use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved; use App\Modules\Users\Domain\Exceptions\SupervisorHasInterns; +use Closure; use Illuminate\Validation\Rule; use Livewire\Form; @@ -35,6 +37,13 @@ class UserForm extends Form public string $supervisor_id = ''; + /** + * Values of MoneyPermission; only for employees and interns. + * + * @var list + */ + public array $money_permissions = []; + public function fillFromSummary(UserSummary $user): void { $this->name = $user->name; @@ -43,6 +52,7 @@ class UserForm extends Form $this->active = $user->active; $this->employment_ends_on = $user->employmentEndsOn ?? ''; $this->supervisor_id = $user->supervisorId === null ? '' : (string) $user->supervisorId; + $this->money_permissions = array_map(fn (MoneyPermission $permission): string => $permission->value, $user->moneyPermissions); } public function isIntern(): bool @@ -50,6 +60,14 @@ class UserForm extends Form return $this->role === Role::Intern->value; } + /** + * Whether the chosen role gets personal money permissions. + */ + public function hasMoneyPermissions(): bool + { + return Role::tryFrom($this->role)?->hasPersonalMoneyPermissions() ?? false; + } + public function toData(): UserAccountData { $this->validate(); @@ -61,6 +79,7 @@ class UserForm extends Form 'active' => $this->active, 'employment_ends_on' => $this->isIntern() ? $this->employment_ends_on : null, 'supervisor_id' => $this->isIntern() ? $this->supervisor_id : null, + 'money_permissions' => $this->hasMoneyPermissions() ? $this->money_permissions : [], ]); } @@ -95,6 +114,15 @@ class UserForm extends Form 'active' => ['boolean'], 'employment_ends_on' => [Rule::requiredIf($this->isIntern()), 'nullable', 'date_format:Y-m-d'], 'supervisor_id' => [Rule::requiredIf($this->isIntern()), 'nullable', 'integer'], + 'money_permissions' => ['array', function (string $attribute, mixed $value, Closure $fail): void { + foreach ((array) $value as $permission) { + if (! is_string($permission) || MoneyPermission::tryFrom($permission) === null) { + $fail(__('users.errors.invalid_money_permission')); + + return; + } + } + }], ]; } diff --git a/app/Modules/Users/Presentation/Livewire/⚡form.blade.php b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php index 8f108bd..90dbfce 100644 --- a/app/Modules/Users/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php @@ -6,6 +6,7 @@ use App\Modules\Users\Application\DTOs\UserOption; use App\Modules\Users\Application\UseCases\CreateUserAccount; use App\Modules\Users\Application\UseCases\SendPasswordSetupLink; use App\Modules\Users\Application\UseCases\UpdateUserAccount; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Exceptions\UserAccountNotFound; use App\Modules\Users\Presentation\Livewire\Forms\UserForm; @@ -161,6 +162,20 @@ new class extends Component @endif + @if ($form->hasMoneyPermissions()) + + @endif +

{{ __('users.fields.active_description') }}

diff --git a/database/factories/ProductFactory.php b/database/factories/ProductFactory.php index b5c731f..9fc20f9 100644 --- a/database/factories/ProductFactory.php +++ b/database/factories/ProductFactory.php @@ -4,6 +4,7 @@ namespace Database\Factories; use App\Modules\Catalog\Domain\Enums\ProductUnit; 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\Database\Eloquent\Factories\Factory; @@ -23,6 +24,7 @@ class ProductFactory extends Factory 'name' => fake()->unique()->words(2, true), 'unit' => ProductUnit::Piece->value, 'price_cents' => fake()->numberBetween(100, 10000), + 'vat_rate_id' => fn (): int => VatRateModel::query()->where('is_default', true)->value('id') ?? VatRateModel::factory()->create(['is_default' => true])->id, 'is_consumer_product' => false, 'auto_hours' => 0, 'work_type_id' => null, diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index 7f952ff..743e061 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -3,7 +3,9 @@ namespace Database\Factories; use App\Models\User; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; +use App\Modules\Users\Infrastructure\Persistence\Eloquent\UserMoneyPermissionsModel; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; @@ -84,4 +86,17 @@ class UserFactory extends Factory { return $this->state(fn (): array => ['is_active' => false]); } + + /** + * Personal money permissions (they apply to employees and interns). + */ + public function withMoneyPermissions(MoneyPermission ...$permissions): static + { + return $this->afterCreating(function (User $user) use ($permissions): void { + UserMoneyPermissionsModel::query()->updateOrCreate( + ['user_id' => $user->id], + UserMoneyPermissionsModel::columnsFor(array_values($permissions)), + ); + }); + } } diff --git a/database/factories/VatRateFactory.php b/database/factories/VatRateFactory.php new file mode 100644 index 0000000..c00a62b --- /dev/null +++ b/database/factories/VatRateFactory.php @@ -0,0 +1,33 @@ + + */ +class VatRateFactory extends Factory +{ + protected $model = VatRateModel::class; + + /** + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->unique()->words(2, true), + 'basis_points' => fake()->randomElement([0, 1000, 1350, 2550]), + 'is_default' => false, + 'is_active' => true, + 'sort_order' => fake()->unique()->numberBetween(100, 100000), + ]; + } + + public function inactive(): static + { + return $this->state(fn (): array => ['is_active' => false]); + } +} diff --git a/database/migrations/2026_11_24_053556_create_vat_rates_table.php b/database/migrations/2026_11_24_053556_create_vat_rates_table.php new file mode 100644 index 0000000..6929b89 --- /dev/null +++ b/database/migrations/2026_11_24_053556_create_vat_rates_table.php @@ -0,0 +1,47 @@ +id(); + $table->string('name', 100); + $table->unsignedInteger('basis_points'); + $table->boolean('is_default')->default(false); + $table->boolean('is_active')->default(true); + $table->unsignedInteger('sort_order'); + $table->timestamps(); + + $table->index('sort_order'); + }); + + $now = now(); + + DB::table('vat_rates')->insert(array_map( + fn (array $rate, int $index): array => $rate + ['is_active' => true, 'sort_order' => $index + 1, 'created_at' => $now, 'updated_at' => $now], + [ + ['name' => 'Yleinen', 'basis_points' => 2550, 'is_default' => true], + ['name' => 'Alennettu 13,5 %', 'basis_points' => 1350, 'is_default' => false], + ['name' => 'Alennettu 10 %', 'basis_points' => 1000, 'is_default' => false], + ['name' => 'Veroton', 'basis_points' => 0, 'is_default' => false], + ], + [0, 1, 2, 3], + )); + } + + public function down(): void + { + Schema::dropIfExists('vat_rates'); + } +}; diff --git a/database/migrations/2026_11_24_053557_add_vat_rate_to_products_table.php b/database/migrations/2026_11_24_053557_add_vat_rate_to_products_table.php new file mode 100644 index 0000000..4609629 --- /dev/null +++ b/database/migrations/2026_11_24_053557_add_vat_rate_to_products_table.php @@ -0,0 +1,31 @@ +foreignId('vat_rate_id')->nullable()->after('price_cents')->constrained()->restrictOnDelete(); + }); + + $defaultId = DB::table('vat_rates')->where('is_default', true)->value('id'); + + DB::table('products')->update(['vat_rate_id' => $defaultId]); + } + + public function down(): void + { + Schema::table('products', function (Blueprint $table) { + $table->dropConstrainedForeignId('vat_rate_id'); + }); + } +}; diff --git a/database/migrations/2026_11_24_053558_create_user_money_permissions_table.php b/database/migrations/2026_11_24_053558_create_user_money_permissions_table.php new file mode 100644 index 0000000..6aff835 --- /dev/null +++ b/database/migrations/2026_11_24_053558_create_user_money_permissions_table.php @@ -0,0 +1,30 @@ +id(); + $table->foreignId('user_id')->unique()->constrained()->cascadeOnDelete(); + $table->boolean('can_see_prices')->default(false); + $table->boolean('can_see_expenses')->default(false); + $table->boolean('can_see_quotes')->default(false); + $table->boolean('can_see_billing')->default(false); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('user_money_permissions'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index c5af9f4..621f55a 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -37,13 +37,14 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli ### 2.3 Rahamäärien näkyvyys *(K8)* - Pääkäyttäjä ja johto näkevät kaikki rahamäärät. -- Työntekijä ja harjoittelija näkevät aina kuluttajille kiinteähintaisina myytävien tuotteiden hinnat (esim. passikuvat, tulosteet). +- Työntekijä ja harjoittelija näkevät aina kuluttajille kiinteähintaisina myytävien tuotteiden hinnat (esim. passikuvat, tulosteet) arvonlisäverollisina. - Muut rahamäärät näytetään työntekijälle tai harjoittelijalle vain, jos pääkäyttäjä on antanut henkilökohtaisen oikeuden. Oikeudet ovat erillisiä: - **Hinnat** (tuntihinnasto, muut tuotehinnat) - **Kulut** (kulujen summat) - **Tarjoukset** (budjetti / tarjoussumma) - **Laskutus** (laskuaineisto ja laskutussummat) - Alihankkija ei näe rahamääriä lukuun ottamatta omien kulujensa tietoja, joita hän ei itse kirjaa. +- Oikeudet asetetaan käyttäjälomakkeella (Rahamäärien näkyvyys), ja ne koskevat vain työntekijää ja harjoittelijaa; muilla rooleilla ne tyhjennetään *(valmis)*. ### 2.4 Oikeustaulukko @@ -290,7 +291,8 @@ Hierarkiaa muokataan pohjatietojen hallinnasta. - **Tuntihinnasto**: tuntihinta on työtehtäväkohtainen (esim. ohjelmointityö 85 €/h, vaativa 110 €/h). Ei asiakas- eikä tekijäkohtaisia hintoja. - **Tuotteet**: kiinteähintaiset kappaletuotteet (passikuvat, tulosteet); hinta, yksikkö, kuluttajatuote-merkintä (näkyy kaikille) ja automaattisen tuntikirjauksen kesto. Yksikkö valitaan listasta: kpl, sivu, m², m, h, paketti. Jos kesto on annettu (0,25 h tarkkuudella, enintään 24 h), tuotteelle valitaan työtehtävä, jolle tunnit kirjataan. Tuotteita ei poisteta, vaan ne poistetaan käytöstä. - **Km-hinta** (asetus). -- Kaikki hinnat verottomina, enintään kaksi desimaalia. +- **ALV-kannat**: nimi ja prosentti (esim. Yleinen 25,5 %, Alennettu 13,5 %, Alennettu 10 %, Veroton 0 %); ylläpidetään hinnastossa. Tuotteelle valitaan kanta. Yksi kanta on oletus, jota käytetään tunneille, kuluille ja km-kuluille laskuaineistossa; oletus on aina käytössä. Kun lain mukainen kanta muuttuu, kannan prosentti muutetaan, ja muutos koskee kaikkia kantaa käyttäviä tuotteita. +- Hinnat verottomina, enintään kaksi desimaalia. Poikkeus: kuluttajatuotteen hinta syötetään ja tallennetaan verollisena (pyöreät kassahinnat), ja veroton hinta lasketaan kannasta. - Hinnoilla ei ole historiaa: laskuaineiston rivi tallentaa yksikköhinnan muodostushetkellä, joten hinnan muutos koskee vain myöhempiä aineistoja ja myyntejä. ## 12. Laskuaineisto *(K48–K51)* @@ -316,7 +318,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up **Users** - `users`: `name`, `email`, `password`, `role`, `is_active`, `employment_ends_on`, `supervisor_id` → users *(olemassa)* -- `user_money_permissions` *(V2)*: `user_id`, `can_see_prices`, `can_see_expenses`, `can_see_quotes`, `can_see_billing` +- `user_money_permissions` *(V2, olemassa)*: `user_id`, `can_see_prices`, `can_see_expenses`, `can_see_quotes`, `can_see_billing` **Customers** - `customers`: `name`, `type` (`company`/`consumer`), `business_id`, `personal_identity_code` (salattu), `personal_identity_code_hash` (HMAC, uniikki), `is_internal` *(olemassa, `is_internal` lisätään)* @@ -328,7 +330,8 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `services`: `service_unit_id`, `name`, `is_active`, `sort_order` *(olemassa)* - `work_types`: `service_unit_id`, `service_id` (nullable), `name`, `is_active`, `sort_order` *(olemassa)*, `hourly_rate_cents` (nullable) *(V2, olemassa)* - Nimi on yksilöllinen saman tason sisällä (kirjainkoosta riippumatta). Rivejä ei poisteta, vaan ne poistetaan käytöstä; viiteavaimet estävät poiston. -- `products` *(V2, olemassa)*: `name`, `unit` (`piece`/`page`/`square_metre`/`metre`/`hour`/`package`), `price_cents`, `is_consumer_product`, `auto_hours`, `work_type_id` (nullable, pakollinen jos `auto_hours` > 0), `is_active`, `sort_order` +- `vat_rates` *(V2, olemassa)*: `name`, `basis_points` (sadasosaprosentteina, 2550 = 25,5 %), `is_default`, `is_active`, `sort_order` +- `products` *(V2, olemassa)*: `name`, `unit` (`piece`/`page`/`square_metre`/`metre`/`hour`/`package`), `price_cents` (kuluttajatuotteella verollinen, muuten veroton), `vat_rate_id`, `is_consumer_product`, `auto_hours`, `work_type_id` (nullable, pakollinen jos `auto_hours` > 0), `is_active`, `sort_order` - `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä) **Jobs** (asiakastyöt) @@ -439,7 +442,11 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t ### 17.1 Hinnasto ja tuotteet *(valmis)* - Pääkäyttäjä ja johto hallitsevat Hinnasto-sivua (`/catalog/prices`, valikossa Hinnasto): tuntihinnat työtehtävittäin palveluyksiköiden mukaan ryhmiteltynä (kenttä tallentuu, kun siitä siirrytään pois; tyhjä poistaa hinnan), tuotteet (lisäys, muokkaus, järjestys, käytöstä poisto) ja km-hinta. Tuntihinnan voi asettaa myös työtehtävän lomakkeella Pohjatiedoissa. -- Muut eivät vielä näe hintoja; henkilökohtaiset rahaoikeudet ja työntekijöiden hinnastonäkymä tehdään seuraavaksi (2.3). + +### 17.2 Rahaoikeudet, hinnastonäkymä ja ALV-kannat *(valmis)* +- Pääkäyttäjä antaa työntekijälle ja harjoittelijalle käyttäjälomakkeella rahaoikeudet Hinnat, Kulut, Tarjoukset ja Laskutus (2.3). +- Työntekijä ja harjoittelija näkevät valikon Hinnasto-linkistä lukusivun (`/catalog/price-list`): kuluttajatuotteet verollisine hintoineen aina; tuntihinnat, muut tuotteet (veroton ja verollinen hinta) ja km-hinta vain Hinnat-oikeudella. Alihankkija ei näe sivua. +- Hinnaston hallinnassa ylläpidetään ALV-kantoja (lisäys, muokkaus, järjestys, käytöstä poisto, oletuskanta). Tuotelomakkeella valitaan ALV-kanta, ja hintakentän nimi kertoo, syötetäänkö hinta verollisena (kuluttajatuote) vai verottomana; toinen hinta näytetään laskettuna. ## 18. Avoimet kysymykset diff --git a/lang/fi/catalog.php b/lang/fi/catalog.php index 1151721..d94c5ce 100644 --- a/lang/fi/catalog.php +++ b/lang/fi/catalog.php @@ -61,7 +61,7 @@ return [ 'prices' => [ 'title' => 'Hinnasto', - 'intro' => 'Kaikki hinnat ovat verottomia (ALV 0). Hinnan muutos koskee laskuaineistoja ja myyntejä, jotka tehdään muutoksen jälkeen; jo muodostetut aineistot säilyttävät hintansa.', + 'intro' => 'Hinnat ovat verottomia (ALV 0), paitsi kuluttajatuotteiden hinnat, jotka syötetään verollisina. Hinnan muutos koskee laskuaineistoja ja myyntejä, jotka tehdään muutoksen jälkeen; jo muodostetut aineistot säilyttävät hintansa.', 'hourly_rates' => 'Tuntihinnat', 'hourly_rates_help' => 'Tuntihinta on työtehtäväkohtainen. Hinta tallentuu, kun siirryt pois kentästä. Tyhjä kenttä poistaa hinnan.', 'work_type' => 'Työtehtävä', @@ -79,9 +79,17 @@ return [ 'create_title' => 'Uusi tuote', 'edit_title' => 'Muokkaa tuotetta', 'unit' => 'Yksikkö', - 'price' => 'Hinta (€ / yksikkö, ALV 0)', - 'price_help' => 'Esim. 12 tai 12,50.', - 'price_column' => 'Hinta (ALV 0)', + 'vat_rate' => 'ALV-kanta', + 'price_net' => 'Hinta ALV 0 (€ / yksikkö)', + 'price_gross' => 'Hinta sis. ALV (€ / yksikkö)', + 'price_help' => 'Veroton hinta, esim. 12 tai 12,50.', + 'price_gross_help' => 'Kuluttajatuotteen hinta syötetään verollisena, esim. 18 tai 18,50. Veroton hinta lasketaan ALV-kannasta.', + 'net_equivalent' => 'Veroton hinta: :price', + 'gross_equivalent' => 'Verollinen hinta: :price', + 'net_column' => 'Hinta ALV 0', + 'gross_column' => 'Hinta sis. ALV', + 'vat_column' => 'ALV', + 'entered' => 'syötetty hinta', 'consumer' => 'Kuluttajatuote', 'consumer_help' => 'Kuluttajatuotteen hinta näkyy kaikille käyttäjille, myös niille, joilla ei ole oikeutta muihin hintoihin.', 'consumer_column' => 'Kuluttajatuote', @@ -98,6 +106,36 @@ return [ 'deactivated' => ':name poistettu käytöstä. Sitä ei voi enää myydä.', ], + 'vat_rates' => [ + 'title' => 'ALV-kannat', + 'help' => 'Tuotteelle valitaan ALV-kanta. Oletuskantaa käytetään tunneille, kuluille ja km-kuluille laskuaineistossa. Kun lain mukainen kanta muuttuu, muuta kannan prosentti: muutos koskee kaikkia kantaa käyttäviä tuotteita.', + 'add' => 'Lisää ALV-kanta', + 'create_title' => 'Uusi ALV-kanta', + 'edit_title' => 'Muokkaa ALV-kantaa', + 'change_help' => 'Prosentin muutos koskee kaikkia tätä kantaa käyttäviä tuotteita. Kuluttajatuotteiden verollinen hinta pysyy ennallaan ja veroton hinta lasketaan uudelleen; muiden tuotteiden veroton hinta pysyy.', + 'name_help' => 'Esim. Yleinen tai Alennettu 10 %.', + 'percentage' => 'ALV-prosentti (%)', + 'percentage_help' => 'Esim. 25,5 tai 0.', + 'percentage_column' => 'Prosentti', + 'default_column' => 'Oletus', + 'is_default' => 'Oletuskanta', + 'is_default_help' => 'Tämä on oletuskanta. Oletuksen voi siirtää toiselle kannalle sen lomakkeella.', + 'make_default' => 'Oletuskanta', + 'make_default_help' => 'Oletuskantaa käytetään tunneille, kuluille ja km-kuluille. Valinta siirtää oletuksen tälle kannalle.', + 'deactivated' => ':name poistettu käytöstä. Sitä ei voi valita uusille tuotteille.', + ], + + 'price_list' => [ + 'product' => 'Tuote', + 'consumer_products' => 'Kuluttajatuotteet', + 'consumer_help' => 'Hinnat sisältävät arvonlisäveron.', + 'other_products' => 'Muut tuotteet', + 'hourly_help' => 'Tuntihinnat ovat verottomia (ALV 0).', + 'no_price' => 'Ei hintaa', + 'mileage_value' => ':rate / km (ALV 0)', + 'no_permission' => 'Tuntihinnat ja muiden tuotteiden hinnat näkyvät vain, jos pääkäyttäjä on antanut sinulle oikeuden hintoihin.', + ], + 'units' => [ 'piece' => 'kpl', 'page' => 'sivu', @@ -133,5 +171,10 @@ return [ 'invalid_duration' => 'Anna kesto tunteina 0,25 h tarkkuudella, enintään 24 h (esim. 0,25 tai 1,5).', 'work_type_required' => 'Valitse työtehtävä, jolle kesto kirjataan.', 'work_type_unavailable' => 'Valittu työtehtävä ei ole käytössä. Valitse toinen.', + 'vat_rate_unavailable' => 'Valitse käytössä oleva ALV-kanta.', + 'vat_rate_name_taken' => 'Tämänniminen ALV-kanta on jo olemassa.', + 'vat_percentage_required' => 'Anna ALV-prosentti.', + 'invalid_vat_percentage' => 'Anna ALV-prosentti väliltä 0–100, enintään kaksi desimaalia (esim. 25,5).', + 'default_vat_rate_active' => ':name on oletuskanta, eikä sitä voi poistaa käytöstä. Siirrä oletus ensin toiselle kannalle.', ], ]; diff --git a/lang/fi/users.php b/lang/fi/users.php index 5ad8d8c..cb356a7 100644 --- a/lang/fi/users.php +++ b/lang/fi/users.php @@ -57,7 +57,21 @@ return [ 'ended_on' => 'Päättyi :date', ], + 'money_permissions' => [ + 'legend' => 'Rahamäärien näkyvyys', + 'hint' => 'Kuluttajatuotteiden hinnat näkyvät kaikille. Muut rahamäärät näkyvät työntekijälle ja harjoittelijalle vain valituilta osin; pääkäyttäjä ja johto näkevät kaiken.', + 'prices' => 'Hinnat', + 'prices_note' => 'tuntihinnat ja muut tuotehinnat', + 'expenses' => 'Kulut', + 'expenses_note' => 'kulujen summat', + 'quotes' => 'Tarjoukset', + 'quotes_note' => 'budjetti ja tarjoussumma', + 'billing' => 'Laskutus', + 'billing_note' => 'laskuaineisto ja laskutussummat', + ], + 'errors' => [ + 'invalid_money_permission' => 'Valitse rahamäärien näkyvyys listasta.', 'name_required' => 'Anna nimi.', 'invalid_name' => 'Nimen pituus voi olla enintään 255 merkkiä.', 'email_required' => 'Anna sähköpostiosoite.', diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 5ac7d65..39030e6 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -72,7 +72,9 @@ @can('catalog.manage') @include('partials.nav-item', ['route' => 'catalog.index', 'pattern' => ['catalog.index', 'catalog.service-units.*', 'catalog.services.*', 'catalog.work-types.*'], 'label' => __('layout.catalog')]) - @include('partials.nav-item', ['route' => 'catalog.prices', 'pattern' => ['catalog.prices', 'catalog.products.*'], 'label' => __('layout.prices')]) + @include('partials.nav-item', ['route' => 'catalog.prices', 'pattern' => ['catalog.prices', 'catalog.products.*', 'catalog.vat-rates.*', 'catalog.price-list'], 'label' => __('layout.prices')]) + @elsecan('catalog.view-prices') + @include('partials.nav-item', ['route' => 'catalog.price-list', 'pattern' => 'catalog.price-list', 'label' => __('layout.prices')]) @endcan @can('users.manage') diff --git a/tests/Browser/CatalogAccessibilityTest.php b/tests/Browser/CatalogAccessibilityTest.php index d9bbad4..0921009 100644 --- a/tests/Browser/CatalogAccessibilityTest.php +++ b/tests/Browser/CatalogAccessibilityTest.php @@ -3,6 +3,7 @@ use App\Models\User; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel; +use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\VatRateModel; use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -28,6 +29,8 @@ it('has no accessibility issues on the catalog pages', function (string $page, s 'price list' => route('catalog.prices'), 'new product' => route('catalog.products.create'), 'edit product' => route('catalog.products.edit', $product->id), + 'edit VAT rate' => route('catalog.vat-rates.edit', VatRateModel::query()->where('is_default', true)->value('id')), + 'read-only price list' => route('catalog.price-list'), }; $visit = visit($url); @@ -36,7 +39,7 @@ it('has no accessibility issues on the catalog pages', function (string $page, s $visit->assertNoJavaScriptErrors() ->assertNoAccessibilityIssues(level: 2); -})->with(['catalog', 'new service unit', 'new service', 'edit work type', 'price list', 'new product', 'edit product'])->with([ +})->with(['catalog', 'new service unit', 'new service', 'edit work type', 'price list', 'new product', 'edit product', 'edit VAT rate', 'read-only price list'])->with([ 'desktop, light' => ['desktop', 'light'], 'desktop, dark' => ['desktop', 'dark'], 'mobile, light' => ['mobile', 'light'], @@ -75,3 +78,21 @@ it('saves an hourly rate with the keyboard and announces it', function () { expect($workType->refresh()->hourly_rate_cents)->toBe(8550); }); + +it('has no accessibility issues on the price list of an employee without the price permission', function (string $device, string $colorScheme) { + $this->actingAs(User::factory()->employee()->create()); + ProductModel::factory()->consumer()->create(['name' => 'Passikuvat']); + + $visit = visit(route('catalog.price-list')); + $visit = $device === 'mobile' ? $visit->on()->mobile() : $visit->on()->desktop(); + $visit = $colorScheme === 'dark' ? $visit->inDarkMode() : $visit->inLightMode(); + + $visit->assertSee('Passikuvat') + ->assertNoJavaScriptErrors() + ->assertNoAccessibilityIssues(level: 2); +})->with([ + 'desktop, light' => ['desktop', 'light'], + 'desktop, dark' => ['desktop', 'dark'], + 'mobile, light' => ['mobile', 'light'], + 'mobile, dark' => ['mobile', 'dark'], +]); diff --git a/tests/Fakes/InMemoryProductRepository.php b/tests/Fakes/InMemoryProductRepository.php index c5e0700..189c836 100644 --- a/tests/Fakes/InMemoryProductRepository.php +++ b/tests/Fakes/InMemoryProductRepository.php @@ -26,6 +26,7 @@ class InMemoryProductRepository implements ProductRepository $product->name(), $product->unit(), $product->price(), + $product->vatRateId(), $product->isConsumerProduct(), $product->duration(), $product->workTypeId(), diff --git a/tests/Fakes/InMemoryUserAccountRepository.php b/tests/Fakes/InMemoryUserAccountRepository.php index 6e46805..9a3e091 100644 --- a/tests/Fakes/InMemoryUserAccountRepository.php +++ b/tests/Fakes/InMemoryUserAccountRepository.php @@ -43,6 +43,7 @@ class InMemoryUserAccountRepository implements UserAccountRepository $user->isActive(), $user->employmentEndsOn(), $user->supervisorId(), + $user->moneyPermissions(), ); return clone $this->users[$id]; diff --git a/tests/Fakes/InMemoryVatRateRepository.php b/tests/Fakes/InMemoryVatRateRepository.php new file mode 100644 index 0000000..9e33474 --- /dev/null +++ b/tests/Fakes/InMemoryVatRateRepository.php @@ -0,0 +1,68 @@ + */ + public array $items = []; + + private int $nextId = 1; + + public function findById(int $id): ?VatRate + { + return isset($this->items[$id]) ? clone $this->items[$id] : null; + } + + public function findDefault(): ?VatRate + { + foreach ($this->items as $vatRate) { + if ($vatRate->isDefault()) { + return clone $vatRate; + } + } + + return null; + } + + public function save(VatRate $vatRate): VatRate + { + $id = $vatRate->id() ?? $this->nextId++; + $this->items[$id] = VatRate::reconstitute($id, $vatRate->name(), $vatRate->percentage(), $vatRate->isDefault(), $vatRate->isActive(), $vatRate->sortOrder()); + + return clone $this->items[$id]; + } + + public function isNameTaken(string $name, ?int $exceptId = null): bool + { + foreach ($this->items as $id => $vatRate) { + if ($id !== $exceptId && mb_strtolower($vatRate->name()->value) === mb_strtolower($name)) { + return true; + } + } + + return false; + } + + public function nextSortOrder(): int + { + return array_reduce($this->items, fn (int $max, VatRate $vatRate): int => max($max, $vatRate->sortOrder()), 0) + 1; + } + + public function neighbour(VatRate $vatRate, MoveDirection $direction): ?VatRate + { + $candidates = array_values(array_filter($this->items, fn (VatRate $other): bool => $direction === MoveDirection::Up + ? $other->sortOrder() < $vatRate->sortOrder() + : $other->sortOrder() > $vatRate->sortOrder())); + + usort($candidates, fn (VatRate $a, VatRate $b): int => $direction === MoveDirection::Up + ? $b->sortOrder() <=> $a->sortOrder() + : $a->sortOrder() <=> $b->sortOrder()); + + return isset($candidates[0]) ? clone $candidates[0] : null; + } +} diff --git a/tests/Feature/Modules/Catalog/PriceListTest.php b/tests/Feature/Modules/Catalog/PriceListTest.php index 857d6d4..b109ab7 100644 --- a/tests/Feature/Modules/Catalog/PriceListTest.php +++ b/tests/Feature/Modules/Catalog/PriceListTest.php @@ -3,6 +3,7 @@ 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; @@ -29,9 +30,11 @@ it('shows the price list pages to admins and management only', function (string 'subcontractor' => ['subcontractor', 403], ]); -it('shows the price list menu link only to those who may manage it', function () { - $this->get(route('customers.index'))->assertSee('Hinnasto'); - $this->actingAs(User::factory()->create())->get(route('customers.index'))->assertDontSee('Hinnasto'); +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 () { @@ -178,3 +181,66 @@ it('saves the mileage rate', function () { ->call('saveMileageRate') ->assertHasErrors(['mileageRate']); }); + +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')]]); +}); diff --git a/tests/Feature/Modules/Catalog/PriceListViewTest.php b/tests/Feature/Modules/Catalog/PriceListViewTest.php new file mode 100644 index 0000000..dd50858 --- /dev/null +++ b/tests/Feature/Modules/Catalog/PriceListViewTest.php @@ -0,0 +1,55 @@ +consumer()->create(['name' => 'Passikuvat', 'price_cents' => 1800]); + ProductModel::factory()->consumer()->inactive()->create(['name' => 'Vanha passikuva']); + ProductModel::factory()->create(['name' => 'Roll-up', 'price_cents' => 12000]); + WorkTypeModel::query()->where('name', 'painotyö')->update(['hourly_rate_cents' => 7500]); + app(Settings::class)->put(SetMileageRate::SETTING_KEY, '59'); +}); + +it('shows consumer prices with VAT but no other prices to an employee without the price permission', function () { + $this->actingAs(User::factory()->employee()->create()) + ->get(route('catalog.price-list')) + ->assertOk() + ->assertSee('Passikuvat') + ->assertSee("18,00\u{00A0}€", false) + ->assertSee("25,5\u{00A0}%", false) + ->assertDontSee('Vanha passikuva') + ->assertDontSee('Roll-up') + ->assertDontSee('painotyö') + ->assertDontSee("75,00\u{00A0}€", false) + ->assertDontSee("0,59\u{00A0}€", false) + ->assertSee(__('catalog.price_list.no_permission')); +}); + +it('shows every price to an employee with the price permission and to management', function (Closure $makeUser) { + $this->actingAs($makeUser()) + ->get(route('catalog.price-list')) + ->assertOk() + ->assertSee('Roll-up') + ->assertSee("120,00\u{00A0}€", false) + ->assertSee("150,60\u{00A0}€", false) + ->assertSee('painotyö') + ->assertSee("75,00\u{00A0}€", false) + ->assertSee("0,59\u{00A0}€", false); +})->with([ + 'employee with prices' => [fn () => User::factory()->employee()->withMoneyPermissions(MoneyPermission::Prices)->create()], + 'management' => [fn () => User::factory()->management()->create()], +]); + +it('keeps subcontractors out of the price list', function () { + $this->actingAs(User::factory()->subcontractor()->create()) + ->get(route('catalog.price-list')) + ->assertForbidden(); +}); diff --git a/tests/Feature/Modules/Users/MoneyPermissionsTest.php b/tests/Feature/Modules/Users/MoneyPermissionsTest.php new file mode 100644 index 0000000..deb4569 --- /dev/null +++ b/tests/Feature/Modules/Users/MoneyPermissionsTest.php @@ -0,0 +1,59 @@ +allows('money.'.$ability))->toBe(in_array($ability, $abilities, true), $ability); + } +})->with([ + 'admin' => [fn () => User::factory()->admin()->create(), ['prices', 'expenses', 'quotes', 'billing']], + 'management' => [fn () => User::factory()->management()->create(), ['prices', 'expenses', 'quotes', 'billing']], + 'employee without permissions' => [fn () => User::factory()->employee()->create(), []], + 'employee with prices and quotes' => [fn () => User::factory()->employee()->withMoneyPermissions(MoneyPermission::Prices, MoneyPermission::Quotes)->create(), ['prices', 'quotes']], + 'intern with billing' => [fn () => User::factory()->intern()->withMoneyPermissions(MoneyPermission::Billing)->create(), ['billing']], + 'subcontractor with a stray permission' => [fn () => User::factory()->subcontractor()->withMoneyPermissions(MoneyPermission::Prices)->create(), []], +]); + +it('saves money permissions on the user form for an employee', function () { + Notification::fake(); + $this->actingAs(User::factory()->admin()->create()); + $employee = User::factory()->employee()->create(); + + Livewire::test('users::form', ['user' => $employee->id]) + ->assertSee('Rahamäärien näkyvyys') + ->set('form.money_permissions', ['prices', 'expenses']) + ->call('save') + ->assertHasNoErrors(); + + expect($employee->refresh()->moneyPermissions?->permissions())->toBe([MoneyPermission::Prices, MoneyPermission::Expenses]); + + Livewire::test('users::form', ['user' => $employee->id]) + ->assertSet('form.money_permissions', ['prices', 'expenses']) + ->set('form.role', 'management') + ->assertDontSee('Rahamäärien näkyvyys') + ->call('save') + ->assertHasNoErrors(); + + expect(UserMoneyPermissionsModel::query()->where('user_id', $employee->id)->sole()->permissions())->toBe([]); +}); + +it('rejects an unknown money permission', function () { + $this->actingAs(User::factory()->admin()->create()); + $employee = User::factory()->employee()->create(); + + Livewire::test('users::form', ['user' => $employee->id]) + ->set('form.money_permissions', ['salaries']) + ->call('save') + ->assertHasErrors(['form.money_permissions']); +}); diff --git a/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php b/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php index a10eda0..698a8bc 100644 --- a/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php +++ b/tests/Unit/Modules/Catalog/Application/PriceListUseCasesTest.php @@ -3,27 +3,35 @@ use App\Modules\Catalog\Application\DTOs\ProductInput; use App\Modules\Catalog\Application\UseCases\AddProduct; use App\Modules\Catalog\Application\UseCases\AddServiceUnit; +use App\Modules\Catalog\Application\UseCases\AddVatRate; use App\Modules\Catalog\Application\UseCases\AddWorkType; use App\Modules\Catalog\Application\UseCases\MoveProduct; use App\Modules\Catalog\Application\UseCases\SetCatalogItemActive; use App\Modules\Catalog\Application\UseCases\SetHourlyRate; use App\Modules\Catalog\Application\UseCases\SetMileageRate; use App\Modules\Catalog\Application\UseCases\SetProductActive; +use App\Modules\Catalog\Application\UseCases\SetVatRateActive; use App\Modules\Catalog\Application\UseCases\UpdateProduct; +use App\Modules\Catalog\Application\UseCases\UpdateVatRate; use App\Modules\Catalog\Application\UseCases\UpdateWorkType; use App\Modules\Catalog\Domain\Enums\CatalogLevel; use App\Modules\Catalog\Domain\Enums\MoveDirection; use App\Modules\Catalog\Domain\Enums\ProductUnit; use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound; +use App\Modules\Catalog\Domain\Exceptions\DefaultVatRateMustBeActive; use App\Modules\Catalog\Domain\Exceptions\InvalidProductDuration; use App\Modules\Catalog\Domain\Exceptions\ProductNameTaken; use App\Modules\Catalog\Domain\Exceptions\ProductNeedsWorkType; +use App\Modules\Catalog\Domain\Exceptions\VatRateNameTaken; +use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound; use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount; +use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage; use Tests\Fakes\FakeSettings; use Tests\Fakes\FakeTransactionManager; use Tests\Fakes\InMemoryProductRepository; use Tests\Fakes\InMemoryServiceRepository; use Tests\Fakes\InMemoryServiceUnitRepository; +use Tests\Fakes\InMemoryVatRateRepository; use Tests\Fakes\InMemoryWorkTypeRepository; beforeEach(function () { @@ -32,6 +40,7 @@ beforeEach(function () { $this->workTypes = new InMemoryWorkTypeRepository; $this->products = new InMemoryProductRepository; $this->settings = new FakeSettings; + $this->vatRates = new InMemoryVatRateRepository; $transactions = new FakeTransactionManager; $this->addWorkType = new AddWorkType($units, $services, $this->workTypes, $transactions); @@ -39,8 +48,14 @@ beforeEach(function () { $this->setWorkTypeActive = new SetCatalogItemActive($units, $services, $this->workTypes, $transactions); $this->setHourlyRate = new SetHourlyRate($this->workTypes, $transactions); $this->setMileageRate = new SetMileageRate($this->settings); - $this->addProduct = new AddProduct($this->products, $this->workTypes, $transactions); - $this->updateProduct = new UpdateProduct($this->products, $this->workTypes, $transactions); + $this->addProduct = new AddProduct($this->products, $this->workTypes, $this->vatRates, $transactions); + $this->updateProduct = new UpdateProduct($this->products, $this->workTypes, $this->vatRates, $transactions); + $this->addVatRate = new AddVatRate($this->vatRates, $transactions); + $this->updateVatRate = new UpdateVatRate($this->vatRates, $transactions); + $this->setVatRateActive = new SetVatRateActive($this->vatRates, $transactions); + + $this->general = $this->addVatRate->execute('Yleinen', '25,5', makeDefault: true); + $this->reduced = $this->addVatRate->execute('Alennettu', '10'); $this->setProductActive = new SetProductActive($this->products, $transactions); $this->moveProduct = new MoveProduct($this->products, $transactions); @@ -48,9 +63,9 @@ beforeEach(function () { $this->passPhotos = $this->addWorkType->execute($consumer, null, 'passikuvat'); }); -function productInput(string $name, string $price = '15', string $duration = '', ?int $workTypeId = null): ProductInput +function productInput(string $name, string $price = '15', string $duration = '', ?int $workTypeId = null, int $vatRateId = 1): ProductInput { - return new ProductInput($name, ProductUnit::Piece, $price, true, $duration, $workTypeId); + return new ProductInput($name, ProductUnit::Piece, $price, $vatRateId, true, $duration, $workTypeId); } it('sets, changes and removes a work type hourly rate', function () { @@ -124,3 +139,35 @@ it('moves and deactivates products', function () { $this->setProductActive->execute($first, false); expect($this->products->findById($first)?->isActive())->toBeFalse(); }); + +it('keeps exactly one default VAT rate', function () { + $this->updateVatRate->execute($this->reduced, 'Alennettu', '10', makeDefault: true); + + expect($this->vatRates->findById($this->reduced)?->isDefault())->toBeTrue() + ->and($this->vatRates->findById($this->general)?->isDefault())->toBeFalse(); + + $this->updateVatRate->execute($this->reduced, 'Alennettu', '14'); + + expect($this->vatRates->findById($this->reduced)?->isDefault())->toBeTrue() + ->and($this->vatRates->findById($this->reduced)?->percentage()->basisPoints)->toBe(1400); +}); + +it('enforces VAT rate rules', function (Closure $change, string $exception) { + expect(fn () => $change->call($this))->toThrow($exception); +})->with([ + 'default stays in use' => [fn () => $this->setVatRateActive->execute($this->general, false), DefaultVatRateMustBeActive::class], + 'name taken, ignoring case' => [fn () => $this->addVatRate->execute('yleinen', '24'), VatRateNameTaken::class], + 'percentage at most 100' => [fn () => $this->addVatRate->execute('Liikaa', '101'), InvalidVatPercentage::class], + 'unknown rate for a product' => [fn () => $this->addProduct->execute(productInput('Tuloste', vatRateId: 99)), VatRateNotFound::class], +]); + +it('does not let an inactive VAT rate be chosen anew but keeps it on a product', function () { + $id = $this->addProduct->execute(productInput('Passikuvat', vatRateId: $this->reduced)); + $this->setVatRateActive->execute($this->reduced, false); + + $this->updateProduct->execute($id, productInput('Passikuvat', '20', vatRateId: $this->reduced)); + expect($this->products->findById($id)?->vatRateId())->toBe($this->reduced); + + expect(fn () => $this->addProduct->execute(productInput('Tuloste', vatRateId: $this->reduced))) + ->toThrow(VatRateNotFound::class); +}); diff --git a/tests/Unit/Modules/Shared/MoneyTest.php b/tests/Unit/Modules/Shared/MoneyTest.php index 0999676..0d53cff 100644 --- a/tests/Unit/Modules/Shared/MoneyTest.php +++ b/tests/Unit/Modules/Shared/MoneyTest.php @@ -1,7 +1,9 @@ cents)->toBe($cents); @@ -28,3 +30,29 @@ it('formats with a no-break space and the currency', function () { expect($money->format())->toBe("1\u{00A0}200,50\u{00A0}€") ->and($money->inputValue())->toBe('1200,50'); }); + +it('adds and removes VAT, rounding half up to the cent', function (int $net, string $vat, int $gross) { + $percentage = VatPercentage::parse($vat); + + expect(Money::fromCents($net)->addVat($percentage)->cents)->toBe($gross); +})->with([ + 'general rate' => [1434, '25,5', 1800], + 'rounds half up' => [2, '25', 3], + 'reduced rate' => [1000, '13,5', 1135], + 'zero rate' => [999, '0', 999], +]); + +it('works out the price without VAT from a consumer price', function () { + expect(Money::fromCents(1800)->removeVat(VatPercentage::parse('25,5'))->cents)->toBe(1434) + ->and(Money::fromCents(1000)->removeVat(VatPercentage::parse('0'))->cents)->toBe(1000); +}); + +it('parses and formats VAT percentages', function () { + expect(VatPercentage::parse('25,5 %')->basisPoints)->toBe(2550) + ->and(VatPercentage::parse('13.5')->format())->toBe("13,5\u{00A0}%") + ->and(VatPercentage::parse('0')->inputValue())->toBe('0'); +}); + +it('rejects invalid VAT percentages', function (string $typed) { + VatPercentage::parse($typed); +})->throws(InvalidVatPercentage::class)->with(['', '-1', '100,01', '12,345', 'abc']); diff --git a/tests/Unit/Modules/Users/Domain/UserAccountTest.php b/tests/Unit/Modules/Users/Domain/UserAccountTest.php index cc3c592..5b1b8d3 100644 --- a/tests/Unit/Modules/Users/Domain/UserAccountTest.php +++ b/tests/Unit/Modules/Users/Domain/UserAccountTest.php @@ -2,6 +2,7 @@ use App\Modules\Shared\Domain\ValueObjects\EmailAddress; use App\Modules\Users\Domain\Entities\UserAccount; +use App\Modules\Users\Domain\Enums\MoneyPermission; use App\Modules\Users\Domain\Enums\Role; use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor; use App\Modules\Users\Domain\Exceptions\InvalidSupervisor; @@ -72,3 +73,13 @@ it('does not let an inactive user log in', function () { expect($user->canLogInOn(new DateTimeImmutable('2026-01-01')))->toBeFalse() ->and($user->isActiveAdmin())->toBeFalse(); }); + +it('keeps money permissions only for employees and interns', function () { + $user = UserAccount::register(new PersonName('Eero'), new EmailAddress('eero@example.test'), Role::Employee, moneyPermissions: [MoneyPermission::Quotes, MoneyPermission::Prices]); + + expect($user->moneyPermissions())->toBe([MoneyPermission::Prices, MoneyPermission::Quotes]); + + $user->changeDetails($user->name(), $user->email(), Role::Management, true, null, null, [MoneyPermission::Prices]); + + expect($user->moneyPermissions())->toBe([]); +});