diff --git a/app/Modules/Inventory/Application/UseCases/ReverseMaintenanceStockUse.php b/app/Modules/Inventory/Application/UseCases/ReverseMaintenanceStockUse.php new file mode 100644 index 0000000..d207ff9 --- /dev/null +++ b/app/Modules/Inventory/Application/UseCases/ReverseMaintenanceStockUse.php @@ -0,0 +1,46 @@ +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); + }); + } +} diff --git a/app/Modules/Inventory/Domain/Contracts/StockMovementRepository.php b/app/Modules/Inventory/Domain/Contracts/StockMovementRepository.php index aa57d27..32da7c0 100644 --- a/app/Modules/Inventory/Domain/Contracts/StockMovementRepository.php +++ b/app/Modules/Inventory/Domain/Contracts/StockMovementRepository.php @@ -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 + */ + public function unreversedUseOfMaintenance(int $maintenanceRecordId): array; + /** * The item's balance in thousandths: the sum of its movements. */ diff --git a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php index de99e73..1959b12 100644 --- a/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php +++ b/app/Modules/Inventory/Infrastructure/Persistence/Repositories/EloquentStockMovementRepository.php @@ -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'); diff --git a/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php b/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php index 80d922f..25de0d2 100644 --- a/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php +++ b/app/Modules/Machines/Application/Contracts/MaintenanceMaterials.php @@ -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; } diff --git a/app/Modules/Machines/Application/UseCases/MachineMaintenance.php b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php index 87cb655..40b5f72 100644 --- a/app/Modules/Machines/Application/UseCases/MachineMaintenance.php +++ b/app/Modules/Machines/Application/UseCases/MachineMaintenance.php @@ -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); }); } } diff --git a/app/Modules/Machines/Infrastructure/Adapters/StockForMachines.php b/app/Modules/Machines/Infrastructure/Adapters/StockForMachines.php index 7c8ecaf..e982695 100644 --- a/app/Modules/Machines/Infrastructure/Adapters/StockForMachines.php +++ b/app/Modules/Machines/Infrastructure/Adapters/StockForMachines.php @@ -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); + } } diff --git a/app/Modules/Users/Presentation/Livewire/⚡pin.blade.php b/app/Modules/Users/Presentation/Livewire/⚡pin.blade.php index e2101a8..b92018e 100644 --- a/app/Modules/Users/Presentation/Livewire/⚡pin.blade.php +++ b/app/Modules/Users/Presentation/Livewire/⚡pin.blade.php @@ -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'); + } }; ?> diff --git a/lang/en/machines.php b/lang/en/machines.php index c61829c..58dfb11 100644 --- a/lang/en/machines.php +++ b/lang/en/machines.php @@ -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.', diff --git a/lang/fi/machines.php b/lang/fi/machines.php index fc83683..7878c18 100644 --- a/lang/fi/machines.php +++ b/lang/fi/machines.php @@ -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.', diff --git a/tests/Feature/Modules/Machines/MaintenanceTest.php b/tests/Feature/Modules/Machines/MaintenanceTest.php index acaf1ef..23eb63a 100644 --- a/tests/Feature/Modules/Machines/MaintenanceTest.php +++ b/tests/Feature/Modules/Machines/MaintenanceTest.php @@ -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 () { diff --git a/tests/Feature/Modules/Users/LoginPinTest.php b/tests/Feature/Modules/Users/LoginPinTest.php index f288598..5654881 100644 --- a/tests/Feature/Modules/Users/LoginPinTest.php +++ b/tests/Feature/Modules/Users/LoginPinTest.php @@ -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());