feat: nạp tiền thủ công mã 30 phút, gia hạn trừ số dư, đồng bộ domain từ Plesk

- Nạp tiền: mã thanh toán sống 30 phút (ManualDepositDraft), khôi phục/huỷ mã, lệnh dọn mã hết hạn; total_pending chỉ tính giao dịch đã nộp chứng từ, admin duyệt/từ chối/xoá giao dịch
- Gia hạn dịch vụ: phát hành invoice gia hạn trên order gốc và trừ số dư ngay
- Đồng bộ domain từ Plesk theo server, ServiceOrderRecorder tạo order/invoice cho dịch vụ admin dựng
- Danh sách dịch vụ trả field theo loại (service_plan, dns_records_count), đếm dịch vụ theo loại

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-11 23:07:51 +07:00
co-authored by Claude Opus 5.5
parent 10af41c5cf
commit c5115b52dd
53 changed files with 1887 additions and 613 deletions
+101 -72
View File
@@ -8,7 +8,9 @@ use App\DTOs\Order\ClientOrderFilters;
use App\Enums\Invoice\InvoiceStatus;
use App\Helpers\OrderHelper;
use App\Jobs\VirtualMachine\Provision\RetryProvisioningOrchestrator;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\ModuleVmware;
use App\Models\Order;
use App\Models\OrderItem;
@@ -16,6 +18,7 @@ use App\Models\Service;
use App\Models\VirtualMachines;
use App\Repositories\Api\Order\OrderRepositoryInterface;
use App\Repositories\Api\Service\ServiceRepositoryInterface;
use App\Services\InvoicePaymentService;
use App\Support\RenewalPricing;
use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
@@ -26,6 +29,7 @@ class OrderQueryService
public function __construct(
private readonly OrderRepositoryInterface $orderRepository,
private readonly ServiceRepositoryInterface $productRepo,
private readonly InvoicePaymentService $invoicePaymentService,
) {
}
@@ -166,12 +170,12 @@ class OrderQueryService
return ['ok' => true, 'message' => 'Đã yêu cầu khởi tạo lại dịch vụ. Hệ thống sẽ kiểm tra và xử lý trong vài phút.'];
}
public function renewService(int $serviceId, int $customerId, int $months): array
public function renewService(int $serviceId, Customer $customer, int $months): array
{
$service = Service::query()
->with(['orderItem.product', 'invoice'])
->with(['orderItem.product'])
->where('id', $serviceId)
->where('customer_id', $customerId)
->where('customer_id', $customer->id)
->whereNotIn('status', ['terminated', 'cancelled'])
->first();
@@ -197,89 +201,114 @@ class OrderQueryService
$cycles = intdiv($months, $cycleMonths);
// Gia hạn luôn dùng giá sản phẩm hiện tại trong bảng giá, không dùng giá đã
// chốt lúc đặt mua ban đầu — giá cũ chỉ để hiển thị trên đơn hàng/hoá đơn gốc.
$currentPrice = $this->productRepo->getPricing((int) $service->product_id, $orderItem->billing_cycle);
$currentPrice = $this->productRepo->getPricing((int) ($service->product_id ?: $orderItem->product_id), $orderItem->billing_cycle);
if ($currentPrice === null) {
return ['ok' => false, 'message' => 'Sản phẩm hiện không còn bán, không thể gia hạn.', 'code' => 400];
}
$renewalPrice = (int) $currentPrice * $cycles;
$addonTotal = RenewalPricing::addonTotal($service, $cycles);
$price = $renewalPrice + $addonTotal;
if ($service->invoice_id && Invoice::where('id', $service->invoice_id)
->where('invoice_type', 2)
->whereIn('status', [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value])
->exists()) {
$invoice = Invoice::find($service->invoice_id);
$invoice = DB::transaction(function () use ($service, $orderItem, $renewalPrice, $cycles, $months) {
$service = Service::query()->whereKey($service->id)->lockForUpdate()->first();
$pending = $this->pendingRenewalInvoice($service);
if ($pending && ((int) $pending->amount_paid > 0 || $this->renewalMonths($pending) === $months)) {
return $pending;
}
return $this->issueRenewalInvoice($service, $orderItem, $renewalPrice, $cycles, $months, $pending);
});
try {
$invoice = $this->invoicePaymentService->payWithBalance($invoice, $customer);
} catch (\InvalidArgumentException $e) {
return [
'ok' => true,
'message' => 'Dịch vụ đã có hóa đơn gia hạn đang chờ thanh toán.',
'data' => [
'order_id' => $invoice?->order_id,
'invoice_id' => $invoice?->id,
'invoice_number' => $invoice?->invoice_number,
'total' => (float) ($invoice?->total ?? 0),
'status' => $invoice?->status,
'payment_url' => $invoice?->clientPath(),
],
'ok' => false,
'message' => $e->getMessage() . ' Hóa đơn gia hạn #' . $invoice->invoice_number . ' đang chờ thanh toán.',
'code' => 422,
'data' => $this->renewalPayload($invoice),
];
}
// Gia hạn là một billing cycle mới của CÙNG một Order/Service — không tạo Order mới.
// Order gốc chính là order đã tạo ra service này (qua order_item -> order_id).
$periodStart = $service->expires_at && $service->expires_at->isFuture() ? $service->expires_at->copy() : now();
$periodEnd = $periodStart->copy()->addMonths($months);
$invoice = DB::transaction(function () use ($service, $orderItem, $price, $renewalPrice, $cycles, $months, $periodStart, $periodEnd) {
$invoice = Invoice::create([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'customer_id' => $service->customer_id,
'order_id' => $orderItem->order_id,
'invoice_type' => 2,
'sub_total' => $price,
'discount_amount' => 0,
'tax' => 0,
'total' => $price,
'status' => InvoiceStatus::UNPAID->value,
'due_date' => now()->addDays(7)->toDateString(),
'billing_period_start' => $periodStart->toDateString(),
'billing_period_end' => $periodEnd->toDateString(),
]);
\App\Models\InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $service->product_id,
'type' => 'renewal',
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
'months' => $months,
'quantity' => 1,
'unit_price' => $renewalPrice,
'total_price' => $renewalPrice,
]);
foreach (RenewalPricing::addonInvoiceItems($service, $cycles, $months) as $addonItem) {
\App\Models\InvoiceItem::create($addonItem + ['invoice_id' => $invoice->id]);
}
$service->update(['invoice_id' => $invoice->id]);
return $invoice;
});
return [
'ok' => true,
'message' => 'Đã tạo hóa đơn gia hạn. Vui lòng thanh toán để gia hạn dịch vụ.',
'data' => [
'order_id' => $invoice->order_id,
'invoice_id' => $invoice->id,
'invoice_number' => $invoice->invoice_number,
'total' => (float) $invoice->total,
'status' => $invoice->status,
'payment_url' => $invoice->clientPath(),
'message' => 'Gia hạn dịch vụ thành công.',
'data' => $this->renewalPayload($invoice) + [
'expires_at' => $service->fresh()->expires_at?->toISOString(),
],
];
}
private function pendingRenewalInvoice(Service $service): ?Invoice
{
if (! $service->invoice_id) {
return null;
}
return Invoice::query()
->where('id', $service->invoice_id)
->where('invoice_type', 2)
->whereIn('status', [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value])
->first();
}
private function renewalMonths(Invoice $invoice): int
{
return (int) $invoice->invoiceItems()->where('type', 'renewal')->value('months');
}
private function issueRenewalInvoice(Service $service, OrderItem $orderItem, int $renewalPrice, int $cycles, int $months, ?Invoice $draft): Invoice
{
$price = $renewalPrice + RenewalPricing::addonTotal($service, $cycles);
$periodStart = $service->expires_at && $service->expires_at->isFuture() ? $service->expires_at->copy() : now();
$invoice = $draft ?? new Invoice([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'status' => InvoiceStatus::UNPAID->value,
]);
$invoice->invoiceItems()->delete();
$invoice->fill([
'customer_id' => $service->customer_id,
'order_id' => $orderItem->order_id,
'invoice_type' => 2,
'sub_total' => $price,
'discount_amount' => 0,
'tax' => 0,
'total' => $price,
'due_date' => now()->addDays(7)->toDateString(),
'billing_period_start' => $periodStart->toDateString(),
'billing_period_end' => $periodStart->copy()->addMonths($months)->toDateString(),
])->save();
InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $service->product_id ?: $orderItem->product_id,
'type' => 'renewal',
'description' => 'Gia hạn dịch vụ: ' . ($orderItem->product?->name ?? $service->server_name ?? ''),
'months' => $months,
'quantity' => 1,
'unit_price' => $renewalPrice,
'total_price' => $renewalPrice,
]);
foreach (RenewalPricing::addonInvoiceItems($service, $cycles, $months) as $addonItem) {
InvoiceItem::create($addonItem + ['invoice_id' => $invoice->id]);
}
$service->update(['invoice_id' => $invoice->id]);
return $invoice;
}
private function renewalPayload(Invoice $invoice): array
{
return [
'order_id' => $invoice->order_id,
'invoice_id' => $invoice->id,
'invoice_number' => $invoice->invoice_number,
'total' => (float) $invoice->total,
'status' => $invoice->status,
'payment_url' => $invoice->clientPath(),
];
}
}
@@ -2,6 +2,8 @@
namespace App\Services\Api\ServiceClient;
use App\Models\DnsDomain;
use App\Models\Service;
use App\Repositories\Api\ServiceClient\ServiceClientRepositoryInterface;
class ServiceClientService
@@ -16,11 +18,51 @@ class ServiceClientService
/**
* Lấy danh sách dịch vụ đang hoạt động
*/
public function getActiveServices(int $customerId, ?string $productType = null, int $limit = 10)
public function getActiveServices(int $customerId, ?string $productType = null, ?int $limit = 10)
{
return $this->serviceClientRepository->getActiveServices($customerId, $productType, $limit);
}
/**
* @return array{vps: int, server: int, hosting: int, domain: int}
*/
public function countByType(int $customerId): array
{
$counts = Service::query()
->where('customer_id', $customerId)
->whereNotIn('status', ['cancelled', 'terminated'])
->selectRaw('type, COUNT(*) as total')
->groupBy('type')
->pluck('total', 'type');
return [
'vps' => (int) $counts->get('vps', 0),
'server' => (int) $counts->get('server', 0),
'hosting' => (int) $counts->get('hosting', 0),
'domain' => (int) $counts->get('domain', 0),
];
}
/**
* @param iterable<Service> $services
*/
public function attachDnsRecordCounts(iterable $services, int $customerId): void
{
$counts = DnsDomain::query()
->withCount('ns')
->whereHas('customer', fn ($query) => $query->where('customers.id', $customerId))
->get(['id', 'domain_name'])
->mapWithKeys(fn (DnsDomain $domain) => [
mb_strtolower(trim($domain->domain_name)) => (int) $domain->ns_count,
]);
foreach ($services as $service) {
if ($service->type === 'domain') {
$service->setAttribute('dns_records_count', $counts->get(mb_strtolower(trim((string) $service->server_name))));
}
}
}
public function findActiveBySlug(string $slug)
{
return $this->serviceClientRepository->findActiveBySlug($slug);
@@ -36,7 +36,7 @@ class CustomerImpersonationService
$token = JWTAuth::fromUser($customer);
$refreshToken = $this->clientAuthService->createRefreshToken($customer->id);
$clientResource = (new ClientResource($customer->loadCount(['vps', 'hosting', 'domain'])))->resolve($request);
$clientResource = (new ClientResource($customer))->resolve($request);
$code = Str::random(48);
Cache::put("impersonate:{$code}", [
@@ -2,16 +2,11 @@
namespace App\Services\Customer;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Helpers\OrderHelper;
use App\Mail\ServiceRenewalReminderMail;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\ModuleVmware;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use App\Models\Transaction;
@@ -21,6 +16,7 @@ use App\Repositories\Module\Hosting\HostingRepositoryInterface as ModuleHostingR
use App\Repositories\Module\Vmware\VmwareRepositoryInterface;
use App\Repositories\Service\ServiceRepositoryInterface;
use App\Services\Customer\Concerns\ResolvesCustomer;
use App\Services\Order\ServiceOrderRecorder;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
@@ -37,6 +33,7 @@ class CustomerServiceProvisioningService
private readonly ModuleHostingRepositoryInterface $moduleHostingRepository,
private readonly VmwareRepositoryInterface $vmwareRepository,
private readonly ServiceRepositoryInterface $serviceRepository,
private readonly ServiceOrderRecorder $orderRecorder,
) {}
public function getServices(string $uuid): Collection
@@ -89,8 +86,11 @@ class CustomerServiceProvisioningService
$this->assignVirtualMachine($service, $customer, (int) $data['virtual_machine_id']);
}
if (array_key_exists('price', $data) && $data['price'] !== null && $service->orderItem) {
$service->orderItem->update(['price' => $data['price']]);
$price = isset($data['price']) ? (int) $data['price'] : null;
if (!$service->order_item_id && ($price !== null || !empty($data['billing_cycle']))) {
$this->orderRecorder->ensureForService($service, $price, $data['billing_cycle'] ?? null);
$service->refresh();
}
if (!empty($data['billing_cycle']) && $service->orderItem) {
@@ -100,6 +100,11 @@ class CustomerServiceProvisioningService
]);
}
if ($price !== null && $service->orderItem) {
$service->orderItem->update(['price' => $price]);
$this->orderRecorder->syncUnpaidInvoice($service->refresh(), $price);
}
// Đồng bộ sang module_vmware nếu có gán VM
if ($service->vm_id) {
$vmData = array_filter([
@@ -196,7 +201,7 @@ class CustomerServiceProvisioningService
{
$customer = $this->resolveCustomer($uuid);
$product = Product::with('pricings')->find($data['product_id']);
$product = Product::find($data['product_id']);
abort_if(
$product->product_type === 'vps' && empty($data['virtual_machine_id']),
422,
@@ -206,9 +211,14 @@ class CustomerServiceProvisioningService
$billingCycle = $data['billing_cycle'] ?? 'monthly';
$months = OrderHelper::cycleToMonths($billingCycle);
$pricing = $product->pricings->where('billing_cycle', $billingCycle)->first();
// Số tiền đã thanh toán: admin nhập tay để khớp với thực tế (có thể lệch giá niêm yết do khuyến mãi/thoả thuận)
$basePrice = isset($data['amount_paid']) ? (int) $data['amount_paid'] : (int) ($pricing->price ?? 0);
$listPrice = $this->orderRecorder->listPrice($product, $billingCycle, $data['server_name'] ?? null);
abort_if(
!isset($data['amount_paid']) && $listPrice === null && $product->product_type === 'domain',
422,
'Tên miền không có giá trong bảng giá tên miền, vui lòng nhập giá.',
);
$basePrice = isset($data['amount_paid']) ? (int) $data['amount_paid'] : (int) $listPrice;
$paymentMethod = $data['payment_method'];
@@ -224,66 +234,25 @@ class CustomerServiceProvisioningService
);
return DB::transaction(function () use ($customer, $product, $data, $billingCycle, $months, $basePrice, $paymentMethod, $clientIp) {
// 1) Order + OrderItem (mô phỏng flow customer đặt hàng)
$order = Order::create([
'order_num' => OrderHelper::generateOrderNumber(),
'customer_id' => $customer->id,
'date' => now()->toDateString(),
'sub_total' => $basePrice,
'discount_amount' => 0,
'total' => $basePrice,
'status' => OrderStatus::ACTIVE->value,
'payment_method' => $paymentMethod,
'client_ip' => $clientIp,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'billing_cycle' => $billingCycle,
'months' => $months,
'server_name' => $data['server_name'] ?? null,
'quantity' => 1,
'price' => $basePrice,
]);
['order' => $order, 'orderItem' => $orderItem, 'invoice' => $invoice] = $this->orderRecorder->create(
$customer->id,
$product,
$billingCycle,
$basePrice,
$data['server_name'] ?? null,
paid: true,
paymentMethod: $paymentMethod,
clientIp: $clientIp,
);
// Ngày bắt đầu/hết hạn dùng chung cho cả module_vmware (next_due_date/next_invoice) và services.
$startedAt = $data['started_at'] ?? now();
$expiresAt = $data['expires_at'] ?? Carbon::parse($startedAt)->addMonths($months);
// 2) ModuleVmware: snapshot từ virtual_machines. `order_id` phải trỏ về
// order vừa tạo — client console-ticket/rebuild resolve VM qua
// service->orderItem->order->vmWare, không qua services.vm_id.
// module_vmware.order_id phải trỏ về order vừa tạo — client console-ticket/rebuild
// resolve VM qua service->orderItem->order->vmWare, không qua services.vm_id.
$vmId = $this->createModuleVmwareIfNeeded($data, $customer, $order, $basePrice, $expiresAt);
// 3) Invoice — đánh dấu PAID luôn vì admin đứng ra tạo & xác nhận thanh toán
$invoice = Invoice::create([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'customer_id' => $customer->id,
'order_id' => $order->id,
'invoice_type' => 1,
'date' => now()->toDateString(),
'sub_total' => $basePrice,
'discount_amount' => 0,
'tax' => 0,
'total' => $basePrice,
'status' => InvoiceStatus::PAID->value,
'payment_method' => $paymentMethod,
'paid_at' => now(),
'due_date' => now()->addMonths($months)->toDateString(),
]);
InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $product->id,
'type' => 'service',
'description' => $product->name ?? 'Dịch vụ',
'months' => $months,
'quantity' => 1,
'unit_price' => $basePrice,
'total_price' => $basePrice,
]);
// 4) Payment processing
if ($paymentMethod === 'balance') {
$customer->total = (int) $customer->total - $basePrice;
@@ -0,0 +1,116 @@
<?php
namespace App\Services\Domain;
use App\Models\DnsDomain;
use App\Models\Service;
use App\Services\Order\ServiceOrderRecorder;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class CustomerDomainServiceSync
{
public const AUTO_CREATED_NOTE = 'Tự động tạo từ phân công DNS domain';
public function __construct(private readonly ServiceOrderRecorder $orderRecorder) {}
public function syncCustomers(DnsDomain $domain, array $customerIds, ?string $previousDomainName = null): void
{
$customerIds = collect($customerIds)->map(fn ($id) => (int) $id)->unique()->values();
$previousCustomerIds = $domain->customer()->pluck('customers.id');
$oldName = $previousDomainName ?? $domain->domain_name;
DB::transaction(function () use ($domain, $customerIds, $previousCustomerIds, $oldName): void {
$domain->customer()->sync($customerIds->all());
foreach ($customerIds as $customerId) {
$service = $this->findService($customerId, $oldName, $domain->domain_name);
if ($service?->trashed()) {
$service->restore();
}
$service ??= new Service([
'customer_id' => $customerId,
'type' => 'domain',
'note' => self::AUTO_CREATED_NOTE,
]);
$service->fill([
'server_name' => $domain->domain_name,
'status' => $this->serviceStatus($domain),
'started_at' => $service->started_at ?? $domain->created_at ?? Carbon::now(),
])->save();
if ($service->status !== 'cancelled') {
$this->orderRecorder->ensureForService($service);
}
}
$removedCustomerIds = $previousCustomerIds->diff($customerIds);
if ($removedCustomerIds->isNotEmpty()) {
Service::query()
->whereIn('customer_id', $removedCustomerIds)
->where('type', 'domain')
->whereIn(DB::raw('LOWER(TRIM(server_name))'), array_unique([
$this->domainKey($oldName),
$this->domainKey($domain->domain_name),
]))
->get()
->each(function (Service $service): void {
$this->orderRecorder->cancelUnpaidInvoice($service);
$service->delete();
});
}
});
}
public function updateCustomerDomain(
DnsDomain $domain,
int $customerId,
?string $expiresAt,
): Service {
$this->syncCustomers($domain, $domain->customer()->pluck('customers.id')->all());
$service = $this->findService($customerId, $domain->domain_name, $domain->domain_name);
abort_if(! $service, 404, 'Không tìm thấy dịch vụ tên miền');
$service->fill([
'status' => $this->serviceStatus($domain),
'started_at' => $domain->created_at,
'expires_at' => $expiresAt
? Carbon::parse($expiresAt)->setTimeFrom($service->expires_at ?? Carbon::today())
: null,
])->save();
return $service;
}
private function findService(int $customerId, string $oldName, string $currentName): ?Service
{
return Service::withTrashed()
->where('customer_id', $customerId)
->where('type', 'domain')
->whereIn(DB::raw('LOWER(TRIM(server_name))'), array_unique([
$this->domainKey($oldName),
$this->domainKey($currentName),
]))
->orderBy('id')
->first();
}
private function serviceStatus(DnsDomain $domain): string
{
return match ((int) $domain->is_created) {
DnsDomain::STATUS_CREATED => 'active',
DnsDomain::STATUS_INACTIVE => 'suspended',
DnsDomain::STATUS_CANCELLED => 'cancelled',
default => 'pending',
};
}
private function domainKey(?string $domainName): string
{
return mb_strtolower(trim((string) $domainName));
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace App\Services\Order;
use App\Enums\Invoice\InvoiceStatus;
use App\Enums\Order\OrderStatus;
use App\Helpers\OrderHelper;
use App\Models\DomainPricing;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use Illuminate\Support\Facades\DB;
class ServiceOrderRecorder
{
/**
* @return array{order: Order, orderItem: OrderItem, invoice: Invoice}
*/
public function create(
int $customerId,
?Product $product,
string $billingCycle,
int $price,
?string $serverName,
bool $paid,
?string $paymentMethod = null,
?string $clientIp = null,
): array {
$months = OrderHelper::cycleToMonths($billingCycle);
$isDomain = $product?->product_type === 'domain';
$order = Order::create([
'order_num' => OrderHelper::generateOrderNumber(),
'customer_id' => $customerId,
'date' => now()->toDateString(),
'sub_total' => $price,
'discount_amount' => 0,
'total' => $price,
'status' => $paid ? OrderStatus::ACTIVE->value : OrderStatus::PENDING->value,
'payment_method' => $paymentMethod,
'client_ip' => $clientIp,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product?->id,
'billing_cycle' => $billingCycle,
'months' => $months,
'server_name' => $serverName,
'domain_name' => $isDomain ? $serverName : null,
'quantity' => 1,
'price' => $price,
]);
$invoice = Invoice::create([
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
'customer_id' => $customerId,
'order_id' => $order->id,
'invoice_type' => 1,
'date' => now()->toDateString(),
'sub_total' => $price,
'discount_amount' => 0,
'tax' => 0,
'total' => $price,
'status' => $paid ? InvoiceStatus::PAID->value : InvoiceStatus::UNPAID->value,
'payment_method' => $paymentMethod,
'paid_at' => $paid ? now() : null,
'due_date' => $paid ? now()->addMonths($months)->toDateString() : now()->toDateString(),
]);
InvoiceItem::create([
'invoice_id' => $invoice->id,
'product_id' => $product?->id,
'type' => 'service',
'description' => $this->describe($product, $serverName),
'months' => $months,
'quantity' => 1,
'unit_price' => $price,
'total_price' => $price,
]);
return compact('order', 'orderItem', 'invoice');
}
public function ensureForService(Service $service, ?int $price = null, ?string $billingCycle = null): void
{
if ($service->order_item_id || ! $service->customer_id) {
return;
}
DB::transaction(function () use ($service, $price, $billingCycle) {
$product = $service->product ?? $this->defaultProductFor($service->type);
$isDomain = ($product?->product_type ?? $service->type) === 'domain';
$billingCycle ??= $isDomain ? 'annually' : 'monthly';
$price ??= $this->listPrice($product, $billingCycle, $service->server_name) ?? 0;
$records = $this->create(
(int) $service->customer_id,
$product,
$billingCycle,
$price,
$service->server_name,
paid: false,
);
$service->forceFill([
'product_id' => $service->product_id ?? $product?->id,
'order_item_id' => $records['orderItem']->id,
'invoice_id' => $records['invoice']->id,
])->save();
});
}
public function syncUnpaidInvoice(Service $service, int $price): void
{
$invoice = $service->invoice;
if (! $invoice || (int) $invoice->status !== InvoiceStatus::UNPAID->value || (int) $invoice->invoice_type !== 1) {
return;
}
$months = (int) ($service->orderItem?->months ?: 1);
$invoice->update(['sub_total' => $price, 'total' => $price]);
$invoice->invoiceItems()->where('type', 'service')->update([
'months' => $months,
'unit_price' => $price,
'total_price' => $price,
]);
$invoice->order?->update(['sub_total' => $price, 'total' => $price]);
}
public function cancelUnpaidInvoice(Service $service): void
{
$invoice = $service->invoice;
if (! $invoice || (int) $invoice->status !== InvoiceStatus::UNPAID->value) {
return;
}
$invoice->update(['status' => InvoiceStatus::CANCELLED->value]);
$invoice->order?->update(['status' => OrderStatus::CANCELLED->value]);
}
public function listPrice(?Product $product, string $billingCycle, ?string $serverName): ?int
{
if ($product?->product_type === 'domain') {
return DomainPricing::matchDomain((string) $serverName)
?->orderPrice(DomainPricing::yearsForMonths(OrderHelper::cycleToMonths($billingCycle)));
}
$price = $product?->pricings()->where('billing_cycle', $billingCycle)->value('price');
return $price === null ? null : (int) $price;
}
private function defaultProductFor(?string $type): ?Product
{
return $type
? Product::where('product_type', $type)->where('is_active', true)->orderBy('id')->first()
: null;
}
private function describe(?Product $product, ?string $serverName): string
{
$name = $product->name ?? 'Dịch vụ';
return $serverName ? "{$name} - {$serverName}" : $name;
}
}
+25
View File
@@ -106,6 +106,31 @@ class PleskDomainService
return false;
}
/**
* @return array<int, array<string, mixed>>|false
*/
public function listDomains(DnsServer $server): array|false
{
$this->lastError = null;
try {
$response = $this->plesk->client($server, 30)
->get($this->plesk->url($server, 'domains'));
} catch (ConnectionException $e) {
$this->lastError = $e->getMessage();
return false;
}
if (!$response->successful() || !is_array($response->json())) {
$this->lastError = $response->json('message') ?? $response->body();
return false;
}
return $response->json();
}
public function getDomainInfo(DnsServer $server, string $domain = ''): array|false
{
if (empty($domain)) {