ultimatepos/Modules/Maintenance/Services/ToolCribService.php

92 lines
3.1 KiB
PHP

<?php
namespace Modules\Maintenance\Services;
use App\Business;
use App\User;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use Modules\Maintenance\Models\MaintenanceTool;
use Modules\Maintenance\Models\MaintenanceToolTransaction;
class ToolCribService
{
public function checkout(
Business $business,
MaintenanceTool $tool,
int $userId,
?int $workOrderId = null,
?int $equipmentId = null,
?string $expectedReturnAt = null,
?string $notes = null,
?User $performer = null
): MaintenanceToolTransaction {
if ($tool->status === 'checked_out') {
throw new InvalidArgumentException('این ابزار در حال حاضر تحویل داده شده است.');
}
return DB::transaction(function () use ($business, $tool, $userId, $workOrderId, $equipmentId, $expectedReturnAt, $notes, $performer) {
$tool->update([
'status' => 'checked_out',
'checked_out_to' => $userId,
'current_work_order_id' => $workOrderId,
]);
return MaintenanceToolTransaction::create([
'business_id' => $business->id,
'tool_id' => $tool->id,
'type' => 'checkout',
'user_id' => $userId,
'work_order_id' => $workOrderId,
'equipment_id' => $equipmentId,
'transaction_at' => now(),
'expected_return_at' => $expectedReturnAt,
'notes' => $notes,
'performed_by' => $performer?->id,
]);
});
}
public function returnTool(
Business $business,
MaintenanceTool $tool,
?string $notes = null,
?User $performer = null
): MaintenanceToolTransaction {
if ($tool->status !== 'checked_out') {
throw new InvalidArgumentException('این ابزار در وضعیت تحویل نیست.');
}
return DB::transaction(function () use ($business, $tool, $notes, $performer) {
$lastCheckout = MaintenanceToolTransaction::where('tool_id', $tool->id)
->where('type', 'checkout')
->whereNull('returned_at')
->orderByDesc('id')
->first();
if ($lastCheckout) {
$lastCheckout->update(['returned_at' => now()]);
}
$tool->update([
'status' => 'available',
'checked_out_to' => null,
'current_work_order_id' => null,
]);
return MaintenanceToolTransaction::create([
'business_id' => $business->id,
'tool_id' => $tool->id,
'type' => 'return',
'user_id' => $lastCheckout?->user_id,
'work_order_id' => $lastCheckout?->work_order_id,
'equipment_id' => $lastCheckout?->equipment_id,
'transaction_at' => now(),
'returned_at' => now(),
'notes' => $notes,
'performed_by' => $performer?->id,
]);
});
}
}