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:
co-authored by
Claude Sonnet 5.5
parent
047c23beff
commit
55a834a2f8
@@ -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.'],
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user