60 lines
2.3 KiB
PHP
60 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Employee;
|
|
use App\Models\StockMovement;
|
|
use App\Models\StockVariant;
|
|
use App\Models\UniformIssue;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class IssueController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
return view('issues.index', [
|
|
'employees' => Employee::where('status', 'active')->orderBy('name')->get(),
|
|
'variants' => StockVariant::with('item')->where('quantity', '>', 0)->orderBy('size')->get()->sortBy('item.name'),
|
|
'issues' => UniformIssue::with(['employee', 'variant.item'])->latest('issued_at')->paginate(15),
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$data = $request->validate([
|
|
'employee_id' => ['required', 'exists:employees,id'],
|
|
'stock_variant_id' => ['required', 'exists:stock_variants,id'],
|
|
'quantity' => ['required', 'integer', 'min:1'],
|
|
'issued_at' => ['required', 'date'],
|
|
'notes' => ['nullable', 'string', 'max:500'],
|
|
]);
|
|
|
|
DB::transaction(function () use ($data) {
|
|
$employee = Employee::lockForUpdate()->findOrFail($data['employee_id']);
|
|
if ($employee->status !== 'active') {
|
|
throw ValidationException::withMessages(['employee_id' => 'Uniforms can only be issued to active employees.']);
|
|
}
|
|
|
|
$variant = StockVariant::lockForUpdate()->findOrFail($data['stock_variant_id']);
|
|
if ($variant->quantity < $data['quantity']) {
|
|
throw ValidationException::withMessages(['quantity' => "Only {$variant->quantity} item(s) are available in this size."]);
|
|
}
|
|
|
|
$issue = UniformIssue::create($data);
|
|
$variant->decrement('quantity', $data['quantity']);
|
|
StockMovement::create([
|
|
'stock_variant_id' => $variant->id,
|
|
'employee_id' => $employee->id,
|
|
'uniform_issue_id' => $issue->id,
|
|
'type' => 'issue',
|
|
'quantity_change' => -$data['quantity'],
|
|
'notes' => "Issued to {$employee->name}",
|
|
]);
|
|
});
|
|
|
|
return back()->with('success', 'Uniform issued and stock adjusted.');
|
|
}
|
|
}
|