73 lines
2.4 KiB
PHP
73 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Modules\Maintenance\Services;
|
|
|
|
use App\Business;
|
|
use App\User;
|
|
use App\Modules\Maintenance\Models\SparePart;
|
|
use App\Modules\Maintenance\Models\SparePartConsumption;
|
|
use App\Modules\Maintenance\Models\WorkOrder;
|
|
use App\Modules\Maintenance\Models\WorkOrderPart;
|
|
use Illuminate\Support\Facades\DB;
|
|
use InvalidArgumentException;
|
|
|
|
class SparePartService
|
|
{
|
|
public function consumeForWorkOrder(
|
|
Business $business,
|
|
WorkOrder $workOrder,
|
|
int $sparePartId,
|
|
float $quantity,
|
|
?User $user = null
|
|
): SparePartConsumption {
|
|
return DB::transaction(function () use ($business, $workOrder, $sparePartId, $quantity, $user) {
|
|
$part = SparePart::where('business_id', $business->id)->lockForUpdate()->findOrFail($sparePartId);
|
|
|
|
if ($part->quantity < $quantity) {
|
|
throw new InvalidArgumentException('موجودی قطعه یدکی کافی نیست.');
|
|
}
|
|
|
|
$unitCost = (int) $part->purchase_price;
|
|
$totalCost = (int) ($unitCost * $quantity);
|
|
|
|
$part->decrement('quantity', $quantity);
|
|
|
|
WorkOrderPart::create([
|
|
'business_id' => $business->id,
|
|
'work_order_id' => $workOrder->id,
|
|
'spare_part_id' => $part->id,
|
|
'quantity' => $quantity,
|
|
'unit_cost' => $unitCost,
|
|
'total_cost' => $totalCost,
|
|
]);
|
|
|
|
$consumption = SparePartConsumption::create([
|
|
'business_id' => $business->id,
|
|
'spare_part_id' => $part->id,
|
|
'work_order_id' => $workOrder->id,
|
|
'equipment_id' => $workOrder->equipment_id,
|
|
'quantity' => $quantity,
|
|
'unit_cost' => $unitCost,
|
|
'notes' => null,
|
|
'consumed_by' => $user?->id,
|
|
]);
|
|
|
|
$workOrder->increment('cost', $totalCost);
|
|
|
|
MaintenanceActivityService::logEquipmentHistory(
|
|
$business,
|
|
$workOrder->equipment_id,
|
|
'spare_part',
|
|
'مصرف قطعه یدکی',
|
|
"قطعه «{$part->name}» به مقدار {$quantity} مصرف شد.",
|
|
$user,
|
|
$totalCost,
|
|
WorkOrder::class,
|
|
$workOrder->id
|
|
);
|
|
|
|
return $consumption;
|
|
});
|
|
}
|
|
}
|