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:
co-authored by
Claude Opus 5.5
parent
8651dde6b1
commit
30898ea46f
@@ -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]);
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user