customer_id !== null, 422, 'Dịch vụ đang thuộc khách hàng khác, hãy gỡ trước khi gán.'); DB::transaction(function () use ($service, $customer) { $service->fill(['customer_id' => $customer->id])->saveQuietly(); $this->syncModuleOwner($service, $customer->id); $this->orderRecorder->ensureForService($service->refresh()); }); $this->activityLogger->log( event: 'attached', logName: 'Service', description: "{$this->activityLogger->getCauserName()} gán dịch vụ #{$service->id} cho khách hàng {$customer->fullname} ({$customer->email})", subject: $service, newValues: [...$this->customerValues($customer), ...$this->orderValues($service)], ); return $service; } public function detach(Service $service): void { $customer = $service->customer; if (! $customer) { return; } $orderValues = $this->orderValues($service); $orderItemId = $service->order_item_id; $service->fill(['customer_id' => null, 'order_item_id' => null, 'invoice_id' => null])->saveQuietly(); $this->syncModuleOwner($service, null); Invoice::where('service_id', $service->id)->delete(); $this->orderRecorder->discardOrder($orderItemId); $this->activityLogger->log( event: 'detached', logName: 'Service', description: "{$this->activityLogger->getCauserName()} gỡ dịch vụ #{$service->id} khỏi khách hàng {$customer->fullname} ({$customer->email}), xoá đơn hàng/hoá đơn", subject: $service, oldValues: [...$this->customerValues($customer), ...$orderValues], ); } private function syncModuleOwner(Service $service, ?int $customerId): void { if ($service->vm_id) { ModuleVmware::whereKey($service->vm_id)->update(['customer_id' => $customerId]); } ModuleHostingAccount::where('service_id', $service->id)->update(['customer_id' => $customerId]); } private function customerValues(Customer $customer): array { return array_filter([ 'customer_id' => $customer->id, 'customer_uuid' => $customer->uuid, 'customer_name' => $customer->fullname, 'customer_email' => $customer->email, ], fn ($value) => $value !== null); } private function orderValues(Service $service): array { $order = $service->orderItem?->order; return array_filter([ 'order_id' => $order?->id, 'order_num' => $order?->order_num, ], fn ($value) => $value !== null); } }