- ProvisionDnsDomainJob/SuspendDnsDomainJob: tạo domain admin lên Plesk, huỷ = suspend (is_created=3) - Khách xem zone DNS được gán ở /dich-vu/domain, quản lý bản ghi A/AAAA/CNAME/TXT/MX/SRV - send-mail hoá đơn đẩy SendInvoiceMailJob, preview + sửa nội dung, ghi mail.order_id - invoice_attachments.type (payment_proof/deployment) - CacheService xoá theo SCAN pattern, Redis không persistent mặc định - Backfill transactions.public_code Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
308 lines
13 KiB
PHP
308 lines
13 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\Invoice\InvoiceStatus;
|
|
use App\Enums\TransactionStatus;
|
|
use App\Models\Customer;
|
|
use App\Models\Invoice;
|
|
use App\Models\Log as CustomerActivityLog;
|
|
use App\Models\Transaction;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use App\Services\Concerns\ActivatesPaidInvoices;
|
|
|
|
class InvoicePaymentService
|
|
{
|
|
use ActivatesPaidInvoices;
|
|
|
|
/** Trạng thái hoá đơn còn có thể thu tiền. Dùng chung cho cả khách trả lẫn admin xác nhận. */
|
|
public const PAYABLE_STATUSES = [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value];
|
|
|
|
/**
|
|
* Chặn thu tiền trên hoá đơn đã huỷ/đã hoàn — trước đây chỉ payWithBalance() kiểm tra,
|
|
* markPaidByAdmin() thì không, nên hoá đơn CANCELLED vẫn bật sang PAID và kích hoạt dịch vụ thật.
|
|
*/
|
|
public static function assertPayable(Invoice $invoice): void
|
|
{
|
|
if (! in_array((int) $invoice->status, self::PAYABLE_STATUSES, true)) {
|
|
throw new \InvalidArgumentException(sprintf(
|
|
'Hóa đơn #%s đang ở trạng thái "%s", không thể ghi nhận thanh toán.',
|
|
$invoice->invoice_number,
|
|
InvoiceStatus::tryFrom((int) $invoice->status)?->label() ?? 'không xác định',
|
|
));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param int|null $amount Số tiền muốn trả lần này. Null = trả hết phần còn thiếu.
|
|
* Trả ít hơn thì hoá đơn giữ nguyên UNPAID/OVERDUE, chỉ cộng dồn
|
|
* amount_paid — dịch vụ chưa được kích hoạt cho tới khi thu đủ.
|
|
*/
|
|
public function payWithBalance(Invoice $invoice, Customer $customer, string $method = 'balance', ?int $amount = null): Invoice
|
|
{
|
|
if ((int) $invoice->customer_id !== (int) $customer->id) {
|
|
throw new \InvalidArgumentException('Hóa đơn không thuộc tài khoản này.');
|
|
}
|
|
|
|
// Balance/status are re-checked below under row locks — this is just a fast
|
|
// fail-fast path so we don't open a transaction for an already-paid invoice.
|
|
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
}
|
|
|
|
return DB::transaction(function () use ($invoice, $customer, $method, $amount) {
|
|
// Lock both rows so two concurrent payment requests for the same invoice/customer
|
|
// (double-click, retry) cannot both pass the balance check before either commits.
|
|
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
|
|
$customer = Customer::where('id', $customer->id)->lockForUpdate()->firstOrFail();
|
|
|
|
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
}
|
|
|
|
self::assertPayable($invoice);
|
|
|
|
$outstanding = self::outstanding($invoice);
|
|
$payNow = $amount === null ? $outstanding : min($amount, $outstanding);
|
|
|
|
if ($payNow <= 0) {
|
|
throw new \InvalidArgumentException('Số tiền thanh toán phải lớn hơn 0.');
|
|
}
|
|
|
|
if ((int) $customer->total < $payNow) {
|
|
throw new \InvalidArgumentException(sprintf(
|
|
'Số dư không đủ. Hiện có: %s VNĐ, cần: %s VNĐ.',
|
|
number_format((int) $customer->total),
|
|
number_format($payNow)
|
|
));
|
|
}
|
|
|
|
$customer->decrement('total', $payNow);
|
|
|
|
$paidSoFar = (int) $invoice->amount_paid + $payNow;
|
|
$settled = $paidSoFar >= (int) $invoice->total;
|
|
|
|
$invoice->update([
|
|
'amount_paid' => $paidSoFar,
|
|
'status' => $settled ? InvoiceStatus::PAID->value : $invoice->status,
|
|
'paid_at' => $settled ? now() : null,
|
|
'payment_method' => $method,
|
|
]);
|
|
|
|
$this->recordTransaction(
|
|
$invoice,
|
|
$method,
|
|
'Khách hàng 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))),
|
|
amount: $payNow,
|
|
sequence: $settled && $payNow === (int) $invoice->total ? null : $paidSoFar,
|
|
);
|
|
|
|
CustomerActivityLog::create([
|
|
'agent' => 'api',
|
|
'client_ip' => request()?->ip(),
|
|
'customer_id' => $customer->id,
|
|
'description' => sprintf(
|
|
'Thanh toán hóa đơn #%s. Số tiền: %s VNĐ.%s Số dư còn: %s VNĐ.',
|
|
$invoice->invoice_number,
|
|
number_format($payNow),
|
|
$settled ? '' : sprintf(' Còn thiếu: %s VNĐ.', number_format(self::outstanding($invoice->fresh()))),
|
|
number_format((int) $customer->fresh()->total)
|
|
),
|
|
]);
|
|
|
|
if (! $settled) {
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
}
|
|
|
|
if ((int) $invoice->invoice_type === 2) {
|
|
$this->activateRenewal($invoice);
|
|
} elseif ((int) $invoice->invoice_type === 3) {
|
|
$this->activateUpgrade($invoice);
|
|
} elseif ($invoice->order) {
|
|
$this->activateOrder($invoice);
|
|
}
|
|
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
});
|
|
}
|
|
|
|
/** Số tiền còn phải thu của một hoá đơn. */
|
|
public static function outstanding(Invoice $invoice): int
|
|
{
|
|
return max(0, (int) $invoice->total - (int) $invoice->amount_paid);
|
|
}
|
|
|
|
/**
|
|
* @param int|null $receivedAmount Số tiền admin xác nhận đã thực nhận. Null = thu đủ hoá đơn.
|
|
* Nhập ít hơn thì hoá đơn ghi nhận trả một phần và KHÔNG kích
|
|
* hoạt dịch vụ — tránh việc bấm "Đã thanh toán" khi tiền chưa
|
|
* về đủ mà sổ vẫn ghi đủ như trước.
|
|
*/
|
|
public function markPaidByAdmin(
|
|
Invoice $invoice,
|
|
?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, $note) {
|
|
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
|
|
|
|
if ((int) $invoice->status === InvoiceStatus::PAID->value) {
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
}
|
|
|
|
self::assertPayable($invoice);
|
|
|
|
$outstanding = self::outstanding($invoice);
|
|
$received = $receivedAmount === null ? $outstanding : min(max(0, $receivedAmount), $outstanding);
|
|
|
|
if ($received <= 0) {
|
|
throw new \InvalidArgumentException('Số tiền thực nhận phải lớn hơn 0.');
|
|
}
|
|
|
|
$paidSoFar = (int) $invoice->amount_paid + $received;
|
|
$settled = $paidSoFar >= (int) $invoice->total;
|
|
|
|
$invoice->update([
|
|
'amount_paid' => $paidSoFar,
|
|
'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,
|
|
$transactionNote,
|
|
$adminId,
|
|
amount: $received,
|
|
sequence: $settled && $received === (int) $invoice->total ? null : $paidSoFar,
|
|
);
|
|
|
|
if (! $settled) {
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
}
|
|
|
|
if ((int) $invoice->invoice_type === 2) {
|
|
$this->activateRenewal($invoice);
|
|
} elseif ((int) $invoice->invoice_type === 3) {
|
|
$this->activateUpgrade($invoice);
|
|
} elseif ($invoice->order) {
|
|
$this->activateOrder($invoice);
|
|
}
|
|
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Hoàn tiền hoá đơn đã thu: cộng lại số dư, ghi Transaction âm, chuyển hoá đơn sang REFUNDED.
|
|
* Trước đây chỉ luồng tên miền có hoàn tiền, VPS/hosting phải làm tay và không để lại dấu vết.
|
|
*/
|
|
public function refund(Invoice $invoice, ?int $adminId = null, ?int $amount = null, string $reason = ''): Invoice
|
|
{
|
|
if ((int) $invoice->status !== InvoiceStatus::PAID->value) {
|
|
throw new \InvalidArgumentException('Chỉ hoàn tiền được hoá đơn đã thanh toán.');
|
|
}
|
|
|
|
return DB::transaction(function () use ($invoice, $adminId, $amount, $reason) {
|
|
$invoice = Invoice::where('id', $invoice->id)->lockForUpdate()->firstOrFail();
|
|
|
|
if ((int) $invoice->status !== InvoiceStatus::PAID->value) {
|
|
throw new \InvalidArgumentException('Chỉ hoàn tiền được hoá đơn đã thanh toán.');
|
|
}
|
|
|
|
$paid = (int) $invoice->amount_paid ?: (int) $invoice->total;
|
|
$refundAmount = $amount === null ? $paid : min(max(0, $amount), $paid);
|
|
|
|
if ($refundAmount <= 0) {
|
|
throw new \InvalidArgumentException('Số tiền hoàn phải lớn hơn 0.');
|
|
}
|
|
|
|
$customer = Customer::where('id', $invoice->customer_id)->lockForUpdate()->firstOrFail();
|
|
$customer->increment('total', $refundAmount);
|
|
|
|
$invoice->update([
|
|
'status' => InvoiceStatus::REFUNDED->value,
|
|
'amount_paid' => max(0, $paid - $refundAmount),
|
|
]);
|
|
|
|
Transaction::create([
|
|
'uuid' => (string) Str::uuid(),
|
|
'public_code' => Transaction::newPublicCode('INV-REF'),
|
|
'trans' => $invoice->invoice_number . '-REFUND',
|
|
'type' => 'refund',
|
|
'amount' => -$refundAmount,
|
|
'received_amount' => -$refundAmount,
|
|
'customer_id' => $customer->id,
|
|
'user_id' => $adminId,
|
|
'status' => TransactionStatus::COMPLETED->value,
|
|
'note' => trim('Hoàn tiền hóa đơn #' . $invoice->invoice_number . ' ' . $reason),
|
|
]);
|
|
|
|
CustomerActivityLog::create([
|
|
'agent' => 'admin',
|
|
'client_ip' => request()?->ip(),
|
|
'customer_id' => $customer->id,
|
|
'description' => sprintf(
|
|
'Hoàn tiền hóa đơn #%s: %s VNĐ. Số dư mới: %s VNĐ.%s',
|
|
$invoice->invoice_number,
|
|
number_format($refundAmount),
|
|
number_format((int) $customer->fresh()->total),
|
|
$reason ? ' Lý do: ' . $reason : '',
|
|
),
|
|
]);
|
|
|
|
return $invoice->fresh(['order.orderItems.product', 'services', 'customer']);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* @param int|null $amount Số thực thu lần này; null = toàn bộ hoá đơn (hành vi cũ).
|
|
* @param int|null $sequence Khoá phụ để mỗi lần trả từng phần là một dòng riêng. Dưới row
|
|
* lock, amount_paid sau mỗi lần trả là duy nhất và tăng dần, nên
|
|
* vẫn chống được ghi trùng khi job retry.
|
|
*/
|
|
public function recordTransaction(
|
|
Invoice $invoice,
|
|
string $method,
|
|
string $note,
|
|
?int $adminId = null,
|
|
?int $amount = null,
|
|
?int $sequence = null,
|
|
): Transaction {
|
|
$amount = $amount ?? (int) $invoice->total;
|
|
|
|
return Transaction::firstOrCreate(
|
|
[
|
|
'customer_id' => $invoice->customer_id,
|
|
'trans' => $invoice->invoice_number . ($sequence === null ? '' : '-P' . $sequence),
|
|
'type' => 'invoice',
|
|
],
|
|
[
|
|
'uuid' => (string) Str::uuid(),
|
|
'public_code' => Transaction::newPublicCode('INV-PAY'),
|
|
'amount' => $amount,
|
|
'received_amount' => $amount,
|
|
'user_id' => $adminId,
|
|
'status' => TransactionStatus::COMPLETED->value,
|
|
'note' => $note . ' (' . $method . ')',
|
|
]
|
|
);
|
|
}
|
|
}
|