Return stock of cancelled maintenance, throttle the PIN page's password

Cancelling a maintenance record now reverses the stock it used, through
Inventory's new ReverseMaintenanceStockUse behind the MaintenanceMaterials
port, in the same transaction as the cancellation.

The PIN page allows 5 wrong current passwords a minute per user, as the
login form does, so a signed-in session cannot be used to guess the
password.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-29 10:10:18 +02:00
co-authored by Claude Sonnet 5.5
parent 6692396a63
commit ef400054b0
11 changed files with 159 additions and 9 deletions
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace App\Modules\Inventory\Application\UseCases;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Exceptions\StockMovementAlreadyReversed;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotFound;
use App\Modules\Inventory\Domain\Exceptions\StockMovementNotReversible;
use App\Modules\Inventory\Domain\Exceptions\StockReversalNotAllowed;
use App\Modules\Shared\Application\Contracts\TransactionManager;
/**
* Returns the stock a cancelled maintenance record used (spec 19.5): each
* of its use movements not yet reversed gets a reversal, recorded today.
*/
final class ReverseMaintenanceStockUse
{
public function __construct(
private StockMovementRepository $movements,
private ReverseStockMovement $reverse,
private TransactionManager $transactions,
) {}
/**
* @return int How many movements were reversed.
*
* @throws StockMovementNotFound
* @throws StockMovementNotReversible
* @throws StockMovementAlreadyReversed
* @throws StockReversalNotAllowed
*/
public function execute(int $maintenanceRecordId, int $actorUserId): int
{
return $this->transactions->run(function () use ($maintenanceRecordId, $actorUserId): int {
$movementIds = $this->movements->unreversedUseOfMaintenance($maintenanceRecordId);
foreach ($movementIds as $movementId) {
$this->reverse->execute($movementId, $actorUserId, true);
}
return count($movementIds);
});
}
}
@@ -14,6 +14,13 @@ interface StockMovementRepository
public function isReversed(int $movementId): bool;
/**
* The ids of a maintenance record's use movements that are not reversed.
*
* @return list<int>
*/
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array;
/**
* The item's balance in thousandths: the sum of its movements.
*/
@@ -4,6 +4,7 @@ namespace App\Modules\Inventory\Infrastructure\Persistence\Repositories;
use App\Modules\Inventory\Domain\Contracts\StockMovementRepository;
use App\Modules\Inventory\Domain\Entities\StockMovement;
use App\Modules\Inventory\Domain\Enums\StockMovementKind;
use App\Modules\Inventory\Domain\ValueObjects\StockUseTarget;
use App\Modules\Inventory\Infrastructure\Persistence\Eloquent\StockMovementModel;
use DateTimeImmutable;
@@ -50,6 +51,19 @@ class EloquentStockMovementRepository implements StockMovementRepository
return StockMovementModel::query()->where('reverses_movement_id', $movementId)->exists();
}
public function unreversedUseOfMaintenance(int $maintenanceRecordId): array
{
return StockMovementModel::query()
->where('maintenance_record_id', $maintenanceRecordId)
->where('kind', StockMovementKind::Consumption)
->whereNotIn('id', StockMovementModel::query()->whereNotNull('reverses_movement_id')->select('reverses_movement_id'))
->orderBy('id')
->pluck('id')
->map(fn (mixed $id): int => (int) $id)
->values()
->all();
}
public function balanceOf(int $itemId): int
{
return (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli');
@@ -13,4 +13,9 @@ interface MaintenanceMaterials
* @return bool False when the stock could not be recorded (e.g. the item is out of use).
*/
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool;
/**
* Returns the stock a cancelled maintenance record used.
*/
public function returnUseOf(int $maintenanceRecordId, int $userId): void;
}
@@ -27,7 +27,7 @@ use App\Modules\Users\Application\Contracts\Clock;
* management; counter usage and maintenance done are recorded by
* anyone using the machine. A maintenance record starts the item's
* intervals again and uses up its stock item; a mistaken record is
* cancelled by management, never deleted.
* cancelled by management, never deleted, and its stock use reversed.
*/
final class MachineMaintenance
{
@@ -169,6 +169,7 @@ final class MachineMaintenance
}
$this->maintenance->cancelRecord($recordId, $actorUserId, $this->clock->now());
$this->materials->returnUseOf($recordId, $actorUserId);
});
}
}
@@ -4,17 +4,22 @@ namespace App\Modules\Machines\Infrastructure\Adapters;
use App\Modules\Inventory\Application\DTOs\StockUseData;
use App\Modules\Inventory\Application\UseCases\RecordStockUse;
use App\Modules\Inventory\Application\UseCases\ReverseMaintenanceStockUse;
use App\Modules\Inventory\Domain\ValueObjects\StockQuantity;
use App\Modules\Machines\Application\Contracts\MaintenanceMaterials;
use App\Modules\Shared\Domain\Exceptions\DomainException;
/**
* Records stock used at machine maintenance through the Inventory module.
* A failure (e.g. the item is out of use) does not undo the maintenance.
* Records stock used at machine maintenance through the Inventory module,
* and returns it when the maintenance record is cancelled. A failure to
* record (e.g. the item is out of use) does not undo the maintenance.
*/
class StockForMachines implements MaintenanceMaterials
{
public function __construct(private RecordStockUse $recordUse) {}
public function __construct(
private RecordStockUse $recordUse,
private ReverseMaintenanceStockUse $reverseUse,
) {}
public function use(int $stockItemId, int $quantityMilli, int $machineId, int $maintenanceRecordId, int $userId): bool
{
@@ -31,4 +36,9 @@ class StockForMachines implements MaintenanceMaterials
return true;
}
public function returnUseOf(int $maintenanceRecordId, int $userId): void
{
$this->reverseUse->execute($maintenanceRecordId, $userId);
}
}
@@ -3,12 +3,14 @@
use App\Modules\Users\Application\UseCases\LoginPins;
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
use App\Modules\Users\Domain\Exceptions\WrongPassword;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The user's own PIN code for switching user on a machine console (spec
* 19.6). Setting or removing it asks for the user's password.
* 19.6). Setting or removing it asks for the user's password, which may
* be wrong 5 times a minute, as on the login page.
*/
new class extends Component
{
@@ -37,6 +39,10 @@ new class extends Component
return;
}
if ($this->passwordThrottled()) {
return;
}
try {
$pins->set((int) auth()->id(), $this->currentPassword, $this->pin);
} catch (InvalidLoginPin) {
@@ -44,11 +50,13 @@ new class extends Component
return;
} catch (WrongPassword) {
$this->addError('currentPassword', __('users.pin.errors.password'));
$this->wrongPassword();
return;
}
RateLimiter::clear($this->throttleKey());
$this->reset('currentPassword', 'pin', 'pinConfirmation');
$this->message = __('users.pin.saved');
}
@@ -58,14 +66,20 @@ new class extends Component
$this->authorize('machines.use');
$this->resetErrorBag();
if ($this->passwordThrottled()) {
return;
}
try {
$pins->remove((int) auth()->id(), $this->currentPassword);
} catch (WrongPassword) {
$this->addError('currentPassword', __('users.pin.errors.password'));
$this->wrongPassword();
return;
}
RateLimiter::clear($this->throttleKey());
$this->reset('currentPassword', 'pin', 'pinConfirmation');
$this->message = __('users.pin.removed');
}
@@ -74,6 +88,30 @@ new class extends Component
{
return $this->view()->title(__('users.pin.title'));
}
private function throttleKey(): string
{
return 'pin-password|'.auth()->id();
}
private function passwordThrottled(): bool
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return false;
}
$this->addError('currentPassword', __('auth.throttle', ['seconds' => RateLimiter::availableIn($this->throttleKey())]));
$this->reset('currentPassword');
return true;
}
private function wrongPassword(): void
{
RateLimiter::hit($this->throttleKey());
$this->addError('currentPassword', __('users.pin.errors.password'));
$this->reset('currentPassword');
}
};
?>
+1 -1
View File
@@ -208,7 +208,7 @@ return [
'cancel' => 'Mark as cancelled',
'cancel_named' => 'Mark as cancelled: :name :at',
'cancel_title' => 'Mark the maintenance as cancelled?',
'cancel_text' => 'The record stays in the history marked as cancelled, and it no longer resets the interval.',
'cancel_text' => 'The record stays in the history marked as cancelled, and it no longer resets the interval. The stock it used is returned with a reversal.',
'cancelled' => 'Maintenance :name marked as cancelled.',
'errors' => [
'needs_interval' => 'Give a counter-based interval, a time-based interval or both.',
+1 -1
View File
@@ -208,7 +208,7 @@ return [
'cancel' => 'Merkitse perutuksi',
'cancel_named' => 'Merkitse perutuksi: :name :at',
'cancel_title' => 'Merkitäänkö huolto perutuksi?',
'cancel_text' => 'Huoltokirjaus jää historiaan perutuksi merkittynä, eikä se enää nollaa huoltoväliä.',
'cancel_text' => 'Huoltokirjaus jää historiaan perutuksi merkittynä, eikä se enää nollaa huoltoväliä. Sen käyttämä varasto palautetaan vastakirjauksella.',
'cancelled' => 'Huolto :name merkitty perutuksi.',
'errors' => [
'needs_interval' => 'Anna laskuriin perustuva huoltoväli, aikaan perustuva huoltoväli tai molemmat.',
@@ -131,6 +131,12 @@ it('shows a maintenance request when due and resets the interval with a maintena
->call('cancelRecord')
->assertSee('Peruttu')
->assertSee('Huolto myöhässä');
$reversal = StockMovementModel::query()->where('reverses_movement_id', $use->id)->sole();
expect($reversal->quantity_milli)->toBe(1_000)
->and($reversal->user_id)->toBe($this->manager->id)
->and((int) StockMovementModel::query()->where('stock_item_id', $this->drum->id)->sum('quantity_milli'))->toBe(0);
});
it('notifies the responsible person of a maintenance request once', function () {
@@ -53,6 +53,29 @@ it('removes the PIN code with the user\'s password', function () {
expect($this->user->fresh()->pin_hash)->toBeNull();
});
it('stops checking the password after 5 wrong ones a minute', function () {
$component = Livewire::test('users::pin');
foreach (range(1, 5) as $attempt) {
$component->set('currentPassword', 'väärä')->call('remove')->assertHasErrors(['currentPassword' => __('users.pin.errors.password')]);
}
$this->user->forceFill(['pin_hash' => Hash::make('2468')])->save();
$component->set('currentPassword', 'Salasana-123!')
->call('remove')
->assertHasErrors('currentPassword')
->assertSet('message', '');
expect($this->user->fresh()->pin_hash)->not->toBeNull();
$this->travel(61)->seconds();
$component->set('currentPassword', 'Salasana-123!')
->call('remove')
->assertSet('message', __('users.pin.removed'));
});
it('is not offered to subcontractors', function () {
$this->actingAs(User::factory()->subcontractor()->create());