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:
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
+58
-2
@@ -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,
|
||||
|
||||
+2
@@ -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,
|
||||
|
||||
+77
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -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
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user