|
- <?php
-
- namespace App\Http\Controllers\Items;
-
- use App\Models\Item;
- use App\Models\Location;
- use App\Models\Stock;
- use App\Models\StockMovement;
- use Framework\Routing\Router;
-
- class ReceiveStockController
- {
- public function handle(Router $router)
- {
- if (!session()->has('user_id')) {
- return redirect($router->route('show-register-form'));
- }
-
- secure();
-
- $parameters = $router->current()->parameters();
-
- $item = Item::find((int) $parameters['item']);
-
- if (!$item) {
- return redirect($router->route('show-items'));
- }
-
- $data = validate($_POST, [
- 'location_id' => ['required'],
- 'quantity' => ['required', 'positive_integer'],
- 'notes' => [],
- ], 'receive_errors');
-
- $location = Location::find((int) $data['location_id']);
-
- if (!$location) {
- return redirect($router->route('show-receive-stock-form', ['item' => $item->id]));
- }
-
- $stock = Stock::forItemAtLocation($item->id, $location->id);
- $stock->quantity = $stock->quantity + (int) $data['quantity'];
- $stock->save();
-
- $movement = new StockMovement();
- $movement->item_id = $item->id;
- $movement->location_id = $location->id;
- $movement->type = 'receive';
- $movement->quantity_change = (int) $data['quantity'];
- $movement->quantity_after = $stock->quantity;
- $movement->notes = $data['notes'] ?? '';
- $movement->user_id = session('user_id');
- $movement->save();
-
- return redirect($router->route('view-item', ['item' => $item->id]));
- }
- }
|