feat: nhắc gia hạn QR theo dịch vụ, failover server hosting, CCCD admin, log cấp phát dịch vụ

- Mail campaign: mẫu nhắc gia hạn thanh toán QR, chọn dịch vụ + chu kỳ từng dòng (renewal_services)
- Hosting: nhiều server Plesk cho một gói (service_plan_servers), chuyển server khi server chết
- Admin xem/sửa giấy tờ định danh khách, tuỳ chọn gia hạn cho khách, nhật ký cấp phát dịch vụ
- Đánh dấu mẫu email dịch vụ là non-marketing

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-30 18:36:41 +07:00
co-authored by Claude Sonnet 5.5
parent 047c23beff
commit 55a834a2f8
53 changed files with 1463 additions and 119 deletions
@@ -17,6 +17,7 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use App\Support\BillingCycleCatalog;
use App\Support\RenewalPeriodGuard;
use App\Support\ServiceProvisionLog;
trait ManagesCustomerServices
{
@@ -134,6 +135,19 @@ trait ManagesCustomerServices
return response()->json(['error' => false, 'data' => $renewals]);
}
public function serviceProvisioningLogs(string $uuid, int $serviceId): JsonResponse
{
$service = Service::where('customer_id', $this->resolveCustomer($uuid)->id)->findOrFail($serviceId);
$logs = ActivityLog::where('subject_type', Service::class)
->where('subject_id', $service->id)
->whereIn('event', ServiceProvisionLog::EVENTS)
->orderBy('id')
->get(['id', 'event', 'description', 'causer_type', 'causer_name', 'new_values', 'created_at']);
return response()->json(['error' => false, 'data' => $logs]);
}
public function renewService(string $uuid, int $serviceId, Request $request): JsonResponse
{
$data = $request->validate([
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Api\Admin\Customer;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Support\CustomerIdentity;
use Illuminate\Http\JsonResponse;
class CustomerIdentityController extends Controller
{
public function show(string $uuid): JsonResponse
{
return response()->json([
'error' => false,
'data' => CustomerIdentity::payload(Customer::where('uuid', $uuid)->firstOrFail()),
]);
}
public function image(Customer $customer, string $side)
{
return CustomerIdentity::response($customer, $side);
}
}
@@ -128,6 +128,7 @@ class EmailTemplateController extends Controller
'message' => 'nullable|string',
'builder_data' => 'nullable|array',
'status' => 'boolean',
'marketing' => 'nullable|boolean',
'mail_config' => 'nullable|array',
'mail_config.from_email' => 'nullable|email',
'mail_config.from_name' => 'nullable|string|max:255',
@@ -151,7 +152,10 @@ class EmailTemplateController extends Controller
'message' => $data['message'] ?? null,
'builder_data' => $data['builder_data'] ?? null,
'status' => $data['status'] ?? 1,
'metadata' => isset($data['mail_config']) ? ['mail' => $data['mail_config']] : null,
'metadata' => array_filter([
'mail' => $data['mail_config'] ?? null,
'marketing' => isset($data['marketing']) ? (bool) $data['marketing'] : null,
], fn ($value) => $value !== null) ?: null,
]);
$this->syncVariables($template, $data['variables'] ?? []);
$guard->assertCanSave($template);
@@ -177,6 +181,7 @@ class EmailTemplateController extends Controller
'message' => 'sometimes|nullable|string',
'builder_data' => 'sometimes|nullable|array',
'status' => 'sometimes|boolean',
'marketing' => 'sometimes|boolean',
'mail_config' => 'sometimes|nullable|array',
'mail_config.from_email' => 'nullable|email',
'mail_config.from_name' => 'nullable|string|max:255',
@@ -194,8 +199,11 @@ class EmailTemplateController extends Controller
$metadata['mail'] = $data['mail_config'] ?? [];
$data['metadata'] = $metadata;
}
if (array_key_exists('marketing', $data)) {
$data['metadata'] = [...($data['metadata'] ?? $template->metadata ?? []), 'marketing' => (bool) $data['marketing']];
}
$variables = $data['variables'] ?? [];
unset($data['mail_config'], $data['variables']);
unset($data['mail_config'], $data['variables'], $data['marketing']);
$template->fill($data);
$this->syncVariables($template, $variables);
@@ -401,7 +409,8 @@ class EmailTemplateController extends Controller
'variables' => array_values($t->variables()),
'mail_config' => $t->mailConfig(),
'placeholders' => $this->placeholders($t),
...collect(EmailScenarioRegistry::describe($t->key, $t->scenario))->only(['registered', 'category', 'group', 'permissions', 'required_variables'])->all(),
...collect(EmailScenarioRegistry::describe($t->key, $t->scenario))->only(['registered', 'group', 'permissions', 'required_variables'])->all(),
'category' => $t->category(),
'global_variables' => collect(MailGlobals::LABELS)->map(fn ($label, $key) => ['key' => $key, 'label' => $label])->values(),
'created_at' => $t->created_at,
'updated_at' => $t->updated_at,
@@ -13,14 +13,14 @@ class ServicePlanController extends Controller
{
public function index(): JsonResponse
{
$plans = ServicePlan::with('plesk', 'dnsServer')->orderBy('sort_order')->orderBy('title')->get();
$plans = ServicePlan::with('plesk', 'servers')->orderBy('sort_order')->orderBy('title')->get();
return response()->json(['error' => false, 'data' => $plans]);
}
public function show(int $id): JsonResponse
{
$plan = ServicePlan::with('plesk', 'dnsServer')->find($id);
$plan = ServicePlan::with('plesk', 'servers')->find($id);
if (!$plan) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy gói hosting.'], 404);
@@ -33,12 +33,13 @@ class ServicePlanController extends Controller
{
$plan = ServicePlan::create($request->planAttributes());
$plan->syncServers($request->serverIds());
$this->savePlesk($plan, $request->validated());
return response()->json([
'error' => false,
'message' => 'Tạo gói hosting thành công.',
'data' => $plan->load('plesk', 'dnsServer'),
'data' => $plan->load('plesk', 'servers'),
], 201);
}
@@ -52,12 +53,13 @@ class ServicePlanController extends Controller
$plan->update($request->planAttributes());
$plan->syncServers($request->serverIds());
$this->savePlesk($plan, $request->validated());
return response()->json([
'error' => false,
'message' => 'Cập nhật gói hosting thành công.',
'data' => $plan->fresh(['plesk', 'dnsServer']),
'data' => $plan->fresh(['plesk', 'servers']),
]);
}
@@ -74,7 +74,7 @@ trait HandlesCampaignBulkActions
$failedLogs = Mail::where('campaign_id', $campaign->id)
->where('status', array_search('failed', Mail::STATUS_MAP, true))
->lockForUpdate()
->get(['id', 'to', 'customer_id']);
->get(['id', 'to', 'customer_id', 'service_id']);
if ($failedLogs->isEmpty()) {
return;
}
@@ -87,7 +87,7 @@ trait HandlesCampaignBulkActions
])->save();
foreach ($failedLogs as $log) {
SendMailCampaignRecipient::dispatch($campaign->id, $log->customer_id, $log->to)->afterCommit();
SendMailCampaignRecipient::dispatch($campaign->id, $log->customer_id, $log->to, $log->service_id)->afterCommit();
}
$retried += $failedLogs->count();
});
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin\MailCampaign\Concerns;
use App\Models\Customer;
use App\Models\MailCampaign;
use App\Models\Service;
use App\Support\RenewalCampaign;
use App\Support\RenewalQuote;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
trait HandlesRenewalCampaigns
{
public function renewalServices(Request $request): JsonResponse
{
$data = $request->validate([
'uuids' => 'required|array|min:1|max:200',
'uuids.*' => 'string|exists:customers,uuid',
'days' => 'nullable|integer|min:1|max:365',
]);
$customerIds = Customer::whereIn('uuid', $data['uuids'])->pluck('id')->all();
$today = now()->startOfDay();
$rows = RenewalQuote::dueServices($customerIds, (int) ($data['days'] ?? 30))
->map(function (Service $service) use ($today) {
$quote = RenewalQuote::forService($service);
return $quote ? [
...$quote,
'customer_uuid' => $service->customer->uuid,
'customer_name' => $service->customer->fullname,
'customer_email' => $service->customer->email,
'days_left' => (int) $today->diffInDays($service->expires_at->copy()->startOfDay(), false),
] : null;
})
->filter()
->values();
return response()->json(['error' => false, 'data' => $rows]);
}
/**
* @param array<int, array{service_id: int, months: int}> $selected
* @return array<int, array{customer_id: int, email: string, service_id: int}>
*/
private function renewalJobs(MailCampaign $campaign, array $selected): array
{
if (! RenewalCampaign::isRenewalTemplate($campaign)) {
throw ValidationException::withMessages(['renewal_services' => 'Template đã chọn không phải mẫu nhắc gia hạn.']);
}
$services = Service::with('customer:id,email')
->whereIn('id', array_column($selected, 'service_id'))
->get();
return $services
->filter(fn (Service $service) => $service->customer && trim((string) $service->customer->email) !== '')
->map(fn (Service $service) => [
'customer_id' => $service->customer->id,
'email' => trim($service->customer->email),
'service_id' => $service->id,
])
->values()
->all();
}
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Http\Controllers\Api\Admin\MailCampaign;
use App\Http\Controllers\Api\Admin\MailCampaign\Concerns\HandlesCampaignBulkActions;
use App\Http\Controllers\Api\Admin\MailCampaign\Concerns\HandlesRenewalCampaigns;
use App\Http\Controllers\Controller;
use App\Jobs\Mail\SendMailCampaignRecipient;
use App\Models\Customer;
@@ -16,6 +17,7 @@ use App\Support\AutoEmailGate;
use App\Support\MailAttachments;
use App\Support\MailPlaceholders;
use App\Support\MailSettings;
use App\Support\RenewalCampaign;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
@@ -28,6 +30,7 @@ use Illuminate\Validation\ValidationException;
final class MailCampaignController extends Controller
{
use HandlesCampaignBulkActions;
use HandlesRenewalCampaigns;
private const MAX_EMAILS = 1000;
@@ -253,6 +256,9 @@ final class MailCampaignController extends Controller
'emails' => 'nullable|array|max:' . self::MAX_EMAILS,
'emails.*' => self::EMAIL_RULE,
'name' => 'nullable|string|max:255',
'renewal_services' => 'nullable|array|max:500',
'renewal_services.*.service_id' => 'required|integer|exists:services,id',
'renewal_services.*.months' => 'required|integer|min:1|max:600',
'cc' => 'nullable|string|max:1000',
'bcc' => 'nullable|string|max:1000',
...MailAttachments::rules(),
@@ -263,12 +269,25 @@ final class MailCampaignController extends Controller
$campaign = $this->draftCampaign($data);
$marketingOnly = $campaign->isMarketing();
$recipients = $data['recipient_type'] === 'all'
? $this->allCustomerRecipients($marketingOnly)
: $this->selectedRecipients($data['uuids'] ?? [], $data['emails'] ?? [], $marketingOnly);
$optedOut = $recipients['opted_out'];
$recipients = $recipients['recipients'];
$renewalJobs = [];
$optedOut = 0;
if (!empty($data['renewal_services'])) {
$renewalJobs = $this->renewalJobs($campaign, $data['renewal_services']);
$campaign->renewal_services = array_values(array_filter(
$data['renewal_services'],
fn (array $item) => in_array((int) $item['service_id'], array_column($renewalJobs, 'service_id'), true),
));
$campaign->variables = RenewalCampaign::withoutServiceValues($campaign->variables);
$data['recipient_type'] = 'selected';
$recipients = $renewalJobs;
} else {
$marketingOnly = $campaign->isMarketing();
$resolved = $data['recipient_type'] === 'all'
? $this->allCustomerRecipients($marketingOnly)
: $this->selectedRecipients($data['uuids'] ?? [], $data['emails'] ?? [], $marketingOnly);
$optedOut = $resolved['opted_out'];
$recipients = $resolved['recipients'];
}
if ($recipients === []) {
return response()->json([
@@ -299,8 +318,14 @@ final class MailCampaignController extends Controller
]);
}
foreach ($recipients as $email => $customerId) {
SendMailCampaignRecipient::dispatch($campaign->id, $customerId, $email);
if ($renewalJobs !== []) {
foreach ($renewalJobs as $job) {
SendMailCampaignRecipient::dispatch($campaign->id, $job['customer_id'], $job['email'], $job['service_id']);
}
} else {
foreach ($recipients as $email => $customerId) {
SendMailCampaignRecipient::dispatch($campaign->id, $customerId, $email);
}
}
return response()->json([
@@ -51,7 +51,7 @@ trait HandlesClientAuthentication
if ($twoFactor->requiresChallenge($client, $request->input('device_token'))) {
return response()->json([
'error' => false,
'data' => ['two_factor' => $twoFactor->startLoginChallenge($client)],
'data' => ['two_factor' => $twoFactor->startLoginChallenge($client, $request->ip(), $request->userAgent())],
]);
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\Api\Client\Service;
use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Support\RenewalPricing;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ServiceRenewalOptionsController extends Controller
{
public function __invoke(Request $request, string $uuid): JsonResponse
{
$service = Service::with(['orderItem.product', 'product', 'customProduct'])
->where('uuid', $uuid)
->where('customer_id', $request->user()->id)
->firstOrFail();
$source = $service->customProduct ?? $service->orderItem?->product ?? $service->product;
return response()->json([
'error' => false,
'data' => [
'options' => RenewalPricing::options($source),
'addon_total' => RenewalPricing::addonTotal($service, 1),
],
]);
}
}
@@ -34,7 +34,8 @@ class ServicePlanRequest extends FormRequest
'features.*' => 'string|distinct|max:100',
'is_active' => 'boolean',
'sort_order' => 'nullable|integer|min:0',
'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id',
'server_ids' => 'nullable|array|max:10',
'server_ids.*' => 'integer|distinct|exists:dns_manager_servers,id',
'plesk_plan_name' => 'nullable|string|max:255',
'note' => 'nullable|string',
];
@@ -48,10 +49,17 @@ class ServicePlanRequest extends FormRequest
$validated = $this->validated();
return [
...collect($validated)->except(['plesk_plan_name', 'note'])->all(),
'dns_manager_server_id' => $validated['dns_manager_server_id'] ?? null,
...collect($validated)->except(['plesk_plan_name', 'note', 'server_ids'])->all(),
'sort_order' => $validated['sort_order'] ?? 0,
'is_active' => $validated['is_active'] ?? true,
];
}
/**
* @return array<int, int>
*/
public function serverIds(): array
{
return $this->validated()['server_ids'] ?? [];
}
}
@@ -14,9 +14,9 @@ class ClientUpdateCccdRequest extends FormRequest
public function rules(): array
{
return [
'cmnd' => 'required|string|max:50',
'cmnd_before' => 'required|mimes:jpg,jpeg,png,webp|max:5120',
'cmnd_after' => 'required|mimes:jpg,jpeg,png,webp|max:5120',
'cmnd' => 'required|string|regex:/^\d{9}(\d{3})?$/',
'cmnd_before' => 'required|file|mimetypes:image/webp|mimes:webp|max:5120|dimensions:min_width=300,min_height=300,max_width=2000,max_height=2000',
'cmnd_after' => 'required|file|mimetypes:image/webp|mimes:webp|max:5120|dimensions:min_width=300,min_height=300,max_width=2000,max_height=2000',
];
}
@@ -24,10 +24,17 @@ class ClientUpdateCccdRequest extends FormRequest
{
return [
'cmnd.required' => 'Số CMT/CCCD là bắt buộc',
'cmnd.regex' => 'Số CMT/CCCD phải gồm 9 hoặc 12 chữ số',
'cmnd_before.required' => 'Ảnh mặt trước là bắt buộc',
'cmnd_before.image' => 'Ảnh mặt trước phải là hình ảnh',
'cmnd_before.mimetypes' => 'Ảnh mặt trước phải là ảnh WebP',
'cmnd_before.mimes' => 'Ảnh mặt trước phải là ảnh WebP',
'cmnd_before.max' => 'Ảnh mặt trước tối đa 5MB',
'cmnd_before.dimensions' => 'Ảnh mặt trước phải từ 300px đến 2000px mỗi cạnh',
'cmnd_after.required' => 'Ảnh mặt sau là bắt buộc',
'cmnd_after.image' => 'Ảnh mặt sau phải là hình ảnh',
'cmnd_after.mimetypes' => 'Ảnh mặt sau phải là ảnh WebP',
'cmnd_after.mimes' => 'Ảnh mặt sau phải là ảnh WebP',
'cmnd_after.max' => 'Ảnh mặt sau tối đa 5MB',
'cmnd_after.dimensions' => 'Ảnh mặt sau phải từ 300px đến 2000px mỗi cạnh',
];
}
}
@@ -98,7 +98,6 @@ class ServiceClientDetailResource extends JsonResource
$vm = $this->resource->vmware;
$product = $orderItem?->product ?? $this->resource->product;
$custom = $this->resource->customProduct;
$renewalSource = $custom ?? $product;
$hosting = $this->resource->hostingAccount;
$pleskCredentials = $hosting ? $this->resolvePleskCredentials($hosting) : null;
$dnsZone = $this->resolveDnsZone();
@@ -124,14 +123,6 @@ class ServiceClientDetailResource extends JsonResource
'total' => (float) $order->total,
'months' => (int) $orderItem->months,
'billing_label' => $orderItem->billing_label,
'cycle_price' => $custom
? (float) $custom->unit_price * (int) $orderItem->months
: (float) ($product?->pricings()
->where('billing_cycle', $orderItem->billing_cycle)
->where('is_active', 1)
->value('price') ?? 0),
'addon_total' => \App\Support\RenewalPricing::addonTotal($this->resource, 1),
'renewal_options' => \App\Support\RenewalPricing::options($renewalSource),
] : null,
'vm' => $vm ? [
'ip_address' => $vm->ipAddress?->ip ?? $vm->ip,
@@ -145,6 +136,7 @@ class ServiceClientDetailResource extends JsonResource
] : null,
'hosting' => $hosting ? [
'ip_address' => $hosting->server?->publicHost(),
'server_ip' => $hosting->server?->ip_address,
'plesk_url' => $hosting->server?->panelUrl(),
'username' => ResponseCipher::encrypt($pleskCredentials['login'] ?? null),
'password' => ResponseCipher::encrypt($pleskCredentials['password'] ?? null),
+57 -61
View File
@@ -7,6 +7,8 @@ namespace App\Jobs\Hosting;
use App\Models\Invoice;
use App\Models\OrderItem;
use App\Models\ServicePlan;
use App\Services\Hosting\HostingProvisionFailure;
use App\Services\Hosting\HostingServerSelector;
use App\Services\Plesk\PleskHostingService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -14,6 +16,8 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Throwable;
use App\Support\ServiceProvisionLog;
/**
* Auto-provisions a Plesk hosting account when a hosting order is paid,
@@ -26,97 +30,89 @@ class ProvisionHostingAccountJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** Plesk subscription creation can take a couple of minutes */
public int $timeout = 300;
/** No auto-retry — hosting provisioning errors need manual review */
public int $tries = 1;
public function __construct(public OrderItem $item)
{
}
public function handle(PleskHostingService $plesk): void
public function handle(PleskHostingService $plesk, HostingServerSelector $servers, HostingProvisionFailure $failure): void
{
try {
$error = $this->provision($plesk, $servers, $failure);
} catch (Throwable $e) {
$error = $e->getMessage();
}
if ($error !== null) {
$failure->handle($this->item, $error);
}
}
private function provision(PleskHostingService $plesk, HostingServerSelector $servers, HostingProvisionFailure $failure): ?string
{
$service = $this->item->service()->first();
$domainName = $this->item->server_name;
if (! $service || ! $domainName) {
Log::channel('Custom')->warning('ProvisionHostingAccountJob skipped: missing service or domain', [
'order_item_id' => $this->item->id,
]);
return;
return 'Không tìm thấy dịch vụ hoặc tên miền của đơn hàng.';
}
$servicePlanId = $this->item->product?->service_plan_id;
$servicePlan = $servicePlanId
? ServicePlan::with(['plesk', 'dnsServer'])->find($servicePlanId)
: null;
$servicePlan = $servicePlanId ? ServicePlan::with('plesk')->find($servicePlanId) : null;
$hostingPlan = $servicePlan?->plesk?->plesk_plan_name;
$server = $servicePlan?->dnsServer;
Log::channel('Custom')->info('ProvisionHostingAccountJob resolved service plan', [
'order_item_id' => $this->item->id,
'product_id' => $this->item->product_id,
'product_name' => $this->item->product?->name,
'service_plan_id' => $servicePlanId,
'plesk_plan_name' => $hostingPlan,
'dns_manager_server_id' => $server?->id,
'dns_manager_server_ip' => $server?->ip_address,
'order_item_id' => $this->item->id,
'product_id' => $this->item->product_id,
'product_name' => $this->item->product?->name,
'service_plan_id' => $servicePlanId,
'plesk_plan_name' => $hostingPlan,
]);
if (! $hostingPlan) {
Log::channel('Custom')->error('ProvisionHostingAccountJob failed: no service_plan_plesk mapping for this product', [
'order_item_id' => $this->item->id,
'product_id' => $this->item->product_id,
'service_plan_id' => $servicePlanId,
]);
return;
return 'Sản phẩm chưa gắn gói Plesk (service_plan_plesk).';
}
if (! $server) {
Log::channel('Custom')->error('ProvisionHostingAccountJob failed: service plan has no dns_manager_server_id configured', [
'order_item_id' => $this->item->id,
'product_id' => $this->item->product_id,
'service_plan_id' => $servicePlanId,
]);
ServiceProvisionLog::record($service, 'provision_started', 'Bắt đầu khởi tạo hosting', ['domain' => $domainName, 'plesk_plan' => $hostingPlan]);
return;
}
$invoiceId = Invoice::where('order_id', $this->item->order_id)->where('invoice_type', 1)->orderBy('id')->value('id');
$triedServerIds = [];
$lastError = null;
if (! $server->servesHosting()) {
Log::channel('Custom')->error('ProvisionHostingAccountJob failed: configured server does not serve hosting', [
'order_item_id' => $this->item->id,
'service_plan_id' => $servicePlanId,
while ($server = $servers->pick($servicePlan, $triedServerIds)) {
$triedServerIds[] = $server->id;
$result = $plesk->provision([
'customer_id' => $this->item->order->customer_id,
'service_id' => $service->id,
'dns_manager_server_id' => $server->id,
'server_type' => $server->type,
'domain_name' => $domainName,
'hosting_plan' => $hostingPlan,
'invoice_id' => $invoiceId,
]);
return;
if (! $result['error']) {
$service->update(['status' => 'active']);
ServiceProvisionLog::record($service, 'provision_completed', 'Khởi tạo hoàn tất — dịch vụ đã hoạt động', ['server_id' => $server->id]);
return null;
}
$lastError = $result['message'] ?? 'Plesk trả về lỗi không rõ.';
$servers->forget($server);
if ($servers->isHealthy($server)) {
return $lastError;
}
$failure->serverFailedOver($this->item, $server, $lastError);
}
$result = $plesk->provision([
'customer_id' => $this->item->order->customer_id,
'service_id' => $service->id,
'dns_manager_server_id' => $server->id,
'domain_name' => $domainName,
'hosting_plan' => $hostingPlan,
'invoice_id' => Invoice::where('order_id', $this->item->order_id)->where('invoice_type', 1)->orderBy('id')->value('id'),
]);
if ($result['error']) {
Log::channel('Custom')->error('ProvisionHostingAccountJob failed', [
'order_item_id' => $this->item->id,
'hosting_plan' => $hostingPlan,
'message' => $result['message'] ?? 'Unknown error',
]);
return;
}
$service->update(['status' => 'active']);
return $lastError === null
? 'Gói hosting không có server Plesk nào đang hoạt động.'
: "Tất cả server Plesk của gói đều lỗi. Lỗi cuối: {$lastError}";
}
}
+26 -1
View File
@@ -9,6 +9,7 @@ use App\Models\MailCampaign;
use App\Models\Notification;
use App\Services\Email\MailCampaignRenderer;
use App\Support\EmailRecipients;
use App\Support\RenewalCampaign;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@@ -27,6 +28,7 @@ class SendMailCampaignRecipient implements ShouldQueue
private readonly int $campaignId,
private readonly ?int $customerId,
private readonly string $email,
private readonly ?int $serviceId = null,
) {}
public function handle(MailCampaignRenderer $renderer): void
@@ -43,7 +45,29 @@ class SendMailCampaignRecipient implements ShouldQueue
return;
}
$rendered = $renderer->render($campaign, $renderer->recipientValues($campaign, $customer, $this->email));
$values = $renderer->recipientValues($campaign, $customer, $this->email);
if ($this->serviceId !== null) {
$renewal = $customer ? RenewalCampaign::valuesFor($campaign, $customer, $this->serviceId) : null;
if ($renewal === null) {
MailLog::create([
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $campaign->subject,
'to' => $this->email,
'customer_id' => $customer?->id,
'service_id' => $this->serviceId,
'sent_by' => $campaign->created_by,
'message' => 'Không gửi: dịch vụ không còn thuộc khách hàng hoặc không thể tính giá gia hạn.',
'status' => 'failed',
]);
$this->markDone($campaign, true);
return;
}
$values = [...$values, ...$renewal];
}
$rendered = $renderer->render($campaign, $values);
$cc = EmailRecipients::parse($campaign->cc);
$bcc = EmailRecipients::parse($campaign->bcc);
$mailConfig = Arr::only($campaign->template?->mailConfig() ?? [], ['from_email', 'from_name', 'reply_to', 'reply_to_name']);
@@ -81,6 +105,7 @@ class SendMailCampaignRecipient implements ShouldQueue
'cc' => implode(', ', $cc),
'bcc' => implode(', ', $bcc),
'customer_id' => $customer?->id,
'service_id' => $this->serviceId,
'sent_by' => $campaign->created_by,
'message' => $rendered['html'],
'status' => $failed ? 'failed' : 'sent',
@@ -28,6 +28,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use RuntimeException;
use Throwable;
use App\Support\ServiceProvisionLog;
class CreateVirtualMachineJob implements ShouldQueue
{
@@ -70,6 +71,8 @@ class CreateVirtualMachineJob implements ShouldQueue
['customer_id' => $customerId, 'status' => 'running'],
);
ServiceProvisionLog::forOrderItem($this->item->id, 'provision_started', $this->isRetry ? 'Bắt đầu khởi tạo lại máy chủ' : 'Bắt đầu khởi tạo máy chủ', ['is_retry' => $this->isRetry]);
$vmLogger->step('Create VM job started', [
'order_item_id' => $this->item->id,
'is_retry' => $this->isRetry,
@@ -110,6 +113,8 @@ class CreateVirtualMachineJob implements ShouldQueue
$this->item->server_name = $combinedName;
ServiceProvisionLog::forOrderItem($this->item->id, 'provision_step', 'Đã giữ IP và bắt đầu clone VM', ['ip' => $reservedIp]);
$vmLogger->step('IP reserved for VM', [
'order_item_id' => $this->item->id,
'ip' => $reservedIp,
@@ -226,6 +231,8 @@ class CreateVirtualMachineJob implements ShouldQueue
$adminDetail = $e instanceof VmProvisionException ? $e->adminDetail : $e->getMessage();
ServiceProvisionLog::forOrderItem($this->item->id, 'provision_failed', 'Khởi tạo máy chủ thất bại — ' . $adminDetail, ['stage' => 'create_vm']);
$vmLogger->exception('Create VM job failed', $e, [
'order_item_id' => $this->item->id,
'is_retry' => $this->isRetry,
@@ -22,6 +22,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
use App\Jobs\VirtualMachine\Provision\Concerns\ManagesIpReservation;
/**
@@ -228,6 +229,8 @@ class AssignIpToGuestJob implements ShouldQueue
'attempt' => $attempt,
]);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_step', 'Đã gán IP cho máy chủ', ['ip' => $ip]);
// CPU/RAM config was already applied by UpdateVmConfigJob before IP assignment.
ChangePasswordViaVsphereJob::dispatch(
$this->moduleVmwareId,
@@ -247,6 +250,7 @@ class AssignIpToGuestJob implements ShouldQueue
ModuleVmware::where('id', $this->moduleVmwareId)->update(['status' => 0]);
Service::where('vm_id', $this->moduleVmwareId)->update(['status' => 'failed']);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_failed', "Gán IP thất bại sau {$maxAttempts} lần thử", ['stage' => 'assign_ip']);
// Notify admin via Telegram with order/customer context
try {
@@ -311,6 +315,7 @@ class AssignIpToGuestJob implements ShouldQueue
ModuleVmware::where('id', $this->moduleVmwareId)->update(['status' => 0]);
Service::where('vm_id', $this->moduleVmwareId)->update(['status' => 'failed']);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_failed', 'Gán IP thất bại — ' . $e->getMessage(), ['stage' => 'assign_ip']);
}
// ─────────────────────────────────────────────────────────────────────────
@@ -16,6 +16,7 @@ use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
/**
* ChangePasswordViaVsphereJob
@@ -91,6 +92,8 @@ class ChangePasswordViaVsphereJob implements ShouldQueue
// Provisioning complete — activate the service record
Service::where('vm_id', $this->moduleVmwareId)->update(['status' => 'active']);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_step', 'Đã đặt mật khẩu máy chủ');
// [8] Send credentials email — IP + new password are both ready at this point
SendVmCredentialsEmailJob::dispatch($this->moduleVmwareId);
@@ -112,6 +115,7 @@ class ChangePasswordViaVsphereJob implements ShouldQueue
ModuleVmware::where('id', $this->moduleVmwareId)->update(['status' => 0]);
Service::where('vm_id', $this->moduleVmwareId)->update(['status' => 'failed']);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_failed', 'Đặt mật khẩu máy chủ thất bại — ' . $e->getMessage(), ['stage' => 'set_password']);
}
// ─────────────────────────────────────────────────────────────────────────
@@ -18,6 +18,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
/**
* RetryProvisioningOrchestrator
@@ -337,6 +338,8 @@ class RetryProvisioningOrchestrator implements ShouldQueue
$service->save();
ServiceProvisionLog::record($service, 'provision_completed', 'Khởi tạo lại hoàn tất — dịch vụ đã hoạt động', ['ip' => $moduleVmware->ip]);
if (!$moduleVmware->service_id) {
$moduleVmware->update(['service_id' => $service->id]);
}
@@ -19,6 +19,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
/**
* SendVmCredentialsEmailJob
@@ -154,6 +155,8 @@ class SendVmCredentialsEmailJob implements ShouldQueue
'service_id' => $service->id,
]);
ServiceProvisionLog::record($service, 'provision_completed', 'Khởi tạo hoàn tất — dịch vụ đã hoạt động', ['ip' => $vm->ip]);
Log::info('SendVmCredentialsEmailJob: service activated', [
'module_vmware_id' => $vm->id,
'service_id' => $service->id,
@@ -22,6 +22,7 @@ use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Support\TlsHttpClientFactory;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
/**
* UpdateVmConfigJob
@@ -208,6 +209,10 @@ class UpdateVmConfigJob implements ShouldQueue
$moduleVmware->update(['cpu' => $totalCpu, 'ram_mb' => $totalRam * 1024]);
if (! $isManualOverride) {
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_step', "Đã cấu hình CPU/RAM ({$totalCpu} vCPU, {$totalRam} GB)");
}
if ($isManualOverride) {
$this->syncServiceAddons($moduleVmware, $totalCpu, $totalRam, $logger);
return;
@@ -227,6 +232,7 @@ class UpdateVmConfigJob implements ShouldQueue
ModuleVmware::where('id', $this->moduleVmwareId)->update(['status' => 0]);
Service::where('vm_id', $this->moduleVmwareId)->update(['status' => 'failed']);
ServiceProvisionLog::forVm($this->moduleVmwareId, 'provision_failed', 'Cấu hình CPU/RAM thất bại — ' . $e->getMessage(), ['stage' => 'update_config']);
try {
$telegram = app(Telegram::class);
+1
View File
@@ -21,6 +21,7 @@ class Mail extends Model
'bcc',
'customer_id',
'order_id',
'service_id',
'sent_by',
'message',
'status'
+2
View File
@@ -26,6 +26,7 @@ class MailCampaign extends Model
'message',
'variables',
'attachments',
'renewal_services',
'cc',
'bcc',
'recipient_type',
@@ -40,6 +41,7 @@ class MailCampaign extends Model
protected $casts = [
'variables' => 'array',
'attachments' => 'array',
'renewal_services' => 'array',
'total_recipients' => 'integer',
'sent_count' => 'integer',
'failed_count' => 'integer',
+15
View File
@@ -41,6 +41,21 @@ class ServicePlan extends Model
return $this->belongsTo(DnsServer::class, 'dns_manager_server_id');
}
public function servers()
{
return $this->belongsToMany(DnsServer::class, 'service_plan_servers', 'service_plan_id', 'dns_manager_server_id')
->withPivot('priority')
->orderByPivot('priority');
}
public function syncServers(array $serverIds): void
{
$ids = array_values(array_unique(array_map('intval', $serverIds)));
$this->servers()->sync(collect($ids)->mapWithKeys(fn (int $id, int $index) => [$id => ['priority' => $index]])->all());
$this->update(['dns_manager_server_id' => $ids[0] ?? null]);
}
public function summary(): array
{
return [
+10 -1
View File
@@ -54,9 +54,18 @@ class Template extends Model
}
}
public function category(): string
{
$described = EmailScenarioRegistry::describe($this->key, $this->scenario);
return $described['registered'] || ($this->metadata['marketing'] ?? true) !== false
? $described['category']
: EmailScenarioRegistry::BUSINESS;
}
public function isMarketing(): bool
{
return EmailScenarioRegistry::describe($this->key, $this->scenario)['category'] === EmailScenarioRegistry::MARKETING;
return $this->category() === EmailScenarioRegistry::MARKETING;
}
/** Danh sách variable hợp lệ khai báo trong metadata.variables, key theo variable key. */
@@ -10,6 +10,7 @@ use App\Models\CustomerTrustedDevice;
use App\Support\AutoEmailGate;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
@@ -19,7 +20,9 @@ class ClientTwoFactorService
{
public const CODE_TTL_MINUTES = 5;
public const RESEND_COOLDOWN_SECONDS = 60;
public const RESEND_COOLDOWN_SECONDS = self::CODE_TTL_MINUTES * 60;
private const ENTRY_TTL_MINUTES = 15;
public const TRUSTED_DEVICE_DAYS = 90;
@@ -37,17 +40,50 @@ class ClientTwoFactorService
/**
* @return array{challenge: string, email: string, expires_in: int, resend_in: int}
*/
public function startLoginChallenge(Customer $customer): array
public function startLoginChallenge(Customer $customer, ?string $ip, ?string $userAgent): array
{
$challenge = Str::random(64);
$this->issueCode($this->challengeKey($challenge), $customer, self::PURPOSE_LOGIN);
$pointerKey = $this->clientPointerKey($customer, $ip, $userAgent);
return [
'challenge' => $challenge,
'email' => $this->maskEmail($customer->email),
'expires_in' => self::CODE_TTL_MINUTES * 60,
'resend_in' => self::RESEND_COOLDOWN_SECONDS,
];
return Cache::lock($pointerKey . ':lock', 10)->block(5, function () use ($customer, $pointerKey) {
$challenge = $this->activeChallenge($pointerKey);
if (!$challenge) {
$challenge = Str::random(64);
$this->issueCode($this->challengeKey($challenge), $customer, self::PURPOSE_LOGIN);
Cache::put($pointerKey, Crypt::encryptString($challenge), now()->addMinutes(self::ENTRY_TTL_MINUTES));
}
$remaining = max(Cache::get($this->challengeKey($challenge))['expires_at'] - now()->getTimestamp(), 0);
return [
'challenge' => $challenge,
'email' => $this->maskEmail($customer->email),
'expires_in' => $remaining,
'resend_in' => $remaining,
];
});
}
private function activeChallenge(string $pointerKey): ?string
{
$stored = Cache::get($pointerKey);
$challenge = $stored ? Crypt::decryptString($stored) : null;
$entry = $challenge ? Cache::get($this->challengeKey($challenge)) : null;
if ($entry && $entry['expires_at'] > now()->getTimestamp()) {
return $challenge;
}
if ($challenge) {
Cache::forget($this->challengeKey($challenge));
}
return null;
}
private function clientPointerKey(Customer $customer, ?string $ip, ?string $userAgent): string
{
return 'client-2fa:client:' . hash('sha256', $customer->id . '|' . $ip . '|' . $userAgent);
}
public function resendLoginChallenge(string $challenge): void
@@ -186,7 +222,7 @@ class ClientTwoFactorService
'attempts' => 0,
'sent_at' => now()->getTimestamp(),
'expires_at' => now()->addMinutes(self::CODE_TTL_MINUTES)->getTimestamp(),
], now()->addMinutes(self::CODE_TTL_MINUTES));
], now()->addMinutes(self::ENTRY_TTL_MINUTES));
AutoEmailGate::markManual();
Mail::to($customer->email)->queue(new TwoFactorCode([
@@ -199,6 +235,12 @@ class ClientTwoFactorService
private function checkCode(string $key, array $entry, string $code): void
{
if ($entry['expires_at'] <= now()->getTimestamp()) {
throw ValidationException::withMessages([
'code' => ['Mã xác thực đã hết hạn, vui lòng gửi lại mã.'],
]);
}
if (hash_equals($entry['code_hash'], hash('sha256', $key . $code))) {
Cache::forget($key);
@@ -214,7 +256,7 @@ class ClientTwoFactorService
]);
}
Cache::put($key, $entry, max($entry['expires_at'] - now()->getTimestamp(), 1));
Cache::put($key, $entry, now()->addMinutes(self::ENTRY_TTL_MINUTES));
throw ValidationException::withMessages([
'code' => ['Mã xác thực không chính xác.'],
+17
View File
@@ -14,6 +14,7 @@ use App\Repositories\Api\Service\ServiceRepository;
use App\Services\InvoicePaymentService;
use App\Services\AdminPaymentNotifier;
use App\Services\Coupon\CouponService;
use App\Services\Hosting\HostingServerSelector;
use App\Services\VirtualMachine\VmIpReservationService;
use App\Support\AddonQuantityValidator;
use Illuminate\Support\Facades\DB;
@@ -28,6 +29,7 @@ class OrderService
protected AdminPaymentNotifier $adminPaymentNotifier,
protected CouponService $couponService,
protected VmIpReservationService $vmIpReservation,
protected HostingServerSelector $hostingServers,
) {}
// =========================================================================
@@ -116,6 +118,21 @@ class OrderService
if ($needsVm && !$this->vmIpReservation->hasFreeIp()) {
throw new \InvalidArgumentException('Hiện tại hạ tầng đang đầy vui lòng liên hệ quản trị viên');
}
$this->assertHostingServerAvailable($products);
}
private function assertHostingServerAvailable(iterable $products): void
{
foreach ($products as $product) {
if ($product?->product_type !== 'hosting' || ! $product->servicePlan) {
continue;
}
if (! $this->hostingServers->hasHealthyServer($product->servicePlan)) {
throw new \InvalidArgumentException('Dịch vụ hosting đang bảo trì, vui lòng thử lại sau hoặc liên hệ quản trị viên.');
}
}
}
/**
@@ -20,6 +20,7 @@ use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Support\ServiceProvisionLog;
trait ActivatesPaidInvoices
{
@@ -59,6 +60,13 @@ trait ActivatesPaidInvoices
$this->attachServiceAddons($service, $item);
if ($service->wasRecentlyCreated && $service->status === 'pending') {
ServiceProvisionLog::record($service, 'provision_requested', 'Khách hàng yêu cầu khởi tạo dịch vụ', [
'order_num' => $order->order_num,
'invoice_number' => $invoice->invoice_number,
]);
}
if ($service->wasRecentlyCreated && $item->product_id) {
if ($item->os_id) {
dispatch(new CreateVirtualMachineJob($item));
+2 -1
View File
@@ -7,6 +7,7 @@ use App\Models\MailCampaign;
use App\Models\Template;
use App\Support\MailGlobals;
use App\Support\MailPlaceholders;
use App\Support\RenewalCampaign;
final class MailCampaignRenderer
{
@@ -43,7 +44,7 @@ final class MailCampaignRenderer
array_keys(MailPlaceholders::RECIPIENT_FIELDS),
));
return [...MailGlobals::values(), ...$samples, ...$this->adminValues($campaign)];
return [...MailGlobals::values(), ...$samples, ...$this->adminValues($campaign), ...RenewalCampaign::sampleValues($campaign)];
}
private function adminValues(MailCampaign $campaign): array
@@ -0,0 +1,100 @@
<?php
declare(strict_types=1);
namespace App\Services\Hosting;
use App\Http\Services\Telegram;
use App\Jobs\Mail\Customer\VMCreationFailedJob;
use App\Models\DnsServer;
use App\Models\OrderItem;
use App\Models\Service;
use App\Services\ActivityLogger;
use App\Services\VirtualMachine\VmProvisionRefund;
use Illuminate\Support\Facades\Log;
use Throwable;
class HostingProvisionFailure
{
public function __construct(
private readonly VmProvisionRefund $refund,
private readonly Telegram $telegram,
private readonly ActivityLogger $activity,
) {
}
public function handle(OrderItem $item, string $reason): void
{
Log::channel('Custom')->error('ProvisionHostingAccountJob failed', [
'order_item_id' => $item->id,
'reason' => $reason,
]);
$service = Service::where('order_item_id', $item->id)->first();
Service::where('order_item_id', $item->id)
->whereIn('status', ['pending', 'provisioning'])
->update(['status' => 'failed']);
if ($service) {
$this->activity->log('provision_failed', 'service', 'Khởi tạo hosting thất bại — ' . $reason, $service);
}
$refunded = $this->refund->refund($item, $reason);
$this->notifyAdmin($item, $reason, $refunded);
$this->notifyCustomer($item);
}
public function serverFailedOver(OrderItem $item, DnsServer $server, string $error): void
{
Log::channel('Custom')->warning('ProvisionHostingAccountJob server failed over', [
'order_item_id' => $item->id,
'server_id' => $server->id,
'error' => $error,
]);
$this->telegram->SendErrorMessage([
'job' => 'ProvisionHostingAccountJob',
'title' => 'Server Plesk lỗi, chuyển sang server dự phòng',
'order' => $item->order?->order_num,
'domain' => $item->server_name,
'server' => "{$server->name} ({$server->ip_address})",
'error' => $error,
]);
}
private function notifyAdmin(OrderItem $item, string $reason, bool $refunded): void
{
$order = $item->order;
$this->telegram->SendErrorMessage([
'job' => 'ProvisionHostingAccountJob',
'title' => 'Khởi tạo hosting thất bại',
'order' => $order?->order_num,
'domain' => $item->server_name,
'customer' => $order?->customer?->email,
'error' => $reason,
'refunded' => $refunded ? 'đã hoàn tiền tự động' : 'chưa hoàn tiền, cần xử lý thủ công',
]);
}
private function notifyCustomer(OrderItem $item): void
{
try {
$order = $item->order;
$customer = $order->customer;
VMCreationFailedJob::dispatch([
'customer_email' => $customer->email,
'customer_name' => (string) $customer->fullname,
'product_name' => $item->getProductAttribute()?->name ?? 'Hosting',
'order_id' => $order->id,
'order_num' => $order->order_num,
'order_item_id' => $item->id,
]);
} catch (Throwable $e) {
Log::error('HostingProvisionFailure: cannot dispatch failure email: ' . $e->getMessage());
}
}
}
@@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Services\Hosting;
use App\Models\DnsServer;
use App\Models\ServicePlan;
use App\Services\Plesk\PleskService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Throwable;
class HostingServerSelector
{
private const HEALTH_TTL_SECONDS = 60;
private const PROBE_TIMEOUT_SECONDS = 5;
public function __construct(private readonly PleskService $plesk)
{
}
public function candidates(ServicePlan $plan): Collection
{
return $plan->servers()->get()
->filter(fn (DnsServer $server) => $server->status === 'activated' && $server->servesHosting())
->values();
}
public function pick(ServicePlan $plan, array $excludeIds = []): ?DnsServer
{
return $this->candidates($plan)->first(
fn (DnsServer $server) => ! in_array($server->id, $excludeIds, true) && $this->isHealthy($server)
);
}
public function hasHealthyServer(ServicePlan $plan): bool
{
return $this->pick($plan) !== null;
}
public function isHealthy(DnsServer $server): bool
{
return Cache::remember($this->cacheKey($server), self::HEALTH_TTL_SECONDS, fn () => $this->probe($server));
}
public function forget(DnsServer $server): void
{
Cache::forget($this->cacheKey($server));
}
private function probe(DnsServer $server): bool
{
try {
return $this->plesk
->client($server, self::PROBE_TIMEOUT_SECONDS)
->get($this->plesk->url($server, 'server'))
->successful();
} catch (Throwable) {
return false;
}
}
private function cacheKey(DnsServer $server): string
{
return 'hosting-server-health:' . $server->id;
}
}
+1
View File
@@ -14,6 +14,7 @@ class PleskService
'clients' => ':8443/api/v2/clients',
'domains' => ':8443/api/v2/domains',
'cli' => ':8443/api/v2/cli',
'server' => ':8443/api/v2/server',
];
public function client(DnsServer $server, int $timeout = 30): PendingRequest
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Support;
use App\Models\Customer;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
class CustomerIdentity
{
public const SIDES = ['front' => 'front_identity_number', 'back' => 'back_identity_number'];
public static function payload(Customer $customer): array
{
return [
'identity_number' => $customer->identity_number,
'front_url' => self::signedUrl($customer, 'front'),
'back_url' => self::signedUrl($customer, 'back'),
];
}
public static function response(Customer $customer, string $side)
{
$disk = self::diskFor($customer->{self::SIDES[$side]});
abort_unless($disk, 404);
return Storage::disk($disk)->response($customer->{self::SIDES[$side]}, null, ['Cache-Control' => 'private, no-store']);
}
private static function signedUrl(Customer $customer, string $side): ?string
{
if (! self::diskFor($customer->{self::SIDES[$side]})) {
return null;
}
return URL::temporarySignedRoute(
'admin.customers.identity-image',
now()->addHour(),
['customer' => $customer->uuid, 'side' => $side],
);
}
private static function diskFor(?string $path): ?string
{
if (! is_string($path) || $path === '' || str_contains($path, '..')) {
return null;
}
foreach (['local', 'public'] as $disk) {
if (Storage::disk($disk)->exists($path)) {
return $disk;
}
}
return null;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Support;
use App\Models\Bank;
use App\Models\Customer;
use App\Models\MailCampaign;
use App\Models\Service;
class RenewalCampaign
{
private const SERVICE_KEYS = ['service_name', 'billing_cycle', 'period_start', 'period_end', 'expires_date', 'total_amount', 'vat_rate', 'vat_amount', 'payment_content', 'bank_qr_url'];
public static function withoutServiceValues(?array $variables): ?array
{
$kept = array_diff_key($variables ?? [], array_flip(self::SERVICE_KEYS));
return $kept ?: null;
}
/**
* @return array<string, string>
*/
public static function sampleValues(MailCampaign $campaign): array
{
$first = $campaign->renewal_services[0]['service_id'] ?? null;
$service = $first ? Service::with('customer')->find($first) : null;
return $service?->customer ? (self::valuesFor($campaign, $service->customer, $service->id) ?? []) : [];
}
public static function isRenewalTemplate(MailCampaign $campaign): bool
{
$keys = MailPlaceholders::extract($campaign->subject, $campaign->message);
return in_array('period_end', $keys, true) && in_array('bank_qr_url', $keys, true);
}
/**
* @return array<string, string>|null null khi dịch vụ không còn thuộc khách hoặc không thể gia hạn
*/
public static function valuesFor(MailCampaign $campaign, Customer $customer, int $serviceId): ?array
{
$months = collect($campaign->renewal_services)->firstWhere('service_id', $serviceId)['months'] ?? null;
$service = Service::with(['orderItem', 'product', 'customProduct'])
->whereKey($serviceId)
->where('customer_id', $customer->id)
->first();
$quote = $service ? RenewalQuote::forService($service, $months) : null;
if (! $quote) {
return null;
}
unset($quote['service_id'], $quote['cycles'], $quote['months']);
$bank = Bank::where('account_no', $campaign->variables['bank_account_no'] ?? '')->first();
return $bank
? [...$quote, 'bank_qr_url' => VietQr::url($bank, $quote['total_amount'], $quote['payment_content'])]
: $quote;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Support;
use App\Helpers\OrderHelper;
use App\Models\Service;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
class RenewalQuote
{
private const TYPE_LABELS = [
'domain' => 'tên miền',
'hosting' => 'hosting',
'vps' => 'Cloud VPS',
'ssl' => 'SSL',
];
/**
* @param array<int, int> $customerIds
* @return Collection<int, Service>
*/
public static function dueServices(array $customerIds, int $days): Collection
{
return Service::query()
->with(['customer:id,uuid,fullname,email', 'orderItem', 'product', 'customProduct'])
->whereIn('customer_id', $customerIds)
->whereNotIn('status', ['terminated', 'cancelled'])
->whereNotNull('expires_at')
->where('expires_at', '<=', now()->addDays($days)->endOfDay())
->orderBy('expires_at')
->get();
}
public static function forService(Service $service, ?int $months = null): ?array
{
$orderItem = $service->orderItem;
$product = $service->customProduct ?? $service->product;
if (! $orderItem || ! $product) {
return null;
}
$baseMonths = OrderHelper::cycleToMonths($orderItem->billing_cycle);
$options = RenewalPricing::options($product);
$base = RenewalPricing::option($product, $baseMonths);
if (! $base) {
return null;
}
$rate = VatSettings::rateFor($service->product?->product_type);
$start = ($service->expires_at ?? now())->copy();
$target = $service->server_name ?: $product->name;
$label = self::TYPE_LABELS[$service->type] ?? null;
$terms = fn (array $option) => self::terms($service, $option, $baseMonths, $start, $rate);
return [
'service_id' => $service->id,
'service_name' => 'Gia hạn ' . ($label ? $label . ' - ' : '') . $target,
'period_start' => $start->format('d/m/Y'),
'expires_date' => $start->format('d/m/Y'),
'vat_rate' => rtrim(rtrim(number_format($rate, 2, '.', ''), '0'), '.'),
'payment_content' => Str::limit('GIA HAN ' . Str::upper(Str::ascii($target)), 50, ''),
...$terms(RenewalPricing::option($product, (int) $months) ?? $base),
'cycles' => array_map($terms, $options),
];
}
/**
* @param array{months: int, price: int} $option
* @return array{months: int, billing_cycle: string, period_end: string, total_amount: string, vat_amount: string}
*/
private static function terms(Service $service, array $option, int $baseMonths, Carbon $start, float $rate): array
{
$months = $option['months'];
$amount = $option['price'] + RenewalPricing::addonTotal($service, $months / $baseMonths);
return [
'months' => $months,
'billing_cycle' => sprintf('%02d %s', $months % 12 === 0 ? $months / 12 : $months, $months % 12 === 0 ? 'năm' : 'tháng'),
'period_end' => $start->copy()->addMonthsNoOverflow($months)->subDay()->format('d/m/Y'),
'total_amount' => number_format($amount, 0, ',', '.'),
'vat_amount' => number_format((int) round($amount * $rate / (100 + $rate)), 0, ',', '.'),
];
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Support;
use App\Models\Service;
use App\Services\ActivityLogger;
class ServiceProvisionLog
{
public const EVENTS = [
'provision_requested',
'provision_started',
'provision_step',
'provision_completed',
'provision_failed',
];
public static function record(?Service $service, string $event, string $description, array $values = []): void
{
if (! $service) {
return;
}
app(ActivityLogger::class)->log($event, 'service', $description, $service, [], $values);
}
public static function forOrderItem(int $orderItemId, string $event, string $description, array $values = []): void
{
self::record(Service::where('order_item_id', $orderItemId)->first(), $event, $description, $values);
}
public static function forVm(int $moduleVmwareId, string $event, string $description, array $values = []): void
{
self::record(Service::where('vm_id', $moduleVmwareId)->first(), $event, $description, $values);
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Support;
use App\Models\Bank;
class VietQr
{
public static function url(Bank $bank, string $amount, string $content): string
{
$params = array_filter([
'amount' => preg_replace('/\D/', '', $amount),
'addInfo' => trim($content),
'accountName' => $bank->account_name,
], fn (?string $value) => $value !== null && $value !== '');
return "https://img.vietqr.io/image/{$bank->bank_code}-{$bank->account_no}-compact2.png?" . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
}