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 <[email protected]>
This commit is contained in:
2026-11-24 07:51:19 +02:00
co-authored by Claude Opus 5.5
parent dc2612cf46
commit bdd8d446d8
68 changed files with 2222 additions and 64 deletions
+2 -2
View File
@@ -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` (`<module>::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/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>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.
+26
View File
@@ -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<UserMoneyPermissionsModel, $this>
*/
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.
*
@@ -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<ProductSummary>
*/
public function consumerProducts(): array;
/**
* Price of a driven kilometre in cents (VAT 0), null when not set.
*/
public function mileageRateCents(): ?int;
/**
* @return list<VatRateSummary>
*/
public function vatRates(bool $includeInactive = true): array;
public function findVatRate(int $id): ?VatRateSummary;
public function defaultVatRate(): ?VatRateSummary;
}
@@ -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,
@@ -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,
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\DTOs;
/**
* A VAT rate with its percentage in hundredths of a percent (2550 = 25,5 %).
*/
final readonly class VatRateSummary
{
public function __construct(
public int $id,
public string $name,
public int $basisPoints,
public bool $isDefault,
public bool $isActive,
) {}
}
@@ -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\Entities\Product;
use App\Modules\Catalog\Domain\Exceptions\CatalogItemNotFound;
@@ -13,6 +14,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\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
@@ -24,6 +26,7 @@ final class AddProduct
public function __construct(
private ProductRepository $products,
private WorkTypeRepository $workTypes,
private VatRateRepository $vatRates,
private TransactionManager $transactions,
) {}
@@ -36,6 +39,7 @@ final class AddProduct
* @throws InvalidProductDuration
* @throws ProductNameTaken
* @throws ProductNeedsWorkType
* @throws VatRateNotFound
*/
public function execute(ProductInput $input): int
{
@@ -43,6 +47,7 @@ final class AddProduct
return $this->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,
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Entities\VatRate;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\VatRateNameTaken;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* Adds a VAT rate last in the list, optionally as the new default.
*/
final class AddVatRate
{
public function __construct(
private VatRateRepository $vatRates,
private TransactionManager $transactions,
) {}
/**
* @return int The new rate's id.
*
* @throws InvalidCatalogName
* @throws InvalidVatPercentage
* @throws VatRateNameTaken
*/
public function execute(string $name, string $percentage, bool $makeDefault = false): int
{
$name = new CatalogName($name);
$percentage = VatPercentage::parse($percentage);
return $this->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();
});
}
}
@@ -0,0 +1,28 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Entities\VatRate;
/**
* Keeps exactly one default VAT rate. Called inside the caller's transaction.
*
* @internal
*/
final class DefaultVatRate
{
public static function moveTo(VatRate $vatRate, VatRateRepository $vatRates): void
{
$current = $vatRates->findDefault();
if ($current !== null && $current->id() !== $vatRate->id()) {
$current->clearDefault();
$vatRates->save($current);
}
$vatRate->makeDefault();
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Moves a VAT rate one place up or down in the list.
*/
final class MoveVatRate
{
public function __construct(
private VatRateRepository $vatRates,
private TransactionManager $transactions,
) {}
/**
* @return bool False when the rate already was first (up) or last (down).
*
* @throws VatRateNotFound
*/
public function execute(int $vatRateId, MoveDirection $direction): bool
{
return $this->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;
});
}
}
@@ -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.
*
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Exceptions\DefaultVatRateMustBeActive;
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Takes a VAT rate out of use or back into use. A rate out of use cannot be
* chosen for products anew; products that have it keep it.
*/
final class SetVatRateActive
{
public function __construct(
private VatRateRepository $vatRates,
private TransactionManager $transactions,
) {}
/**
* @throws DefaultVatRateMustBeActive
* @throws VatRateNotFound
*/
public function execute(int $vatRateId, bool $active): void
{
$this->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);
});
}
}
@@ -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);
});
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Application\UseCases;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\VatRateNameTaken;
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* Renames a VAT rate and changes its percentage, which then applies to every
* product using it. $makeDefault moves the default to this rate; the
* default cannot be cleared, only moved to another rate.
*/
final class UpdateVatRate
{
public function __construct(
private VatRateRepository $vatRates,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidCatalogName
* @throws InvalidVatPercentage
* @throws VatRateNameTaken
* @throws VatRateNotFound
*/
public function execute(int $vatRateId, string $name, string $percentage, bool $makeDefault = false): void
{
$name = new CatalogName($name);
$percentage = VatPercentage::parse($percentage);
$this->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);
});
}
}
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Contracts;
use App\Modules\Catalog\Domain\Entities\VatRate;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
interface VatRateRepository
{
public function findById(int $id): ?VatRate;
public function findDefault(): ?VatRate;
/**
* Inserts a new rate or updates a stored one, and returns the stored rate.
*/
public function save(VatRate $vatRate): VatRate;
/**
* Whether a rate other than $exceptId has this name, ignoring case.
*/
public function isNameTaken(string $name, ?int $exceptId = null): bool;
/**
* The sort order that puts a new rate last.
*/
public function nextSortOrder(): int;
/**
* The rate just before or after this one, or null at either end.
*/
public function neighbour(VatRate $vatRate, MoveDirection $direction): ?VatRate;
}
@@ -11,9 +11,11 @@ use App\Modules\Catalog\Domain\ValueObjects\ProductDuration;
use App\Modules\Shared\Domain\ValueObjects\Money;
/**
* A fixed-price product (passikuvat, tulosteet). Consumer products' prices
* are visible to every user. Selling a product with a duration books those
* hours for the seller on the product's work type.
* A fixed-price product (passikuvat, tulosteet) with a VAT rate. Consumer
* products' prices are visible to every user and are entered and stored
* with VAT, so cash prices stay round; other prices are without VAT.
* Selling a product with a duration books those hours for the seller on
* the product's work type.
*/
final class Product extends CatalogItem
{
@@ -22,6 +24,7 @@ final class Product extends CatalogItem
CatalogName $name,
private ProductUnit $unit,
private Money $price,
private int $vatRateId,
private bool $consumerProduct,
private ProductDuration $duration,
private ?int $workTypeId,
@@ -34,28 +37,29 @@ final class Product extends CatalogItem
/**
* @throws ProductNeedsWorkType
*/
public static function create(CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, int $sortOrder): self
public static function create(CatalogName $name, ProductUnit $unit, Money $price, int $vatRateId, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, int $sortOrder): self
{
self::ensureWorkTypeForDuration($duration, $workTypeId);
return new self(null, $name, $unit, $price, $consumerProduct, $duration, $workTypeId, true, $sortOrder);
return new self(null, $name, $unit, $price, $vatRateId, $consumerProduct, $duration, $workTypeId, true, $sortOrder);
}
public static function reconstitute(int $id, CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, bool $active, int $sortOrder): self
public static function reconstitute(int $id, CatalogName $name, ProductUnit $unit, Money $price, int $vatRateId, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId, bool $active, int $sortOrder): self
{
return new self($id, $name, $unit, $price, $consumerProduct, $duration, $workTypeId, $active, $sortOrder);
return new self($id, $name, $unit, $price, $vatRateId, $consumerProduct, $duration, $workTypeId, $active, $sortOrder);
}
/**
* @throws ProductNeedsWorkType
*/
public function update(CatalogName $name, ProductUnit $unit, Money $price, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId): void
public function update(CatalogName $name, ProductUnit $unit, Money $price, int $vatRateId, bool $consumerProduct, ProductDuration $duration, ?int $workTypeId): void
{
self::ensureWorkTypeForDuration($duration, $workTypeId);
$this->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;
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Entities;
use App\Modules\Catalog\Domain\Exceptions\DefaultVatRateMustBeActive;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
/**
* A VAT rate products are sold with, e.g. "Yleinen 25,5 %". When the law
* changes, the percentage is changed and every product using the rate
* follows. The default rate applies to hours, expenses and mileage, so it
* is always in use.
*/
final class VatRate extends CatalogItem
{
private function __construct(
?int $id,
CatalogName $name,
private VatPercentage $percentage,
private bool $default,
bool $active,
int $sortOrder,
) {
parent::__construct($id, $name, $active, $sortOrder);
}
public static function create(CatalogName $name, VatPercentage $percentage, int $sortOrder): self
{
return new self(null, $name, $percentage, false, true, $sortOrder);
}
public static function reconstitute(int $id, CatalogName $name, VatPercentage $percentage, bool $default, bool $active, int $sortOrder): self
{
return new self($id, $name, $percentage, $default, $active, $sortOrder);
}
public function changePercentage(VatPercentage $percentage): void
{
$this->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;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class DefaultVatRateMustBeActive extends DomainException
{
public function __construct()
{
parent::__construct('The default VAT rate cannot be taken out of use.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class VatRateNameTaken extends DomainException
{
public function __construct()
{
parent::__construct('Another VAT rate already has this name.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Catalog\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class VatRateNotFound extends DomainException
{
public function __construct(public readonly int $vatRateId)
{
parent::__construct("VAT rate {$vatRateId} was not found.");
}
}
@@ -17,15 +17,17 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
* @property string $name
* @property string $unit
* @property int $price_cents
* @property int|null $vat_rate_id
* @property bool $is_consumer_product
* @property string $auto_hours
* @property int|null $work_type_id
* @property bool $is_active
* @property int $sort_order
* @property-read WorkTypeModel|null $workType
* @property-read VatRateModel|null $vatRate
*/
#[Table('products')]
#[Fillable(['name', 'unit', 'price_cents', 'is_consumer_product', 'auto_hours', 'work_type_id', 'is_active', 'sort_order'])]
#[Fillable(['name', 'unit', 'price_cents', 'vat_rate_id', 'is_consumer_product', 'auto_hours', 'work_type_id', 'is_active', 'sort_order'])]
#[UseFactory(ProductFactory::class)]
class ProductModel extends Model
{
@@ -40,6 +42,14 @@ class ProductModel extends Model
return $this->belongsTo(WorkTypeModel::class, 'work_type_id');
}
/**
* @return BelongsTo<VatRateModel, $this>
*/
public function vatRate(): BelongsTo
{
return $this->belongsTo(VatRateModel::class, 'vat_rate_id');
}
/**
* @return array<string, string>
*/
@@ -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',
@@ -0,0 +1,42 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Eloquent;
use Database\Factories\VatRateFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Catalog Infrastructure layer.
*
* @property int $id
* @property string $name
* @property int $basis_points
* @property bool $is_default
* @property bool $is_active
* @property int $sort_order
*/
#[Table('vat_rates')]
#[Fillable(['name', 'basis_points', 'is_default', 'is_active', 'sort_order'])]
#[UseFactory(VatRateFactory::class)]
class VatRateModel extends Model
{
/** @use HasFactory<VatRateFactory> */
use HasFactory;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'basis_points' => 'integer',
'is_default' => 'boolean',
'is_active' => 'boolean',
'sort_order' => 'integer',
];
}
}
@@ -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,
@@ -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,
@@ -0,0 +1,77 @@
<?php
namespace App\Modules\Catalog\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Entities\VatRate;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
use App\Modules\Catalog\Domain\ValueObjects\CatalogName;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\VatRateModel;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
class EloquentVatRateRepository implements VatRateRepository
{
public function findById(int $id): ?VatRate
{
$model = VatRateModel::query()->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,
);
}
}
@@ -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);
}
}
@@ -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'),
];
@@ -0,0 +1,231 @@
<?php
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\DTOs\HourlyRateGroup;
use App\Modules\Catalog\Application\DTOs\ProductSummary;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
use Livewire\Attributes\Computed;
use Livewire\Component;
/**
* The price list for reading. Consumer product prices with VAT are shown to
* everyone but subcontractors; hourly rates, other products and the
* mileage rate only to those who may see prices (`money.prices`). Amounts
* stay in computed properties, never in public ones sent to the browser.
*/
new class extends Component
{
public function mount(): void
{
$this->authorize('catalog.view-prices');
}
#[Computed]
public function canSeePrices(): bool
{
return auth()->user()?->can('money.prices') ?? false;
}
/**
* @return list<ProductSummary>
*/
#[Computed]
public function consumerProducts(): array
{
return app(PriceListQueries::class)->consumerProducts();
}
/**
* Active products that are not consumer products; only with the price permission.
*
* @return list<ProductSummary>
*/
#[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<HourlyRateGroup>
*/
#[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<array{index: string, label: string, sortable: bool, align?: string}>
*/
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<array{index: string, label: string, sortable: bool, align?: string}>
*/
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'));
}
};
?>
<div class="mx-auto max-w-5xl space-y-8 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('catalog.prices.title') }}</h1>
<section aria-labelledby="consumer-products-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="consumer-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.consumer_products') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.consumer_help') }}</p>
</div>
@if ($this->consumerProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
@else
<x-table :headers="$this->consumerHeaders()" :rows="$this->consumerProducts">
@interact('column_name', $product)
<span class="font-medium break-words">{{ $product->name }}</span>
@endinteract
@interact('column_unit', $product)
{{ __('catalog.units.'.$product->unit->value) }}
@endinteract
@interact('column_gross', $product)
<span class="whitespace-nowrap font-medium">{{ $this->money($product->grossCents) }}</span>
@endinteract
@interact('column_vat', $product)
<span class="whitespace-nowrap">{{ $this->percentage($product->vatBasisPoints) }}</span>
@endinteract
</x-table>
@endif
</section>
@if ($this->canSeePrices)
<section aria-labelledby="hourly-rates-heading" class="space-y-4">
<div class="space-y-1">
<h2 id="hourly-rates-heading" class="text-xl font-semibold">{{ __('catalog.prices.hourly_rates') }}</h2>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.hourly_help') }}</p>
</div>
@foreach ($this->hourlyRates as $group)
<table wire:key="rates-{{ $group->serviceUnitId }}" class="w-full border-collapse text-sm">
<caption class="pb-2 text-left text-lg font-medium break-words">{{ $group->serviceUnitName }}</caption>
<thead>
<tr class="border-b border-zinc-300 dark:border-zinc-600">
<th scope="col" class="py-2 pr-3 text-left font-semibold">{{ __('catalog.prices.work_type') }}</th>
<th scope="col" class="w-32 py-2 text-right font-semibold">{{ __('catalog.prices.hourly_rate') }}</th>
</tr>
</thead>
<tbody>
@foreach ($group->rows as $row)
<tr wire:key="rate-{{ $row->workTypeId }}" class="border-b border-zinc-200 dark:border-zinc-700">
<th scope="row" class="py-2 pr-3 text-left font-normal break-words">
@if ($row->serviceName !== null)
<span class="text-zinc-600 dark:text-zinc-300">{{ $row->serviceName }}:</span>
@endif
{{ $row->name }}
</th>
<td class="py-2 text-right whitespace-nowrap">
{{ $row->hourlyRateCents === null ? __('catalog.price_list.no_price') : $this->money($row->hourlyRateCents) }}
</td>
</tr>
@endforeach
</tbody>
</table>
@endforeach
</section>
<section aria-labelledby="other-products-heading" class="space-y-4">
<h2 id="other-products-heading" class="text-xl font-semibold">{{ __('catalog.price_list.other_products') }}</h2>
@if ($this->otherProducts === [])
<p class="text-sm">{{ __('catalog.products.none') }}</p>
@else
<x-table :headers="$this->otherHeaders()" :rows="$this->otherProducts">
@interact('column_name', $product)
<span class="font-medium break-words">{{ $product->name }}</span>
@endinteract
@interact('column_unit', $product)
{{ __('catalog.units.'.$product->unit->value) }}
@endinteract
@interact('column_net', $product)
<span class="whitespace-nowrap">{{ $this->money($product->netCents) }}</span>
@endinteract
@interact('column_gross', $product)
<span class="whitespace-nowrap">{{ $this->money($product->grossCents) }}</span>
@endinteract
@interact('column_vat', $product)
<span class="whitespace-nowrap">{{ $this->percentage($product->vatBasisPoints) }}</span>
@endinteract
</x-table>
@endif
</section>
<section aria-labelledby="mileage-heading" class="space-y-2">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
<p>
{{ $this->mileageRateCents === null
? __('catalog.price_list.no_price')
: __('catalog.price_list.mileage_value', ['rate' => $this->money($this->mileageRateCents)]) }}
</p>
</section>
@else
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.price_list.no_permission') }}</p>
@endif
</div>
@@ -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<VatRateSummary>
*/
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<array{index: string, label: string, sortable: bool}>
*/
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)
<span class="whitespace-nowrap">{{ $this->money($product->priceCents) }}</span>
@interact('column_net', $product)
<span class="whitespace-nowrap">{{ $this->money($product->netCents) }}</span>
@unless ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span>
@endunless
@endinteract
@interact('column_gross', $product)
<span class="whitespace-nowrap">{{ $this->money($product->grossCents) }}</span>
@if ($product->priceIncludesVat)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.entered') }}</span>
@endif
@endinteract
@interact('column_vat', $product)
<span class="whitespace-nowrap">{{ $this->percentage($product->vatBasisPoints) }}</span>
@endinteract
@interact('column_consumer', $product)
@@ -352,6 +437,41 @@ new class extends Component
@endif
</section>
<section aria-labelledby="vat-rates-heading" class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-4">
<h2 id="vat-rates-heading" class="text-xl font-semibold">{{ __('catalog.vat_rates.title') }}</h2>
<x-button :href="route('catalog.vat-rates.create')" wire:navigate icon="plus" :text="__('catalog.vat_rates.add')" />
</div>
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.help') }}</p>
<x-table :headers="$this->vatRateHeaders()" :rows="$this->vatRates">
@interact('column_name', $vatRate)
<span class="font-medium break-words">{{ $vatRate->name }}</span>
@unless ($vatRate->isActive)
<span class="ml-1 text-sm">({{ __('catalog.inactive') }})</span>
@endunless
@endinteract
@interact('column_percentage', $vatRate)
<span class="whitespace-nowrap">{{ $this->percentage($vatRate->basisPoints) }}</span>
@endinteract
@interact('column_default', $vatRate)
{{ $vatRate->isDefault ? __('catalog.vat_rates.is_default') : '' }}
@endinteract
@interact('column_actions', $vatRate)
<x-catalog.item-actions
level="vat_rate"
:id="$vatRate->id"
:name="$vatRate->name"
:active="$vatRate->isActive"
:edit-url="route('catalog.vat-rates.edit', $vatRate->id)"
/>
@endinteract
</x-table>
</section>
<section aria-labelledby="mileage-heading" class="space-y-4">
<h2 id="mileage-heading" class="text-xl font-semibold">{{ __('catalog.mileage.title') }}</h2>
@@ -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<VatRateSummary>
*/
#[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
</x-select.native>
<x-input
wire:model="form.price"
:label="__('catalog.products.price')"
:hint="__('catalog.products.price_help')"
inputmode="decimal"
autocomplete="off"
required
/>
<div class="space-y-1">
<x-checkbox id="product-consumer" wire:model.live="form.is_consumer_product" :label="__('catalog.products.consumer')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.consumer_help') }}</p>
</div>
<x-select.native wire:model.live="form.vat_rate_id" :label="__('catalog.products.vat_rate')" :aria-label="__('catalog.products.vat_rate')">
@foreach ($this->vatRates as $vatRate)
<option wire:key="vat-rate-option-{{ $vatRate->id }}" value="{{ $vatRate->id }}">
{{ $vatRate->name }} ({{ (new VatPercentage($vatRate->basisPoints))->format() }})@unless ($vatRate->isActive), {{ __('catalog.inactive') }}@endunless
</option>
@endforeach
</x-select.native>
<div class="space-y-1">
<x-checkbox id="product-consumer" wire:model="form.is_consumer_product" :label="__('catalog.products.consumer')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.products.consumer_help') }}</p>
<x-input
wire:model.blur="form.price"
:label="__($form->is_consumer_product ? 'catalog.products.price_gross' : 'catalog.products.price_net')"
:hint="__($form->is_consumer_product ? 'catalog.products.price_gross_help' : 'catalog.products.price_help')"
inputmode="decimal"
autocomplete="off"
required
/>
<p aria-live="polite" class="min-h-5 text-sm">{{ $this->otherPrice() }}</p>
</div>
<fieldset class="space-y-4 rounded-lg border border-zinc-200 p-4 dark:border-zinc-700">
@@ -0,0 +1,138 @@
<?php
use App\Modules\Catalog\Application\Contracts\PriceListQueries;
use App\Modules\Catalog\Application\UseCases\AddVatRate;
use App\Modules\Catalog\Application\UseCases\UpdateVatRate;
use App\Modules\Catalog\Domain\Exceptions\InvalidCatalogName;
use App\Modules\Catalog\Domain\Exceptions\VatRateNameTaken;
use App\Modules\Catalog\Domain\Exceptions\VatRateNotFound;
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Add page (no {vatRate}) and edit page (with {vatRate}) of a VAT rate.
*/
new class extends Component
{
#[Locked]
public ?int $vatRateId = null;
/**
* Whether the edited rate already is the default, which can only be moved to another rate.
*/
#[Locked]
public bool $isDefault = false;
public string $name = '';
public string $percentage = '';
public bool $makeDefault = false;
public function mount(PriceListQueries $priceList, ?int $vatRate = null): void
{
$this->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());
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ $this->heading() }}</h1>
@if ($vatRateId !== null)
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.change_help') }}</p>
@endif
<form wire:submit="save" class="space-y-6" novalidate>
<x-input wire:model="name" :label="__('catalog.fields.name')" :hint="__('catalog.vat_rates.name_help')" autocomplete="off" required />
<x-input
wire:model="percentage"
:label="__('catalog.vat_rates.percentage')"
:hint="__('catalog.vat_rates.percentage_help')"
inputmode="decimal"
autocomplete="off"
required
/>
@if ($isDefault)
<p class="text-sm">{{ __('catalog.vat_rates.is_default_help') }}</p>
@else
<div class="space-y-1">
<x-checkbox id="vat-rate-default" wire:model="makeDefault" :label="__('catalog.vat_rates.make_default')" />
<p class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('catalog.vat_rates.make_default_help') }}</p>
</div>
@endif
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('catalog.save')" />
<x-button :href="route('catalog.prices')" wire:navigate subtle color="black" :text="__('catalog.cancel')" />
</div>
</form>
</div>
@@ -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');
});
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\Exceptions;
final class InvalidVatPercentage extends DomainException
{
public function __construct()
{
parent::__construct('A VAT rate must be 0–100 % with at most two decimals.');
}
}
@@ -55,6 +55,24 @@ final readonly class Money
return new self((int) $matches[1] * 100 + (int) $fraction);
}
/**
* This amount without VAT plus the VAT, rounded half up to the cent.
*/
public function addVat(VatPercentage $vat): self
{
return new self(intdiv($this->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 €".
*/
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Modules\Shared\Domain\ValueObjects;
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
/**
* A VAT rate such as 25,5 %, stored in hundredths of a percent (2550) so
* that calculations stay in whole numbers.
*/
final readonly class VatPercentage
{
public const int MAX_BASIS_POINTS = 10_000;
public int $basisPoints;
public function __construct(int $basisPoints)
{
if ($basisPoints < 0 || $basisPoints > 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'), '.'));
}
}
@@ -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<MoneyPermission> $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<string>} $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'] ?? []),
);
}
}
@@ -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<MoneyPermission> $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 = [],
) {}
}
@@ -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 {
@@ -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;
@@ -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<MoneyPermission> $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<MoneyPermission> $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<MoneyPermission> $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<MoneyPermission> $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<MoneyPermission>
*/
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;
@@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Enums;
/**
* Personal permissions of employees and interns to see money amounts.
* Admins and management see all amounts by role; subcontractors none.
* Other modules check these through the `money.<value>` 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<self|string> $values
* @return list<self>
*/
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)));
}
}
+16
View File
@@ -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.
*/
@@ -0,0 +1,70 @@
<?php
namespace App\Modules\Users\Infrastructure\Persistence\Eloquent;
use App\Modules\Users\Domain\Enums\MoneyPermission;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model, used only inside the Users Infrastructure layer.
*
* @property int $id
* @property int $user_id
* @property bool $can_see_prices
* @property bool $can_see_expenses
* @property bool $can_see_quotes
* @property bool $can_see_billing
*/
#[Table('user_money_permissions')]
#[Fillable(['user_id', 'can_see_prices', 'can_see_expenses', 'can_see_quotes', 'can_see_billing'])]
class UserMoneyPermissionsModel extends Model
{
public static function column(MoneyPermission $permission): string
{
return 'can_see_'.$permission->value;
}
/**
* @param list<MoneyPermission> $permissions
* @return array<string, bool>
*/
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<MoneyPermission>
*/
public function permissions(): array
{
return array_values(array_filter(MoneyPermission::cases(), fn (MoneyPermission $permission): bool => $this->allows($permission)));
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_id' => 'integer',
'can_see_prices' => 'boolean',
'can_see_expenses' => 'boolean',
'can_see_quotes' => 'boolean',
'can_see_billing' => 'boolean',
];
}
}
@@ -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() ?? [],
);
}
}
@@ -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() ?? [],
);
}
}
@@ -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(
@@ -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<string>
*/
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;
}
}
}],
];
}
@@ -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
</x-select.native>
@endif
@if ($form->hasMoneyPermissions())
<x-checkbox-group
:legend="__('users.money_permissions.legend')"
model="form.money_permissions"
:hint="__('users.money_permissions.hint')"
:columns="false"
:options="collect(MoneyPermission::cases())->map(fn (MoneyPermission $permission) => [
'value' => $permission->value,
'label' => __('users.money_permissions.'.$permission->value),
'note' => __('users.money_permissions.'.$permission->value.'_note'),
])->all()"
/>
@endif
<div>
<x-checkbox wire:model="form.active" :label="__('users.fields.active')" aria-describedby="active-description" />
<p id="active-description" class="mt-1 text-sm text-zinc-600 dark:text-zinc-300">{{ __('users.fields.active_description') }}</p>
+2
View File
@@ -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,
+15
View File
@@ -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)),
);
});
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace Database\Factories;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\VatRateModel;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<VatRateModel>
*/
class VatRateFactory extends Factory
{
protected $model = VatRateModel::class;
/**
* @return array<string, mixed>
*/
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]);
}
}
@@ -0,0 +1,47 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* VAT rates in hundredths of a percent (2550 = 25,5 %). One rate is the
* default, used for hours, expenses and mileage. Rows are never
* deleted, only deactivated.
*/
public function up(): void
{
Schema::create('vat_rates', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Every product has a VAT rate; existing products get the default one.
* The column stays nullable in the database, the domain requires it.
*/
public function up(): void
{
Schema::table('products', function (Blueprint $table) {
$table->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');
});
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Personal permissions of employees and interns to see money amounts.
* Admins and management see all amounts by role.
*/
public function up(): void
{
Schema::create('user_money_permissions', function (Blueprint $table) {
$table->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');
}
};
+12 -5
View File
@@ -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
+47 -4
View File
@@ -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.',
],
];
+14
View File
@@ -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.',
+3 -1
View File
@@ -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')
+22 -1
View File
@@ -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'],
]);
@@ -26,6 +26,7 @@ class InMemoryProductRepository implements ProductRepository
$product->name(),
$product->unit(),
$product->price(),
$product->vatRateId(),
$product->isConsumerProduct(),
$product->duration(),
$product->workTypeId(),
@@ -43,6 +43,7 @@ class InMemoryUserAccountRepository implements UserAccountRepository
$user->isActive(),
$user->employmentEndsOn(),
$user->supervisorId(),
$user->moneyPermissions(),
);
return clone $this->users[$id];
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace Tests\Fakes;
use App\Modules\Catalog\Domain\Contracts\VatRateRepository;
use App\Modules\Catalog\Domain\Entities\VatRate;
use App\Modules\Catalog\Domain\Enums\MoveDirection;
class InMemoryVatRateRepository implements VatRateRepository
{
/** @var array<int, VatRate> */
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;
}
}
@@ -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')]]);
});
@@ -0,0 +1,55 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Application\UseCases\SetMileageRate;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ProductModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Shared\Application\Contracts\Settings;
use App\Modules\Users\Domain\Enums\MoneyPermission;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
ProductModel::factory()->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();
});
@@ -0,0 +1,59 @@
<?php
use App\Models\User;
use App\Modules\Users\Domain\Enums\MoneyPermission;
use App\Modules\Users\Infrastructure\Persistence\Eloquent\UserMoneyPermissionsModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Notification;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('lets admins and management see all money, employees and interns only by permission, subcontractors none', function (Closure $makeUser, array $abilities) {
$user = $makeUser();
foreach (['prices', 'expenses', 'quotes', 'billing'] as $ability) {
expect(Gate::forUser($user)->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']);
});
@@ -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);
});
+28
View File
@@ -1,7 +1,9 @@
<?php
use App\Modules\Shared\Domain\Exceptions\InvalidMoneyAmount;
use App\Modules\Shared\Domain\Exceptions\InvalidVatPercentage;
use App\Modules\Shared\Domain\ValueObjects\Money;
use App\Modules\Shared\Domain\ValueObjects\VatPercentage;
it('parses euro amounts typed in Finnish or English notation', function (string $typed, int $cents) {
expect(Money::parse($typed)?->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']);
@@ -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('[email protected]'), 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([]);
});