feat: Implement Plesk domain and hosting services

- Added PleskDomainService for managing domain operations (create, update, remove, get info).
- Introduced PleskHostingService for provisioning hosting accounts and notifying customers.
- Created PleskService for handling API requests to Plesk.
- Added migration to include 'type' column in dns_manager_servers table.
- Created migration for module_hosting_accounts table to track hosting subscriptions.
- Created migration for module_hosting_plesk_clients table to manage Plesk client credentials.
- Added email templates for notifying customers and admins about hosting account creation.
This commit is contained in:
baodev0
2026-08-06 17:24:01 +07:00
parent 79f06c2fa2
commit d6d63e5152
29 changed files with 1744 additions and 113 deletions
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Enums\Server;
enum ServerType: string
{
case DOMAIN = 'domain';
case HOSTING = 'hosting';
case BOTH = 'both';
public function label(): string
{
return match ($this) {
self::DOMAIN => 'Domain / DNS',
self::HOSTING => 'Hosting',
self::BOTH => 'Domain & Hosting',
};
}
}
@@ -74,6 +74,7 @@ class ServerController extends Controller
'password' => 'required|string|max:255',
'api_key' => 'nullable|string',
'status' => 'nullable|string|in:activated,Stopped',
'type' => 'nullable|string|in:domain,hosting,both',
]);
DB::beginTransaction();
@@ -86,6 +87,7 @@ class ServerController extends Controller
'password' => Crypt::encryptString($validated['password']),
'api_key' => $validated['api_key'] ?? null,
'status' => $validated['status'] ?? 'activated',
'type' => $validated['type'] ?? 'domain',
]);
DB::commit();
@@ -116,6 +118,7 @@ class ServerController extends Controller
'password' => 'nullable|string|max:255',
'api_key' => 'nullable|string',
'status' => 'nullable|string|in:activated,Stopped',
'type' => 'nullable|string|in:domain,hosting,both',
]);
DB::beginTransaction();
@@ -182,6 +185,7 @@ class ServerController extends Controller
'username' => $server->username,
'api_key' => $server->api_key,
'status' => $server->status,
'type' => $server->type,
'created_at' => $server->created_at,
'updated_at' => $server->updated_at,
];
@@ -0,0 +1,146 @@
<?php
namespace App\Http\Controllers\Api\Admin\Hosting;
use App\Http\Controllers\Controller;
use App\Http\Requests\ModuleHosting\CreateHostingAccountRequest;
use App\Http\Requests\ModuleHosting\UpdateHostingAccountRequest;
use App\Http\Resources\Api\Admin\HostingAccountResource;
use App\Repositories\Module\HostingAccount\HostingAccountRepositoryInterface;
use App\Services\Plesk\PleskHostingService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class HostingAccountController extends Controller
{
private const RELATIONSHIPS = ['customer', 'server', 'domain'];
public function __construct(
private readonly HostingAccountRepositoryInterface $accounts,
private readonly PleskHostingService $pleskHostingService,
) {}
public function index(Request $request): JsonResponse
{
$perPage = min((int) $request->get('per_page', 15), 500);
$filter = $request->get('filter');
$status = $request->get('status');
$customerId = $request->get('customer_id');
$query = $this->accounts->model
->with(self::RELATIONSHIPS)
->newQuery();
if ($filter) {
$query->where(function ($sub) use ($filter) {
$sub->where('hosting_plan', 'like', "%{$filter}%")
->orWhere('ftp_username', 'like', "%{$filter}%")
->orWhere('system_username', 'like', "%{$filter}%");
});
}
if ($status !== null && $status !== '') {
$query->where('status', $status);
}
if ($customerId) {
$query->where('customer_id', $customerId);
}
$paginator = $query->orderByDesc('id')->paginate($perPage);
return response()->json([
'error' => false,
'data' => [
'items' => HostingAccountResource::collection($paginator->getCollection()),
'total' => $paginator->total(),
'per_page' => $paginator->perPage(),
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
],
]);
}
public function show(int $id): JsonResponse
{
$account = $this->accounts->model->with(self::RELATIONSHIPS)->find($id);
if (!$account) {
return response()->json(['error' => true, 'message' => "Không tìm thấy hosting account #$id"], 404);
}
return response()->json(['error' => false, 'data' => new HostingAccountResource($account)]);
}
public function store(CreateHostingAccountRequest $request): JsonResponse
{
$result = $this->pleskHostingService->provision($request->validated());
if ($result['error']) {
return response()->json([
'error' => true,
'message' => $result['message'] ?? 'Không thể tạo hosting account trên Plesk',
], 422);
}
$account = $result['data']->load(self::RELATIONSHIPS);
return response()->json([
'error' => false,
'data' => new HostingAccountResource($account),
// Not persisted anywhere — this response is the only place it's ever shown.
'ftp_password' => $result['ftp_password'],
], 201);
}
public function update(int $id, UpdateHostingAccountRequest $request): JsonResponse
{
$account = $this->accounts->find($id);
if (!$account) {
return response()->json(['error' => true, 'message' => "Không tìm thấy hosting account #$id"], 404);
}
$this->accounts->update($id, $request->validated());
return $this->show($id);
}
public function destroy(int $id): JsonResponse
{
$account = $this->accounts->find($id);
if (!$account) {
return response()->json(['error' => true, 'message' => "Không tìm thấy hosting account #$id"], 404);
}
// Local record only — does not deprovision the subscription on Plesk,
// same as DnsManager\DomainController::destroy leaving the Plesk side alone.
$this->accounts->delete($id);
return response()->json(['error' => false, 'message' => 'Đã xoá hosting account']);
}
public function suspend(int $id): JsonResponse
{
return $this->notImplemented();
}
public function unsuspend(int $id): JsonResponse
{
return $this->notImplemented();
}
public function resetFtpPassword(int $id): JsonResponse
{
return $this->notImplemented();
}
private function notImplemented(): JsonResponse
{
return response()->json([
'error' => true,
'message' => 'Not implemented in this phase',
], 501);
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests\ModuleHosting;
use Illuminate\Foundation\Http\FormRequest;
class CreateHostingAccountRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'customer_id' => 'required|integer|exists:customers,id',
'dns_manager_server_id' => 'required|integer|exists:dns_manager_servers,id',
'dns_manager_domain_id' => 'nullable|integer|exists:dns_manager_domain,id',
'service_id' => 'nullable|integer|exists:services,id',
'domain_name' => 'required|string|max:255',
'hosting_plan' => 'required|string|max:100',
'ftp_password' => 'nullable|string|min:8|max:100',
];
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests\ModuleHosting;
use Illuminate\Foundation\Http\FormRequest;
class UpdateHostingAccountRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* Phase 1 only re-links local metadata — it does not call Plesk, so
* fields that would require re-provisioning (server, domain name,
* plan) are not editable here.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'dns_manager_domain_id' => 'nullable|integer|exists:dns_manager_domain,id',
'service_id' => 'nullable|integer|exists:services,id',
'hosting_plan' => 'sometimes|required|string|max:100',
];
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Http\Resources\Api\Admin;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class HostingAccountResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'customer_id' => $this->customer_id,
'customer_name' => $this->whenLoaded('customer', fn () => $this->customer?->fullname),
'service_id' => $this->service_id,
'dns_manager_server_id' => $this->dns_manager_server_id,
'server_name' => $this->whenLoaded('server', fn () => $this->server?->name),
'dns_manager_domain_id' => $this->dns_manager_domain_id,
'domain_name' => $this->whenLoaded('domain', fn () => $this->domain?->domain_name),
'plesk_client_id' => $this->plesk_client_id,
'plesk_subscription_id' => $this->plesk_subscription_id,
'plesk_guid' => $this->plesk_guid,
'hosting_plan' => $this->hosting_plan,
'ftp_username' => $this->ftp_username,
'system_username' => $this->system_username,
'document_root' => $this->document_root,
'status' => $this->status,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
@@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Jobs\Mail\Admin;
use App\Mail\Admin\HostingAccountCreatedAdminNotification;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class HostingAccountCreatedAdminNotificationJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 60;
public function __construct(public readonly array $data) {}
public function handle(): void
{
$setting = Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode((string) $setting->value, true) : [];
$adminEmail = $settingValue['admin_email'] ?? null;
if (empty($adminEmail)) {
Log::warning('HostingAccountCreatedAdminNotificationJob: admin_email not configured in settings.');
return;
}
$payload = array_merge($this->data, [
'company_name' => $settingValue['company'] ?? 'Portal Admin',
]);
try {
Mail::to($adminEmail)->send(new HostingAccountCreatedAdminNotification($payload));
} catch (\Throwable $e) {
Log::error('HostingAccountCreatedAdminNotificationJob: failed to send email. ' . $e->getMessage(), [
'admin_email' => $adminEmail,
'domain_name' => $this->data['domain_name'] ?? null,
]);
}
}
public function failed(\Throwable $e): void
{
Log::error('HostingAccountCreatedAdminNotificationJob: job failed.', [
'error' => $e->getMessage(),
'domain_name' => $this->data['domain_name'] ?? null,
]);
}
}
@@ -0,0 +1,54 @@
<?php
namespace App\Jobs\Mail\Customer;
use App\Mail\Customer\HostingAccountCreated;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class HostingAccountCreatedJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public array $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function handle(): void
{
if (empty($this->data['customer_email'])) {
Log::warning('HostingAccountCreatedJob: missing customer_email, skipped.', [
'domain_name' => $this->data['domain_name'] ?? null,
]);
return;
}
try {
Mail::to($this->data['customer_email'])
->send(new HostingAccountCreated($this->data));
} catch (\Throwable $e) {
Log::error('Không thể gửi email thông báo khởi tạo hosting: ' . $e->getMessage(), [
'customer_email' => $this->data['customer_email'] ?? null,
'domain_name' => $this->data['domain_name'] ?? null,
]);
}
}
public function failed(\Throwable $e): void
{
Log::error('HostingAccountCreatedJob: job failed.', [
'error' => $e->getMessage(),
'domain_name' => $this->data['domain_name'] ?? null,
]);
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Mail\Admin;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class HostingAccountCreatedAdminNotification extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public readonly array $data) {}
public function envelope(): Envelope
{
return new Envelope(
subject: '[ADMIN] Hosting account mới — ' . ($this->data['domain_name'] ?? 'N/A'),
);
}
public function content(): Content
{
return new Content(
view: 'emails.admin.hosting-account-created',
with: $this->data,
);
}
public function attachments(): array
{
return [];
}
}
@@ -0,0 +1,72 @@
<?php
namespace App\Mail\Customer;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class HostingAccountCreated extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public array $data) {}
public function envelope(): Envelope
{
$appName = $this->payload()['company_name'] ?? config('app.name', 'The Gioi So');
return new Envelope(
subject: 'Hosting của bạn đã sẵn sàng — ' . ($this->data['domain_name'] ?? '') . ' — ' . $appName,
);
}
public function content(): Content
{
$data = $this->payload();
return new Content(
view: 'emails.customer.hosting-account-created',
with: [
'appName' => $data['company_name'] ?? config('app.name', 'The Gioi So'),
'fullName' => $data['customer_name'] ?? 'Quý khách',
'domainName' => $data['domain_name'] ?? '',
'hostingPlan' => $data['hosting_plan'] ?? '',
'serverHost' => $data['server_host'] ?? '',
'ftpUsername' => $data['ftp_username'] ?? '',
'ftpPassword' => $data['ftp_password'] ?? '',
'pleskLogin' => $data['plesk_login'] ?? '',
'pleskPassword' => $data['plesk_password'] ?? '',
'pleskPanelUrl' => $data['plesk_panel_url'] ?? '',
'loginUrl' => $data['login_url'] ?? rtrim(config('app.frontend_url', ''), '/') . '/dang-nhap',
'supportEmail' => $data['support_email'] ?? config('mail.support_email', 'support@thegioiso.com'),
'supportPhone' => $data['support_phone'] ?? config('mail.support_phone', '1900.xxxx'),
],
);
}
public function attachments(): array
{
return [];
}
private function payload(): array
{
try {
$setting = Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode((string) $setting->value, true) : [];
} catch (\Throwable) {
$settingValue = [];
}
return array_merge([
'company_name' => $settingValue['company'] ?? config('app.name', 'The Gioi So'),
'support_email' => $settingValue['email'] ?? config('mail.support_email', 'support@thegioiso.com'),
'support_phone' => $settingValue['hotline'] ?? ($settingValue['phone'] ?? config('mail.support_phone', '1900.xxxx')),
'login_url' => rtrim(config('app.frontend_url', ''), '/') . '/dang-nhap',
], $this->data);
}
}
+9
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Enums\Server\ServerType;
use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -19,6 +20,7 @@ class DnsServer extends Model
'username',
'api_key',
'status',
'type',
];
public function getStatus(): string
@@ -30,6 +32,13 @@ class DnsServer extends Model
};
}
public function servesHosting(): bool
{
$type = $this->attributes['type'] ?? ServerType::DOMAIN->value;
return in_array($type, [ServerType::HOSTING->value, ServerType::BOTH->value], true);
}
protected function scopeIsActive($query)
{
return $query->where('status', 'activated');
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Models;
use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ModuleHostingAccount extends Model
{
use HasFactory, LogsActivity;
protected $table = 'module_hosting_accounts';
protected $fillable = [
'customer_id',
'service_id',
'dns_manager_server_id',
'dns_manager_domain_id',
'plesk_client_id',
'plesk_subscription_id',
'plesk_guid',
'hosting_plan',
'ftp_username',
'system_username',
'document_root',
'status',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function service()
{
return $this->belongsTo(Service::class);
}
public function server()
{
return $this->belongsTo(DnsServer::class, 'dns_manager_server_id');
}
public function domain()
{
return $this->belongsTo(DnsDomain::class, 'dns_manager_domain_id');
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ModuleHostingPleskClient extends Model
{
use HasFactory;
protected $table = 'module_hosting_plesk_clients';
protected $fillable = [
'customer_id',
'dns_manager_server_id',
'plesk_client_id',
'login',
'password',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function server()
{
return $this->belongsTo(DnsServer::class, 'dns_manager_server_id');
}
}
+4
View File
@@ -82,6 +82,8 @@ use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingR
use App\Repositories\Module\HostingServer\HostingServerCachedRepository;
use App\Repositories\Module\HostingServer\HostingServerRepositoryInterface;
use App\Repositories\Module\HostingAccount\HostingAccountCachedRepository;
use App\Repositories\Module\HostingAccount\HostingAccountRepositoryInterface;
use App\Repositories\Module\IpAddress\IpAddressCachedRepository;
use App\Repositories\Module\IpAddress\IpAddressRepositoryInterface;
use App\Repositories\Module\Network\NetworkCachedRepository;
@@ -198,6 +200,8 @@ class RepositoryProvider extends ServiceProvider
$this->app->singleton(ModuleHostingRepositoryInterface::class, ModuleHostingCachedRepository::class);
//Hosting Server
$this->app->singleton(HostingServerRepositoryInterface::class, HostingServerCachedRepository::class);
//Hosting Account
$this->app->singleton(HostingAccountRepositoryInterface::class, HostingAccountCachedRepository::class);
//IpAddress
$this->app->singleton(IpAddressRepositoryInterface::class, IpAddressCachedRepository::class);
//Network
@@ -0,0 +1,48 @@
<?php
namespace App\Repositories\Module\HostingAccount;
use App\Repositories\BaseCachedRepository;
use Illuminate\Support\Facades\Cache;
class HostingAccountCachedRepository extends BaseCachedRepository implements HostingAccountRepositoryInterface
{
public function __construct(
public HostingAccountRepository $hostingAccountRepository
) {
parent::__construct();
}
public function getModel()
{
return $this->hostingAccountRepository->getModel();
}
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
) {
if (
$returnQuery ||
!empty($data['paginate'])
) {
return $this->hostingAccountRepository
->filter($data, $relationships, $withCount, $select, $returnQuery);
}
$cacheKey = $this->getCacheKey(md5(json_encode([
'filter' => compact('data', 'relationships', 'withCount', 'select')
])));
return Cache::remember(
$cacheKey,
$this->cacheTime,
fn() =>
$this->hostingAccountRepository
->filter($data, $relationships, $withCount, $select, $returnQuery)
);
}
}
@@ -0,0 +1,50 @@
<?php
namespace App\Repositories\Module\HostingAccount;
use App\Models\ModuleHostingAccount;
use App\Repositories\BaseRepository;
class HostingAccountRepository extends BaseRepository implements HostingAccountRepositoryInterface
{
public function getModel()
{
return ModuleHostingAccount::class;
}
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
) {
$query = $this->model
->select($select)
->with($relationships);
if (!empty($data['customer_id'])) {
$query->where('customer_id', $data['customer_id']);
}
if (!empty($data['status'])) {
$query->where('status', $data['status']);
}
if (!empty($withCount)) {
$query->withCount($withCount);
}
if ($returnQuery) {
return $query;
}
if (!empty($data['paginate'])) {
return $query->paginate(
$data['per_page'] ?? 15
);
}
return $query->get();
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Repositories\Module\HostingAccount;
use App\Repositories\BaseRepositoryInterface;
interface HostingAccountRepositoryInterface extends BaseRepositoryInterface
{
public function filter(
array $data = [],
array $relationships = [],
array $withCount = [],
array $select = ['*'],
bool $returnQuery = false
);
}
+175
View File
@@ -0,0 +1,175 @@
<?php
namespace App\Services\Plesk;
use App\Http\Facade\HelperFacade as Helper;
use App\Models\Customer;
use App\Models\DnsServer;
use App\Models\ModuleHostingPleskClient;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
/**
* Plesk `/clients` entry point — the customer's own Plesk Panel login,
* separate from the FTP/hosting credential PleskDomainService hands out.
* Plesk never returns a client's password after creation, so it's stored
* (encrypted) in module_hosting_plesk_clients — the only way to ever show
* it again on reuse.
*/
class PleskClientService
{
public function __construct(private PleskService $plesk)
{
}
/**
* @return array{error: bool, data?: array{id: int, login: string, password: ?string}, status?: int, message?: string}
*/
public function findOrCreateCustomer(DnsServer $server, Customer $customer): array
{
$existing = ModuleHostingPleskClient::query()
->where('customer_id', $customer->id)
->where('dns_manager_server_id', $server->id)
->first();
if ($existing) {
return [
'error' => false,
'data' => [
'id' => $existing->plesk_client_id,
'login' => $existing->login,
'password' => Crypt::decryptString($existing->password),
],
];
}
$login = $this->generateUsername($customer);
$password = Helper::general_password();
$created = $this->createCustomer($server, $customer, $login, $password);
if (!$created['error']) {
$this->persist($customer, $server, $created['data']['id'], $login, $password);
return ['error' => false, 'data' => ['id' => $created['data']['id'], 'login' => $login, 'password' => $password]];
}
// login already exists on this Plesk box but we have no local record of it (created
// out-of-band, or our own table was reset) — Plesk never gives back the old password,
// so reset it to one we generate now and persist that, instead of losing it again.
if (in_array($created['status'] ?? null, [400, 409], true)) {
$existingRemote = $this->findByLogin($server, $login);
if ($existingRemote) {
$reset = $this->resetPassword($server, (int) $existingRemote['id'], $password);
if ($reset) {
$this->persist($customer, $server, (int) $existingRemote['id'], $login, $password);
return ['error' => false, 'data' => ['id' => (int) $existingRemote['id'], 'login' => $login, 'password' => $password]];
}
Log::error('Plesk client found but password reset failed — reusing without a known password', [
'plesk_client_id' => $existingRemote['id'],
'login' => $login,
]);
return ['error' => false, 'data' => ['id' => (int) $existingRemote['id'], 'login' => $login, 'password' => null]];
}
}
return $created;
}
private function createCustomer(DnsServer $server, Customer $customer, string $login, string $password): array
{
$param = [
'name' => $customer->fullname ?: $login,
'login' => $login,
'email' => $customer->email,
'password' => $password,
'type' => 'customer',
];
try {
$response = $this->plesk->client($server, 30)
->post($this->plesk->url($server, 'clients'), $param);
$data = $response->json();
if ($response->successful() && isset($data['id'], $data['guid'])) {
return ['error' => false, 'data' => $data];
}
Log::error('Plesk client creation failed', ['status' => $response->status(), 'response' => $data]);
return [
'error' => true,
'status' => $response->status(),
'message' => $data['message'] ?? 'Plesk client creation failed',
];
} catch (RequestException $e) {
Log::error('Plesk client creation failed', ['error' => $e->getMessage(), 'response' => $e->response?->body()]);
return ['error' => true, 'status' => $e->response?->status(), 'message' => $e->getMessage()];
}
}
private function resetPassword(DnsServer $server, int $pleskClientId, string $password): bool
{
try {
$response = $this->plesk->client($server, 15)
->put($this->plesk->url($server, 'clients', "/{$pleskClientId}"), ['password' => $password]);
return $response->successful();
} catch (RequestException $e) {
Log::error('Plesk client password reset failed', ['error' => $e->getMessage(), 'plesk_client_id' => $pleskClientId]);
return false;
}
}
private function findByLogin(DnsServer $server, string $login): ?array
{
try {
$response = $this->plesk->client($server, 15)->get($this->plesk->url($server, 'clients'));
if (!$response->successful()) {
return null;
}
foreach ($response->json() ?? [] as $client) {
if (($client['login'] ?? null) === $login) {
return $client;
}
}
} catch (RequestException $e) {
Log::error($e->getMessage());
}
return null;
}
/**
* Plesk `login` is a short username, not the email (email is its own field
* on the same payload). Derived from the email's local part + customer id
* so it's stable and never collides across customers — needed because a
* 409 on create is treated as "this customer already has a client".
*/
private function generateUsername(Customer $customer): string
{
$localPart = strtolower((string) strstr($customer->email, '@', true) ?: 'user');
$sanitized = trim((string) preg_replace('/[^a-z0-9]+/', '_', $localPart), '_') ?: 'user';
return substr($sanitized, 0, 32) . '_' . $customer->id;
}
private function persist(Customer $customer, DnsServer $server, int $pleskClientId, string $login, string $password): void
{
ModuleHostingPleskClient::query()->updateOrCreate(
['customer_id' => $customer->id, 'dns_manager_server_id' => $server->id],
['plesk_client_id' => $pleskClientId, 'login' => $login, 'password' => Crypt::encryptString($password)]
);
}
}
+184
View File
@@ -0,0 +1,184 @@
<?php
namespace App\Services\Plesk;
use App\Models\DnsServer;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* Plesk `/domains` entry point — shared by the DNS module (ServerService)
* and the Hosting module (PleskHostingService). Extracted from
* ServerService so both stop drifting apart on the same Plesk call.
*/
class PleskDomainService
{
private ?string $lastError = null;
public function __construct(private PleskService $plesk)
{
}
/** Message from the most recent failed call — null if the last call succeeded or hasn't run yet. */
public function getLastError(): ?string
{
return $this->lastError;
}
public function createDomain(DnsServer $server, array $data = []): array|false
{
$this->lastError = null;
if (empty($data['domain_name'])) {
$this->lastError = 'Domain name is required';
return false;
}
$param = [
'name' => $data['domain_name'],
'description' => '',
'hosting_type' => 'virtual',
'hosting_settings' => [
'ftp_login' => $data['ftp_login'] ?? str_replace('.', '_', $data['domain_name']),
'ftp_password' => $data['ftp_password'] ?? Str::random(12),
],
'plan' => ['name' => $data['plan'] ?? 'Default Domain'],
];
// Omit ip_addresses/ipv4 unless explicitly given — Plesk assigns its
// own default IP for the domain, and a wrong hardcoded IP here gets
// rejected outright ("IP address 'x.x.x.x' is not available").
if (!empty($data['ip_addresses'])) {
$param['ip_addresses'] = $data['ip_addresses'];
$param['ipv4'] = $data['ip_addresses'];
}
if (!empty($data['owner_client_id'])) {
$param['owner_client'] = ['id' => $data['owner_client_id']];
}
try {
$response = $this->plesk->client($server, 30)
->post($this->plesk->url($server, 'domains'), $param);
$responseData = $response->json();
Log::info('Response Plesk API Created', ['data' => $responseData]);
if ($response->successful() && isset($responseData['id'], $responseData['guid'])) {
return $responseData + ['hosting_settings' => $param['hosting_settings']];
}
$this->lastError = $responseData['message'] ?? 'Plesk domain creation failed';
} catch (RequestException $e) {
$this->lastError = $e->response?->json('message') ?? $e->getMessage();
Log::error('Plesk domain creation failed', [
'error' => $e->getMessage(),
'response' => $e->response?->body(),
'data' => $param,
]);
}
return false;
}
public function updateDomain(DnsServer $server, int $pleskDomainId, array $data = []): array|false
{
$this->lastError = null;
if (empty($pleskDomainId) || empty($data)) {
$this->lastError = 'Invalid request';
return false;
}
$param = [
'name' => $data['domain_name'],
'description' => '',
'hosting_type' => 'virtual',
'hosting_settings' => [
'ftp_login' => $data['ftp_login'] ?? str_replace('.', '_', $data['domain_name']),
'ftp_password' => $data['ftp_password'] ?? Str::random(12),
],
'plan' => ['name' => $data['plan'] ?? 'Default Domain'],
];
if (!empty($data['ip_addresses'])) {
$param['ip_addresses'] = $data['ip_addresses'];
$param['ipv4'] = $data['ip_addresses'];
}
try {
$response = $this->plesk->client($server, 30)
->put($this->plesk->url($server, 'domains', "/{$pleskDomainId}"), $param);
$responseData = $response->json();
Log::info('Response Plesk API Updated', ['data' => $responseData]);
if ($response->successful() && isset($responseData['id'], $responseData['guid'])) {
return $responseData;
}
$this->lastError = $responseData['message'] ?? 'Plesk domain update failed';
} catch (RequestException $e) {
$this->lastError = $e->response?->json('message') ?? $e->getMessage();
Log::error('Plesk domain update failed', [
'error' => $e->getMessage(),
'response' => $e->response?->body(),
'data' => $param,
]);
}
return false;
}
public function removeDomain(DnsServer $server, int $pleskDomainId): bool
{
try {
$response = $this->plesk->client($server, 30)
->delete($this->plesk->url($server, 'domains', "/{$pleskDomainId}"));
if ($response->successful()) {
Log::info('Xoá domain thành công', ['plesk_id' => $pleskDomainId, 'status' => $response->status()]);
return true;
}
Log::error('Xoá domain thất bại', [
'plesk_id' => $pleskDomainId,
'status' => $response->status(),
'response' => $response->body(),
]);
return false;
} catch (\Exception $e) {
Log::error('Exception khi xoá domain', ['plesk_id' => $pleskDomainId, 'error' => $e->getMessage()]);
return false;
}
}
public function getDomainInfo(DnsServer $server, string $domain = ''): array|false
{
if (empty($domain)) {
return false;
}
try {
$response = $this->plesk->client($server, 10)
->get($this->plesk->url($server, 'domains'), ['name' => $domain]);
if ($response->successful()) {
foreach ($response->json() ?? [] as $domainInfo) {
if (isset($domainInfo['name']) && $domainInfo['name'] === $domain) {
return $domainInfo;
}
}
}
return false;
} catch (RequestException $e) {
Log::error($e->getMessage());
return false;
}
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
namespace App\Services\Plesk;
use App\Http\Facade\HelperFacade as Helper;
use App\Jobs\Mail\Admin\HostingAccountCreatedAdminNotificationJob;
use App\Jobs\Mail\Customer\HostingAccountCreatedJob;
use App\Models\Customer;
use App\Models\DnsServer;
use App\Models\ModuleHostingAccount;
use App\Repositories\DnsManager\Domain\DnsDomainRepositoryInterface;
use App\Repositories\Module\HostingAccount\HostingAccountRepositoryInterface;
/**
* Phase 1 orchestration: Create Customer -> Create Hosting Subscription ->
* Assign Plan -> persist module_hosting_accounts. No database/SSL/mail/git
* deploy — that's later phases.
*/
class PleskHostingService
{
public function __construct(
private PleskClientService $clients,
private PleskDomainService $domains,
private HostingAccountRepositoryInterface $accounts,
private DnsDomainRepositoryInterface $dnsDomains,
) {
}
public function provision(array $data): array
{
$server = DnsServer::find($data['dns_manager_server_id'] ?? null);
if (!$server) {
return ['error' => true, 'message' => 'Hosting server not found'];
}
if (!$server->servesHosting()) {
return ['error' => true, 'message' => 'This server does not support hosting'];
}
$customer = Customer::find($data['customer_id'] ?? null);
if (!$customer) {
return ['error' => true, 'message' => 'Customer not found'];
}
$client = $this->clients->findOrCreateCustomer($server, $customer);
if ($client['error']) {
return $client;
}
$pleskClientId = $client['data']['id'];
$pleskLogin = $client['data']['login'];
$pleskPassword = $client['data']['password'];
$ftpLogin = str_replace('.', '_', $data['domain_name']);
// Not persisted anywhere — the only record of it is this response, once.
$ftpPassword = $data['ftp_password'] ?? Helper::general_password();
$subscription = $this->domains->createDomain($server, [
'domain_name' => $data['domain_name'],
'ftp_login' => $ftpLogin,
'ftp_password' => $ftpPassword,
'plan' => $data['hosting_plan'] ?? null,
'owner_client_id' => $pleskClientId,
]);
if (!$subscription) {
return [
'error' => true,
'message' => $this->domains->getLastError() ?? 'Failed to create Plesk hosting subscription',
];
}
$domainInfo = $this->domains->getDomainInfo($server, $data['domain_name']) ?: [];
$dnsManagerDomainId = $data['dns_manager_domain_id'] ?? null;
if (!$dnsManagerDomainId) {
// Plesk's /domains object is the same entity the DNS module tracks —
// creating a hosting subscription there already created the DNS zone
// on Plesk, so mirror it locally instead of leaving it unlinked.
$dnsDomain = $this->dnsDomains->model->firstOrCreate(
[
'domain_name' => $data['domain_name'],
'dns_manager_server_id' => $server->id,
],
[
'plesk_id' => $subscription['id'],
'is_created' => 1,
]
);
$dnsManagerDomainId = $dnsDomain->id;
}
$account = $this->accounts->create([
'customer_id' => $customer->id,
'service_id' => $data['service_id'] ?? null,
'dns_manager_server_id' => $server->id,
'dns_manager_domain_id' => $dnsManagerDomainId,
'plesk_client_id' => $pleskClientId,
'plesk_subscription_id' => $subscription['id'],
'plesk_guid' => $subscription['guid'],
'hosting_plan' => $data['hosting_plan'] ?? null,
'ftp_username' => $subscription['hosting_settings']['ftp_login'] ?? $ftpLogin,
'system_username' => $subscription['hosting_settings']['ftp_login'] ?? $ftpLogin,
'document_root' => $domainInfo['www_root'] ?? null,
'status' => 'active',
]);
$this->notify($customer, $server, $account, $data['domain_name'], $ftpPassword, $pleskLogin, $pleskPassword);
return ['error' => false, 'data' => $account, 'ftp_password' => $ftpPassword];
}
private function notify(
Customer $customer,
DnsServer $server,
ModuleHostingAccount $account,
string $domainName,
string $ftpPassword,
string $pleskLogin,
?string $pleskPassword,
): void {
$shared = [
'customer_name' => $customer->fullname,
'customer_email' => $customer->email,
'domain_name' => $domainName,
'hosting_plan' => $account->hosting_plan,
'server_name' => $server->name,
'ftp_username' => $account->ftp_username,
'ftp_password' => $ftpPassword,
'plesk_login' => $pleskLogin,
'plesk_password' => $pleskPassword,
// Plesk's actual login page — not the :8443 REST API entry point.
'plesk_panel_url' => 'https://' . $server->ip_address . '/login_up.php',
'created_at' => now()->format('d/m/Y H:i:s'),
];
dispatch(new HostingAccountCreatedJob(array_merge($shared, [
'server_host' => $server->ip_address,
])));
dispatch(new HostingAccountCreatedAdminNotificationJob(array_merge($shared, [
'server_ip' => $server->ip_address,
'plesk_client_id' => $account->plesk_client_id,
'plesk_subscription_id' => $account->plesk_subscription_id,
])));
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Services\Plesk;
use App\Facades\BaseHelperFacade as BaseHelper;
use App\Models\DnsServer;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
class PleskService
{
protected array $entryPoints = [
'clients' => ':8443/api/v2/clients',
'domains' => ':8443/api/v2/domains',
];
public function client(DnsServer $server, int $timeout = 30): PendingRequest
{
return Http::withoutVerifying()
->withBasicAuth($server->username, Crypt::decryptString($server->password))
->timeout($timeout);
}
public function url(DnsServer $server, string $entryPoint, string $suffix = ''): string
{
return BaseHelper::url($server->ip_address) . $this->entryPoints[$entryPoint] . $suffix;
}
}
+16 -113
View File
@@ -5,11 +5,11 @@ namespace App\Services;
use App\Facades\BaseHelperFacade as BaseHelper;
use App\Models\DnsServer;
use App\Repositories\DnsManager\Server\DnsServerRepositoryInterface;
use App\Services\Plesk\PleskDomainService;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
class ServerService
{
@@ -33,7 +33,8 @@ class ServerService
];
public function __construct(
public DnsServerRepositoryInterface $serverRepository
public DnsServerRepositoryInterface $serverRepository,
private PleskDomainService $pleskDomainService,
) {
$this->server = $this->getServer();
}
@@ -205,32 +206,15 @@ class ServerService
public function getDomainInfo(string $domain = ''): array|false
{
if (empty($domain)) {
if (empty($domain) || empty($this->server)) {
return false;
}
try {
$response = Http::withoutVerifying()
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
->timeout(10)
->get(BaseHelper::url($this->server->ip_address) . $this->entry_points['domain'], ['name' => $domain]);
$result = $this->pleskDomainService->getDomainInfo($this->server, $domain);
$this->resetServer();
$this->resetServer();
if ($response->successful()) {
$domains = $response->json();
foreach ($domains as $domainInfo) {
if (isset($domainInfo['name']) && $domainInfo['name'] === $domain) {
return $domainInfo;
}
}
}
return false;
} catch (RequestException $e) {
Log::error($e->getMessage());
return false;
}
return $result;
}
public function createDomain(array $data = []): array|false
@@ -243,42 +227,11 @@ class ServerService
$this->server = $this->serverRepository->find($data['dns_manager_server_id']);
}
$param = [
'name' => $data['domain_name'],
'description' => '',
'hosting_type' => 'virtual',
'hosting_settings' => [
'ftp_login' => str_replace('.', '_', $data['domain_name']),
'ftp_password' => Str::random(12),
],
'ip_addresses' => ['103.42.58.124'],
'ipv4' => ['103.42.58.124'],
'plan' => ['name' => 'Default Domain'],
];
$result = $this->pleskDomainService->createDomain($this->server, $data);
try {
$response = Http::withoutVerifying()
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
->timeout(30)
->post(BaseHelper::url($this->server->ip_address) . $this->entry_points['domain'], $param);
$this->resetServer();
$this->resetServer();
$responseData = $response->json();
Log::info('Response Plesk API Created', ['data' => $responseData]);
if ($response->successful() && isset($responseData['id'], $responseData['guid'])) {
return $responseData;
}
} catch (RequestException $e) {
Log::error('Plesk domain creation failed', [
'error' => $e->getMessage(),
'response' => $e->response?->body(),
'data' => $param,
]);
}
return false;
return $result;
}
public function updateDomain(int $pleskDomainId, array $data = []): array|false
@@ -291,42 +244,11 @@ class ServerService
$this->server = $this->serverRepository->find($data['dns_manager_server_id']);
}
$param = [
'name' => $data['domain_name'],
'description' => '',
'hosting_type' => 'virtual',
'hosting_settings' => [
'ftp_login' => str_replace('.', '_', $data['domain_name']),
'ftp_password' => Str::random(12),
],
'ip_addresses' => ['103.42.58.124'],
'ipv4' => ['103.42.58.124'],
'plan' => ['name' => 'Default Domain'],
];
$result = $this->pleskDomainService->updateDomain($this->server, $pleskDomainId, $data);
try {
$response = Http::withoutVerifying()
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
->timeout(30)
->put(BaseHelper::url($this->server->ip_address) . $this->entry_points['domain'] . "/{$pleskDomainId}", $param);
$this->resetServer();
$this->resetServer();
$responseData = $response->json();
Log::info('Response Plesk API Updated', ['data' => $responseData]);
if ($response->successful() && isset($responseData['id'], $responseData['guid'])) {
return $responseData;
}
} catch (RequestException $e) {
Log::error('Plesk domain update failed', [
'error' => $e->getMessage(),
'response' => $e->response?->body(),
'data' => $param,
]);
}
return false;
return $result;
}
public function removeDomain(int $pleskDomainId): bool
@@ -335,30 +257,11 @@ class ServerService
return false;
}
try {
$response = Http::withoutVerifying()
->withBasicAuth($this->server->username, Crypt::decryptString($this->server->password))
->timeout(30)
->delete(BaseHelper::url($this->server->ip_address) . $this->entry_points['domain'] . "/{$pleskDomainId}");
$result = $this->pleskDomainService->removeDomain($this->server, $pleskDomainId);
$this->resetServer();
$this->resetServer();
if ($response->successful()) {
Log::info('Xoá domain thành công', ['plesk_id' => $pleskDomainId, 'status' => $response->status()]);
return true;
}
Log::error('Xoá domain thất bại', [
'plesk_id' => $pleskDomainId,
'status' => $response->status(),
'response' => $response->body(),
]);
return false;
} catch (\Exception $e) {
Log::error('Exception khi xoá domain', ['plesk_id' => $pleskDomainId, 'error' => $e->getMessage()]);
return false;
}
return $result;
}
public function addServerById(int $serverId): bool
@@ -0,0 +1,26 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('dns_manager_servers', function (Blueprint $table) {
$table->string('type', 20)->default('domain')->after('status');
});
// every existing server already serves DNS today
DB::table('dns_manager_servers')->update(['type' => 'domain']);
}
public function down(): void
{
Schema::table('dns_manager_servers', function (Blueprint $table) {
$table->dropColumn('type');
});
}
};
@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('module_hosting_accounts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->index();
$table->unsignedBigInteger('service_id')->nullable()->index();
$table->unsignedBigInteger('dns_manager_server_id')->index();
$table->unsignedBigInteger('dns_manager_domain_id')->nullable()->index();
$table->unsignedInteger('plesk_client_id')->nullable();
$table->unsignedInteger('plesk_subscription_id')->nullable()->index();
$table->string('plesk_guid', 64)->nullable();
$table->string('hosting_plan', 100)->nullable();
$table->string('ftp_username', 100)->nullable();
$table->string('system_username', 100)->nullable();
$table->string('document_root', 255)->nullable();
// pending -> active -> suspended -> terminated (mirrors services.status)
$table->string('status', 20)->default('pending')->index();
$table->timestamps();
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->foreign('service_id')->references('id')->on('services')->onDelete('set null');
$table->foreign('dns_manager_server_id')->references('id')->on('dns_manager_servers')->onDelete('restrict');
$table->foreign('dns_manager_domain_id')->references('id')->on('dns_manager_domain')->onDelete('set null');
});
}
public function down(): void
{
Schema::dropIfExists('module_hosting_accounts');
}
};
@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('module_hosting_plesk_clients', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->index();
$table->unsignedBigInteger('dns_manager_server_id')->index();
$table->unsignedInteger('plesk_client_id')->index();
$table->string('login', 100);
// Plesk panel login password (Crypt::encryptString) — separate credential
// from the FTP/hosting password, which is never stored anywhere.
$table->text('password');
$table->timestamps();
$table->unique(['dns_manager_server_id', 'customer_id'], 'hosting_plesk_clients_server_customer_unique');
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->foreign('dns_manager_server_id')->references('id')->on('dns_manager_servers')->onDelete('cascade');
});
}
public function down(): void
{
Schema::dropIfExists('module_hosting_plesk_clients');
}
};
+6
View File
@@ -139,6 +139,12 @@ class RolesAndPermissions extends Seeder
'domain.destroy',
'domain.manager',
// Hosting
'hosting.view',
'hosting.create',
'hosting.edit',
'hosting.destroy',
// Vai trò & Phân quyền
'role.view',
'role.create',
@@ -0,0 +1,130 @@
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Thông báo hosting mới</title>
<style>
* { box-sizing: border-box; }
body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0f4f8; margin: 0; padding: 0; }
.wrapper { max-width: 620px; margin: 30px auto; }
.card { background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
.header { background: linear-gradient(135deg, #f06824 0%, #d9531a 100%); padding: 36px 40px; text-align: center; }
.header .icon { font-size: 48px; margin-bottom: 12px; }
.header h1 { color: #fff; margin: 0 0 6px; font-size: 22px; font-weight: 700; }
.header p { color: #fde3d3; margin: 0; font-size: 14px; }
.body { padding: 36px 40px; }
.section-label { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: #9ca3af; margin: 24px 0 10px; }
.section-label:first-child { margin-top: 0; }
.info-table { width: 100%; border-collapse: collapse; background: #f9fafb; border: 1px solid #e5e7eb; border-radius: 8px; overflow: hidden; }
.info-table td { padding: 10px 16px; font-size: 14px; border-bottom: 1px solid #f3f4f6; }
.info-table tr:last-child td { border-bottom: none; }
.info-table td:first-child { color: #6b7280; width: 45%; }
.info-table td:last-child { font-weight: 600; color: #111827; }
.badge { display: inline-block; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; }
.badge-green { background: #dcfce7; color: #15803d; }
.cred-box { background: #fff7ed; border: 1.5px solid #fdba74; border-radius: 10px; padding: 20px 24px; margin-top: 10px; }
.cred-row { display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #fed7aa; }
.cred-row:last-child { border-bottom: none; }
.cred-label { color: #c2410c; font-size: 13px; width: 150px; flex-shrink: 0; }
.cred-value { font-family: 'Courier New', monospace; font-size: 14px; font-weight: 700; color: #111827; word-break: break-all; }
.note { margin-top: 16px; font-size: 12px; color: #9ca3af; }
.footer { text-align: center; padding: 20px 40px; border-top: 1px solid #f3f4f6; font-size: 12px; color: #9ca3af; }
</style>
</head>
<body>
<div class="wrapper">
<div class="card">
<div class="header">
<div class="icon">🖥️</div>
<h1>Hosting account mới được khởi tạo</h1>
<p>{{ $domain_name ?? 'N/A' }} — {{ $created_at ?? now()->format('d/m/Y H:i:s') }}</p>
</div>
<div class="body">
<div class="section-label">Thông tin khách hàng</div>
<table class="info-table">
<tr>
<td>Tên khách hàng</td>
<td>{{ $customer_name ?? 'N/A' }}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $customer_email ?? 'N/A' }}</td>
</tr>
</table>
<div class="section-label">Thông tin dịch vụ Hosting</div>
<table class="info-table">
<tr>
<td>Tên miền</td>
<td>{{ $domain_name ?? 'N/A' }}</td>
</tr>
<tr>
<td>Gói hosting</td>
<td>{{ $hosting_plan ?? 'N/A' }}</td>
</tr>
<tr>
<td>Server</td>
<td>{{ $server_name ?? 'N/A' }} ({{ $server_ip ?? 'N/A' }})</td>
</tr>
<tr>
<td>Plesk Client ID</td>
<td>{{ $plesk_client_id ?? 'N/A' }}</td>
</tr>
<tr>
<td>Plesk Subscription ID</td>
<td>{{ $plesk_subscription_id ?? 'N/A' }}</td>
</tr>
<tr>
<td>Trạng thái</td>
<td><span class="badge badge-green">✅ Active</span></td>
</tr>
</table>
<div class="section-label">Tài khoản FTP / System User (đã gửi cho khách)</div>
<div class="cred-box">
<div class="cred-row">
<span class="cred-label">👤 FTP Username</span>
<span class="cred-value">{{ $ftp_username ?? 'N/A' }}</span>
</div>
@if(!empty($ftp_password))
<div class="cred-row">
<span class="cred-label">🔑 FTP Password</span>
<span class="cred-value">{{ $ftp_password }}</span>
</div>
@endif
</div>
<div class="section-label">Tài khoản đăng nhập Plesk Panel của khách hàng</div>
<div class="cred-box">
<div class="cred-row">
<span class="cred-label">🌐 Panel URL</span>
<span class="cred-value">{{ $plesk_panel_url ?? 'N/A' }}</span>
</div>
<div class="cred-row">
<span class="cred-label">👤 Login</span>
<span class="cred-value">{{ $plesk_login ?? 'N/A' }}</span>
</div>
@if(!empty($plesk_password))
<div class="cred-row">
<span class="cred-label">🔑 Password</span>
<span class="cred-value">{{ $plesk_password }}</span>
</div>
@endif
</div>
<div class="note">
Đây là tài khoản Plesk riêng của khách hàng (đã gửi kèm cho khách), khác với tài khoản quản trị
của server dùng chung — tài khoản quản trị server không được đính kèm trong email này vì lý do
bảo mật.
</div>
</div>
<div class="footer">
© {{ date('Y') }} {{ $company_name ?? 'Portal Admin' }} — Hệ thống quản lý dịch vụ<br>
Email này được gửi tự động. Vui lòng không trả lời.
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,231 @@
@php
$appName = $appName ?? config('app.name', 'Thế Giới Số');
$fullName = $fullName ?? 'Quý khách';
$domainName = $domainName ?? '';
$hostingPlan = $hostingPlan ?? '';
$serverHost = $serverHost ?? '';
$ftpUsername = $ftpUsername ?? '';
$ftpPassword = $ftpPassword ?? '';
$pleskLogin = $pleskLogin ?? '';
$pleskPassword = $pleskPassword ?? '';
$pleskPanelUrl = $pleskPanelUrl ?? '';
$loginUrl = $loginUrl ?? rtrim(config('app.frontend_url', ''), '/') . '/dang-nhap';
$supportEmail = $supportEmail ?? 'support@tgs.com.vn';
$supportPhone = $supportPhone ?? '1900. 6119';
@endphp
<table style="border-collapse: collapse; width: 100%; background-color: #efefef;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding: 20px;" align="center" valign="top">
<table style="padding-top: 20px; padding-bottom: 20px; border-collapse: collapse; background-color: #ffffff; width: 700px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr class="NoiDungKM">
<td style="width: 700px;" valign="top">
<table style="border-collapse: collapse; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="background-color: #f06824; padding: 34px 30px 30px; text-align: center; font-family: Arial, Helvetica, sans-serif; color: #ffffff;" align="center" valign="top" bgcolor="#f06824">
<div style="font-size: 42px; line-height: 1; margin-bottom: 12px;">🎉</div>
<h1 style="margin: 0 0 8px; padding: 0; color: #ffffff; font-family: Arial, Helvetica, sans-serif; font-size: 24px; line-height: 1.35; font-weight: 700;">
Hosting của bạn đã sẵn sàng
</h1>
<div style="font-size: 14px; line-height: 1.6; color: #ffffff;">
Gói hosting cho tên miền <strong>{{ $domainName }}</strong> đã được khởi tạo thành công
</div>
</td>
</tr>
<tr class="MXH">
<td style="text-align: center; padding: 0 30px;" align="center" valign="top">
<table style="border-collapse: collapse; background-color: #ffffff; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="height: 15px; font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 1.7; color: #000000;" valign="top" height="15">
<div style="text-align: left;">&nbsp;</div>
<div style="text-align: left;">Xin chào <strong>{{ $fullName }}</strong>,</div>
<div style="text-align: left;">&nbsp;</div>
<div style="text-align: left;">
Dịch vụ hosting của bạn tại <strong>{{ $appName }}</strong> đã được khởi tạo thành công. Dưới đây là thông tin truy cập:
</div>
<div style="text-align: left;">&nbsp;</div>
<table style="border-collapse: collapse; width: 100%; background-color: #f9fafb; border: 1px dashed #d1d5db; border-radius: 6px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding: 14px 18px; font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 1.8; color: #000000;">
<div>Tên miền: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $domainName }}</strong></div>
<div>Gói hosting: <strong style="color: #111827;">{{ $hostingPlan }}</strong></div>
@if($serverHost)
<div>Máy chủ / FTP Host: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $serverHost }}</strong></div>
@endif
@if($ftpUsername)
<div>Tài khoản FTP: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $ftpUsername }}</strong></div>
@endif
@if($ftpPassword)
<div>Mật khẩu FTP: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $ftpPassword }}</strong></div>
@endif
<div>Trạng thái: <strong style="color: #16a34a;">Đang hoạt động ✓</strong></div>
</td>
</tr>
</tbody>
</table>
<div style="text-align: left;">&nbsp;</div>
@if($ftpPassword)
<div style="text-align: left; color: #b45309; font-size: 13px;">
⚠️ Vì lý do bảo mật, mật khẩu FTP chỉ được gửi một lần duy nhất qua email và không được lưu trữ trên hệ thống. Vui lòng lưu lại ở nơi an toàn.
</div>
<div style="text-align: left;">&nbsp;</div>
@endif
@if($pleskLogin)
<div style="text-align: left;"><strong>Tài khoản đăng nhập Plesk Panel</strong> (để tự quản lý domain, DNS, database, mail...):</div>
<div style="text-align: left;">&nbsp;</div>
<table style="border-collapse: collapse; width: 100%; background-color: #f9fafb; border: 1px dashed #d1d5db; border-radius: 6px;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="padding: 14px 18px; font-family: Arial, Helvetica, sans-serif; font-size: 14px; line-height: 1.8; color: #000000;">
<div>Địa chỉ Panel: <strong><a style="color: #f06824; text-decoration: none;" href="{{ $pleskPanelUrl }}" target="_blank" rel="noopener">{{ $pleskPanelUrl }}</a></strong></div>
<div>Tên đăng nhập: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $pleskLogin }}</strong></div>
@if($pleskPassword)
<div>Mật khẩu: <strong style="font-family: 'Menlo','Consolas',monospace; color: #111827;">{{ $pleskPassword }}</strong></div>
@endif
</td>
</tr>
</tbody>
</table>
<div style="text-align: left;">&nbsp;</div>
@endif
<div style="text-align: left;">
Bạn có thể đăng nhập vào cổng quản lý để theo dõi và quản lý dịch vụ của mình.
</div>
<div style="text-align: left;">&nbsp;</div>
<div style="text-align: center;">
<a style="display: inline-block; background-color: #f06824; color: #ffffff !important; text-decoration: none; padding: 12px 28px; border-radius: 3px; font-family: Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 700;" href="{{ $loginUrl }}" target="_blank" rel="noopener">
Đăng nhập ngay
</a>
</div>
<div style="text-align: left;">&nbsp;</div>
<div style="text-align: left; color: #6b7280; font-size: 13px;">
Nếu bạn không yêu cầu dịch vụ này, vui lòng liên hệ ngay với chúng tôi qua <strong>{{ $supportEmail }}</strong> hoặc <strong>{{ $supportPhone }}</strong>.
</div>
<div style="text-align: left;">&nbsp;</div>
<div style="text-align: left; color: #666666; font-size: 13px;">
Email này được gửi tự động. Vui lòng không trả lời email này.
</div>
<div style="text-align: left;">&nbsp;</div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="CacDV">
<td style="background-color: #f06824; width: 700px; color: #ffffff;" valign="top" bgcolor="#f06824">
<table style="border-collapse: collapse; background-color: #f06824; width: 100%; color: #ffffff;" border="0" cellspacing="0" cellpadding="0" align="left" bgcolor="#f06824">
<tbody>
<tr>
<td style="padding: 0;" width="100%">
<table style="border-collapse: collapse; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="width: 100%; height: 1px; background: #ffffff;" bgcolor="#ffffff" width="100%" height="1"><span style="font-size: 14px; color: #ffffff;">&nbsp;</span></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="height: 10px; color: #ffffff;" valign="top" height="10"><span style="font-size: 14px; color: #ffffff;">&nbsp;</span></td>
</tr>
<tr>
<td style="padding: 0; text-align: left; font-family: Helvetica, Arial, sans-serif; color: #ffffff; font-size: 16px; line-height: 150%;" align="center" valign="top">
<table style="border-collapse: collapse; color: #ffffff;" border="0" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td style="width: 3%; color: #ffffff;"><span style="color: #ffffff;">&nbsp;</span></td>
<td style="vertical-align: middle; text-align: center; padding: 5px 10px; border: 1px solid #ffffff; color: #ffffff;" valign="top">
<a style="color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 10px; line-height: 1; font-weight: normal; text-transform: uppercase; word-wrap: break-word; text-decoration: none;" href="https://tgs.com.vn/premium-hosting/" target="_blank" rel="noopener"><span style="color: #ffffff;">Premium HOSTING</span></a>
</td>
<td style="width: 3%; color: #ffffff;"><span style="color: #ffffff;">&nbsp;</span></td>
<td style="vertical-align: middle; text-align: center; padding: 5px 10px; border: 1px solid #ffffff; color: #ffffff;" valign="top">
<a style="color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 10px; line-height: 1; font-weight: normal; text-transform: uppercase; word-wrap: break-word; text-decoration: none;" href="https://tgs.com.vn/cloud-server/" target="_blank" rel="noopener"><span style="color: #ffffff;">Cloud SERVER</span></a>
</td>
<td style="width: 3%; color: #ffffff;"><span style="color: #ffffff;">&nbsp;</span></td>
<td style="vertical-align: middle; text-align: center; padding: 5px 10px; border: 1px solid #ffffff; color: #ffffff;" valign="top">
<a style="color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 10px; line-height: 1; font-weight: normal; text-transform: uppercase; word-wrap: break-word; text-decoration: none;" href="https://cloudemail.vn/" target="_blank" rel="noopener"><span style="color: #ffffff;">EMAIL DOANH NGHIỆP</span></a>
</td>
<td style="width: 3%; color: #ffffff;"><span style="color: #ffffff;">&nbsp;</span></td>
<td style="vertical-align: middle; text-align: center; padding: 5px 10px; border: 1px solid #ffffff; color: #ffffff;" valign="top">
<a style="color: #ffffff; font-family: Helvetica, Arial, sans-serif; font-size: 10px; line-height: 1; font-weight: normal; text-transform: uppercase; word-wrap: break-word; text-decoration: none;" href="https://tgs.com.vn/thiet-ke-website/" target="_blank" rel="noopener"><span style="color: #ffffff;">Thiết Kế WEBSITE</span></a>
</td>
<td style="width: 3%; color: #ffffff;"><span style="color: #ffffff;">&nbsp;</span></td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td style="height: 10px; color: #ffffff;" valign="top" height="10"><span style="font-size: 14px; color: #ffffff;">&nbsp;</span></td>
</tr>
<tr>
<td style="padding: 0;" width="100%">
<table style="border-collapse: collapse; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="width: 100%; height: 1px; background: #ffffff;" bgcolor="#ffffff" width="100%" height="1"><span style="font-size: 14px; color: #ffffff;">&nbsp;</span></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr class="ThongTin">
<td align="center" valign="top" bgcolor="#065d88">
<table style="border-collapse: collapse; background-color: #f06824; border-top: 0; border-bottom: 0; width: 100%;" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 30px;">
<td style="height: 30px;" valign="top" height="10">&nbsp;</td>
</tr>
<tr style="height: 148px;">
<td style="padding: 0; font-family: Helvetica, Arial, sans-serif; text-decoration: none; color: #e7e7e7; font-size: 16px; font-weight: normal; line-height: 150%; vertical-align: top; text-align: center; height: 148px;" align="center">
<p style="margin: 0; padding: 0; font-family: Helvetica, Arial, sans-serif; color: white; font-size: 11pt; line-height: 200%;">
<span style="color: #ffffff; font-family: 'times new roman', times, serif;"><strong style="font-size: 20px;">CÔNG TY CỔ PHẦN GIẢI PHÁP CÔNG NGHỆ THẾ GIỚI SỐ</strong></span><br>
<span style="color: #ffffff; font-family: arial, helvetica, sans-serif; font-size: 12pt;">Địa chỉ: 128/38 Tân Hương, Phường Phú Thọ Hòa, Thành Phố Hồ Chí Minh</span><br>
<span style="color: #ffffff; font-family: arial, helvetica, sans-serif; font-size: 12pt;">Tel: (028) 7309. 7379 - Tổng đài: {{ $supportPhone }}</span><br>
<span style="font-family: arial, helvetica, sans-serif; font-size: 12pt;">Email: <span style="color: #ffffff;"><a style="color: #ffffff; text-decoration: none;" href="mailto:{{ $supportEmail }}">{{ $supportEmail }}</a></span></span><br>
<span style="text-decoration: none; font-family: arial, helvetica, sans-serif; font-size: 12pt; color: #ffffff !important;">
<a style="color: #ffffff !important; text-decoration: none;" href="https://www.tgs.com.vn">www.TGS.com.vn</a> &amp;
<a style="color: #ffffff !important; text-decoration: none;" href="https://www.thegioiso.cloud">www.thegioiso.CLOUD</a> &amp;
<a style="color: #ffffff !important; text-decoration: none;" href="https://www.thegioiserver.com">www.thegioiSERVER.com</a> &amp;
<a style="color: #ffffff !important; text-decoration: none;" href="https://www.cloudemail.vn">www.CloudEmail.vn</a>
</span>
</p>
<p style="margin: 0; padding: 0; font-family: Helvetica, Arial, sans-serif; color: white; font-size: 11pt; line-height: 200%;">
<span style="text-decoration: none; font-family: 'times new roman', times, serif; color: #ffffff !important; font-size: 12pt;">
<span style="color: #ffffff; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 10pt;">
<span style="text-decoration: none; font-family: 'times new roman', times, serif; color: #ffffff !important;">
<span style="font-family: arial, sans-serif;"><strong>🥇Thế Giới Số🥇</strong>- Premium HOSTING • CLOUD • SERVER &amp; WEBSITE | 15+ năm Phụng Sự 🚀</span>
</span>
</span>
</span>
</p>
</td>
</tr>
<tr>
<td style="height: 30px; color: #ffffff;" valign="top" height="30"><span style="font-size: 14px; color: #ffffff;">&nbsp;</span></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
+15
View File
@@ -25,6 +25,7 @@ use App\Http\Controllers\Api\Admin\VCenter\VCenterController;
use App\Http\Controllers\Api\Admin\DnsManager\ServerController as DnsServerController;
use App\Http\Controllers\Api\Admin\DnsManager\DomainController as DnsDomainController;
use App\Http\Controllers\Api\Admin\DnsManager\RecordController as DnsRecordController;
use App\Http\Controllers\Api\Admin\Hosting\HostingAccountController;
use App\Http\Controllers\Api\Admin\OsManager\OsGroupController;
use App\Http\Controllers\Api\Admin\OsManager\OsController;
use App\Http\Controllers\Api\Admin\IpPool\IpPoolController;
@@ -420,6 +421,20 @@ Route::prefix('v1')
Route::put('{id}', 'update')->middleware('perm:domain.manager');
});
// Hosting Manager (module: hosting)
Route::prefix('hosting-accounts')
->controller(HostingAccountController::class)
->group(function () {
Route::get('/', 'index')->middleware('perm:hosting.view');
Route::get('{id}', 'show')->middleware('perm:hosting.view');
Route::post('/', 'store')->middleware('perm:hosting.create');
Route::put('{id}', 'update')->middleware('perm:hosting.edit');
Route::delete('{id}', 'destroy')->middleware('perm:hosting.destroy');
Route::post('{id}/suspend', 'suspend')->middleware('perm:hosting.edit');
Route::post('{id}/unsuspend', 'unsuspend')->middleware('perm:hosting.edit');
Route::post('{id}/reset-ftp-password', 'resetFtpPassword')->middleware('perm:hosting.edit');
});
// InfraManagement (jumphost, vcenter config)
Route::prefix('infra-management')
->controller(InfraManagementController::class)