You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1113 lines
56 KiB
PHP
1113 lines
56 KiB
PHP
<?php
|
|
|
|
namespace App\Services {
|
|
final class Config
|
|
{
|
|
public static array $values = [];
|
|
public static function get($name, $default = null)
|
|
{
|
|
return self::$values[$name] ?? $default;
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace App\Services\Cloud {
|
|
final class CloudSecrets
|
|
{
|
|
public static function key(string $purpose): string
|
|
{
|
|
return str_repeat('i', 32);
|
|
}
|
|
|
|
public static function encrypt(array $payload, string $purpose): string
|
|
{
|
|
return json_encode([
|
|
'purpose' => $purpose,
|
|
'payload' => $payload,
|
|
], JSON_THROW_ON_ERROR);
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace App\Services\Payment {
|
|
/** Keep this lifecycle test independent from configured/live gateways. */
|
|
final class PaytaroConfig
|
|
{
|
|
public static function isUserVisible($user = null): bool
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
final class YipayConfig
|
|
{
|
|
public static function visibleMethods($user = null): array
|
|
{
|
|
return ['alipay'];
|
|
}
|
|
}
|
|
}
|
|
|
|
namespace {
|
|
require dirname(__DIR__) . '/vendor/autoload.php';
|
|
|
|
use App\Models\CloudInstance;
|
|
use App\Models\CloudInvoice;
|
|
use App\Models\CloudInvoicePayment;
|
|
use App\Models\CloudJob;
|
|
use App\Models\CloudMailOutbox;
|
|
use App\Models\CloudRenewal;
|
|
use App\Models\CloudServicePeriod;
|
|
use App\Models\User;
|
|
use App\Services\Cloud\CloudError;
|
|
use App\Services\Cloud\CloudInvoicePaymentService;
|
|
use App\Services\Cloud\CloudInvoiceService;
|
|
use Illuminate\Database\Capsule\Manager as Capsule;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
|
|
$assert = static function ($condition, string $message): void {
|
|
if (!$condition) throw new RuntimeException($message);
|
|
};
|
|
$capsule = new Capsule();
|
|
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
|
|
$capsule->setAsGlobal();
|
|
$capsule->bootEloquent();
|
|
$schema = $capsule->schema('default');
|
|
$schema->create('user', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->string('money'); $table->integer('enable')->default(1);
|
|
});
|
|
$schema->create('cloud_instances', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->integer('host_id'); $table->integer('user_id');
|
|
$table->integer('order_id')->nullable(); $table->integer('plan_id')->nullable();
|
|
$table->integer('current_period_id')->nullable(); $table->string('uuid'); $table->string('name');
|
|
$table->string('status'); $table->string('service_status'); $table->string('network_status');
|
|
$table->integer('expires_at')->nullable(); $table->string('renewal_price')->nullable();
|
|
$table->integer('renewal_days')->default(0); $table->integer('renewal_traffic_bytes')->default(0);
|
|
$table->integer('traffic_quota_bytes')->default(0); $table->integer('traffic_download_bytes')->default(0);
|
|
$table->integer('traffic_upload_bytes')->default(0); $table->integer('lifetime_download_bytes')->default(0);
|
|
$table->integer('lifetime_upload_bytes')->default(0); $table->integer('traffic_synced_at')->default(0);
|
|
$table->integer('suspended_at')->nullable(); $table->integer('network_suspended_at')->nullable();
|
|
$table->text('spec_json'); $table->text('sealed_credential')->nullable();
|
|
$table->integer('created_at'); $table->integer('updated_at');
|
|
});
|
|
$schema->create('cloud_instance_network_policy_states',
|
|
static function (Blueprint $table): void {
|
|
$table->integer('instance_id')->primary();
|
|
$table->integer('user_id');
|
|
$table->boolean('desired_suspended')->default(false);
|
|
$table->boolean('applied_suspended')->default(false);
|
|
$table->integer('revision')->default(1);
|
|
$table->string('state')->default('applied');
|
|
$table->string('operation_id')->nullable()->unique();
|
|
$table->integer('created_at');
|
|
$table->integer('updated_at');
|
|
});
|
|
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->integer('instance_id'); $table->integer('user_id');
|
|
$table->integer('plan_id')->nullable(); $table->integer('order_id')->nullable();
|
|
$table->integer('renewal_id')->nullable(); $table->integer('starts_at'); $table->integer('ends_at');
|
|
$table->integer('traffic_pool_group_id')->nullable(); $table->string('traffic_quota_mode')->default('finite');
|
|
$table->integer('traffic_quota_bytes'); $table->integer('download_base_bytes')->nullable();
|
|
$table->integer('upload_base_bytes')->nullable(); $table->integer('download_used_bytes')->default(0);
|
|
$table->integer('upload_used_bytes')->default(0); $table->string('status');
|
|
$table->integer('activated_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
|
|
$table->unique('order_id'); $table->unique('renewal_id');
|
|
});
|
|
$schema->create('cloud_renewals', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->integer('instance_id'); $table->integer('user_id');
|
|
$table->integer('plan_id')->nullable(); $table->integer('period_id')->nullable();
|
|
$table->string('idempotency_key'); $table->string('request_hash'); $table->string('amount');
|
|
$table->integer('validity_days'); $table->integer('traffic_bytes_added');
|
|
$table->integer('previous_expires_at'); $table->integer('new_expires_at'); $table->integer('created_at');
|
|
$table->unique(['user_id', 'idempotency_key']);
|
|
});
|
|
$schema->create('cloud_backup_subscriptions', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->integer('instance_id')->unique();
|
|
$table->integer('user_id');
|
|
$table->integer('offer_id');
|
|
$table->boolean('enabled');
|
|
$table->boolean('renew_next_period');
|
|
$table->string('price');
|
|
$table->string('currency');
|
|
});
|
|
$schema->create('cloud_jobs', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->string('operation_id')->nullable()->unique();
|
|
$table->string('request_idempotency_key')->nullable();
|
|
$table->string('request_fingerprint')->nullable();
|
|
$table->integer('parent_job_id')->nullable();
|
|
$table->integer('order_id')->nullable();
|
|
$table->integer('invoice_id')->nullable();
|
|
$table->integer('instance_id')->nullable();
|
|
$table->integer('snapshot_id')->nullable();
|
|
$table->integer('user_id')->nullable();
|
|
$table->integer('host_id')->nullable();
|
|
$table->string('kind');
|
|
$table->string('execution_mode')->default('agent');
|
|
$table->string('phase')->default('accepted');
|
|
$table->string('outcome')->nullable();
|
|
$table->string('status');
|
|
$table->text('sealed_payload')->nullable();
|
|
$table->integer('attempts')->default(0);
|
|
$table->integer('dispatch_attempts')->default(0);
|
|
$table->integer('dispatch_deadline_at')->default(0);
|
|
$table->integer('dispatch_started_at')->nullable();
|
|
$table->integer('agent_accepted_at')->nullable();
|
|
$table->integer('receipt_deadline_at')->nullable();
|
|
$table->integer('terminal_at')->nullable();
|
|
$table->boolean('effect_may_have_applied')->nullable();
|
|
$table->boolean('safe_to_resubmit')->nullable();
|
|
$table->string('effect_resolution')->default('not_applicable');
|
|
$table->integer('effect_resolved_at')->nullable();
|
|
$table->integer('effect_resolved_by')->nullable();
|
|
$table->text('effect_resolution_reason')->nullable();
|
|
$table->string('completion_event_id')->nullable();
|
|
$table->integer('read_at')->nullable();
|
|
$table->integer('dispatched_at')->nullable();
|
|
$table->string('lease_token')->nullable();
|
|
$table->integer('lease_until')->default(0);
|
|
$table->integer('available_at')->default(0);
|
|
$table->string('error_code')->nullable();
|
|
$table->boolean('finalization_incident')->default(0);
|
|
$table->string('finalization_error_code')->nullable();
|
|
$table->text('result_json')->nullable();
|
|
$table->integer('created_at')->default(0);
|
|
$table->integer('updated_at')->default(0);
|
|
});
|
|
$schema->create('cloud_invoices', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->string('invoice_no')->unique();
|
|
$table->string('purpose')->default('renewal'); $table->integer('instance_id')->nullable();
|
|
$table->integer('order_id')->nullable()->unique(); $table->integer('user_id');
|
|
$table->integer('plan_id')->nullable(); $table->integer('renewal_id')->nullable();
|
|
$table->integer('renews_expires_at')->nullable(); $table->integer('due_at'); $table->string('amount');
|
|
$table->string('currency')->default('USD');
|
|
$table->integer('validity_days'); $table->integer('traffic_quota_bytes'); $table->string('status');
|
|
$table->string('paid_via')->nullable(); $table->string('payment_reference')->nullable();
|
|
$table->integer('paid_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
|
|
$table->index(['instance_id', 'renews_expires_at', 'status']); $table->unique('renewal_id');
|
|
});
|
|
$schema->create('cloud_invoice_items', static function (Blueprint $table): void {
|
|
$table->increments('id');
|
|
$table->integer('invoice_id');
|
|
$table->integer('order_item_id')->nullable();
|
|
$table->string('code');
|
|
$table->string('label');
|
|
$table->string('amount');
|
|
$table->string('currency')->default('USD');
|
|
$table->text('snapshot_json');
|
|
$table->integer('created_at');
|
|
});
|
|
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->integer('invoice_id'); $table->integer('user_id');
|
|
$table->string('provider'); $table->string('provider_order_no'); $table->string('idempotency_key');
|
|
$table->string('amount'); $table->string('status'); $table->integer('created_at'); $table->integer('updated_at');
|
|
$table->unique(['provider', 'provider_order_no']); $table->unique(['user_id', 'idempotency_key']);
|
|
});
|
|
$schema->create('paytaro_orders', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->string('order_no')->unique(); $table->integer('user_id');
|
|
$table->string('status'); $table->string('payment_kind')->nullable();
|
|
$table->text('payment_value')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
|
|
});
|
|
$schema->create('cloud_mail_outbox', static function (Blueprint $table): void {
|
|
$table->increments('id'); $table->integer('invoice_id'); $table->string('kind'); $table->string('status');
|
|
$table->integer('attempts'); $table->integer('available_at'); $table->string('lease_token')->nullable();
|
|
$table->integer('lease_until'); $table->integer('sent_at')->nullable(); $table->string('last_error');
|
|
$table->integer('created_at'); $table->integer('updated_at'); $table->unique(['invoice_id', 'kind']);
|
|
});
|
|
|
|
$user = new User(); $user->id = 1; $user->money = '50.00'; $user->enable = 1;
|
|
$user->save();
|
|
$now = time();
|
|
$instance = new CloudInstance(); $instance->host_id = 1; $instance->user_id = 1; $instance->plan_id = 8;
|
|
$instance->uuid = '11111111-2222-4333-8444-555555555555'; $instance->name = 'invoice-vm';
|
|
$instance->status = 'active'; $instance->service_status = 'active'; $instance->network_status = 'active';
|
|
$instance->expires_at = $now + CloudInvoiceService::REMINDER_SECONDS; $instance->renewal_price = '12.50';
|
|
$instance->renewal_days = 30; $instance->renewal_traffic_bytes = 4096; $instance->traffic_quota_bytes = 4096;
|
|
$instance->spec_json = json_encode(['plan_name' => '2c2g', 'vcpu' => 2,
|
|
'memory_mib' => 2048, 'disk_gib' => 20, 'bandwidth_mbps' => 100]);
|
|
$instance->created_at = $instance->updated_at = $now; $instance->save();
|
|
$period = new CloudServicePeriod(); $period->instance_id = $instance->id; $period->user_id = 1;
|
|
$period->plan_id = 8; $period->starts_at = $now - 100; $period->ends_at = $instance->expires_at;
|
|
$period->traffic_quota_bytes = 4096; $period->download_base_bytes = 0; $period->upload_base_bytes = 0;
|
|
$period->status = 'active'; $period->activated_at = $now - 100; $period->created_at = $period->updated_at = $now;
|
|
$period->save(); $instance->current_period_id = $period->id; $instance->save();
|
|
|
|
$assert(CloudInvoiceService::issueDue() === 1 && CloudInvoiceService::issueDue() === 0,
|
|
'T-7 invoice generation was not idempotent.');
|
|
$invoice = CloudInvoice::first();
|
|
$renewalDisplay = $invoice === null ? [] : CloudInvoiceService::display($invoice);
|
|
$assert($invoice !== null && (string) $invoice->purpose === 'renewal'
|
|
&& ($renewalDisplay['purpose'] ?? null) === 'renewal'
|
|
&& ($renewalDisplay['title'] ?? null) === '实例续费'
|
|
&& ($renewalDisplay['type_label'] ?? null) === '实例续费'
|
|
&& ($renewalDisplay['plan_name'] ?? null) === '2c2g'
|
|
&& ($renewalDisplay['cpu_cores'] ?? null) === 2
|
|
&& ($renewalDisplay['memory_mib'] ?? null) === 2048
|
|
&& ($renewalDisplay['renewal_result'] ?? null) === null
|
|
&& !array_key_exists('invoice_no', $renewalDisplay)
|
|
&& ($renewalDisplay['order_id'] ?? null) === null
|
|
&& CloudMailOutbox::count() === 1
|
|
&& (string) CloudMailOutbox::first()->kind === 'renewal_due'
|
|
&& (string) $invoice->amount === '12.50',
|
|
'Renewal invoice type, snapshot or reminder outbox is missing.');
|
|
$originalExpiry = (int) $instance->expires_at;
|
|
$graceExpiry = $now - 60;
|
|
$instance->expires_at = $graceExpiry;
|
|
$instance->service_status = 'expired_grace';
|
|
$instance->save();
|
|
$invoice->renews_expires_at = $graceExpiry;
|
|
$invoice->due_at = $graceExpiry;
|
|
$invoice->save();
|
|
$graceDisplay = CloudInvoiceService::display($invoice->fresh());
|
|
$graceStatus = CloudInvoiceService::status($invoice->fresh());
|
|
$graceSummary = CloudInvoiceService::listSummaries([
|
|
$invoice->fresh(),
|
|
])[0] ?? [];
|
|
$assert(($graceDisplay['status'] ?? null) === 'overdue'
|
|
&& ($graceDisplay['display_status'] ?? null) === 'renewal_grace'
|
|
&& ($graceDisplay['available_action'] ?? null) === 'pay'
|
|
&& ($graceDisplay['payable'] ?? false) === true
|
|
&& ($graceStatus['status'] ?? null) === ($graceDisplay['status'] ?? null)
|
|
&& ($graceStatus['display_status'] ?? null)
|
|
=== ($graceDisplay['display_status'] ?? null)
|
|
&& ($graceStatus['available_action'] ?? null)
|
|
=== ($graceDisplay['available_action'] ?? null)
|
|
&& ($graceStatus['payable'] ?? null) === ($graceDisplay['payable'] ?? null)
|
|
&& ($graceSummary['status'] ?? null) === ($graceDisplay['status'] ?? null)
|
|
&& ($graceSummary['display_status'] ?? null)
|
|
=== ($graceDisplay['display_status'] ?? null),
|
|
'An expired but payable renewal was not projected as payment grace.');
|
|
|
|
$upgradeBlocker = new CloudJob();
|
|
$upgradeBlocker->instance_id = $instance->id;
|
|
$upgradeBlocker->user_id = 1;
|
|
$upgradeBlocker->host_id = 1;
|
|
$upgradeBlocker->kind = 'instance_upgrade';
|
|
$upgradeBlocker->execution_mode = 'agent';
|
|
$upgradeBlocker->sealed_payload = '{}';
|
|
$upgradeBlocker->created_at = $now;
|
|
$upgradeBlocker->updated_at = $now;
|
|
$upgradeBlocker->save();
|
|
$blockedDisplay = CloudInvoiceService::display($invoice->fresh());
|
|
$blockedStatus = CloudInvoiceService::status($invoice->fresh());
|
|
$blockedSummary = CloudInvoiceService::listSummaries([
|
|
$invoice->fresh(),
|
|
])[0] ?? [];
|
|
$assert(($blockedDisplay['status'] ?? null) === 'overdue'
|
|
&& ($blockedDisplay['display_status'] ?? null) === 'overdue'
|
|
&& ($blockedDisplay['payable'] ?? true) === false
|
|
&& array_key_exists('available_action', $blockedDisplay)
|
|
&& $blockedDisplay['available_action'] === null
|
|
&& ($blockedStatus['status'] ?? null) === ($blockedDisplay['status'] ?? null)
|
|
&& ($blockedStatus['display_status'] ?? null)
|
|
=== ($blockedDisplay['display_status'] ?? null)
|
|
&& ($blockedStatus['payable'] ?? true) === false
|
|
&& ($blockedSummary['status'] ?? null) === ($blockedDisplay['status'] ?? null)
|
|
&& ($blockedSummary['display_status'] ?? null)
|
|
=== ($blockedDisplay['display_status'] ?? null),
|
|
'A blocking instance upgrade made renewal list, detail and polling drift.');
|
|
$upgradeBlocker->delete();
|
|
|
|
$expiredAt = $now - CloudInvoiceService::PAYMENT_GRACE_SECONDS - 60;
|
|
$instance->expires_at = $expiredAt;
|
|
$instance->save();
|
|
$invoice->renews_expires_at = $expiredAt;
|
|
$invoice->due_at = $expiredAt;
|
|
$invoice->save();
|
|
$expiredDisplay = CloudInvoiceService::display($invoice->fresh());
|
|
$expiredStatus = CloudInvoiceService::status($invoice->fresh());
|
|
$expiredSummary = CloudInvoiceService::listSummaries([
|
|
$invoice->fresh(),
|
|
])[0] ?? [];
|
|
$assert(($expiredDisplay['status'] ?? null) === 'overdue'
|
|
&& ($expiredDisplay['display_status'] ?? null) === 'expired'
|
|
&& array_key_exists('available_action', $expiredDisplay)
|
|
&& $expiredDisplay['available_action'] === null
|
|
&& ($expiredDisplay['payable'] ?? true) === false
|
|
&& ($expiredStatus['status'] ?? null) === ($expiredDisplay['status'] ?? null)
|
|
&& ($expiredStatus['display_status'] ?? null)
|
|
=== ($expiredDisplay['display_status'] ?? null)
|
|
&& array_key_exists('available_action', $expiredStatus)
|
|
&& $expiredStatus['available_action'] === null
|
|
&& ($expiredStatus['payable'] ?? true) === false
|
|
&& ($expiredSummary['status'] ?? null) === ($expiredDisplay['status'] ?? null)
|
|
&& ($expiredSummary['display_status'] ?? null)
|
|
=== ($expiredDisplay['display_status'] ?? null),
|
|
'A renewal past its fixed grace cutoff still exposed a payment action.');
|
|
|
|
$instance->expires_at = $originalExpiry;
|
|
$instance->service_status = 'active';
|
|
$instance->save();
|
|
$invoice->renews_expires_at = $originalExpiry;
|
|
$invoice->due_at = $originalExpiry;
|
|
$invoice->save();
|
|
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
|
|
'can_manage' => false, 'session_id' => ''];
|
|
$paid = CloudInvoiceService::payBalance($invoice, $actor, 'invoice-balance-test-0001');
|
|
$expiry = (int) $instance->expires_at;
|
|
$assert($paid->status === 'paid' && User::find(1)->money === '37.50'
|
|
&& CloudRenewal::count() === 1 && (int) $instance->fresh()->expires_at === $expiry + 30 * 86400,
|
|
'Balance invoice settlement was not atomic.');
|
|
$firstRenewal = CloudRenewal::first();
|
|
$firstPeriod = $firstRenewal === null || $firstRenewal->period_id === null
|
|
? null : CloudServicePeriod::find((int) $firstRenewal->period_id);
|
|
$paidDisplay = CloudInvoiceService::display($paid->fresh());
|
|
$assert($firstRenewal !== null && $firstPeriod !== null
|
|
&& ($paidDisplay['renewal_result']['previous_expires_at'] ?? null)
|
|
=== (int) $firstRenewal->previous_expires_at
|
|
&& ($paidDisplay['renewal_result']['new_expires_at'] ?? null)
|
|
=== (int) $firstRenewal->new_expires_at
|
|
&& ($paidDisplay['renewal_result']['period_starts_at'] ?? null)
|
|
=== (int) $firstPeriod->starts_at
|
|
&& ($paidDisplay['renewal_result']['period_ends_at'] ?? null)
|
|
=== (int) $firstPeriod->ends_at
|
|
&& ($paidDisplay['renewal_result']['validity_days'] ?? null) === 30,
|
|
'Paid renewal invoice does not expose its immutable settled period.');
|
|
CloudInvoiceService::payBalance($paid->fresh(), $actor, 'invoice-balance-test-0001');
|
|
$assert(User::find(1)->money === '37.50' && CloudRenewal::count() === 1,
|
|
'Repeated invoice payment debited or renewed twice.');
|
|
CloudInvoiceService::deliverReminders();
|
|
$assert(CloudMailOutbox::first()->status === 'cancelled',
|
|
'A settled invoice reminder remained in the retry queue.');
|
|
|
|
$currentExpiry = (int) $instance->fresh()->expires_at;
|
|
$second = new CloudInvoice(); $second->invoice_no = 'VC-GATEWAY'; $second->instance_id = $instance->id;
|
|
$second->user_id = 1; $second->plan_id = 8; $second->renews_expires_at = $currentExpiry;
|
|
$second->due_at = $currentExpiry; $second->amount = '12.50'; $second->validity_days = 30;
|
|
$second->traffic_quota_bytes = 4096; $second->status = 'open'; $second->created_at = $second->updated_at = $now;
|
|
$second->save();
|
|
Capsule::table('cloud_invoice_items')->insert([
|
|
'invoice_id' => (int) $second->id,
|
|
'order_item_id' => null,
|
|
'code' => 'instance',
|
|
'label' => '实例套餐续费',
|
|
'amount' => '12.50',
|
|
'currency' => 'USD',
|
|
'snapshot_json' => '{}',
|
|
'created_at' => $now,
|
|
]);
|
|
$paytaroJob = CloudInvoicePaymentService::enqueue(
|
|
$second,
|
|
User::find(1),
|
|
[
|
|
'method' => 'paytaro',
|
|
'idempotency_key' => 'invoice-switch-paytaro-0001',
|
|
],
|
|
'192.0.2.20',
|
|
'invoice-switch-test'
|
|
);
|
|
$yipayJob = CloudInvoicePaymentService::enqueue(
|
|
$second,
|
|
User::find(1),
|
|
[
|
|
'method' => 'yipay_alipay',
|
|
'idempotency_key' => 'invoice-switch-yipay-0002',
|
|
],
|
|
'192.0.2.20',
|
|
'invoice-switch-test'
|
|
);
|
|
$sameProviderJob = CloudInvoicePaymentService::enqueue(
|
|
$second,
|
|
User::find(1),
|
|
[
|
|
'method' => 'paytaro',
|
|
'idempotency_key' => 'invoice-switch-paytaro-0003',
|
|
],
|
|
'192.0.2.20',
|
|
'invoice-switch-test'
|
|
);
|
|
$sameRequestJob = CloudInvoicePaymentService::enqueue(
|
|
$second,
|
|
User::find(1),
|
|
[
|
|
'method' => 'paytaro',
|
|
'idempotency_key' => 'invoice-switch-paytaro-0001',
|
|
],
|
|
'192.0.2.20',
|
|
'invoice-switch-test'
|
|
);
|
|
$assert((int) $paytaroJob->id !== (int) $yipayJob->id
|
|
&& (int) $sameProviderJob->id === (int) $paytaroJob->id
|
|
&& (int) $sameRequestJob->id === (int) $paytaroJob->id
|
|
&& CloudJob::where('invoice_id', (int) $second->id)
|
|
->where('kind', 'payment_create')->count() === 2,
|
|
'An unfinished provider task blocked switching or duplicated one provider.');
|
|
CloudJob::whereIn('id', [(int) $paytaroJob->id, (int) $yipayJob->id])
|
|
->update([
|
|
'phase' => 'terminal',
|
|
'outcome' => 'succeeded',
|
|
'status' => 'succeeded',
|
|
'terminal_at' => $now,
|
|
'effect_may_have_applied' => 0,
|
|
'safe_to_resubmit' => 0,
|
|
'effect_resolution' => 'applied',
|
|
'effect_resolved_at' => $now,
|
|
'updated_at' => $now,
|
|
]);
|
|
$payment = new CloudInvoicePayment(); $payment->invoice_id = $second->id; $payment->user_id = 1;
|
|
$payment->provider = 'paytaro'; $payment->provider_order_no = 'PT-GATEWAY';
|
|
$payment->idempotency_key = 'invoice-gateway-test-0001'; $payment->amount = '12.50';
|
|
$payment->status = 'pending'; $payment->created_at = $payment->updated_at = $now; $payment->save();
|
|
CloudInvoicePaymentService::recordAttempt([
|
|
'invoice_id' => (int) $second->id,
|
|
'idempotency_key' => 'invoice-gateway-switch-0002',
|
|
'provider' => 'yipay_alipay',
|
|
], 'YIPAY-GATEWAY-LATE', '12.50', 1, $now + 1);
|
|
$alternatePayment = CloudInvoicePayment::where('user_id', 1)
|
|
->where('idempotency_key', 'invoice-gateway-switch-0002')->first();
|
|
$assert($alternatePayment !== null
|
|
&& (string) $alternatePayment->status === 'creating',
|
|
'An unpaid provider attempt blocked switching to another provider.');
|
|
$alternatePayment->status = 'pending';
|
|
$alternatePayment->save();
|
|
$user = User::find(1); $user->money = '50.00'; $user->save();
|
|
$outcome = CloudInvoiceService::settleCreditedPayment($payment);
|
|
$assert($outcome === 'paid_invoice' && User::find(1)->money === '37.50'
|
|
&& $second->fresh()->status === 'paid' && CloudRenewal::count() === 2
|
|
&& (int) $instance->fresh()->expires_at === $currentExpiry + 30 * 86400,
|
|
'Provider credit was not consumed exactly once to settle the invoice.');
|
|
$user = User::find(1); $user->money = '50.00'; $user->save();
|
|
$alternateOutcome = CloudInvoiceService::settleCreditedPayment(
|
|
$alternatePayment->fresh()
|
|
);
|
|
$assert($alternateOutcome === 'credited_balance'
|
|
&& User::find(1)->money === '50.00'
|
|
&& $second->fresh()->status === 'paid'
|
|
&& CloudRenewal::count() === 2,
|
|
'A later provider payment was not retained as account balance.');
|
|
$firstDisplayAfterLaterRenewal = CloudInvoiceService::display($paid->fresh());
|
|
$assert(($firstDisplayAfterLaterRenewal['renewal_result']['new_expires_at']
|
|
?? null) === (int) $firstRenewal->new_expires_at
|
|
&& ($firstDisplayAfterLaterRenewal['renewal_result']['period_ends_at']
|
|
?? null) === (int) $firstPeriod->ends_at,
|
|
'A later renewal rewrote the first invoice settlement result.');
|
|
try {
|
|
// `$second` is deliberately the stale pre-callback model. Starting a
|
|
// provider order from it must not overwrite the freshly paid row.
|
|
CloudInvoicePaymentService::create($second, User::find(1), [
|
|
'method' => 'paytaro',
|
|
'idempotency_key' => 'stale-paid-invoice-guard-0001',
|
|
], '192.0.2.10', 'invoice-test');
|
|
throw new RuntimeException('Stale paid invoice unexpectedly created another payment.');
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409, 'Stale paid invoice returned the wrong conflict status.');
|
|
}
|
|
$assert($second->fresh()->status === 'paid' && CloudRenewal::count() === 2,
|
|
'A stale provider-order request overwrote the paid invoice state.');
|
|
|
|
$third = new CloudInvoice(); $third->invoice_no = 'VC-STALE'; $third->instance_id = $instance->id;
|
|
$third->user_id = 1; $third->plan_id = 8; $third->renews_expires_at = $currentExpiry - 1;
|
|
$third->due_at = $currentExpiry - 1; $third->amount = '12.50'; $third->validity_days = 30;
|
|
$third->traffic_quota_bytes = 4096; $third->status = 'open'; $third->created_at = $third->updated_at = $now;
|
|
$third->save();
|
|
$late = new CloudInvoicePayment(); $late->invoice_id = $third->id; $late->user_id = 1;
|
|
$late->provider = 'paytaro'; $late->provider_order_no = 'PT-STALE';
|
|
$late->idempotency_key = 'invoice-gateway-test-0002'; $late->amount = '12.50';
|
|
$late->status = 'pending'; $late->created_at = $late->updated_at = $now; $late->save();
|
|
$user = User::find(1); $user->money = '50.00'; $user->save();
|
|
$outcome = CloudInvoiceService::settleCreditedPayment($late);
|
|
$assert($outcome === 'credited_balance' && User::find(1)->money === '50.00'
|
|
&& $third->fresh()->status === 'void' && CloudRenewal::count() === 2,
|
|
'Late provider payment was lost or renewed a stale invoice.');
|
|
|
|
$actualExpiry = (int) $instance->fresh()->expires_at;
|
|
$fourth = new CloudInvoice(); $fourth->invoice_no = 'VC-AMOUNT'; $fourth->instance_id = $instance->id;
|
|
$fourth->user_id = 1; $fourth->plan_id = 8; $fourth->renews_expires_at = $actualExpiry;
|
|
$fourth->due_at = $actualExpiry; $fourth->amount = '12.50'; $fourth->validity_days = 30;
|
|
$fourth->traffic_quota_bytes = 4096; $fourth->status = 'open'; $fourth->created_at = $fourth->updated_at = $now;
|
|
$fourth->save();
|
|
$mismatch = new CloudInvoicePayment(); $mismatch->invoice_id = $fourth->id; $mismatch->user_id = 1;
|
|
$mismatch->provider = 'paytaro'; $mismatch->provider_order_no = 'PT-AMOUNT';
|
|
$mismatch->idempotency_key = 'invoice-gateway-test-0003'; $mismatch->amount = '1.00';
|
|
$mismatch->status = 'pending'; $mismatch->created_at = $mismatch->updated_at = $now; $mismatch->save();
|
|
$user = User::find(1); $user->money = '51.00'; $user->save();
|
|
$outcome = CloudInvoiceService::settleCreditedPayment($mismatch);
|
|
$assert($outcome === 'credited_balance' && User::find(1)->money === '51.00'
|
|
&& $fourth->fresh()->status === 'open' && CloudRenewal::count() === 2,
|
|
'Mismatched provider payment amount unexpectedly settled an invoice.');
|
|
|
|
$makeDueInstance = static function (string $uuid, string $name, int $expiry) use ($now): CloudInstance {
|
|
$candidate = new CloudInstance(); $candidate->host_id = 1; $candidate->user_id = 1;
|
|
$candidate->plan_id = 8; $candidate->uuid = $uuid; $candidate->name = $name;
|
|
$candidate->status = 'active'; $candidate->service_status = 'active';
|
|
$candidate->network_status = 'active'; $candidate->expires_at = $expiry;
|
|
$candidate->renewal_price = '12.50'; $candidate->renewal_days = 30;
|
|
$candidate->renewal_traffic_bytes = 4096; $candidate->traffic_quota_bytes = 4096;
|
|
$candidate->spec_json = json_encode([
|
|
'automatic_backup' => false,
|
|
], JSON_THROW_ON_ERROR);
|
|
$candidate->created_at = $candidate->updated_at = $now;
|
|
$candidate->save();
|
|
return $candidate;
|
|
};
|
|
$alreadyBilled = $makeDueInstance('11111111-2222-4333-8444-555555555556',
|
|
'already-billed', $now + 60);
|
|
$existingInvoice = new CloudInvoice(); $existingInvoice->invoice_no = 'VC-EXISTING';
|
|
$existingInvoice->instance_id = $alreadyBilled->id; $existingInvoice->user_id = 1;
|
|
$existingInvoice->plan_id = 8; $existingInvoice->renews_expires_at = $alreadyBilled->expires_at;
|
|
$existingInvoice->due_at = $alreadyBilled->expires_at; $existingInvoice->amount = '12.50';
|
|
$existingInvoice->validity_days = 30; $existingInvoice->traffic_quota_bytes = 4096;
|
|
$existingInvoice->status = 'open'; $existingInvoice->created_at = $existingInvoice->updated_at = $now;
|
|
$existingInvoice->save();
|
|
$nextDue = $makeDueInstance('11111111-2222-4333-8444-555555555557',
|
|
'next-due', $now + 120);
|
|
$assert(CloudInvoiceService::issueDue(1) === 1
|
|
&& CloudInvoice::where('instance_id', $nextDue->id)
|
|
->where('renews_expires_at', $nextDue->expires_at)->exists(),
|
|
'Already billed instances starved a later invoice batch.');
|
|
|
|
$corrected = $makeDueInstance('11111111-2222-4333-8444-555555555558',
|
|
'corrected-plan', $now + 180);
|
|
$assert(CloudInvoiceService::issueDue(10) === 1,
|
|
'Correctable invoice fixture was not generated.');
|
|
$oldInvoice = CloudInvoice::where('instance_id', $corrected->id)->first();
|
|
$corrected->renewal_price = '13.00';
|
|
$corrected->save();
|
|
try {
|
|
CloudInvoicePaymentService::create($oldInvoice, User::find(1), [
|
|
'method' => 'paytaro',
|
|
'idempotency_key' => 'corrected-invoice-provider-0001',
|
|
], '192.0.2.11', 'invoice-test');
|
|
throw new RuntimeException('Changed plan snapshot unexpectedly created a payment order.');
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409, 'Changed snapshot returned the wrong conflict status.');
|
|
}
|
|
$assert($oldInvoice->fresh()->status === 'void'
|
|
&& CloudInvoiceService::issueDue(10) === 1,
|
|
'Void invoice prevented a corrected replacement from being issued.');
|
|
$replacement = CloudInvoice::where('instance_id', $corrected->id)
|
|
->where('status', 'open')->orderByDesc('id')->first();
|
|
$assert($replacement !== null && (string) $replacement->amount === '13.00'
|
|
&& CloudInvoice::where('instance_id', $corrected->id)->count() === 2,
|
|
'Corrected invoice did not retain the void audit row and current snapshot.');
|
|
CloudInvoicePaymentService::recordAttempt([
|
|
'invoice_id' => (int) $replacement->id,
|
|
'idempotency_key' => 'record-attempt-cutoff-guard-0001',
|
|
'provider' => 'paytaro',
|
|
], 'PT-RECORD-ATTEMPT', (string) $replacement->amount, 1, $now);
|
|
$assert(CloudInvoicePayment::where('invoice_id', $replacement->id)
|
|
->where('provider_order_no', 'PT-RECORD-ATTEMPT')
|
|
->where('status', 'creating')->exists(),
|
|
'Gateway pre-dispatch billing recheck did not persist a valid attempt.');
|
|
|
|
$makeLifecycleInstance = static function (string $uuid, string $name, int $expiry,
|
|
string $serviceStatus = 'expired_grace', string $networkStatus = 'blocked_expired'
|
|
) use ($now): CloudInstance {
|
|
$candidate = new CloudInstance(); $candidate->host_id = 1; $candidate->user_id = 1;
|
|
$candidate->plan_id = 8; $candidate->uuid = $uuid; $candidate->name = $name;
|
|
$candidate->status = 'active'; $candidate->service_status = $serviceStatus;
|
|
$candidate->network_status = $networkStatus; $candidate->expires_at = $expiry;
|
|
$candidate->renewal_price = '12.50'; $candidate->renewal_days = 30;
|
|
$candidate->renewal_traffic_bytes = 4096; $candidate->traffic_quota_bytes = 4096;
|
|
$candidate->spec_json = json_encode([
|
|
'automatic_backup' => false,
|
|
], JSON_THROW_ON_ERROR);
|
|
$candidate->created_at = $candidate->updated_at = $now;
|
|
$candidate->save();
|
|
|
|
$candidatePeriod = new CloudServicePeriod();
|
|
$candidatePeriod->instance_id = $candidate->id; $candidatePeriod->user_id = 1;
|
|
$candidatePeriod->plan_id = 8; $candidatePeriod->starts_at = $expiry - 30 * 86400;
|
|
$candidatePeriod->ends_at = $expiry; $candidatePeriod->traffic_quota_bytes = 4096;
|
|
$candidatePeriod->download_base_bytes = 0; $candidatePeriod->upload_base_bytes = 0;
|
|
$candidatePeriod->status = 'active'; $candidatePeriod->activated_at = $expiry - 30 * 86400;
|
|
$candidatePeriod->created_at = $candidatePeriod->updated_at = $now;
|
|
$candidatePeriod->save();
|
|
$candidate->current_period_id = $candidatePeriod->id; $candidate->save();
|
|
return $candidate;
|
|
};
|
|
$makeLifecycleInvoice = static function (CloudInstance $target, string $number, int $dueAt,
|
|
int $createdAt, string $status = 'open'): CloudInvoice {
|
|
$bill = new CloudInvoice(); $bill->invoice_no = $number; $bill->instance_id = $target->id;
|
|
$bill->user_id = $target->user_id; $bill->plan_id = $target->plan_id;
|
|
$bill->renews_expires_at = $target->expires_at; $bill->due_at = $dueAt;
|
|
$bill->amount = '12.50'; $bill->validity_days = 30; $bill->traffic_quota_bytes = 4096;
|
|
$bill->status = $status; $bill->created_at = $bill->updated_at = $createdAt;
|
|
$bill->save();
|
|
Capsule::table('cloud_invoice_items')->insert([
|
|
'invoice_id' => (int) $bill->id,
|
|
'order_item_id' => null,
|
|
'code' => 'instance',
|
|
'label' => '实例套餐续费',
|
|
'amount' => '12.50',
|
|
'currency' => 'USD',
|
|
'snapshot_json' => '{}',
|
|
'created_at' => $createdAt,
|
|
]);
|
|
return $bill;
|
|
};
|
|
|
|
// A late-generated invoice must retain the instance's fixed deletion
|
|
// cutoff. Creating the bill after expiry cannot extend the grace period.
|
|
$gatewayGraceInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555559', 'gateway-grace', $now - 120);
|
|
$gatewayGraceInvoice = $makeLifecycleInvoice($gatewayGraceInstance, 'VC-GRACE-GATEWAY',
|
|
$now - 120, $now - 60);
|
|
$gatewayGraceDisplay = CloudInvoiceService::display($gatewayGraceInvoice);
|
|
$assert((int) ($gatewayGraceDisplay['deletion_at'] ?? 0)
|
|
=== (int) $gatewayGraceInstance->expires_at
|
|
+ CloudInvoiceService::PAYMENT_GRACE_SECONDS
|
|
&& ($gatewayGraceDisplay['payable'] ?? false) === true,
|
|
'Late invoice creation changed the authoritative deletion cutoff or payable state.');
|
|
|
|
// Replaying an existing gateway attempt exercises the same authoritative
|
|
// cutoff validation without making a network request from this test.
|
|
$gatewayPayment = new CloudInvoicePayment(); $gatewayPayment->invoice_id = $gatewayGraceInvoice->id;
|
|
$gatewayPayment->user_id = 1; $gatewayPayment->provider = 'paytaro';
|
|
$gatewayPayment->provider_order_no = 'PT-GRACE-EXISTING';
|
|
$gatewayPayment->idempotency_key = 'gateway-grace-payment-0001';
|
|
$gatewayPayment->amount = '12.50'; $gatewayPayment->status = 'pending';
|
|
$gatewayPayment->created_at = $gatewayPayment->updated_at = $now; $gatewayPayment->save();
|
|
Capsule::table('paytaro_orders')->insert([
|
|
'order_no' => 'PT-GRACE-EXISTING', 'user_id' => 1, 'status' => 'pending',
|
|
'payment_kind' => 'payurl', 'payment_value' => 'https://pay.example.test/order',
|
|
'created_at' => $now, 'updated_at' => $now,
|
|
]);
|
|
$gatewayResult = CloudInvoicePaymentService::create($gatewayGraceInvoice, User::find(1), [
|
|
'method' => 'paytaro', 'idempotency_key' => 'gateway-grace-payment-0001',
|
|
], '192.0.2.12', 'invoice-test');
|
|
$assert(($gatewayResult['status'] ?? '') === 'pending'
|
|
&& ($gatewayResult['method'] ?? '') === 'paytaro'
|
|
&& $gatewayGraceInvoice->fresh()->status === 'open',
|
|
'Gateway payment was rejected while the invoice was still inside its grace period.');
|
|
|
|
$balanceGraceInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555560', 'balance-grace', $now - 180);
|
|
$balanceGraceInvoice = $makeLifecycleInvoice($balanceGraceInstance, 'VC-GRACE-BALANCE',
|
|
$now - 180, $now - 90);
|
|
$user = User::find(1); $user->money = '50.00'; $user->save();
|
|
$renewalsBeforeGracePayment = CloudRenewal::count();
|
|
$paidGraceInvoice = CloudInvoiceService::payBalance(
|
|
$balanceGraceInvoice, $actor, 'balance-grace-payment-0001');
|
|
$assert($paidGraceInvoice->status === 'paid' && User::find(1)->money === '37.50'
|
|
&& CloudRenewal::count() === $renewalsBeforeGracePayment + 1
|
|
&& (int) $balanceGraceInstance->fresh()->expires_at > $now,
|
|
'Balance payment did not renew an expired instance inside the grace period.');
|
|
|
|
$balanceCutoffInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555561', 'balance-cutoff',
|
|
$now - CloudInvoiceService::PAYMENT_GRACE_SECONDS - 30);
|
|
$balanceCutoffInvoice = $makeLifecycleInvoice($balanceCutoffInstance, 'VC-CUTOFF-BALANCE',
|
|
$balanceCutoffInstance->expires_at, $balanceCutoffInstance->expires_at);
|
|
$user = User::find(1); $user->money = '50.00'; $user->save();
|
|
$renewalsBeforeCutoff = CloudRenewal::count();
|
|
try {
|
|
CloudInvoiceService::payBalance(
|
|
$balanceCutoffInvoice, $actor, 'balance-cutoff-payment-0001');
|
|
throw new RuntimeException('Balance payment unexpectedly passed the deletion cutoff.');
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409, 'Cutoff balance payment returned the wrong conflict status.');
|
|
}
|
|
$balanceCutoffDisplay = CloudInvoiceService::display($balanceCutoffInvoice->fresh());
|
|
$assert(User::find(1)->money === '50.00'
|
|
&& CloudRenewal::count() === $renewalsBeforeCutoff
|
|
&& $balanceCutoffInvoice->fresh()->status === 'expired'
|
|
&& ($balanceCutoffDisplay['payable'] ?? true) === false,
|
|
'Cutoff balance payment deducted money, renewed, or remained payable.');
|
|
|
|
$gatewayCutoffInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555562', 'gateway-cutoff',
|
|
$now - CloudInvoiceService::PAYMENT_GRACE_SECONDS);
|
|
$gatewayCutoffInvoice = $makeLifecycleInvoice($gatewayCutoffInstance, 'VC-CUTOFF-GATEWAY',
|
|
$gatewayCutoffInstance->expires_at, $gatewayCutoffInstance->expires_at);
|
|
$gatewayPaymentsBeforeCutoff = CloudInvoicePayment::count();
|
|
try {
|
|
CloudInvoicePaymentService::create($gatewayCutoffInvoice, User::find(1), [
|
|
'method' => 'paytaro', 'idempotency_key' => 'gateway-cutoff-payment-0001',
|
|
], '192.0.2.13', 'invoice-test');
|
|
throw new RuntimeException('Gateway order unexpectedly passed the deletion cutoff.');
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409, 'Cutoff gateway order returned the wrong conflict status.');
|
|
}
|
|
$assert(CloudInvoicePayment::count() === $gatewayPaymentsBeforeCutoff
|
|
&& User::find(1)->money === '50.00'
|
|
&& $gatewayCutoffInvoice->fresh()->status === 'expired',
|
|
'Cutoff gateway order created a payment, deducted money, or stayed open.');
|
|
|
|
$lateInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555563', 'late-gateway-credit',
|
|
$now - CloudInvoiceService::PAYMENT_GRACE_SECONDS - 50);
|
|
$lateInvoice = $makeLifecycleInvoice($lateInstance, 'VC-LATE-CREDIT',
|
|
$lateInstance->expires_at, $lateInstance->expires_at);
|
|
$latePayment = new CloudInvoicePayment(); $latePayment->invoice_id = $lateInvoice->id;
|
|
$latePayment->user_id = 1; $latePayment->provider = 'paytaro';
|
|
$latePayment->provider_order_no = 'PT-LATE-CREDIT';
|
|
$latePayment->idempotency_key = 'gateway-late-credit-0001'; $latePayment->amount = '12.50';
|
|
$latePayment->status = 'pending'; $latePayment->created_at = $latePayment->updated_at = $now;
|
|
$latePayment->save();
|
|
$user = User::find(1); $user->money = '62.50'; $user->save();
|
|
$lateExpiry = (int) $lateInstance->expires_at;
|
|
$renewalsBeforeLateCredit = CloudRenewal::count();
|
|
$lateOutcome = CloudInvoiceService::settleCreditedPayment($latePayment);
|
|
$assert($lateOutcome === 'credited_balance' && User::find(1)->money === '62.50'
|
|
&& CloudRenewal::count() === $renewalsBeforeLateCredit
|
|
&& (int) $lateInstance->fresh()->expires_at === $lateExpiry
|
|
&& $lateInvoice->fresh()->status === 'expired',
|
|
'Late gateway credit was consumed for renewal instead of remaining in the wallet.');
|
|
|
|
$expiredBilledInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555564', 'expired-billed', $now + 240,
|
|
'active', 'active');
|
|
$expiredBill = $makeLifecycleInvoice($expiredBilledInstance, 'VC-EXPIRED-AUDIT',
|
|
$expiredBilledInstance->expires_at, $now, 'expired');
|
|
$expiredBillCount = CloudInvoice::where('instance_id', $expiredBilledInstance->id)->count();
|
|
CloudInvoiceService::issueDue(100);
|
|
$assert(CloudInvoice::where('instance_id', $expiredBilledInstance->id)->count()
|
|
=== $expiredBillCount
|
|
&& $expiredBill->fresh()->status === 'expired',
|
|
'An expired invoice was reopened or replaced by issueDue.');
|
|
|
|
$operationalInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555565',
|
|
'operational-invoice-vm',
|
|
$now + 3600
|
|
);
|
|
$ipInvoice = new CloudInvoice();
|
|
$ipInvoice->invoice_no = 'VC-IP-CHANGE-AUDIT';
|
|
$ipInvoice->purpose = 'ip_change';
|
|
$ipInvoice->instance_id = $operationalInstance->id;
|
|
$ipInvoice->user_id = 1;
|
|
$ipInvoice->due_at = $now;
|
|
$ipInvoice->amount = '5.00';
|
|
$ipInvoice->currency = 'USD';
|
|
$ipInvoice->validity_days = 0;
|
|
$ipInvoice->traffic_quota_bytes = 0;
|
|
$ipInvoice->status = 'paid';
|
|
$ipInvoice->paid_via = 'balance';
|
|
$ipInvoice->paid_at = $now;
|
|
$ipInvoice->created_at = $ipInvoice->updated_at = $now;
|
|
$ipInvoice->save();
|
|
$networkJob = new CloudJob();
|
|
$networkJob->invoice_id = $ipInvoice->id;
|
|
$networkJob->instance_id = $operationalInstance->id;
|
|
$networkJob->user_id = 1;
|
|
$networkJob->host_id = 1;
|
|
$networkJob->kind = 'network_change';
|
|
$networkJob->execution_mode = 'agent';
|
|
$networkJob->phase = 'accepted';
|
|
$networkJob->outcome = null;
|
|
$networkJob->status = 'queued';
|
|
$networkJob->effect_resolution = 'not_applicable';
|
|
$networkJob->created_at = $networkJob->updated_at = $now;
|
|
$networkJob->save();
|
|
|
|
$ipDisplay = CloudInvoiceService::display($ipInvoice->fresh());
|
|
$ipSummary = CloudInvoiceService::listSummaries([
|
|
$ipInvoice->fresh(),
|
|
])[0] ?? [];
|
|
$assert(($ipDisplay['instance_id'] ?? null)
|
|
=== (string) $operationalInstance->id
|
|
&& ($ipDisplay['instance_name'] ?? null) === 'operational-invoice-vm'
|
|
&& ($ipDisplay['task_id'] ?? null) === (string) $networkJob->id
|
|
&& ($ipDisplay['job_status'] ?? null) === 'active'
|
|
&& ($ipSummary['instance_name'] ?? null) === 'operational-invoice-vm'
|
|
&& ($ipSummary['task_id'] ?? null) === (string) $networkJob->id
|
|
&& ($ipSummary['fulfillment_status'] ?? null) === 'active',
|
|
'Paid IP-change invoice lost its target instance or active task.');
|
|
|
|
$networkJob->phase = 'terminal';
|
|
$networkJob->outcome = 'failed';
|
|
$networkJob->status = 'failed';
|
|
$networkJob->effect_resolution = 'unknown';
|
|
$networkJob->safe_to_resubmit = 0;
|
|
$networkJob->save();
|
|
$unknownIpDisplay = CloudInvoiceService::display($ipInvoice->fresh());
|
|
$assert(($unknownIpDisplay['job_status'] ?? null) === 'review',
|
|
'Unknown IP-change effect was reduced to an ordinary retryable failure.');
|
|
|
|
$networkJob->effect_resolution = 'applied';
|
|
$networkJob->save();
|
|
$appliedIpDisplay = CloudInvoiceService::display($ipInvoice->fresh());
|
|
$assert(($appliedIpDisplay['job_status'] ?? null) === 'succeeded',
|
|
'Applied IP-change effect was not presented as fulfilled.');
|
|
|
|
$backupInvoice = new CloudInvoice();
|
|
$backupInvoice->invoice_no = 'VC-BACKUP-ADDON-AUDIT';
|
|
$backupInvoice->purpose = 'backup_addon';
|
|
$backupInvoice->instance_id = $operationalInstance->id;
|
|
$backupInvoice->user_id = 1;
|
|
$backupInvoice->due_at = $now;
|
|
$backupInvoice->amount = '2.00';
|
|
$backupInvoice->currency = 'USD';
|
|
$backupInvoice->validity_days = 0;
|
|
$backupInvoice->traffic_quota_bytes = 0;
|
|
$backupInvoice->status = 'paid';
|
|
$backupInvoice->paid_via = 'balance';
|
|
$backupInvoice->paid_at = $now;
|
|
$backupInvoice->created_at = $backupInvoice->updated_at = $now;
|
|
$backupInvoice->save();
|
|
$backupSummary = CloudInvoiceService::listSummaries([
|
|
$backupInvoice->fresh(),
|
|
])[0] ?? [];
|
|
$assert(($backupSummary['instance_name'] ?? null)
|
|
=== 'operational-invoice-vm'
|
|
&& ($backupSummary['instance_id'] ?? null)
|
|
=== (string) $operationalInstance->id,
|
|
'Automatic-backup invoice lost its target instance association.');
|
|
|
|
$compensatedInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555566',
|
|
'compensated-invoice-vm',
|
|
$now + 300,
|
|
'active',
|
|
'active'
|
|
);
|
|
$compensatedOldExpiry = (int) $compensatedInstance->expires_at;
|
|
$compensatedOldInvoice = $makeLifecycleInvoice(
|
|
$compensatedInstance,
|
|
'VC-COMPENSATION-OLD',
|
|
$compensatedOldExpiry,
|
|
$now
|
|
);
|
|
$compensatedOldMail = new CloudMailOutbox();
|
|
$compensatedOldMail->invoice_id = (int) $compensatedOldInvoice->id;
|
|
$compensatedOldMail->kind = 'renewal_due';
|
|
$compensatedOldMail->status = 'pending';
|
|
$compensatedOldMail->attempts = 0;
|
|
$compensatedOldMail->available_at = $now;
|
|
$compensatedOldMail->lease_token = null;
|
|
$compensatedOldMail->lease_until = 0;
|
|
$compensatedOldMail->sent_at = null;
|
|
$compensatedOldMail->last_error = '';
|
|
$compensatedOldMail->created_at = $compensatedOldMail->updated_at = $now;
|
|
$compensatedOldMail->save();
|
|
$compensatedNewExpiry = $compensatedOldExpiry + 3600;
|
|
$compensatedInstance->expires_at = $compensatedNewExpiry;
|
|
$compensatedInstance->save();
|
|
$compensatedResult = CloudInvoiceService::
|
|
reconcileRenewalAfterCompensationLocked(
|
|
$compensatedInstance,
|
|
$compensatedOldExpiry,
|
|
$compensatedNewExpiry,
|
|
$now
|
|
);
|
|
$compensatedReplacement = $compensatedResult['replacement_invoice'];
|
|
$assert((int) $compensatedResult['source_invoice_id']
|
|
=== (int) $compensatedOldInvoice->id
|
|
&& (string) $compensatedOldInvoice->fresh()->status === 'void'
|
|
&& $compensatedReplacement instanceof CloudInvoice
|
|
&& (int) $compensatedReplacement->renews_expires_at
|
|
=== $compensatedNewExpiry
|
|
&& (int) $compensatedReplacement->due_at
|
|
=== $compensatedNewExpiry
|
|
&& (string) $compensatedReplacement->status === 'open'
|
|
&& (string) $compensatedOldMail->fresh()->status === 'cancelled'
|
|
&& str_contains(
|
|
(string) $compensatedOldMail->fresh()->last_error,
|
|
'服务时间补偿'
|
|
)
|
|
&& CloudMailOutbox::where(
|
|
'invoice_id',
|
|
(int) $compensatedReplacement->id
|
|
)->where('kind', 'renewal_due')->where('status', 'pending')->exists(),
|
|
'Service compensation rewrote or failed to replace the old renewal target.');
|
|
|
|
$sendingMailInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555576',
|
|
'sending-mail-compensated-invoice-vm',
|
|
$now + 1200,
|
|
'active',
|
|
'active'
|
|
);
|
|
$sendingMailOldExpiry = (int) $sendingMailInstance->expires_at;
|
|
$sendingMailInvoice = $makeLifecycleInvoice(
|
|
$sendingMailInstance,
|
|
'VC-COMPENSATION-MAIL-SENDING',
|
|
$sendingMailOldExpiry,
|
|
$now
|
|
);
|
|
$sendingMail = new CloudMailOutbox();
|
|
$sendingMail->invoice_id = (int) $sendingMailInvoice->id;
|
|
$sendingMail->kind = 'renewal_due';
|
|
$sendingMail->status = 'sending';
|
|
$sendingMail->attempts = 1;
|
|
$sendingMail->available_at = $now;
|
|
$sendingMail->lease_token = str_repeat('a', 32);
|
|
$sendingMail->lease_until = $now + 300;
|
|
$sendingMail->sent_at = null;
|
|
$sendingMail->last_error = '';
|
|
$sendingMail->created_at = $sendingMail->updated_at = $now;
|
|
$sendingMail->save();
|
|
$sendingMailNewExpiry = $sendingMailOldExpiry + 3600;
|
|
$sendingMailInstance->expires_at = $sendingMailNewExpiry;
|
|
$sendingMailInstance->save();
|
|
try {
|
|
CloudInvoiceService::reconcileRenewalAfterCompensationLocked(
|
|
$sendingMailInstance,
|
|
$sendingMailOldExpiry,
|
|
$sendingMailNewExpiry,
|
|
$now
|
|
);
|
|
throw new RuntimeException(
|
|
'A sending renewal reminder did not fence service compensation.'
|
|
);
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409
|
|
&& str_contains($error->getMessage(), '提醒邮件仍在投递'),
|
|
'Sending renewal reminder returned the wrong compensation fence.');
|
|
}
|
|
$assert((string) $sendingMailInvoice->fresh()->status === 'open'
|
|
&& (string) $sendingMail->fresh()->status === 'sending'
|
|
&& !CloudInvoice::where(
|
|
'instance_id',
|
|
(int) $sendingMailInstance->id
|
|
)->where('renews_expires_at', $sendingMailNewExpiry)
|
|
->where('status', '<>', 'void')->exists(),
|
|
'Sending renewal reminder allowed compensation to replace its invoice.');
|
|
|
|
$farInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555567',
|
|
'far-compensated-invoice-vm',
|
|
$now + CloudInvoiceService::REMINDER_SECONDS + 7200,
|
|
'active',
|
|
'active'
|
|
);
|
|
$farOldExpiry = (int) $farInstance->expires_at;
|
|
$farOldInvoice = $makeLifecycleInvoice(
|
|
$farInstance,
|
|
'VC-COMPENSATION-FAR',
|
|
$farOldExpiry,
|
|
$now
|
|
);
|
|
$farNewExpiry = $farOldExpiry + 3600;
|
|
$farInstance->expires_at = $farNewExpiry;
|
|
$farInstance->save();
|
|
$farResult = CloudInvoiceService::reconcileRenewalAfterCompensationLocked(
|
|
$farInstance,
|
|
$farOldExpiry,
|
|
$farNewExpiry,
|
|
$now
|
|
);
|
|
$assert($farResult['replacement_invoice'] === null
|
|
&& (string) $farOldInvoice->fresh()->status === 'void'
|
|
&& !CloudInvoice::where('instance_id', (int) $farInstance->id)
|
|
->where('renews_expires_at', $farNewExpiry)
|
|
->where('status', '<>', 'void')->exists(),
|
|
'A far-future compensation created a premature renewal invoice.');
|
|
|
|
$fencedInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555568',
|
|
'fenced-compensated-invoice-vm',
|
|
$now + 600,
|
|
'active',
|
|
'active'
|
|
);
|
|
$fencedOldExpiry = (int) $fencedInstance->expires_at;
|
|
$fencedInvoice = $makeLifecycleInvoice(
|
|
$fencedInstance,
|
|
'VC-COMPENSATION-FENCED',
|
|
$fencedOldExpiry,
|
|
$now
|
|
);
|
|
$fencedPayment = new CloudInvoicePayment();
|
|
$fencedPayment->invoice_id = (int) $fencedInvoice->id;
|
|
$fencedPayment->user_id = 1;
|
|
$fencedPayment->provider = 'paytaro';
|
|
$fencedPayment->provider_order_no = 'PT-COMPENSATION-FENCED';
|
|
$fencedPayment->idempotency_key = 'compensation-payment-fence-0001';
|
|
$fencedPayment->amount = '12.50';
|
|
$fencedPayment->status = 'pending';
|
|
$fencedPayment->created_at = $fencedPayment->updated_at = $now;
|
|
$fencedPayment->save();
|
|
$fencedNewExpiry = $fencedOldExpiry + 3600;
|
|
$fencedInstance->expires_at = $fencedNewExpiry;
|
|
$fencedInstance->save();
|
|
try {
|
|
CloudInvoiceService::reconcileRenewalAfterCompensationLocked(
|
|
$fencedInstance,
|
|
$fencedOldExpiry,
|
|
$fencedNewExpiry,
|
|
$now
|
|
);
|
|
throw new RuntimeException(
|
|
'A pending renewal payment did not fence service compensation.'
|
|
);
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409,
|
|
'The compensation payment fence returned the wrong status.');
|
|
}
|
|
$assert((string) $fencedInvoice->fresh()->status === 'open'
|
|
&& !CloudInvoice::where('instance_id', (int) $fencedInstance->id)
|
|
->where('renews_expires_at', $fencedNewExpiry)->exists(),
|
|
'A fenced compensation changed renewal invoices before payment reconciliation.');
|
|
foreach (['credited_balance', 'paid_invoice'] as $settledPaymentStatus) {
|
|
$fencedPayment->status = $settledPaymentStatus;
|
|
$fencedPayment->save();
|
|
try {
|
|
CloudInvoiceService::reconcileRenewalAfterCompensationLocked(
|
|
$fencedInstance,
|
|
$fencedOldExpiry,
|
|
$fencedNewExpiry,
|
|
$now
|
|
);
|
|
throw new RuntimeException(
|
|
'A settled payment row did not fence service compensation.'
|
|
);
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409,
|
|
'Settled payment compensation returned the wrong status.');
|
|
}
|
|
$assert((string) $fencedInvoice->fresh()->status === 'open',
|
|
'A settled payment row allowed the old invoice to be voided.');
|
|
}
|
|
|
|
$unknownInstance = $makeLifecycleInstance(
|
|
'11111111-2222-4333-8444-555555555569',
|
|
'unknown-compensated-invoice-vm',
|
|
$now + 900,
|
|
'active',
|
|
'active'
|
|
);
|
|
$unknownOldExpiry = (int) $unknownInstance->expires_at;
|
|
$unknownInvoice = $makeLifecycleInvoice(
|
|
$unknownInstance,
|
|
'VC-COMPENSATION-UNKNOWN',
|
|
$unknownOldExpiry,
|
|
$now
|
|
);
|
|
$unknownPaymentJob = new CloudJob();
|
|
$unknownPaymentJob->invoice_id = (int) $unknownInvoice->id;
|
|
$unknownPaymentJob->instance_id = (int) $unknownInstance->id;
|
|
$unknownPaymentJob->user_id = 1;
|
|
$unknownPaymentJob->kind = 'payment_create';
|
|
$unknownPaymentJob->execution_mode = 'local';
|
|
$unknownPaymentJob->phase = 'terminal';
|
|
$unknownPaymentJob->outcome = 'failed';
|
|
$unknownPaymentJob->status = 'failed';
|
|
$unknownPaymentJob->effect_resolution = 'unknown';
|
|
$unknownPaymentJob->safe_to_resubmit = 0;
|
|
$unknownPaymentJob->created_at = $unknownPaymentJob->updated_at = $now;
|
|
$unknownPaymentJob->save();
|
|
$unknownNewExpiry = $unknownOldExpiry + 3600;
|
|
$unknownInstance->expires_at = $unknownNewExpiry;
|
|
$unknownInstance->save();
|
|
try {
|
|
CloudInvoiceService::reconcileRenewalAfterCompensationLocked(
|
|
$unknownInstance,
|
|
$unknownOldExpiry,
|
|
$unknownNewExpiry,
|
|
$now
|
|
);
|
|
throw new RuntimeException(
|
|
'An unknown payment effect did not fence service compensation.'
|
|
);
|
|
} catch (CloudError $error) {
|
|
$assert($error->httpStatus === 409,
|
|
'Unknown payment compensation returned the wrong conflict status.');
|
|
}
|
|
$assert((string) $unknownInvoice->fresh()->status === 'open'
|
|
&& !CloudInvoice::where('instance_id', (int) $unknownInstance->id)
|
|
->where('renews_expires_at', $unknownNewExpiry)->exists(),
|
|
'Unknown payment reconciliation changed compensation invoice targets.');
|
|
|
|
$operationalInstance->delete();
|
|
$deletedIpDisplay = CloudInvoiceService::display($ipInvoice->fresh());
|
|
$assert(($deletedIpDisplay['instance_id'] ?? null)
|
|
=== (string) $operationalInstance->id
|
|
&& ($deletedIpDisplay['instance_name'] ?? null) === '已删除实例',
|
|
'Deleted IP-change target lost its safe historical instance identity.');
|
|
|
|
echo "Cloud invoice generation, grace cutoff and provider-payment safety passed.\n";
|
|
}
|