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.
virt/web/tests/CloudAdminBillingServiceTes...

843 lines
45 KiB
PHP

<?php
namespace App\Services {
final class AdminPermission
{
public static bool $superAdmin = true;
public static function isSuperAdmin(): bool
{
return self::$superAdmin;
}
}
final class Auth
{
public static $user = null;
public static function getUser()
{
return self::$user;
}
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static function decrypt(string $value, string $purpose): array
{
$decoded = json_decode($value, true);
if (!is_array($decoded)) {
throw new \RuntimeException('Invalid test upgrade payload.');
}
return $decoded;
}
}
final class CloudSessionService
{
public static int $calls = 0;
public static function current($user): string
{
self::$calls++;
throw new \RuntimeException('Read-only billing requested an engine session.');
}
}
final class CloudAgentSettingsService
{
public static int $calls = 0;
public function __construct()
{
self::$calls++;
throw new \RuntimeException('Read-only billing contacted a host Agent.');
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\User;
use App\Services\AdminPermission;
use App\Services\Auth;
use App\Services\Cloud\CloudAdminBillingService;
use App\Services\Cloud\CloudAgentSettingsService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudSessionService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
use Slim\Http\Environment;
use Slim\Http\Request;
use Slim\Http\Response;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$expectError = static function (callable $callback, int $status, string $message) use ($assert): void {
try {
$callback();
} catch (CloudError $error) {
$assert($error->httpStatus === $status,
$message . ': unexpected HTTP status ' . $error->httpStatus);
return;
}
throw new RuntimeException($message . ': request was accepted.');
};
$ids = static fn (array $rows): array => array_map('intval', array_column($rows, 'id'));
$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('user_name');
$table->string('email');
$table->boolean('is_admin')->default(false);
$table->boolean('enable')->default(true);
$table->string('money')->default('999.99');
$table->string('pass')->default('must-not-expose-account-password');
});
$schema->create('shop', static function (Blueprint $table): void {
$table->increments('id');
$table->string('name');
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
$table->string('uuid');
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->string('name');
$table->string('status')->default('active');
$table->string('service_status')->default('active');
$table->string('network_status')->default('active');
$table->integer('expires_at')->nullable();
$table->text('spec_json')->default('{}');
$table->text('sealed_credential')->default('must-not-expose-instance-credential');
});
$schema->create('cloud_orders', static function (Blueprint $table): void {
$table->increments('id');
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('host_id')->default(7);
$table->string('amount')->default('1.25');
$table->string('currency')->default('USD');
$table->string('status')->default('queued');
$table->text('spec_json')->default('{}');
$table->text('sealed_payload')->default('must-not-expose-order-payload');
$table->integer('instance_id')->nullable();
$table->integer('refunded_at')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id');
$table->string('operation_id')->default('must-not-expose-operation-id');
$table->integer('order_id')->nullable();
$table->integer('invoice_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->default(7);
$table->string('kind')->default('create');
$table->string('execution_mode')->default('agent');
$table->string('phase')->default('terminal');
$table->string('outcome')->nullable();
$table->string('status')->default('active');
$table->integer('attempts')->default(1);
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution')->default('not_applicable');
$table->integer('terminal_at')->nullable();
$table->string('error_code')->nullable();
$table->boolean('finalization_incident')->default(0);
$table->string('finalization_error_code')->nullable();
$table->text('result_json')->nullable();
$table->text('sealed_payload')->default('must-not-expose-job-payload');
$table->integer('created_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id');
$table->string('invoice_no')->default('must-not-expose-invoice-number');
$table->string('purpose')->default('provision');
$table->integer('instance_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('offer_id')->nullable();
$table->integer('renewal_id')->nullable();
$table->integer('renews_expires_at')->nullable();
$table->integer('due_at');
$table->string('amount')->default('1.25');
$table->string('currency')->default('USD');
$table->integer('validity_days')->default(30);
$table->integer('traffic_quota_bytes')->default(107374182400);
$table->string('status')->default('paid');
$table->string('paid_via')->nullable();
$table->string('payment_reference')->default('must-not-expose-payment-reference');
$table->integer('paid_at')->nullable();
$table->integer('created_at');
$table->integer('updated_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')->default('yipay_alipay');
$table->string('provider_order_no')->default('must-not-expose-provider-reference');
$table->string('idempotency_key')->default('must-not-expose-idempotency-key');
$table->string('amount')->default('1.25');
$table->string('status')->default('pending');
$table->integer('created_at');
$table->integer('updated_at');
});
$now = time();
Capsule::table('user')->insert([
['id' => 1, 'user_name' => 'Alice Finance', 'email' => 'alice@example.test'],
['id' => 2, 'user_name' => 'Bob Client', 'email' => 'bob@example.test'],
['id' => 3, 'user_name' => 'Foreign Owner', 'email' => 'foreign@example.test'],
['id' => 10, 'user_name' => 'Bulk Customer', 'email' => 'bulk@example.test'],
['id' => 20, 'user_name' => 'Mixed Currency', 'email' => 'mixed@example.test'],
['id' => 21, 'user_name' => 'Euro Customer', 'email' => 'euro@example.test'],
]);
Capsule::table('shop')->insert([
['id' => 7, 'name' => 'Standard Cloud'],
['id' => 8, 'name' => 'Mutable Catalog Name'],
]);
$spec = json_encode([
'name' => 'production-vm', 'plan_name' => 'Historical Plan',
'cpu_cores' => 2, 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100,
'password' => 'must-not-expose-spec-password',
'unreviewed_note' => 'must-not-expose-unknown-spec-field',
]);
$insertInstance = static function (int $id, array $overrides = []) use ($now, $spec): void {
Capsule::table('cloud_instances')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'name' => 'vm-' . $id,
'uuid' => sprintf('11111111-1111-4111-8111-%012d', $id),
'expires_at' => $now + 30 * 86400, 'spec_json' => $spec,
], $overrides));
};
$insertOrder = static function (int $id, array $overrides = []) use ($now, $spec): void {
Capsule::table('cloud_orders')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7, 'spec_json' => $spec,
'created_at' => $now - 1000, 'updated_at' => $now - 100,
], $overrides));
};
$insertJob = static function (int $id, array $overrides = []) use ($now): void {
$values = array_replace([
'id' => $id, 'user_id' => 1,
'phase' => 'terminal', 'outcome' => 'succeeded',
'created_at' => $now - 900, 'updated_at' => $now - 100,
'result_json' => json_encode([
'phase' => 'complete', 'password' => 'must-not-expose-job-password',
'unreviewed_note' => 'must-not-expose-unknown-job-field',
]),
], $overrides);
if ($values['phase'] === 'terminal') {
if (!in_array($values['outcome'], ['succeeded', 'failed'], true)) {
throw new RuntimeException('Terminal job fixtures require a supported outcome.');
}
$values['status'] = $values['outcome'];
} elseif ($values['phase'] === 'active' && $values['outcome'] === null) {
$values['status'] = 'active';
} else {
throw new RuntimeException('Active job fixtures cannot carry a terminal outcome.');
}
$values['terminal_at'] = $values['phase'] === 'terminal'
? ($values['terminal_at'] ?? $now - 100) : null;
$values['effect_may_have_applied'] ??= $values['outcome'] === 'succeeded'
? false : null;
$values['safe_to_resubmit'] ??= false;
Capsule::table('cloud_jobs')->insert($values);
};
$insertInvoice = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_invoices')->insert(array_replace([
'id' => $id, 'user_id' => 1, 'plan_id' => 7,
'due_at' => $now + 3600, 'created_at' => $now - 1000, 'updated_at' => $now - 100,
], $overrides));
};
$insertPayment = static function (int $id, array $overrides = []) use ($now): void {
Capsule::table('cloud_invoice_payments')->insert(array_replace([
'id' => $id, 'invoice_id' => $id, 'user_id' => 1,
'created_at' => $now - 800, 'updated_at' => $now - 100,
], $overrides));
};
$insertInstance(501);
$insertInstance(502, ['status' => 'deleted']);
$insertInstance(503, ['user_id' => 2, 'name' => 'upgrade-target']);
$insertOrder(101, ['instance_id' => 501, 'status' => 'succeeded', 'amount' => '100.00']);
$insertOrder(102, ['status' => 'failed', 'amount' => '30.00', 'refunded_at' => $now - 200]);
$insertOrder(103, ['status' => 'awaiting_payment', 'amount' => '40.00']);
$insertOrder(109, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
$insertOrder(110, ['user_id' => 3, 'status' => 'refunded', 'refunded_at' => $now - 200]);
$insertJob(201, ['order_id' => 101, 'instance_id' => 501]);
$insertJob(202, ['order_id' => 102, 'outcome' => 'failed',
'error_code' => 'provision_failed']);
$upgradeSnapshot = [
'method' => 'POST',
'body' => [
'from_vcpu' => 2, 'target_vcpu' => 4,
'from_memory_mib' => 2048, 'target_memory_mib' => 4096,
'from_disk_gib' => 40, 'target_disk_gib' => 80,
'from_bandwidth_mbps' => 100,
'target_bandwidth_mbps' => 200,
'confirm_shutdown' => true,
],
'upgrade_snapshot' => [
'version' => 1,
'charged_amount' => '15.00',
'reservation_id' => 91,
'source' => [
'offer_id' => 7,
'reservation_id' => 91,
'spec_hash' => str_repeat('a', 64),
'resources' => [
'cpu_cores' => 2, 'memory_mib' => 2048,
'disk_gib' => 40, 'bandwidth_mbps' => 100,
],
],
'target' => [
'plan_id' => 8,
'offer_id' => 88,
'plan_name' => 'Immutable Upgrade Target',
'offer_name' => 'Immutable Upgrade Offer',
'price' => '30.00',
'validity_days' => 30,
'traffic_quota_bytes' => 107374182400,
'resources' => [
'cpu_cores' => 4, 'memory_mib' => 4096,
'disk_gib' => 80, 'bandwidth_mbps' => 200,
],
],
],
];
$insertJob(203, ['user_id' => 2, 'invoice_id' => 17, 'instance_id' => 503,
'kind' => 'instance_upgrade', 'phase' => 'active', 'outcome' => null,
'sealed_payload' => json_encode($upgradeSnapshot, JSON_THROW_ON_ERROR)]);
// Financial state is independent from fulfilment and payment-attempt state.
$insertInvoice(1, ['order_id' => 101, 'instance_id' => 501,
'amount' => '100.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
$insertInvoice(2, ['order_id' => 102, 'amount' => '30.00', 'status' => 'refunded',
'paid_via' => 'yipay_alipay', 'paid_at' => $now - 700]);
$insertInvoice(3, ['order_id' => 103, 'amount' => '40.00', 'status' => 'open']);
$insertInvoice(4, ['purpose' => 'renewal', 'instance_id' => 501,
'amount' => '50.00', 'status' => 'open', 'due_at' => $now - 60]);
$insertInvoice(5, ['purpose' => 'recharge', 'plan_id' => null, 'amount' => '60.00',
'status' => 'paid', 'paid_via' => 'yipay_wxpay', 'paid_at' => $now - 700]);
$insertInvoice(6, ['purpose' => 'renewal', 'instance_id' => 501, 'renewal_id' => 301,
'amount' => '20.00', 'status' => 'paid', 'paid_via' => 'balance', 'paid_at' => $now - 700]);
$insertInvoice(7, ['purpose' => 'recharge', 'plan_id' => null,
'amount' => '10.00', 'status' => 'expired', 'due_at' => $now - 4 * 86400]);
$insertInvoice(8, ['purpose' => 'renewal', 'instance_id' => 502,
'amount' => '80.00', 'status' => 'open', 'due_at' => $now - 60]);
$insertInvoice(9, ['user_id' => 2, 'order_id' => 109, 'instance_id' => 501]);
$insertInvoice(10, ['user_id' => 2, 'order_id' => 110, 'status' => 'refunded']);
$insertInvoice(11, ['user_id' => 404, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'open']);
foreach ([
1 => ['amount' => '100.00', 'status' => 'paid_invoice'],
2 => ['amount' => '30.00', 'status' => 'paid_invoice'],
3 => ['amount' => '40.00', 'status' => 'pending'],
4 => ['amount' => '50.00', 'status' => 'failed'],
5 => ['amount' => '60.00', 'status' => 'credited_balance', 'provider' => 'yipay_wxpay'],
6 => ['amount' => '20.00', 'status' => 'paid_invoice'],
7 => ['amount' => '10.00', 'status' => 'credited_balance'],
8 => ['invoice_id' => 3, 'amount' => '40.00', 'status' => 'creating'],
] as $id => $values) {
$insertPayment($id, $values);
}
$insertPayment(9, ['invoice_id' => 9, 'user_id' => 3, 'status' => 'credited_balance', 'amount' => '999.00']);
$insertInvoice(12, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null, 'status' => 'expired']);
for ($id = 6000; $id < 6105; $id++) {
$insertPayment($id, ['invoice_id' => 12, 'user_id' => 2,
'status' => 'credited_balance', 'amount' => '1.10']);
}
$insertPayment(6200, ['invoice_id' => 12, 'user_id' => 3,
'status' => 'credited_balance', 'amount' => '999.00']);
$insertInvoice(13, ['user_id' => 2, 'purpose' => 'recharge', 'plan_id' => null,
'status' => 'paid', 'amount' => '12.00', 'paid_at' => null]);
$insertOrder(114, ['user_id' => 2, 'status' => 'refunded',
'amount' => '9.00', 'refunded_at' => $now - 200]);
$insertInvoice(14, ['user_id' => 2, 'order_id' => 114,
'status' => 'refunded', 'amount' => '10.00', 'paid_at' => $now - 700]);
$insertInvoice(15, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
'status' => 'open', 'paid_at' => null]);
$insertInvoice(16, ['user_id' => 2, 'purpose' => 'renewal', 'instance_id' => 999999,
'status' => 'overdue', 'paid_at' => null]);
$insertInvoice(17, ['user_id' => 2, 'purpose' => 'upgrade', 'instance_id' => 503,
'plan_id' => 8, 'offer_id' => 88,
'amount' => '15.00', 'status' => 'paid', 'paid_via' => 'balance',
'payment_reference' => 'instance-upgrade-203',
'paid_at' => $now - 90]);
// Currency is frozen on invoices/orders. Payment rows inherit the
// owner-scoped invoice currency because the payment table has no currency.
$insertOrder(320, ['user_id' => 21, 'amount' => '12.50',
'currency' => 'EUR']);
$insertInvoice(320, ['user_id' => 21, 'order_id' => 320,
'purpose' => 'recharge', 'amount' => '12.50', 'currency' => 'EUR',
'status' => 'paid', 'paid_at' => $now - 70]);
$insertPayment(320, ['user_id' => 21, 'invoice_id' => 320,
'amount' => '12.50', 'status' => 'paid_invoice']);
foreach ([330 => ['USD', '10.00'], 331 => ['EUR', '12.50']]
as $id => [$currency, $amount]) {
$insertOrder($id, ['user_id' => 20, 'amount' => $amount,
'currency' => $currency]);
$insertInvoice($id, ['user_id' => 20, 'order_id' => $id,
'purpose' => 'recharge', 'amount' => $amount,
'currency' => $currency, 'status' => 'paid',
'paid_at' => $now - 70]);
$insertPayment($id, ['user_id' => 20, 'invoice_id' => $id,
'amount' => $amount, 'status' => 'paid_invoice']);
}
// More than one page for every view, with identical timestamps to require
// an ID tie-breaker and a complete summary independent of the visible page.
for ($offset = 0; $offset < 135; $offset++) {
$created = $offset === 0 ? $now - 2 * 86400 : $now - 100;
$insertInstance(3000 + $offset, ['user_id' => 10]);
$insertOrder(2000 + $offset, ['user_id' => 10, 'instance_id' => 3000 + $offset,
'status' => 'queued', 'created_at' => $created]);
$insertJob(4000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
'instance_id' => 3000 + $offset, 'phase' => 'active', 'outcome' => null]);
$insertInvoice(1000 + $offset, ['user_id' => 10, 'order_id' => 2000 + $offset,
'instance_id' => 3000 + $offset, 'status' => 'paid', 'paid_at' => $now - 50,
'created_at' => $created]);
$insertPayment(5000 + $offset, ['user_id' => 10, 'invoice_id' => 1000 + $offset,
'created_at' => $created]);
}
// Exercise the real SQL implementation, including the existing invoice
// service's deadline calculation. Only authentication/infrastructure edges
// above are test doubles; no financial service or model is substituted.
$before = [];
foreach (['user', 'cloud_orders', 'cloud_jobs', 'cloud_invoices', 'cloud_invoice_payments'] as $table) {
$before[$table] = Capsule::table($table)->orderBy('id')->get()->toJson();
}
$queryCounts = [];
foreach (['invoices' => 1000, 'orders' => 2000, 'payments' => 5000] as $view => $baseId) {
$page = CloudAdminBillingService::page(['view' => $view, 'user_id' => '10']);
$assert($page['view'] === $view && $page['pagination']['total'] === 135
&& count($page['items']) === 30 && $page['summary']['total_records'] === 135
&& $page['summary']['total_amount'] === '168.75'
&& $ids($page['items']) === range($baseId + 134, $baseId + 105),
'Three-view page routing, full-population summary, or stable newest-first ordering failed: ' . $view);
$assert(isset($page['presentation']['catalog'])
&& isset($page['items'][0]['presentation'])
&& ($page['items'][0]['presentation']['amount_display'] ?? '') === '$1.25',
'Administrator billing page did not attach its shared presentation: ' . $view);
$seen = [];
for ($number = 1; $number <= 2; $number++) {
$chunk = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10', 'page' => (string) $number, 'per_page' => '100',
]);
$seen = array_merge($seen, $ids($chunk['items']));
}
$assert($seen === range($baseId + 134, $baseId),
'Pagination duplicated, omitted, or truncated billing records: ' . $view);
$last = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10', 'page' => '9999', 'per_page' => '1000',
]);
$assert($last['pagination']['page'] === 2 && $last['pagination']['per_page'] === 100
&& count($last['items']) === 35, 'Pagination bounds were not enforced: ' . $view);
$dateFiltered = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '10',
'created_from' => (string) ($now - 100), 'created_to' => (string) ($now - 100),
]);
$assert($dateFiltered['pagination']['total'] === 134,
'Date filters must include their boundary and apply to the summary: ' . $view);
$empty = CloudAdminBillingService::page(['view' => $view, 'user_id' => '999999']);
$assert($empty['items'] === [] && $empty['pagination']['total'] === 0
&& $empty['pagination']['total_pages'] === 1 && $empty['summary']['total_amount'] === '0.00',
'Empty billing results reused old data or reported invalid totals: ' . $view);
$search = CloudAdminBillingService::page(['view' => $view, 'q' => 'bulk@example.test']);
$assert($search['pagination']['total'] === 135, 'Account search failed: ' . $view);
$quoted = CloudAdminBillingService::page(['view' => $view, 'q' => "' OR 1=1 --"]);
$assert($quoted['items'] === [], 'Quoted search escaped its SQL parameter: ' . $view);
$counts = [];
foreach ([30, 100] as $size) {
$connection = Capsule::connection('default');
$connection->flushQueryLog();
$connection->enableQueryLog();
CloudAdminBillingService::page(['view' => $view, 'user_id' => '10', 'per_page' => (string) $size]);
$queries = $connection->getQueryLog();
$connection->disableQueryLog();
$counts[] = count($queries);
foreach ($queries as $query) {
$assert(preg_match('/^\s*(select|with)\b/i', $query['query']) === 1,
'Billing list performed a write instead of a read: ' . $view);
}
}
$assert($counts[0] <= 12 && $counts[1] === $counts[0],
'Billing rows introduced N+1 queries: ' . $view . ' ' . implode('/', $counts));
$queryCounts[$view] = $counts;
}
$ledger = CloudAdminBillingService::page(['user_id' => '1']);
$assert($ledger['view'] === 'invoices' && $ledger['summary']['total_records'] === 8
&& $ledger['summary']['total_amount'] === '390.00'
&& $ledger['summary']['paid_count'] === 3 && $ledger['summary']['paid_amount'] === '180.00'
&& $ledger['summary']['refunded_count'] === 1 && $ledger['summary']['refunded_amount'] === '30.00'
&& $ledger['summary']['outstanding_count'] === 2 && $ledger['summary']['outstanding_amount'] === '90.00',
'Paid invoices must exclude refunds once; refunded 30 must not be subtracted again from paid 180.');
$paymentSummary = CloudAdminBillingService::payments(['user_id' => '1'])['summary'];
$assert($paymentSummary['total_records'] === 8 && $paymentSummary['total_amount'] === '350.00'
&& $paymentSummary['paid_invoice_amount'] === '150.00'
&& $paymentSummary['credited_balance_amount'] === '70.00'
&& $paymentSummary['status_counts']['creating'] === 1
&& $paymentSummary['status_counts']['pending'] === 1
&& $paymentSummary['status_counts']['failed'] === 1,
'Attempted amounts, invoice settlement records, and retained balance were incorrectly combined.');
foreach (['invoices', 'orders', 'payments'] as $view) {
$euro = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '21',
]);
$assert($euro['summary']['currency_count'] === 1
&& $euro['summary']['currency'] === 'EUR'
&& $euro['summary']['mixed_currency'] === false
&& $euro['summary']['total_amount'] === '12.50'
&& $euro['summary']['presentation']['total_amount_display']
=== '12.50 EUR'
&& $euro['items'][0]['currency'] === 'EUR'
&& $euro['items'][0]['presentation']['amount_display']
=== '12.50 EUR',
'Single EUR row and summary diverged: ' . $view);
$mixed = CloudAdminBillingService::page([
'view' => $view, 'user_id' => '20',
]);
$rowCurrencies = array_column($mixed['items'], 'currency');
sort($rowCurrencies);
$assert($mixed['summary']['currency_count'] === 2
&& $mixed['summary']['currency'] === null
&& $mixed['summary']['mixed_currency'] === true
&& $mixed['summary']['total_amount'] === null
&& $mixed['summary']['presentation']['total_amount_display']
=== '多币种'
&& $rowCurrencies === ['EUR', 'USD'],
'Mixed currencies were combined into a fabricated amount: ' . $view);
}
$mixedInvoices = CloudAdminBillingService::invoices(['user_id' => '20']);
$assert($mixedInvoices['summary']['paid_amount'] === null
&& $mixedInvoices['summary']['presentation']['paid_amount_display']
=== '多币种',
'Mixed-currency invoice paid amount was still combined.');
$mixedPayments = CloudAdminBillingService::payments(['user_id' => '20']);
$assert($mixedPayments['summary']['paid_invoice_amount'] === null
&& $mixedPayments['summary']['presentation']['paid_invoice_amount_display']
=== '多币种',
'Mixed-currency payment settlement amount was still combined.');
foreach ([
['financial_status' => 'paid', 'expected' => [6, 5, 1]],
['financial_status' => 'refunded', 'expected' => [2]],
['financial_status' => 'open', 'expected' => [3]],
['financial_status' => 'overdue', 'expected' => [4]],
['financial_status' => 'void', 'expected' => [8]],
['purpose' => 'recharge', 'expected' => [7, 5]],
['purpose' => 'renewal', 'expected' => [8, 6, 4]],
['payment_method' => 'balance', 'expected' => [6, 1]],
['fulfillment_status' => 'failed', 'expected' => [2]],
] as $case) {
$expected = $case['expected'];
unset($case['expected']);
$filtered = CloudAdminBillingService::invoices(['user_id' => '1'] + $case);
$assert($ids($filtered['items']) === $expected
&& $filtered['summary']['total_records'] === count($expected),
'Invoice filter disagreed with the displayed financial/fulfilment state: ' . json_encode($case));
}
$active = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'active']);
$assert($active['summary']['total_records'] === 135
&& $active['summary']['status_counts']['active'] === 135,
'Order filters must use the active task phase rather than the stale queued order state.');
$succeeded = CloudAdminBillingService::orders(['user_id' => '10', 'status' => 'succeeded']);
$assert($succeeded['items'] === [],
'The same order appeared in both active and terminal-success filters.');
$refundedOrder = CloudAdminBillingService::orders(['user_id' => '1', 'financial_status' => 'refunded']);
$assert($ids($refundedOrder['items']) === [102], 'Order financial filtering lost its owner-scoped invoice relation.');
$retainedPayments = CloudAdminBillingService::payments(['user_id' => '1', 'status' => 'credited_balance']);
$assert($ids($retainedPayments['items']) === [7, 5], 'Retained-balance payment filter was confused with refunds.');
$providerPayments = CloudAdminBillingService::payments(['user_id' => '1', 'provider' => 'yipay_wxpay']);
$assert($ids($providerPayments['items']) === [5], 'Payment provider filtering was ignored.');
$invoicePayments = CloudAdminBillingService::payments(['user_id' => '1', 'invoice_id' => '3']);
$assert($ids($invoicePayments['items']) === [8, 3], 'Exact invoice payment filtering crossed another invoice.');
$upgrades = CloudAdminBillingService::invoices([
'user_id' => '2', 'purpose' => 'upgrade',
]);
$assert($ids($upgrades['items']) === [17]
&& $upgrades['items'][0]['subject_name'] === 'upgrade-target'
&& $upgrades['items'][0]['instance_id'] === '503'
&& $upgrades['items'][0]['task_id'] === '203'
&& $upgrades['items'][0]['fulfillment_status'] === 'active',
'Administrator billing did not join upgrade tasks through invoice_id.');
$expectError(static fn () => CloudAdminBillingService::page(['view' => ['invoices']]), 400,
'An array cannot select a billing view');
$expectError(static fn () => CloudAdminBillingService::page(['view' => 'invented']), 400,
'An unknown billing view must not silently become invoices');
foreach (['invoices', 'orders', 'payments'] as $view) {
foreach (['page', 'per_page', 'user_id', 'q', 'created_from', 'created_to'] as $key) {
$expectError(static fn () => CloudAdminBillingService::page(['view' => $view, $key => ['bad']]), 422,
'Array filter must be rejected: ' . $view . '/' . $key);
}
$expectError(static fn () => CloudAdminBillingService::page([
'view' => $view, 'created_from' => (string) $now, 'created_to' => (string) ($now - 1),
]), 422, 'An inverted date interval must not be queried');
}
$expectError(static fn () => CloudAdminBillingService::invoice('999999'), 404,
'A missing invoice must not fabricate details');
$details = [];
foreach (range(1, 17) as $id) {
$details[$id] = CloudAdminBillingService::invoice((string) $id);
}
$assert($details[1]['funds']['settled_amount'] === '100.00'
&& $details[1]['funds']['refund_amount'] === null
&& $details[1]['invoice']['payment_deadline_at'] === $now + 3600
&& $details[1]['invoice']['specification']['cpu_cores'] === 2,
'Settled provisioning detail lost its specification, deadline, or financial meaning.');
$assert(($details[1]['invoice']['presentation']['amount_display'] ?? null)
=== '$100.00'
&& ($details[1]['invoice']['presentation']['financial_status']['label'] ?? null)
=== '已支付'
&& ($details[1]['timeline'][0]['at_display'] ?? '') !== '',
'Administrator invoice detail did not attach stable display fields.');
$assert($details[2]['funds']['settled_amount'] === '30.00'
&& $details[2]['funds']['refund_amount'] === '30.00'
&& $details[2]['funds']['refund_destination'] === 'balance'
&& $details[2]['funds']['refunded_at'] === $now - 200
&& $details[2]['job']['status'] === 'failed',
'A confirmed failed-provision refund must identify the original settlement and balance return independently.');
$assert($details[3]['funds']['settled_amount'] === null
&& $details[3]['funds']['refund_amount'] === null
&& $details[3]['funds']['refund_destination'] === null,
'An unpaid order was described as a paid or refunded order.');
$assert($details[4]['invoice']['financial_status'] === 'overdue'
&& $details[4]['invoice']['fulfillment_status'] === 'awaiting_payment'
&& $details[4]['invoice']['payment_deadline_at'] === $now - 60 + 3 * 86400
&& $details[6]['invoice']['fulfillment_status'] === 'succeeded',
'Renewal detail lost its grace deadline or mixed renewal completion with payment state.');
$assert($details[5]['invoice']['purpose'] === 'recharge'
&& $details[5]['job'] === null && $details[5]['instance'] === null
&& $details[5]['invoice']['fulfillment_status'] === null,
'Recharge detail fabricated a virtual machine or provisioning task.');
$assert($details[7]['funds']['settled_amount'] === null
&& $details[7]['funds']['refund_amount'] === null
&& $details[7]['funds']['balance_retained_amount'] === '10.00'
&& $details[7]['funds']['balance_retained_count'] === 1,
'An expired unpaid invoice with retained payment funds was incorrectly called a refund.');
$assert($details[8]['invoice']['financial_status'] === 'void'
&& $details[8]['links']['instance'] === null,
'An orphan renewal still offered payment or a deleted-instance link.');
$assert($details[9]['order'] === null && $details[9]['job'] === null
&& $details[9]['instance'] === null && $details[9]['payment_attempts'] === []
&& $details[9]['links']['instance'] === null
&& $details[9]['funds']['balance_retained_amount'] === '0.00',
'Invoice detail crossed ownership through orders, instances or gateway attempts.');
$assert($details[10]['funds']['refund_amount'] === null
&& $details[10]['funds']['refund_destination'] === null
&& $details[10]['funds']['refunded_at'] === null,
'A foreign order\'s refund timestamp falsely confirmed another user\'s refund.');
$assert($details[11]['links']['user'] === null, 'A missing account received a fabricated administrative link.');
$assert(count($details[12]['payment_attempts']) === 100
&& $details[12]['payment_attempts_truncated'] === true
&& $ids($details[12]['payment_attempts']) === range(6104, 6005)
&& $details[12]['funds']['balance_retained_count'] === 105
&& $details[12]['funds']['balance_retained_amount'] === '115.50'
&& $details[12]['funds']['payment_records_truncated'] === true,
'Retained balance must aggregate every same-owner payment, not just the latest 100 display rows.');
$assert($details[14]['funds']['refund_amount'] === '9.00'
&& str_contains(implode(' ', $details[14]['funds']['notes']), '不同'),
'Refund explanation replaced the recorded order amount with a conflicting invoice face value.');
$assert($details[17]['invoice']['purpose'] === 'upgrade'
&& $details[17]['invoice']['subject_name'] === 'upgrade-target'
&& $details[17]['invoice']['plan_name']
=== 'Immutable Upgrade Target'
&& $details[17]['invoice']['specification'] === [
'cpu_cores' => 4,
'memory_mib' => 4096,
'disk_gib' => 80,
'bandwidth_mbps' => 200,
]
&& $details[17]['invoice']['payment_deadline_at'] === null
&& $details[17]['invoice']['fulfillment_status'] === 'active'
&& $details[17]['job']['id'] === '203'
&& $details[17]['job']['kind'] === 'instance_upgrade'
&& $details[17]['instance']['id'] === '503',
'Upgrade invoice detail lost its target instance or invoice-linked task.');
Capsule::table('cloud_jobs')->where('id', 203)->update([
'phase' => 'terminal',
'outcome' => 'failed',
'status' => 'failed',
'effect_resolution' => 'unknown',
]);
$unknownUpgrade = CloudAdminBillingService::invoice('17');
$unknownFiltered = CloudAdminBillingService::invoices([
'user_id' => '2', 'purpose' => 'upgrade',
'fulfillment_status' => 'active',
]);
$assert($unknownUpgrade['invoice']['fulfillment_status'] === 'active'
&& $unknownUpgrade['job']['status'] === 'active'
&& $unknownUpgrade['job']['completed'] === false
&& $ids($unknownFiltered['items']) === [17],
'Administrator billing treated an unknown upgrade effect as a completed failure.');
Capsule::table('cloud_jobs')->where('id', 203)->update([
'effect_resolution' => 'applied',
]);
$appliedUpgrade = CloudAdminBillingService::invoice('17');
$appliedFiltered = CloudAdminBillingService::invoices([
'user_id' => '2', 'purpose' => 'upgrade',
'fulfillment_status' => 'succeeded',
]);
$assert($appliedUpgrade['invoice']['fulfillment_status'] === 'succeeded'
&& $appliedUpgrade['job']['status'] === 'succeeded'
&& $appliedUpgrade['job']['completed'] === true
&& $ids($appliedFiltered['items']) === [17],
'Administrator billing did not converge an applied upgrade receipt to success.');
Capsule::table('cloud_jobs')->where('id', 203)->update([
'phase' => 'active',
'outcome' => null,
'status' => 'active',
'effect_resolution' => 'not_applicable',
'terminal_at' => null,
]);
$eventsOf = static fn (array $detail, string $kind): array => array_values(array_filter(
$detail['timeline'], static fn (array $event): bool => $event['kind'] === $kind
));
$assert($eventsOf($details[2], 'invoice_refunded')[0]['at'] === $now - 200
&& $eventsOf($details[10], 'invoice_refunded')[0]['at'] === null
&& $eventsOf($details[13], 'invoice_paid')[0]['at'] === null,
'Timeline invented missing financial event timestamps from generic updated_at values.');
$assert($eventsOf($details[3], 'invoice_paid') === []
&& $eventsOf($details[3], 'invoice_refunded') === []
&& $eventsOf($details[7], 'invoice_refunded') === []
&& $eventsOf($details[7], 'invoice_closed')[0]['at'] === null,
'Unpaid/expired timeline fabricated settlement or refund events.');
foreach ([8, 15, 16] as $id) {
$void = $details[$id];
$assert($void['invoice']['financial_status'] === 'void'
&& $void['funds']['title'] === '账单已作废'
&& $void['funds']['settled_amount'] === null
&& $void['funds']['refund_amount'] === null
&& $void['funds']['refund_destination'] === null
&& $eventsOf($void, 'invoice_paid') === []
&& $eventsOf($void, 'invoice_refunded') === []
&& count($eventsOf($void, 'invoice_closed')) === 1
&& $eventsOf($void, 'invoice_closed')[0]['at'] === null,
'Deleted/missing renewal targets must show the same derived void state in funds and timeline without inventing financial events.');
}
foreach ($eventsOf($details[7], 'payment_updated') as $event) {
$assert($event['at'] === $now - 100 && str_contains($event['description'], '更新时间')
&& str_contains($event['description'], '不代表'),
'A payment record update was presented as the gateway receipt time.');
}
foreach ($details as $detail) {
$dated = array_values(array_filter(array_column($detail['timeline'], 'at'),
static fn ($at): bool => $at !== null));
$sorted = $dated;
sort($sorted);
$assert($dated === $sorted, 'Timeline did not preserve chronological order.');
}
$assert($details[1]['links']['user'] === '/admin/user/1/edit'
&& $details[1]['links']['instance'] === '/admin/cloud/instances?q=11111111-1111-4111-8111-000000000501'
&& $details[1]['links']['payments'] === '/admin/billing?view=payments&invoice_id=1',
'Validated account, exact-instance, or payment deep links were lost.');
AdminPermission::$superAdmin = false;
$masked = CloudAdminBillingService::invoice('1');
$assert($masked['invoice']['user_email'] !== 'alice@example.test'
&& $masked['invoice']['user_name'] !== 'Alice Finance'
&& $masked['links']['user'] === null && $masked['links']['instance'] !== null,
'Read-only admins gained unmasked account data or a restricted account-edit link.');
foreach (['invoices', 'orders', 'payments'] as $view) {
$hidden = CloudAdminBillingService::page(['view' => $view, 'q' => 'alice@example.test']);
$assert($hidden['items'] === [], 'Masked account search disclosed a hidden identity: ' . $view);
}
AdminPermission::$superAdmin = true;
$serialized = json_encode([$details, $ledger, $masked], JSON_THROW_ON_ERROR);
$assert(!str_contains($serialized, 'must-not-expose')
&& !str_contains($serialized, 'sealed_credential')
&& !str_contains($serialized, 'provider_order_no')
&& !str_contains($serialized, 'idempotency_key')
&& !str_contains($serialized, 'payment_reference')
&& !str_contains($serialized, 'unreviewed_note'),
'Billing detail leaked unreviewed provider, credential or metadata fields.');
$login = static function (bool $admin, bool $super = false): void {
$user = new User();
$user->id = 1;
$user->enable = 1;
$user->is_admin = $admin;
$user->isLogin = true;
Auth::$user = $user;
AdminPermission::$superAdmin = $super;
};
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
require dirname(__DIR__) . '/config/routes_cloud.php';
$requestApi = static function (string $path, array $query = []) use ($app): array {
$request = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $path,
]))->withQueryParams($query);
$response = $app->process($request, new Response());
return [$response, json_decode((string) $response->getBody(), true)];
};
$login(true, true);
foreach (['invoices', 'orders', 'payments'] as $view) {
[$response, $payload] = $requestApi('/api/v1/admin/billing/' . $view, ['user_id' => '10']);
$assert($response->getStatusCode() === 200 && $payload['pagination']['total'] === 135
&& $response->getHeaderLine('Cache-Control') === 'private, no-store',
'Registered billing route lost its private database response: ' . $view);
}
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/2');
$assert($response->getStatusCode() === 200 && $payload['funds']['refund_destination'] === 'balance',
'The invoice API did not expose the verified read-only funds explanation.');
$login(true);
[$response, $payload] = $requestApi('/api/v1/admin/billing/invoices/1');
$assert($response->getStatusCode() === 200 && $payload['links']['user'] === null,
'Read-only admins lost billing detail access or gained account-edit permission.');
$login(false);
foreach (['invoices', 'orders', 'payments', 'invoices/1'] as $suffix) {
[$response] = $requestApi('/api/v1/admin/billing/' . $suffix);
$assert($response->getStatusCode() === 403, 'Customer access to an admin billing route was not denied.');
}
Auth::$user = null;
[$response] = $requestApi('/api/v1/admin/billing/invoices');
$assert($response->getStatusCode() === 401, 'Anonymous access bypassed billing authentication.');
// Authentication rejection must return before the inherited constructor's
// Redis/theme work or view rendering is needed. This invokes the real page
// controller and CloudAccess, with no substitute business or view service.
$pageController = (new \ReflectionClass(\App\Controllers\Admin\CloudPageController::class))
->newInstanceWithoutConstructor();
$pageRequest = Request::createFromEnvironment(Environment::mock([
'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => '/admin/billing',
]));
foreach (['disabled' => 401, 'anonymous' => 401, 'customer' => 403] as $identity => $status) {
$login($identity !== 'customer', true);
if ($identity === 'disabled') Auth::$user->enable = 0;
if ($identity === 'anonymous') Auth::$user = null;
$response = $pageController->billing($pageRequest, new Response(), []);
$assert($response->getStatusCode() === $status
&& $response->getHeaderLine('Cache-Control') === 'private, no-store'
&& (string) $response->getBody() === '',
'Page authentication failure became a 500 or rendered the admin shell: ' . $identity);
}
foreach ($before as $table => $snapshot) {
$assert(Capsule::table($table)->orderBy('id')->get()->toJson() === $snapshot,
'Read-only billing mutated financial/account records: ' . $table);
}
$assert(CloudAgentSettingsService::$calls === 0 && CloudSessionService::$calls === 0,
'Database-only billing reads created a console session or contacted a host Agent.');
echo 'Administrator billing SQL pagination/filtering, financial separation, funds/timeline/links, ownership and API access passed. Queries for 30/100 rows: '
. json_encode($queryCounts) . ".\n";
}