diff --git a/app/Http/Controllers/Api/Admin/Customer/Concerns/ManagesCustomerServices.php b/app/Http/Controllers/Api/Admin/Customer/Concerns/ManagesCustomerServices.php index 24462ed..5611edf 100644 --- a/app/Http/Controllers/Api/Admin/Customer/Concerns/ManagesCustomerServices.php +++ b/app/Http/Controllers/Api/Admin/Customer/Concerns/ManagesCustomerServices.php @@ -14,13 +14,22 @@ trait ManagesCustomerServices return response()->json(['error' => false, 'data' => $this->serviceProvisioning->getServices($uuid)]); } + public function attachService(string $uuid, Request $request): JsonResponse + { + $data = $request->validate(['service_id' => 'required|integer|exists:services,id']); + + $service = $this->serviceProvisioning->attachService($uuid, $data['service_id']); + + return response()->json(['error' => false, 'message' => 'Đã gán dịch vụ cho khách hàng', 'data' => $service]); + } + public function bulkDeleteServices(string $uuid, Request $request): JsonResponse { $data = $request->validate(['ids' => 'required|array|min:1', 'ids.*' => 'integer']); $deleted = $this->serviceProvisioning->bulkDeleteServices($uuid, $data['ids']); - return response()->json(['error' => false, 'message' => "Đã xoá {$deleted} dịch vụ", 'data' => ['deleted' => $deleted]]); + return response()->json(['error' => false, 'message' => "Đã gỡ {$deleted} dịch vụ khỏi khách hàng", 'data' => ['deleted' => $deleted]]); } public function updateService(string $uuid, int $serviceId, Request $request): JsonResponse diff --git a/app/Http/Controllers/Api/Admin/Service/ServiceController.php b/app/Http/Controllers/Api/Admin/Service/ServiceController.php index 1c7761b..ecd3ee0 100644 --- a/app/Http/Controllers/Api/Admin/Service/ServiceController.php +++ b/app/Http/Controllers/Api/Admin/Service/ServiceController.php @@ -5,14 +5,19 @@ namespace App\Http\Controllers\Api\Admin\Service; use App\Helpers\OrderHelper; use App\Http\Controllers\Controller; use App\Jobs\VirtualMachine\Provision\ResendVmCredentialsEmailJob; +use App\Models\ActivityLog; use App\Models\DomainPricing; use App\Models\ModuleVmware; use App\Models\Service; +use App\Services\Customer\CustomerServiceAssignment; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Facades\DB; class ServiceController extends Controller { + public function __construct(private readonly CustomerServiceAssignment $assignment) {} + public function index(Request $request): JsonResponse { $perPage = min((int) ($request->per_page ?? 15), 100); @@ -21,7 +26,8 @@ class ServiceController extends Controller ->where(fn($q) => $q->whereNull('order_item_id')->orWhereNull('type')->orWhere('type', '!=', 'domain')) ->when($request->filter, fn($q, $v) => $q->where('server_name', 'like', "%{$v}%")) ->when($request->status, fn($q, $v) => $q->where('status', $v)) - ->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v)); + ->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v)) + ->when($request->boolean('unassigned'), fn($q) => $q->whereNull('customer_id')); $paginator = $query->latest()->paginate($perPage); @@ -71,6 +77,12 @@ class ServiceController extends Controller ModuleVmware::resolveVirtualMachineIds([$service->vmware]); + $service->setAttribute('activity_logs', ActivityLog::where('subject_type', Service::class) + ->where('subject_id', $service->id) + ->latest('id') + ->limit(50) + ->get(['id', 'event', 'description', 'causer_type', 'causer_name', 'old_values', 'new_values', 'created_at'])); + return response()->json(['error' => false, 'data' => $service]); } @@ -82,14 +94,17 @@ class ServiceController extends Controller 'action' => 'required|in:activate,suspend,cancel,detach-customer', ]); - $updates = match ($data['action']) { - 'activate' => ['status' => 'active', 'suspended_at' => null, 'cancelled_at' => null], - 'suspend' => ['status' => 'suspended', 'suspended_at' => now()], - 'cancel' => ['status' => 'cancelled', 'cancelled_at' => now()], - 'detach-customer' => ['customer_id' => null], - }; + if ($data['action'] === 'detach-customer') { + $updated = $this->detachCustomers($data['ids']); + } else { + $updates = match ($data['action']) { + 'activate' => ['status' => 'active', 'suspended_at' => null, 'cancelled_at' => null], + 'suspend' => ['status' => 'suspended', 'suspended_at' => now()], + 'cancel' => ['status' => 'cancelled', 'cancelled_at' => now()], + }; - $updated = Service::whereIn('id', $data['ids'])->update($updates); + $updated = Service::whereIn('id', $data['ids'])->update($updates); + } return response()->json([ 'error' => false, @@ -100,12 +115,21 @@ class ServiceController extends Controller public function detachCustomer(int $id): JsonResponse { - $service = Service::findOrFail($id); - $service->update(['customer_id' => null]); + $this->detachCustomers([Service::findOrFail($id)->id]); return response()->json(['error' => false, 'message' => 'Đã gỡ khách hàng khỏi dịch vụ.']); } + private function detachCustomers(array $ids): int + { + return DB::transaction(function () use ($ids) { + $services = Service::with('customer')->whereIn('id', $ids)->whereNotNull('customer_id')->get(); + $services->each(fn (Service $service) => $this->assignment->detach($service)); + + return $services->count(); + }); + } + public function resendCredentials(int $id): JsonResponse { $service = Service::findOrFail($id); diff --git a/app/Services/Customer/CustomerServiceAssignment.php b/app/Services/Customer/CustomerServiceAssignment.php new file mode 100644 index 0000000..74711bf --- /dev/null +++ b/app/Services/Customer/CustomerServiceAssignment.php @@ -0,0 +1,94 @@ +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); + } +} diff --git a/app/Services/Customer/CustomerServiceProvisioningService.php b/app/Services/Customer/CustomerServiceProvisioningService.php index 3d39dfe..a7487d1 100644 --- a/app/Services/Customer/CustomerServiceProvisioningService.php +++ b/app/Services/Customer/CustomerServiceProvisioningService.php @@ -5,7 +5,6 @@ namespace App\Services\Customer; use App\Helpers\OrderHelper; use App\Mail\ServiceRenewalReminderMail; use App\Models\Customer; -use App\Models\Invoice; use App\Models\ModuleVmware; use App\Models\Order; use App\Models\Product; @@ -35,6 +34,7 @@ class CustomerServiceProvisioningService private readonly VmwareRepositoryInterface $vmwareRepository, private readonly ServiceRepositoryInterface $serviceRepository, private readonly ServiceOrderRecorder $orderRecorder, + private readonly CustomerServiceAssignment $assignment, ) {} public function getServices(string $uuid): Collection @@ -55,6 +55,11 @@ class CustomerServiceProvisioningService return $services; } + public function attachService(string $uuid, int $serviceId): Service + { + return $this->assignment->attach(Service::findOrFail($serviceId), $this->resolveCustomer($uuid)); + } + public function bulkDeleteServices(string $uuid, array $ids): int { $customer = $this->resolveCustomer($uuid); @@ -63,9 +68,7 @@ class CustomerServiceProvisioningService $services = Service::where('customer_id', $customer->id)->whereIn('id', $ids)->get(); foreach ($services as $service) { - $service->delete(); - Invoice::where('service_id', $service->id)->delete(); - $this->orderRecorder->discardOrder($service->order_item_id); + $this->assignment->detach($service); } return $services->count(); diff --git a/routes/api/admin/customers.php b/routes/api/admin/customers.php index bc2ce58..9e2c550 100644 --- a/routes/api/admin/customers.php +++ b/routes/api/admin/customers.php @@ -29,6 +29,7 @@ Route::prefix('customers') Route::post('{uuid}/add-total', 'addTotal')->middleware('perm:customer.edit'); Route::get('{uuid}/services', 'getServices')->middleware('perm:customer.view'); Route::post('{uuid}/services', 'createService')->middleware('perm:customer.edit'); + Route::post('{uuid}/services/attach', 'attachService')->middleware('perm:customer.edit'); Route::post('{uuid}/services/bulk-delete', 'bulkDeleteServices')->middleware( 'perm:customer.edit', ); diff --git a/tests/Feature/Api/Admin/Customer/DeleteCustomerServiceOrdersTest.php b/tests/Feature/Api/Admin/Customer/DeleteCustomerServiceOrdersTest.php index 27056e5..ca67f9c 100644 --- a/tests/Feature/Api/Admin/Customer/DeleteCustomerServiceOrdersTest.php +++ b/tests/Feature/Api/Admin/Customer/DeleteCustomerServiceOrdersTest.php @@ -45,7 +45,7 @@ class DeleteCustomerServiceOrdersTest extends TestCase return Service::where('server_name', $serverName)->firstOrFail(); } - public function test_deleting_service_hides_its_order_and_invoices(): void + public function test_deleting_service_detaches_customer_and_hides_its_order_and_invoices(): void { $kept = $this->createService('kept.vn'); $removed = $this->createService('removed.vn'); @@ -60,6 +60,54 @@ class DeleteCustomerServiceOrdersTest extends TestCase $this->assertSoftDeleted('invoices', ['order_id' => $removedOrderId]); $this->assertSame([$kept->orderItem->order_id], Order::pluck('id')->all()); $this->assertSame(1, Invoice::count()); + + $removed->refresh(); + $this->assertNull($removed->deleted_at); + $this->assertNull($removed->customer_id); + $this->assertNull($removed->order_item_id); + + $log = $this->actingAs($this->admin, 'admin') + ->getJson("/api/v1/administrator/services/{$removed->id}") + ->assertOk() + ->json('data.activity_logs.0'); + $this->assertSame('detached', $log['event']); + $this->assertSame($this->customer->email, $log['old_values']['customer_email']); + $this->assertSame($removedOrderId, $log['old_values']['order_id']); + } + + public function test_detached_service_can_be_attached_to_another_customer(): void + { + $service = $this->createService('moved.vn'); + $this->actingAs($this->admin, 'admin')->postJson( + "/api/v1/administrator/customers/{$this->customer->uuid}/services/bulk-delete", + ['ids' => [$service->id]], + )->assertOk(); + + $this->actingAs($this->admin, 'admin') + ->getJson('/api/v1/administrator/services?unassigned=1') + ->assertOk() + ->assertJsonPath('data.items.0.id', $service->id); + + $other = Customer::factory()->create(); + $this->actingAs($this->admin, 'admin')->postJson( + "/api/v1/administrator/customers/{$other->uuid}/services/attach", + ['service_id' => $service->id], + )->assertOk(); + + $service->refresh(); + $this->assertSame($other->id, $service->customer_id); + $this->assertSame($other->id, $service->orderItem->order->customer_id); + + $log = $this->actingAs($this->admin, 'admin') + ->getJson("/api/v1/administrator/services/{$service->id}") + ->json('data.activity_logs.0'); + $this->assertSame('attached', $log['event']); + $this->assertSame($other->email, $log['new_values']['customer_email']); + + $this->actingAs($this->admin, 'admin')->postJson( + "/api/v1/administrator/customers/{$this->customer->uuid}/services/attach", + ['service_id' => $service->id], + )->assertStatus(422); } public function test_recreating_same_service_discards_previous_order(): void