feat: email gửi tay/nhắc gia hạn, gói hosting, sửa dữ liệu sản phẩm

- Gửi email theo template cho 1 khách, tab lịch sử email, nhắc gia hạn dịch vụ hàng loạt
- Mail lưu from/bcc/sent_by; mẫu MARKETING và mẫu cũ trong TemplateSeeder
- Gói hosting: giới hạn, trạng thái, lấy plan Plesk qua CLI gateway
- Backfill payment_method và ngày đơn hàng còn thiếu
- Bổ sung field CPU/RAM/Disk/Băng thông cho loại sản phẩm vps và cloud

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-09 11:32:05 +07:00
co-authored by Claude Opus 5.5
parent 8651dde6b1
commit 30898ea46f
59 changed files with 1771 additions and 108 deletions
+3 -3
View File
@@ -10,7 +10,7 @@ enum ProductTypeEnums: string
case EMAIL = 'email';
case SSL = 'ssl';
case DOMAIN = 'domain';
case WEB_DESIGN = 'web design';
case WEB_DESIGN = 'web_design';
case ADDON = 'addon';
case HARDWARE = 'hardware';
case IT_SUPPORT = 'it_support';
@@ -24,7 +24,7 @@ enum ProductTypeEnums: string
self::CLOUD => 'Cloud',
self::EMAIL => 'Email',
self::SSL => 'SSL',
self::DOMAIN => 'Domain',
self::DOMAIN => 'Tên miền',
self::WEB_DESIGN => 'Web Design',
self::ADDON => 'Addon',
self::HARDWARE => 'Hardware',
@@ -49,4 +49,4 @@ enum ProductTypeEnums: string
self::SERVER_RENTAL => 'magenta',
};
}
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace App\Exports;
use App\Models\Product;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Events\AfterSheet;
final class ProductsExport implements FromCollection, WithHeadings, WithMapping, WithEvents, ShouldAutoSize
{
public function collection(): Collection
{
return Product::query()
->with(['category', 'pricings', 'operatingSystems'])
->orderBy('id')
->get();
}
public function headings(): array
{
return [
'ID', 'UUID', 'Tên sản phẩm', 'Slug', 'Ảnh đại diện', 'Loại sản phẩm',
'ID danh mục', 'Danh mục', 'ID gói dịch vụ', 'CPU', 'RAM', 'Ổ đĩa',
'Băng thông', 'Số tên miền', 'Phí khởi tạo', 'Giá thấp nhất', 'Loại thanh toán',
'Tiền tệ', 'Giá tháng', 'Giá quý', 'Giá 6 tháng', 'Giá năm', 'Giá 2 năm',
'Giá 3 năm', 'Giá một lần', 'Tính năng', 'Đang hoạt động', 'ID hệ điều hành',
'ID máy chủ module', 'ID datastore module', 'Ngày tạo', 'Ngày cập nhật',
];
}
public function map($product): array
{
$prices = $product->pricings->keyBy('billing_cycle');
$hasOneTime = $prices->has('one_time');
$hasRecurring = $prices->keys()->contains(fn ($cycle) => $cycle !== 'one_time');
return [
$product->id,
$product->uuid,
$product->name,
$product->slug,
$product->thumbnail,
$product->product_type,
$product->product_categories_id,
$product->category?->name,
$product->service_plan_id,
$product->cpu,
$product->ram,
$product->disk,
$product->bandwidth,
$product->domain_count,
$product->setup_fee,
$prices->min('price'),
$hasOneTime && !$hasRecurring ? 'Một lần' : 'Định kỳ',
$prices->first()?->currency ?? 'VND',
$prices->get('monthly')?->price,
$prices->get('quarterly')?->price,
$prices->get('semi_annually')?->price,
$prices->get('annually')?->price,
$prices->get('biennially')?->price,
$prices->get('triennially')?->price,
$prices->get('one_time')?->price,
$product->features ? json_encode($product->features, JSON_UNESCAPED_UNICODE) : null,
$product->is_active ? 'Có' : 'Không',
$product->operatingSystems->pluck('id')->implode(', '),
$product->module_host_id,
$product->module_datastore_id,
optional($product->created_at)->format('Y-m-d H:i:s'),
optional($product->updated_at)->format('Y-m-d H:i:s'),
];
}
public function registerEvents(): array
{
return [
AfterSheet::class => function (AfterSheet $event): void {
$sheet = $event->sheet->getDelegate();
$sheet->freezePane('A2');
$sheet->setAutoFilter($sheet->calculateWorksheetDimension());
$sheet->getStyle('A1:AF1')->getFont()->setBold(true)->getColor()->setARGB('FFFFFFFF');
$sheet->getStyle('A1:AF1')->getFill()->setFillType('solid')->getStartColor()->setARGB('FF1677FF');
$sheet->getStyle('A1:AF1')->getAlignment()->setVertical('center');
$sheet->getRowDimension(1)->setRowHeight(24);
},
];
}
}
@@ -0,0 +1,68 @@
<?php
namespace App\Http\Controllers\Api\Admin\Customer\Concerns;
use App\Models\Mail;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
trait ListsCustomerEmails
{
public function emails(Request $request, string $uuid): JsonResponse
{
$customer = $this->resolveCustomer($uuid);
$search = trim((string) $request->get('search', ''));
$paginator = Mail::query()
->with(['sender', 'template:id,name'])
->where('customer_id', $customer->id)
->when($search !== '', fn ($q) => $q->where(fn ($q) => $q
->where('subject', 'like', "%{$search}%")
->orWhere('to', 'like', "%{$search}%")))
->latest('id')
->paginate(min((int) $request->get('per_page', 10), 100), ['id', 'template_id', 'subject', 'from_address', 'to', 'cc', 'bcc', 'sent_by', 'status', 'created_at']);
return response()->json([
'error' => false,
'data' => [
'items' => $paginator->getCollection()->map($this->mapCustomerEmail(...))->all(),
'total' => $paginator->total(),
'current_page' => $paginator->currentPage(),
'per_page' => $paginator->perPage(),
],
]);
}
public function emailDetail(string $uuid, int $id): JsonResponse
{
$customer = $this->resolveCustomer($uuid);
$mail = Mail::with(['sender', 'template:id,name'])
->where('customer_id', $customer->id)
->find($id);
if (!$mail) {
return response()->json(['error' => true, 'message' => 'Không tìm thấy email'], 404);
}
return response()->json([
'error' => false,
'data' => [...$this->mapCustomerEmail($mail), 'html' => $mail->message],
]);
}
private function mapCustomerEmail(Mail $mail): array
{
return [
'id' => $mail->id,
'subject' => $mail->subject,
'from_address' => $mail->from_address,
'sent_by' => $mail->sender ? ($mail->sender->name ?: $mail->sender->username) : null,
'to' => $mail->to,
'cc' => $mail->cc,
'bcc' => $mail->bcc,
'template' => $mail->template?->name,
'status' => $mail->status,
'created_at' => $mail->created_at,
];
}
}
@@ -34,6 +34,26 @@ trait ManagesCustomerAccount
return response()->json(['error' => false, 'message' => 'Đã gửi mật khẩu mới cho khách hàng.']);
}
public function emailPreview(Request $request, string $uuid): JsonResponse
{
$data = $request->validate(['template_id' => 'required|integer']);
return response()->json([
'error' => false,
'data' => $this->mailService->previewTemplateEmail($uuid, (int) $data['template_id']),
]);
}
public function emailLayout(Request $request, string $uuid): JsonResponse
{
$data = $request->validate(['message' => 'nullable|string']);
return response()->json([
'error' => false,
'data' => ['html' => $this->mailService->wrapWithLayout($uuid, (string) ($data['message'] ?? ''))],
]);
}
public function sendEmail(Request $request, string $uuid): JsonResponse
{
$data = $request->validate([
@@ -43,6 +63,7 @@ trait ManagesCustomerAccount
'to' => 'nullable|string|max:1000',
'cc' => 'nullable|string|max:1000',
'bcc' => 'nullable|string|max:1000',
'with_layout' => 'nullable|boolean',
]);
$this->mailService->sendCustomEmail($uuid, $data, Auth::guard('admin')->user(), $request->ip());
@@ -35,6 +35,7 @@ trait ManagesCustomerServices
'requirements' => 'nullable|string',
'feedback' => 'nullable|string',
'price' => 'nullable|numeric|min:0',
'billing_cycle' => 'nullable|in:monthly,quarterly,semi_annually,annually,biennially,triennially',
'virtual_machine_id' => 'nullable|integer|exists:virtual_machines,id',
'os_id' => 'nullable|integer|exists:os,id',
'vm_cpu' => 'nullable|integer|min:1',
@@ -24,6 +24,7 @@ use App\Http\Controllers\Api\Admin\Customer\Concerns\ManagesCustomerDomains;
use App\Http\Controllers\Api\Admin\Customer\Concerns\ManagesCustomerServices;
use App\Http\Controllers\Api\Admin\Customer\Concerns\ManagesCustomerBulkActions;
use App\Http\Controllers\Api\Admin\Customer\Concerns\ManagesCustomerNotes;
use App\Http\Controllers\Api\Admin\Customer\Concerns\ListsCustomerEmails;
class CustomerController extends Controller
{
@@ -34,6 +35,7 @@ class CustomerController extends Controller
use ManagesCustomerServices;
use ManagesCustomerBulkActions;
use ManagesCustomerNotes;
use ListsCustomerEmails;
public function __construct(
private readonly CustomerRepositoryInterface $customerRepository,
@@ -16,6 +16,8 @@ use App\Repositories\Api\Domain\DomainOrderRepository;
use App\Services\Api\Domain\DomainOrderService;
use App\Services\Api\Domain\DomainRegistrantService;
use App\Services\Email\EmailTemplateService;
use App\Support\EmailTemplateShell;
use App\Support\MailGlobals;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
@@ -278,22 +280,46 @@ class AdminDomainOrderController extends Controller
return;
}
$setting = \App\Models\Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode((string) $setting->value, true) : [];
app(EmailTemplateService::class)->send($scenario, $customer->email, [
'company_name' => $settingValue['company'] ?? config('app.name'),
'company_logo' => $settingValue['logo'] ?? '',
'domain_name' => $domainName,
'client_name' => $customer->fullname,
'order_num' => $orderNum,
'reason' => $reason,
...MailGlobals::values(),
...$this->domainHandoverVariables($order),
'domain_name' => $domainName,
'client_name' => $customer->fullname,
'customer_email' => $customer->email,
'order_num' => $orderNum,
'reason' => $reason,
]);
} catch (\Throwable $e) {
Log::error('AdminDomainOrderController: không thể gửi email khách hàng: ' . $e->getMessage());
}
}
/**
* @return array<string, string>
*/
private function domainHandoverVariables(Order $order): array
{
$service = $order->orderItems->first()?->service?->fresh();
if (!$service) {
return [];
}
return [
'registered_at' => $service->started_at?->format('d/m/Y') ?? '',
'expires_at' => $service->expires_at?->format('d/m/Y') ?? '',
'kyc_block' => $service->kyc_url ? $this->kycBlock($service->kyc_url) : '',
];
}
private function kycBlock(string $kycUrl): string
{
return EmailTemplateShell::heading('📋 Lưu ý quan trọng')
. EmailTemplateShell::paragraph('Căn cứ Khoản 2 Điều 9 và Khoản 6 Điều 21 Thông tư số 48/2025/TT-BKHCN ngày 25/12/2025 của Bộ Khoa học và Công nghệ về Quản lý và sử dụng tài nguyên Internet, chủ thể đăng ký tên miền là cá nhân có trách nhiệm hoàn thiện hồ sơ đăng ký thông qua hình thức xác thực điện tử (eKYC) trong vòng <strong>03 ngày</strong> kể từ thời điểm nhận được email này.')
. EmailTemplateShell::button(htmlspecialchars($kycUrl, ENT_QUOTES, 'UTF-8'), '✅ Xác thực eKYC ngay')
. EmailTemplateShell::note('Việc không hoàn thành xác thực đúng hạn có thể ảnh hưởng đến quyền sử dụng tên miền của Quý khách.', '⏰ Lưu ý:');
}
// =========================================================================
// Private formatters
// =========================================================================
@@ -3,15 +3,17 @@
namespace App\Http\Controllers\Api\Admin\Hosting;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Hosting\ServicePlanRequest;
use App\Models\DnsServer;
use App\Models\ServicePlan;
use App\Services\Plesk\PleskServicePlanService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class ServicePlanController extends Controller
{
public function index(): JsonResponse
{
$plans = ServicePlan::with('plesk', 'dnsServer')->orderBy('title')->get();
$plans = ServicePlan::with('plesk', 'dnsServer')->orderBy('sort_order')->orderBy('title')->get();
return response()->json(['error' => false, 'data' => $plans]);
}
@@ -27,29 +29,11 @@ class ServicePlanController extends Controller
return response()->json(['error' => false, 'data' => $plan]);
}
public function store(Request $request): JsonResponse
public function store(ServicePlanRequest $request): JsonResponse
{
$validated = $request->validate([
'title' => 'required|string|max:255',
'vcpu' => 'required|integer|min:0',
'ram' => 'required|integer|min:0',
'disk' => 'required|integer|min:0',
'domain' => 'required|integer|min:0',
'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id',
'plesk_plan_name' => 'nullable|string|max:255',
'note' => 'nullable|string',
]);
$plan = ServicePlan::create($request->planAttributes());
$plan = ServicePlan::create([
'title' => $validated['title'],
'vcpu' => $validated['vcpu'],
'ram' => $validated['ram'],
'disk' => $validated['disk'],
'domain' => $validated['domain'],
'dns_manager_server_id' => $validated['dns_manager_server_id'] ?? null,
]);
$this->savePlesk($plan, $validated);
$this->savePlesk($plan, $request->validated());
return response()->json([
'error' => false,
@@ -58,7 +42,7 @@ class ServicePlanController extends Controller
], 201);
}
public function update(Request $request, int $id): JsonResponse
public function update(ServicePlanRequest $request, int $id): JsonResponse
{
$plan = ServicePlan::find($id);
@@ -66,27 +50,9 @@ class ServicePlanController extends Controller
return response()->json(['error' => true, 'message' => 'Không tìm thấy gói hosting.'], 404);
}
$validated = $request->validate([
'title' => 'required|string|max:255',
'vcpu' => 'required|integer|min:0',
'ram' => 'required|integer|min:0',
'disk' => 'required|integer|min:0',
'domain' => 'required|integer|min:0',
'dns_manager_server_id' => 'nullable|integer|exists:dns_manager_servers,id',
'plesk_plan_name' => 'nullable|string|max:255',
'note' => 'nullable|string',
]);
$plan->update($request->planAttributes());
$plan->update([
'title' => $validated['title'],
'vcpu' => $validated['vcpu'],
'ram' => $validated['ram'],
'disk' => $validated['disk'],
'domain' => $validated['domain'],
'dns_manager_server_id' => $validated['dns_manager_server_id'] ?? null,
]);
$this->savePlesk($plan, $validated);
$this->savePlesk($plan, $request->validated());
return response()->json([
'error' => false,
@@ -108,6 +74,23 @@ class ServicePlanController extends Controller
return response()->json(['error' => false, 'message' => 'Xoá gói hosting thành công.']);
}
public function pleskPlans(int $serverId, PleskServicePlanService $plans): JsonResponse
{
$server = DnsServer::find($serverId);
if (!$server || !$server->servesHosting()) {
return response()->json(['error' => true, 'message' => 'Server không hỗ trợ hosting.'], 404);
}
$names = $plans->names($server);
if ($names === null) {
return response()->json(['error' => true, 'message' => 'Không lấy được danh sách plan từ Plesk.'], 502);
}
return response()->json(['error' => false, 'data' => $names]);
}
private function savePlesk(ServicePlan $plan, array $data): void
{
if (empty($data['plesk_plan_name'])) {
@@ -28,6 +28,8 @@ trait HandlesInvoicePayments
// hoá đơn ghi nhận trả một phần và chưa kích hoạt dịch vụ.
$validated = $request->validate([
'received_amount' => 'nullable|integer|min:1',
'recording_mode' => 'nullable|string|in:manual,automatic',
'note' => 'nullable|string|max:1000',
]);
try {
@@ -37,7 +39,9 @@ trait HandlesInvoicePayments
$invoice = $this->invoicePaymentService->markPaidByAdmin(
$invoice,
auth()->id(),
method: $validated['recording_mode'] ?? 'manual',
receivedAmount: $validated['received_amount'] ?? null,
note: $validated['note'] ?? '',
);
DB::commit();
@@ -74,6 +74,36 @@ final class MailCampaignController extends Controller
]);
}
public function variableSuggestions(Request $request): JsonResponse
{
$data = $request->validate([
'template_id' => 'required|integer|exists:template,id',
]);
$suggestions = MailCampaign::query()
->where('template_id', $data['template_id'])
->whereNotNull('variables')
->where('sent_count', '>', 0)
->orderByDesc('created_at')
->limit(20)
->get(['uuid', 'name', 'variables', 'created_at'])
->filter(fn (MailCampaign $campaign) => !empty($campaign->variables))
->unique(fn (MailCampaign $campaign) => json_encode($campaign->variables))
->take(8)
->map(fn (MailCampaign $campaign) => [
'uuid' => $campaign->uuid,
'name' => $campaign->name,
'variables' => $campaign->variables,
'created_at' => $campaign->created_at,
])
->values();
return response()->json([
'error' => false,
'data' => $suggestions,
]);
}
public function preview(Request $request, MailCampaignRenderer $renderer): JsonResponse
{
$campaign = $this->draftCampaign($request->validate($this->contentRules()));
@@ -7,6 +7,7 @@ use App\Http\Requests\OrderRequest;
use App\Http\Requests\UpdateOrderRequest;
use App\Http\Resources\Api\Admin\OrderResource;
use App\Models\Order;
use App\Models\DomainPricing;
use App\Repositories\Order\OrderRepositoryInterface;
use App\Services\OrderService;
use Illuminate\Http\JsonResponse;
@@ -42,6 +43,14 @@ class OrderController extends Controller
]);
}
public function domainPricing(): JsonResponse
{
return response()->json([
'error' => false,
'data' => DomainPricing::toResponseArray(),
]);
}
public function store(OrderRequest $request): JsonResponse
{
try {
@@ -5,12 +5,24 @@ namespace App\Http\Controllers\Api\Admin\Product;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\Admin\ProductCategoryResource;
use App\Models\ProductCategories;
use App\Services\Product\ProductCategorySampleService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ProductCategoryController extends Controller
{
public function seedSample(ProductCategorySampleService $service): JsonResponse
{
$result = $service->seed();
return response()->json([
'error' => false,
'message' => "Đã tạo {$result['created']} và bổ sung thông tin cho {$result['updated']} nhóm dịch vụ.",
'data' => $result,
]);
}
public function index(Request $request): JsonResponse
{
$perPage = min((int) $request->get('per_page', 15), 100);
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api\Admin\Product;
use App\Exports\ProductsExport;
use App\Http\Controllers\Controller;
use App\Http\Resources\Api\Admin\ProductResource;
use App\Http\Services\NextjsRevalidationService;
@@ -12,6 +13,9 @@ use App\Models\Os;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Excel as ExcelWriter;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ProductController extends Controller
{
@@ -40,6 +44,13 @@ class ProductController extends Controller
]);
}
public function export(): BinaryFileResponse
{
$filename = 'danh-sach-san-pham-' . now()->format('Y-m-d-His') . '.xlsx';
return Excel::download(new ProductsExport(), $filename, ExcelWriter::XLSX);
}
public function show(int $id): JsonResponse
{
$product = $this->products->findWithPricings($id);
@@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers\Api\Admin\Service;
use App\Http\Controllers\Controller;
use App\Models\Service;
use App\Services\ServiceRenewalReminderService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ServiceRenewalReminderController extends Controller
{
public function __construct(private readonly ServiceRenewalReminderService $reminders) {}
public function index(Request $request): JsonResponse
{
$days = (int) $request->validate(['days' => 'required|integer|min:1|max:365'])['days'];
$items = $this->reminders->expiring($days)->map(fn (Service $service) => [
'id' => $service->id,
'server_name' => $service->server_name,
'product_name' => $service->product?->name,
'expires_at' => $service->expires_at,
'days_left' => $this->reminders->daysLeft($service),
'auto_renew' => (bool) $service->auto_renew,
'customer' => [
'uuid' => $service->customer->uuid,
'fullname' => $service->customer->fullname,
'email' => $service->customer->email,
],
]);
return response()->json([
'error' => false,
'data' => $items->values(),
'truncated' => $items->count() >= ServiceRenewalReminderService::MAX_RESULTS,
]);
}
public function send(Request $request): JsonResponse
{
$data = $request->validate([
'service_ids' => 'required|array|min:1|max:' . ServiceRenewalReminderService::MAX_RESULTS,
'service_ids.*' => 'integer',
]);
$count = $this->reminders->send($data['service_ids'], Auth::guard('admin')->user());
return response()->json([
'error' => false,
'message' => "Đã đưa {$count} email nhắc gia hạn vào hàng đợi gửi.",
]);
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Http\Requests\Admin\Hosting;
use Illuminate\Foundation\Http\FormRequest;
class ServicePlanRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, string>
*/
public function rules(): array
{
return [
'title' => 'required|string|max:255',
'description' => 'nullable|string|max:2000',
'vcpu' => 'required|integer|min:0',
'ram' => 'required|integer|min:0',
'disk' => 'required|integer|min:0',
'domain' => 'required|integer|min:0',
'bandwidth' => 'nullable|integer|min:0',
'databases' => 'nullable|integer|min:0',
'mailboxes' => 'nullable|integer|min:0',
'mailbox_quota' => 'nullable|integer|min:0',
'ftp_accounts' => 'nullable|integer|min:0',
'subdomains' => 'nullable|integer|min:0',
'domain_aliases' => 'nullable|integer|min:0',
'features' => 'nullable|array|max:30',
'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',
'plesk_plan_name' => 'nullable|string|max:255',
'note' => 'nullable|string',
];
}
/**
* @return array<string, mixed>
*/
public function planAttributes(): array
{
$validated = $this->validated();
return [
...collect($validated)->except(['plesk_plan_name', 'note'])->all(),
'dns_manager_server_id' => $validated['dns_manager_server_id'] ?? null,
'sort_order' => $validated['sort_order'] ?? 0,
'is_active' => $validated['is_active'] ?? true,
];
}
}
@@ -65,6 +65,17 @@ class OrderResource extends JsonResource
'reminder_step' => (int) $invoice->reminder_step,
'billing_period_start' => $invoice->billing_period_start,
'billing_period_end' => $invoice->billing_period_end,
'payment_method' => $invoice->payment?->name ?? $invoice->payment_method,
'note' => $invoice->note,
'attachments' => $invoice->relationLoaded('attachments')
? $invoice->attachments->map(fn($attachment) => [
'id' => $attachment->id,
'filename' => $attachment->filename,
'url' => $attachment->url,
'mime_type' => $attachment->mime_type,
'size' => $attachment->size,
])
: [],
// Which service(s)/product(s) this invoice actually bills for — without this,
// an invoice was a black box: just a total with no visible line items.
'items' => $invoice->relationLoaded('invoiceItems')
+15 -10
View File
@@ -39,6 +39,8 @@ class SendMailCampaignRecipient implements ShouldQueue
$customer = $this->customerId ? Customer::find($this->customerId) : null;
$rendered = $renderer->render($campaign, $renderer->recipientValues($campaign, $customer, $this->email));
$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']);
$failed = false;
try {
@@ -46,13 +48,13 @@ class SendMailCampaignRecipient implements ShouldQueue
if ($cc) {
$mailer->cc($cc);
}
if ($bcc = EmailRecipients::parse($campaign->bcc)) {
if ($bcc) {
$mailer->bcc($bcc);
}
$failed = $mailer->send(new GenericTemplateMail(
$rendered['subject'],
$rendered['html'],
Arr::only($campaign->template?->mailConfig() ?? [], ['from_email', 'from_name', 'reply_to', 'reply_to_name']),
$mailConfig,
)) === null;
} catch (\Throwable $e) {
$failed = true;
@@ -64,14 +66,17 @@ class SendMailCampaignRecipient implements ShouldQueue
}
MailLog::create([
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $rendered['subject'],
'to' => $this->email,
'cc' => implode(', ', $cc),
'customer_id' => $customer?->id,
'message' => $rendered['html'],
'status' => $failed ? 'failed' : 'sent',
'campaign_id' => $campaign->id,
'template_id' => $campaign->template_id ?? 0,
'subject' => $rendered['subject'],
'from_address' => $mailConfig['from_email'] ?? config('mail.from.address'),
'to' => $this->email,
'cc' => implode(', ', $cc),
'bcc' => implode(', ', $bcc),
'customer_id' => $customer?->id,
'sent_by' => $campaign->created_by,
'message' => $rendered['html'],
'status' => $failed ? 'failed' : 'sent',
]);
$this->markDone($campaign, $failed);
+1 -5
View File
@@ -2,7 +2,6 @@
namespace App\Listeners\Mail;
use App\Models\Setting;
use App\Support\AutoEmailGate;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Log;
@@ -17,10 +16,7 @@ class CheckMailEnabled
*/
public function handle(MessageSending $event): bool
{
$setting = Setting::where('key', 'email_settings')->first();
$config = $setting ? json_decode($setting->value, true) : [];
if (array_key_exists('mail_enabled', $config) && !$config['mail_enabled']) {
if (!AutoEmailGate::mailEnabled()) {
Log::info('Mail sending blocked: mail_enabled is off.', [
'subject' => $event->message->getSubject(),
]);
+5 -1
View File
@@ -3,6 +3,7 @@
namespace App\Mail\Customer;
use App\Models\Template;
use App\Support\EmailTemplateShell;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -17,6 +18,7 @@ class ManualCustomerEmail extends Mailable implements ShouldQueue
public function __construct(
private readonly string $emailSubject,
private readonly string $htmlContent,
private readonly bool $wrapLayout = true,
) {}
public function envelope(): Envelope
@@ -27,7 +29,9 @@ class ManualCustomerEmail extends Mailable implements ShouldQueue
public function content(): Content
{
return new Content(
html: Template::renderWithLayout($this->emailSubject, $this->htmlContent),
htmlString: $this->wrapLayout
? Template::renderWithLayout($this->emailSubject, $this->htmlContent)
: EmailTemplateShell::document($this->emailSubject, $this->htmlContent),
);
}
+8
View File
@@ -15,9 +15,12 @@ class Mail extends Model
'campaign_id',
'template_id',
'subject',
'from_address',
'to',
'cc',
'bcc',
'customer_id',
'sent_by',
'message',
'status'
];
@@ -44,6 +47,11 @@ class Mail extends Model
return $this->belongsTo(Customer::class, 'customer_id');
}
public function sender()
{
return $this->belongsTo(User::class, 'sent_by');
}
public function template()
{
return $this->belongsTo(Template::class, 'template_id');
+1 -1
View File
@@ -69,7 +69,7 @@ class Order extends Model
public function payment()
{
return $this->belongsTo(Payment::class);
return $this->belongsTo(Payment::class, 'payment_method', 'id');
}
public function moduleVmwares()
+16
View File
@@ -8,13 +8,29 @@ class ServicePlan extends Model
{
protected $fillable = [
'title',
'description',
'vcpu',
'ram',
'disk',
'domain',
'bandwidth',
'databases',
'mailboxes',
'mailbox_quota',
'ftp_accounts',
'subdomains',
'domain_aliases',
'features',
'is_active',
'sort_order',
'dns_manager_server_id',
];
protected $casts = [
'features' => 'array',
'is_active' => 'boolean',
];
public function plesk()
{
return $this->hasOne(ServicePlanPlesk::class);
+6 -3
View File
@@ -108,14 +108,17 @@ class Template extends Model
* dùng khung header/footer chuẩn trong code thay vì gửi ra nội dung trần.
*/
public static function renderWithLayout(?string $subject, string $contentHtml): string
{
return EmailTemplateShell::document($subject, self::layoutBody($contentHtml));
}
public static function layoutBody(string $contentHtml): string
{
$layout = self::where('scenario', 'layout')->where('status', 1)->first();
$body = $layout && $layout->message
return $layout && $layout->message
? str_replace('{{$content}}', $contentHtml, $layout->message)
: EmailTemplateShell::wrap(EmailTemplateShell::body($contentHtml));
return EmailTemplateShell::document($subject, $body);
}
public function type()
+1 -1
View File
@@ -64,7 +64,7 @@ class User extends Authenticatable implements JWTSubject
public function getNameAttribute(): string
{
return trim((string) $this->fullname);
return trim("{$this->firstname} {$this->lastname}") ?: trim((string) $this->fullname);
}
public function staffOnline()
@@ -152,6 +152,8 @@ class OrderRepository extends BaseRepository implements OrderRepositoryInterface
'payment',
'discount',
'invoices.invoiceItems.product',
'invoices.attachments',
'invoices.payment',
])->where('order_num', $orderNum)->first();
}
}
@@ -274,9 +274,12 @@ class DomainOrderService
throw new \InvalidArgumentException('Chỉ có thể kích hoạt tên miền sau khi đã tạo tại nhà đăng ký (hoặc sau khi KYC).');
}
$startedAt = $service->started_at ?? now();
$service->update([
'status' => DomainProvisioningStatus::ACTIVE->value,
'started_at' => $service->started_at ?? now(),
'started_at' => $startedAt,
'expires_at' => $service->expires_at ?? $startedAt->copy()->addMonths((int) $orderItem->months),
]);
$order->update(['status' => OrderStatus::ACTIVE->value]);
+74 -9
View File
@@ -2,8 +2,9 @@
namespace App\Services\Customer;
use App\Support\EmailRecipients;
use App\Exceptions\InvalidTemplateVariableException;
use App\Mail\Customer\ManualCustomerEmail;
use App\Mail\GenericTemplateMail;
use App\Mail\Customer\PasswordResetByAdmin;
use App\Models\Customer;
use App\Models\Log;
@@ -12,6 +13,11 @@ use App\Models\Template;
use App\Models\User;
use App\Repositories\Customer\CustomerRepositoryInterface;
use App\Services\Customer\Concerns\ResolvesCustomer;
use App\Services\Email\EmailTemplateRenderer;
use App\Support\AutoEmailGate;
use App\Support\EmailRecipients;
use App\Support\MailGlobals;
use App\Support\MailPlaceholders;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
@@ -22,8 +28,62 @@ class CustomerMailService
public function __construct(
private readonly CustomerRepositoryInterface $customerRepository,
private readonly EmailTemplateRenderer $renderer,
) {}
/**
* @return array{subject: string, html: string, cc: array<int, string>, bcc: array<int, string>}
*/
public function previewTemplateEmail(string $uuid, int $templateId): array
{
$customer = $this->resolveCustomer($uuid);
$template = $this->sendableTemplate($templateId);
$config = $template->mailConfig();
return [
...$this->renderForCustomer($template, $customer),
'cc' => $config['cc'] ?? [],
'bcc' => $config['bcc'] ?? [],
];
}
public function wrapWithLayout(string $uuid, string $contentHtml): string
{
$customer = $this->resolveCustomer($uuid);
return MailPlaceholders::fill(Template::layoutBody($contentHtml), [
...MailGlobals::values(),
...MailPlaceholders::recipientValues($customer, $customer->email),
]);
}
private function sendableTemplate(int $templateId): Template
{
$template = Template::query()->whereKey($templateId)->where('status', 1)->first();
abort_if(!$template, 422, 'Template không tồn tại hoặc đang bị tắt.');
abort_if($template->format === 'json', 422, 'Không thể gửi template JSON (hoá đơn).');
return $template;
}
/**
* @return array{subject: string, html: string}
*/
private function renderForCustomer(Template $template, Customer $customer): array
{
$values = collect($template->variables())
->map(fn ($definition) => $definition['example'] ?? '')
->merge(MailGlobals::values())
->merge(MailPlaceholders::recipientValues($customer, $customer->email))
->all();
try {
return $this->renderer->render($template, $values);
} catch (InvalidTemplateVariableException $e) {
abort(422, $e->getMessage());
}
}
/**
* Reset về mật khẩu ngẫu nhiên và gửi mail cho khách hàng.
*/
@@ -80,16 +140,16 @@ class CustomerMailService
{
$customer = $this->resolveCustomer($uuid);
$template = null;
abort_if(!AutoEmailGate::mailEnabled(), 422, 'Hệ thống đang tắt gửi email (Mẫu email → Cài đặt → Bật gửi email).');
$template = empty($data['template_id']) ? null : $this->sendableTemplate((int) $data['template_id']);
$subject = trim((string) ($data['subject'] ?? ''));
$message = trim((string) ($data['message'] ?? ''));
if (!empty($data['template_id'])) {
$template = Template::query()->whereKey($data['template_id'])->where('status', 1)->first();
abort_if(!$template, 422, 'Template không tồn tại hoặc đang bị tắt.');
$subject = trim((string) $template->subject);
$message = trim((string) $template->message);
if ($template && ($subject === '' || $message === '')) {
$rendered = $this->renderForCustomer($template, $customer);
$subject = $subject ?: $rendered['subject'];
$message = $message ?: $rendered['html'];
}
abort_if($subject === '' || $message === '', 422, 'Subject và content không được để trống.');
@@ -107,14 +167,19 @@ class CustomerMailService
if ($bcc !== []) {
$mailer->bcc($bcc);
}
$mailer->send(new ManualCustomerEmail($subject, $message));
$mailer->send($template
? new GenericTemplateMail($subject, $message, array_diff_key($template->mailConfig(), array_flip(['cc', 'bcc'])))
: new ManualCustomerEmail($subject, $message, wrapLayout: (bool) ($data['with_layout'] ?? true)));
MailLog::create([
'template_id' => $template->id ?? 0,
'subject' => $subject,
'from_address' => $template?->mailConfig()['from_email'] ?? config('mail.from.address'),
'to' => implode(', ', $to),
'cc' => implode(', ', $cc),
'bcc' => implode(', ', $bcc),
'customer_id' => $customer->id,
'sent_by' => $admin->id,
'message' => $message,
]);
@@ -82,7 +82,7 @@ class CustomerServiceProvisioningService
return DB::transaction(function () use ($customer, $service, $data) {
$vmFields = ['virtual_machine_id', 'os_id', 'vm_cpu', 'vm_ram_mb', 'vm_disk_gb', 'vm_ip', 'vm_dns', 'vm_user', 'vm_password', 'vm_port'];
$service->fill(collect($data)->except(['price', ...$vmFields])->all());
$service->fill(collect($data)->except(['price', 'billing_cycle', ...$vmFields])->all());
$service->save();
if (!empty($data['virtual_machine_id'])) {
@@ -93,6 +93,13 @@ class CustomerServiceProvisioningService
$service->orderItem->update(['price' => $data['price']]);
}
if (!empty($data['billing_cycle']) && $service->orderItem) {
$service->orderItem->update([
'billing_cycle' => $data['billing_cycle'],
'months' => OrderHelper::cycleToMonths($data['billing_cycle']),
]);
}
// Đồng bộ sang module_vmware nếu có gán VM
if ($service->vm_id) {
$vmData = array_filter([
+10 -3
View File
@@ -145,12 +145,13 @@ class InvoicePaymentService
?int $adminId = null,
string $method = 'admin',
?int $receivedAmount = null,
string $note = '',
): Invoice {
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
}
return DB::transaction(function () use ($invoice, $adminId, $method, $receivedAmount) {
return DB::transaction(function () use ($invoice, $adminId, $method, $receivedAmount, $note) {
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
@@ -174,13 +175,19 @@ class InvoicePaymentService
'status' => $settled ? InvoiceStatus::PAID->value : $invoice->status,
'paid_at' => $settled ? now() : null,
'payment_method' => $invoice->payment_method ?: $method,
'note' => $note !== '' ? $note : $invoice->note,
]);
$transactionNote = 'Admin xác nhận thanh toán hóa đơn #' . $invoice->invoice_number
. ($settled ? '' : sprintf(' (một phần: %s/%s VNĐ)', number_format($paidSoFar), number_format((int) $invoice->total)));
if ($note !== '') {
$transactionNote .= '. Ghi chú: ' . $note;
}
$this->recordTransaction(
$invoice,
$method,
'Admin xác nhận thanh toán hóa đơn #' . $invoice->invoice_number
. ($settled ? '' : sprintf(' (một phần: %s/%s VNĐ)', number_format($paidSoFar), number_format((int) $invoice->total))),
$transactionNote,
$adminId,
amount: $received,
sequence: $settled && $received === (int) $invoice->total ? null : $paidSoFar,
+23 -5
View File
@@ -13,6 +13,7 @@ use App\Jobs\Mail\Customer\OrderCreatedJob;
use App\Jobs\VirtualMachine\Create\CreateVirtualMachineJob;
use App\Jobs\VirtualMachine\Upgrade\UpgradeVirtualMachine;
use App\Models\Customer;
use App\Models\DomainPricing;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Payment;
@@ -155,11 +156,15 @@ class OrderService
$orderData = [
'order_num' => Helper::generateUniqueCode(),
'date' => Carbon::today()->toDateString(),
'customer_id' => $data['customer_id'],
'discount_id' => $data['discount_id'] ?? null,
'sub_total' => $total,
'total' => $orderTotal,
'payment_method' => $paymentRecord?->code ?? null,
// `payment` has no `code` column. Store its primary key in the
// legacy string column so the selected method can be resolved
// consistently on both orders and invoices.
'payment_method' => $paymentRecord?->id,
'payment_proof' => $data['payment_proof'] ?? null,
'user_id' => Auth::guard('admin')->id(),
'status' => $effectiveOrderStatus,
@@ -287,7 +292,20 @@ class OrderService
};
$billingDetails = $this->calculateBillingDetails($item['billing']);
$priceSelect = $item['price_custom'] ?? $product->price_sale ?? $product->price;
$isDomain = $categoryType === ProductTypeEnums::DOMAIN;
$billingMultiplier = $isDomain ? 1 : $billingDetails['billing'];
if ($isDomain) {
$domainName = strtolower(trim((string) ($item['server_name'] ?? $item['domain'] ?? '')));
if ($domainName === '') {
throw new \InvalidArgumentException('Vui lòng nhập đầy đủ tên miền.');
}
$domainPrice = DomainPricing::findByDomain($domainName)->orderPrice(1);
$priceSelect = $item['price_custom'] ?? $domainPrice;
} else {
$priceSelect = $item['price_custom'] ?? $product->price_sale ?? $product->price;
}
$billingCycle = ProductBillingCycle::fromLegacyCode((int) $item['billing']);
$generalCode = Helper::generateUniqueCode();
@@ -312,8 +330,8 @@ class OrderService
'customer_id' => $data['customer_id'],
'status' => 0,
'name' => $item['server_name'] ?? $item['domain'] ?? $product->name,
'first_payment' => $priceSelect * $billingDetails['billing'],
'next_payment' => ($item['price_custom'] ?? $product->price) * $billingDetails['billing'],
'first_payment' => $priceSelect * $billingMultiplier,
'next_payment' => $priceSelect * $billingMultiplier,
...$billingDetails,
],
];
@@ -326,7 +344,7 @@ class OrderService
}
}
$total += $item['quantity'] * ($item['price_custom'] ?? ($product->price_sale ?? $product->price)) * $billingDetails['billing'];
$total += $item['quantity'] * $priceSelect * $billingMultiplier;
}
return [$productItems, $relIdData, $total];
+1
View File
@@ -13,6 +13,7 @@ class PleskService
protected array $entryPoints = [
'clients' => ':8443/api/v2/clients',
'domains' => ':8443/api/v2/domains',
'cli' => ':8443/api/v2/cli',
];
public function client(DnsServer $server, int $timeout = 30): PendingRequest
@@ -0,0 +1,39 @@
<?php
namespace App\Services\Plesk;
use App\Models\DnsServer;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Log;
class PleskServicePlanService
{
public function __construct(private PleskService $plesk)
{
}
/**
* @return list<string>|null
*/
public function names(DnsServer $server): ?array
{
try {
$response = $this->plesk->client($server, 15)
->post($this->plesk->url($server, 'cli', '/service_plan/call'), ['params' => ['--list']]);
} catch (ConnectionException $e) {
Log::error('Plesk service plan list failed', ['error' => $e->getMessage(), 'server_id' => $server->id]);
return null;
}
if (!$response->successful() || (int) $response->json('code', 1) !== 0) {
Log::error('Plesk service plan list failed', ['status' => $response->status(), 'server_id' => $server->id]);
return null;
}
$lines = preg_split('/\R/', (string) $response->json('stdout', ''));
return array_values(array_unique(array_filter(array_map('trim', $lines), 'strlen')));
}
}
@@ -0,0 +1,91 @@
<?php
namespace App\Services\Product;
use App\Models\ProductCategories;
use Illuminate\Support\Facades\DB;
final class ProductCategorySampleService
{
/**
* Fill missing metadata on known groups and create missing sample groups.
* Existing administrator-entered values are never overwritten.
*
* @return array{created: int, updated: int}
*/
public function seed(): array
{
$definitions = [
['slug' => 'vps', 'name' => 'VPS', 'type' => 'vps', 'sort_order' => 10, 'billing_cycles' => $this->recurringCycles()],
['slug' => 'hosting', 'name' => 'Hosting', 'type' => 'hosting', 'sort_order' => 20, 'billing_cycles' => $this->recurringCycles()],
['slug' => 'cloud-storage', 'name' => 'Cloud Storage', 'type' => 'cloud', 'sort_order' => 30, 'billing_cycles' => $this->recurringCycles()],
['slug' => 'email', 'name' => 'Email', 'type' => 'email', 'sort_order' => 40, 'billing_cycles' => $this->recurringCycles()],
['slug' => 'hardware', 'name' => 'Hardware', 'type' => 'hardware', 'sort_order' => 50, 'billing_cycles' => ['one_time']],
['slug' => 'thiet-ke-website', 'name' => 'Thiết kế website', 'type' => 'web_design', 'sort_order' => 60, 'billing_cycles' => ['one_time']],
['slug' => 'it-support', 'name' => 'IT Support', 'type' => 'it_support', 'sort_order' => 70, 'billing_cycles' => ['monthly', 'annually', 'one_time']],
['slug' => 'domain', 'name' => 'Tên miền Việt Nam', 'type' => 'domain', 'sort_order' => 75, 'billing_cycles' => ['annually']],
['slug' => 'other', 'name' => 'Other', 'type' => 'addon', 'sort_order' => 80, 'billing_cycles' => ['one_time']],
];
return DB::transaction(function () use ($definitions): array {
$created = 0;
$updated = 0;
foreach ($definitions as $definition) {
$group = ProductCategories::withTrashed()->firstOrNew(['slug' => $definition['slug']]);
$isNew = ! $group->exists;
if ($isNew) {
$group->fill([
...$definition,
'parent_id' => null,
'is_active' => true,
]);
} else {
foreach (['type', 'billing_cycles'] as $field) {
if (blank($group->{$field})) {
$group->{$field} = $definition[$field];
}
}
}
if ($isNew || $group->isDirty()) {
$group->save();
$isNew ? $created++ : $updated++;
}
if ($group->trashed()) {
$group->restore();
$updated++;
}
}
ProductCategories::query()
->whereNotNull('type')
->whereNull('billing_cycles')
->get()
->each(function (ProductCategories $group) use (&$updated): void {
$group->billing_cycles = $this->cyclesForType($group->type);
$group->save();
$updated++;
});
return compact('created', 'updated');
});
}
private function cyclesForType(string $type): array
{
return match ($type) {
'hardware', 'web_design', 'addon' => ['one_time'],
'domain' => ['annually'],
'it_support' => ['monthly', 'annually', 'one_time'],
default => $this->recurringCycles(),
};
}
private function recurringCycles(): array
{
return ['monthly', 'quarterly', 'semi_annually', 'annually', 'biennially', 'triennially'];
}
}
@@ -0,0 +1,81 @@
<?php
namespace App\Services;
use App\Mail\ServiceRenewalReminderMail;
use App\Models\Mail as MailLog;
use App\Models\Service;
use App\Models\User;
use App\Services\Email\EmailTemplateService;
use App\Support\AutoEmailGate;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Mail;
class ServiceRenewalReminderService
{
private const SCENARIO = 'service_renewal_reminder';
public const MAX_RESULTS = 1000;
public function __construct(private readonly EmailTemplateService $templates) {}
/**
* @return Collection<int, Service>
*/
public function expiring(int $days): Collection
{
return Service::with(['customer:id,uuid,fullname,email', 'product:id,name'])
->where('status', 'active')
->whereHas('customer')
->whereBetween('expires_at', [now()->startOfDay(), now()->addDays($days)->endOfDay()])
->orderBy('expires_at')
->limit(self::MAX_RESULTS)
->get();
}
public function daysLeft(Service $service): int
{
return (int) now()->startOfDay()->diffInDays($service->expires_at->copy()->startOfDay(), false);
}
/**
* @param array<int, int> $serviceIds
*/
public function send(array $serviceIds, User $admin): int
{
abort_if(!AutoEmailGate::mailEnabled(), 422, 'Hệ thống đang tắt gửi email (Mẫu email → Cài đặt → Bật gửi email).');
try {
$template = $this->templates->loadTemplate(self::SCENARIO);
} catch (ModelNotFoundException) {
abort(422, 'Chưa có template nhắc gia hạn (service_renewal_reminder) đang bật trong Mẫu email.');
}
AutoEmailGate::markManual();
$services = Service::with(['customer', 'product', 'orderItem'])
->whereIn('id', $serviceIds)
->whereNotNull('expires_at')
->get()
->filter(fn (Service $service) => filled($service->customer?->email));
foreach ($services as $service) {
$mail = new ServiceRenewalReminderMail($service->customer, $service);
MailLog::create([
'template_id' => $template->id,
'subject' => $mail->envelope()->subject,
'from_address' => $template->mailConfig()['from_email'] ?? config('mail.from.address'),
'to' => $service->customer->email,
'customer_id' => $service->customer_id,
'sent_by' => $admin->id,
'message' => $mail->render(),
]);
Mail::to($service->customer->email)->queue($mail);
}
return $services->count();
}
}
+11 -1
View File
@@ -25,13 +25,23 @@ final class AutoEmailGate
return in_array($scenario, self::disabledScenarios(), true);
}
public static function mailEnabled(): bool
{
return (bool) (self::emailSettings()['mail_enabled'] ?? true);
}
/**
* @return array<int, string>
*/
public static function disabledScenarios(): array
{
return (array) (self::emailSettings()['auto_disabled'] ?? []);
}
private static function emailSettings(): array
{
$value = Setting::where('key', 'email_settings')->value('value');
return (array) (json_decode($value ?? '', true)['auto_disabled'] ?? []);
return (array) (json_decode($value ?? '', true) ?? []);
}
}
+1 -1
View File
@@ -124,7 +124,7 @@ final class EmailScenarioRegistry
'required_variables' => ['domain_name', 'order_num'],
],
'domain_order_approved' => [
'label' => 'Tên miền được duyệt', 'category' => self::BUSINESS, 'group' => 'ORDER',
'label' => 'Bàn giao tên miền (đã duyệt)', 'category' => self::BUSINESS, 'group' => 'ORDER',
'required_variables' => ['domain_name'], 'permissions' => ['disable' => true],
],
'domain_order_rejected' => [