update
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Models\Invoice;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class CheckOverdueInvoices extends Command
|
||||
{
|
||||
protected $signature = 'invoices:check-overdue {--dry-run : Preview invoices without updating data}';
|
||||
protected $description = 'Mark unpaid invoices past due date as overdue and keep related orders unpaid.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$today = now()->toDateString();
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
|
||||
$overdueByStatus = Invoice::query()
|
||||
->whereNotNull('due_date')
|
||||
->whereDate('due_date', '<', $today)
|
||||
->selectRaw('status, count(*) as total')
|
||||
->groupBy('status')
|
||||
->orderBy('status')
|
||||
->get();
|
||||
|
||||
if ($overdueByStatus->isNotEmpty()) {
|
||||
$this->line('invoices:check-overdue | Past-due invoices by current status:');
|
||||
foreach ($overdueByStatus as $row) {
|
||||
$label = InvoiceStatus::tryFrom((int) $row->status)?->label() ?? 'Không xác định';
|
||||
$this->line(" - {$label} ({$row->status}): {$row->total}");
|
||||
}
|
||||
}
|
||||
|
||||
$invoices = Invoice::query()
|
||||
->with('order:id,status')
|
||||
->whereNotNull('due_date')
|
||||
->whereDate('due_date', '<', $today)
|
||||
->whereIn('status', [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value])
|
||||
->get();
|
||||
|
||||
$this->info("invoices:check-overdue | Found {$invoices->count()} invoice(s) due before {$today}.");
|
||||
|
||||
$updatedInvoices = 0;
|
||||
$updatedOrders = 0;
|
||||
|
||||
foreach ($invoices as $invoice) {
|
||||
$needsInvoiceUpdate = (int) $invoice->status !== InvoiceStatus::OVERDUE->value;
|
||||
$order = $invoice->order;
|
||||
$needsOrderUpdate = $order
|
||||
&& ! in_array((int) $order->status, [OrderStatus::PENDING->value, OrderStatus::CANCELLED->value], true);
|
||||
|
||||
$this->line(sprintf(
|
||||
' [%s] Invoice #%s due %s%s',
|
||||
$dryRun ? 'dry-run' : 'check',
|
||||
$invoice->invoice_number,
|
||||
$invoice->due_date?->format('Y-m-d') ?? '-',
|
||||
$order ? " | order #{$invoice->order_id}" : ''
|
||||
));
|
||||
|
||||
if ($dryRun || (! $needsInvoiceUpdate && ! $needsOrderUpdate)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($invoice, $order, $needsInvoiceUpdate, $needsOrderUpdate, &$updatedInvoices, &$updatedOrders) {
|
||||
if ($needsInvoiceUpdate) {
|
||||
$invoice->update(['status' => InvoiceStatus::OVERDUE->value]);
|
||||
$updatedInvoices++;
|
||||
}
|
||||
|
||||
if ($needsOrderUpdate && $order) {
|
||||
$order->update(['status' => OrderStatus::PENDING->value]);
|
||||
$updatedOrders++;
|
||||
}
|
||||
});
|
||||
|
||||
Log::info('Invoice marked overdue', [
|
||||
'invoice_id' => $invoice->id,
|
||||
'invoice_number' => $invoice->invoice_number,
|
||||
'order_id' => $invoice->order_id,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->info("invoices:check-overdue | Updated {$updatedInvoices} invoice(s), {$updatedOrders} order(s).");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\Invoice\InvoiceStatus;
|
||||
use App\Enums\Order\OrderStatus;
|
||||
use App\Helpers\OrderHelper;
|
||||
use App\Jobs\VirtualMachine\Action\VMJobs;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceItem;
|
||||
use App\Models\Order;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Service;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -14,11 +17,35 @@ use Illuminate\Support\Facades\Log;
|
||||
|
||||
class ServiceExpiry extends Command
|
||||
{
|
||||
protected $signature = 'service:expiry';
|
||||
protected $signature = 'service:expiry {--dry-run : Preview service expiry actions without updating data}';
|
||||
protected $description = 'Suspend expired services, power off VMs, create renewal invoices, terminate after 30 days';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$renewalWindowDays = 7;
|
||||
$upcoming = Service::query()
|
||||
->with(['orderItem.product'])
|
||||
->whereNotNull('expires_at')
|
||||
->whereBetween('expires_at', [now(), now()->addDays($renewalWindowDays)])
|
||||
->whereNotIn('status', ['terminated', 'cancelled'])
|
||||
->get();
|
||||
|
||||
$this->info("service:expiry | Found {$upcoming->count()} service(s) expiring in {$renewalWindowDays} day(s).");
|
||||
|
||||
foreach ($upcoming as $service) {
|
||||
try {
|
||||
if ($dryRun) {
|
||||
$this->createRenewalInvoiceIfMissing($service, true);
|
||||
} else {
|
||||
DB::transaction(fn () => $this->createRenewalInvoiceIfMissing($service));
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('service:expiry upcoming renewal error', ['service_id' => $service->id, 'error' => $e->getMessage()]);
|
||||
$this->error(" [error] Service #{$service->id}: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Note: 'invoice' is NOT eager-loaded — createRenewalInvoiceIfMissing queries fresh
|
||||
$expired = Service::query()
|
||||
->with(['orderItem.product'])
|
||||
@@ -38,6 +65,11 @@ class ServiceExpiry extends Command
|
||||
|
||||
// --- 30-day threshold: terminate (idempotent) ---
|
||||
if ($daysExpired >= 30) {
|
||||
if ($dryRun) {
|
||||
$this->line(" [dry-run:terminate] Service #{$service->id}");
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($service->status !== 'terminated') {
|
||||
$service->update(['status' => 'terminated']);
|
||||
Log::info('Service terminated', ['service_id' => $service->id, 'days_overdue' => $daysExpired]);
|
||||
@@ -49,6 +81,12 @@ class ServiceExpiry extends Command
|
||||
// Capture before transaction so dispatch is conditional and outside the transaction
|
||||
$needsVmPowerOff = $service->status !== 'suspended' && $service->vm_id;
|
||||
|
||||
if ($dryRun) {
|
||||
$this->line(" [dry-run:suspend] Service #{$service->id}");
|
||||
$this->createRenewalInvoiceIfMissing($service, true);
|
||||
continue;
|
||||
}
|
||||
|
||||
// --- Transaction: status update + invoice creation (atomic) ---
|
||||
DB::transaction(function () use ($service) {
|
||||
if ($service->status !== 'suspended') {
|
||||
@@ -68,7 +106,6 @@ class ServiceExpiry extends Command
|
||||
$this->createRenewalInvoiceIfMissing($service);
|
||||
});
|
||||
|
||||
// --- Dispatch VMJobs OUTSIDE transaction (safe: DB is committed) ---
|
||||
if ($needsVmPowerOff) {
|
||||
dispatch(new VMJobs((int) $service->vm_id, 'PowerOff', false));
|
||||
Log::info('PowerOff dispatched', ['service_id' => $service->id, 'vm_id' => $service->vm_id]);
|
||||
@@ -84,16 +121,17 @@ class ServiceExpiry extends Command
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
|
||||
private function createRenewalInvoiceIfMissing(Service $service): void
|
||||
private function createRenewalInvoiceIfMissing(Service $service, bool $dryRun = false): void
|
||||
{
|
||||
// Fresh DB query via invoice_id FK — does NOT rely on stale eager-loaded relation.
|
||||
// invoices table has no service_id column; service->invoice_id is the correct pointer.
|
||||
$hasUnpaidRenewal = $service->invoice_id && Invoice::where('id', $service->invoice_id)
|
||||
->where('invoice_type', 2)
|
||||
->where('status', InvoiceStatus::UNPAID->value)
|
||||
->whereIn('status', [InvoiceStatus::UNPAID->value, InvoiceStatus::OVERDUE->value])
|
||||
->exists();
|
||||
|
||||
if ($hasUnpaidRenewal) {
|
||||
$this->line(" [skip] Service #{$service->id} already has open renewal invoice.");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -105,17 +143,46 @@ class ServiceExpiry extends Command
|
||||
|
||||
$price = (int) $orderItem->price;
|
||||
|
||||
if ($dryRun) {
|
||||
$this->line(" [dry-run:invoice] Would create renewal order + invoice for Service #{$service->id}, amount " . number_format($price) . ' VND.');
|
||||
return;
|
||||
}
|
||||
|
||||
$order = Order::create([
|
||||
'order_num' => OrderHelper::generateOrderNumber(),
|
||||
'customer_id' => $service->customer_id,
|
||||
'sub_total' => $price,
|
||||
'discount_amount' => 0,
|
||||
'total' => $price,
|
||||
'status' => OrderStatus::PENDING->value,
|
||||
'client_ip' => null,
|
||||
'note' => 'Đơn hàng gia hạn dịch vụ #' . $service->id,
|
||||
]);
|
||||
|
||||
OrderItem::create([
|
||||
'order_id' => $order->id,
|
||||
'product_id' => $service->product_id,
|
||||
'billing_cycle' => $orderItem->billing_cycle,
|
||||
'months' => $orderItem->months ?? 1,
|
||||
'os_id' => $orderItem->os_id,
|
||||
'quantity' => 1,
|
||||
'server_name' => $service->server_name,
|
||||
'price' => $price,
|
||||
]);
|
||||
|
||||
$invoice = Invoice::create([
|
||||
'invoice_number' => OrderHelper::generateOrderNumber('INV'),
|
||||
'customer_id' => $service->customer_id,
|
||||
'order_id' => null,
|
||||
'order_id' => $order->id,
|
||||
'invoice_type' => 2, // renewal
|
||||
'sub_total' => $price,
|
||||
'discount_amount' => 0,
|
||||
'tax' => 0,
|
||||
'total' => $price,
|
||||
'status' => InvoiceStatus::UNPAID->value,
|
||||
'due_date' => now()->addDays(30)->toDateString(),
|
||||
'due_date' => $service->expires_at && $service->expires_at->isFuture()
|
||||
? $service->expires_at->toDateString()
|
||||
: now()->addDays(7)->toDateString(),
|
||||
]);
|
||||
|
||||
InvoiceItem::create([
|
||||
@@ -132,7 +199,11 @@ class ServiceExpiry extends Command
|
||||
// Update service to point to the new renewal invoice
|
||||
$service->update(['invoice_id' => $invoice->id]);
|
||||
|
||||
Log::info('Renewal invoice created', ['service_id' => $service->id, 'invoice_number' => $invoice->invoice_number]);
|
||||
$this->line(" [invoice] Renewal {$invoice->invoice_number} for Service #{$service->id}.");
|
||||
Log::info('Renewal order and invoice created', [
|
||||
'service_id' => $service->id,
|
||||
'order_num' => $order->order_num,
|
||||
'invoice_number' => $invoice->invoice_number,
|
||||
]);
|
||||
$this->line(" [invoice] Renewal {$order->order_num} / {$invoice->invoice_number} for Service #{$service->id}.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,6 +43,12 @@ class Kernel extends ConsoleKernel
|
||||
->timezone("Asia/Ho_Chi_Minh")
|
||||
->everyFiveMinutes()
|
||||
->withoutOverlapping();
|
||||
|
||||
/* Mark overdue unpaid invoices */
|
||||
$schedule->command('invoices:check-overdue')
|
||||
->timezone("Asia/Ho_Chi_Minh")
|
||||
->dailyAt("00:10")
|
||||
->withoutOverlapping();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user