refactor(billing): consume invoice detail presentation

go
codex 3 weeks ago
parent 4cd29ed7ff
commit 1bf1c7aec9

@ -347,7 +347,7 @@ final class CloudPageController
}
return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId, [
'cloud_invoice_detail_view' => CloudInvoicePresentation::detail($payload),
'cloud_invoice_detail_view' => $payload['presentation'],
'cloud_invoice_detail_bootstrap_json' => $this->safeJson($payload),
]);
}

@ -53,7 +53,7 @@ final class CloudInvoiceDetailPageService
if ($activePayment !== null) {
$activePayment['can_submit'] = $canStartPayment;
}
return [
$payload = [
'invoice' => $detail,
'active_payment' => $activePayment,
'payment_methods' => $canStartPayment
@ -66,6 +66,8 @@ final class CloudInvoiceDetailPageService
'username' => (string) ($user->user_name ?: $user->email),
'admin' => $isAdmin,
];
$payload['presentation'] = CloudInvoicePresentation::detail($payload);
return $payload;
}
/**
@ -149,10 +151,13 @@ final class CloudInvoiceDetailPageService
$activePayment['can_submit'] =
($status['payable'] ?? false) === true;
}
return [
$payload = [
'invoice' => $status,
'active_payment' => $activePayment,
];
$payload['presentation_patch'] =
CloudInvoicePresentation::statusPatch($payload);
return $payload;
}, 3
);
}

@ -117,6 +117,10 @@ final class CloudInvoicePresentation
return [
'id' => (string) ($invoice['id'] ?? ''),
'title' => self::invoiceTitle($invoice, $purpose),
'number_text' => '账单 #' . (string) ($invoice['id'] ?? '—'),
'created_text' => '创建于 ' . $created,
'subtitle' => '账单 #' . (string) ($invoice['id'] ?? '—')
. ' · ' . $created,
'created_display' => $created,
'amount_display' => self::formatMoney(
$invoice['amount'] ?? null,
@ -144,6 +148,16 @@ final class CloudInvoicePresentation
'fulfillment_failed' => $fulfillment['fulfillment_failed'],
'task_id' => $fulfillment['task_id'],
'instance_id' => $fulfillment['instance_id'],
'polling_required' => self::pollingRequired(
$invoice,
$payload['active_payment'] ?? null,
$fulfillment
),
'completion_notice' => self::completionNotice(
$invoice,
$purpose,
$fulfillment
),
];
}
@ -190,6 +204,8 @@ final class CloudInvoicePresentation
'invoice' => $mutable,
'active_payment' => $activePayment,
'status' => [
'code' => (string) ($invoice['display_status']
?? $invoice['status'] ?? ''),
'label' => $statusLabel,
'class' => $statusClass,
],
@ -201,6 +217,11 @@ final class CloudInvoicePresentation
],
'fulfillment' => $fulfillment,
'polling' => [
'required' => self::pollingRequired(
$invoice,
$activePayment,
$fulfillment
),
'task_id' => self::firstText(
$rawFulfillment['task_id'] ?? null,
$invoice['task_id'] ?? null
@ -215,6 +236,11 @@ final class CloudInvoicePresentation
'job_updated_at' => ($invoice['job_updated_at'] ?? null) === null
? null : max(0, (int) $invoice['job_updated_at']),
],
'completion_notice' => self::completionNotice(
$invoice,
$purpose,
$fulfillment
),
];
}
@ -455,9 +481,118 @@ final class CloudInvoicePresentation
$fulfillment['instance_id'] ?? null,
$invoice['instance_id'] ?? null
),
'status_code' => $fulfillmentStatus,
];
}
/**
* @param array<string, mixed> $invoice
* @param array<string, mixed>|null $activePayment
* @param array<string, mixed> $fulfillment
*/
private static function pollingRequired(array $invoice, $activePayment,
array $fulfillment): bool
{
$fulfillmentStatus = strtolower((string) (
$fulfillment['status_code'] ?? ''
));
if (in_array($fulfillmentStatus,
['queued', 'pending', 'provisioning', 'running', 'active'], true)) {
return true;
}
$activeStatus = is_array($activePayment)
? strtolower((string) ($activePayment['status'] ?? '')) : '';
return ($invoice['payable'] ?? false) === true
&& in_array($activeStatus, ['creating', 'pending', 'review'], true);
}
/**
* @param array<string, mixed> $invoice
* @param array<string, mixed> $fulfillment
* @return array{message: string, tone: string}|null
*/
private static function completionNotice(array $invoice, string $purpose,
array $fulfillment): ?array
{
$status = strtolower((string) ($invoice['status'] ?? ''));
$taskStatus = strtolower((string) ($fulfillment['status_code'] ?? ''));
if ($status === 'paid') {
if ($purpose === 'upgrade') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'message' => '实例升级完成。', 'tone' => 'success',
],
'failed', 'cancelled', 'canceled' => [
'message' => '实例升级未完成,请在账单详情查看任务状态。',
'tone' => 'error',
],
default => null,
};
}
if ($purpose === 'ip_change') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'message' => '公网 IP 已更换。', 'tone' => 'success',
],
'review' => [
'message' => '公网 IP 更换结果待人工核对,请勿重复提交。',
'tone' => 'error',
],
'failed', 'cancelled', 'canceled' => [
'message' => '公网 IP 更换未完成,请在账单详情查看任务状态。',
'tone' => 'error',
],
default => null,
};
}
if ($purpose === 'provision') {
return match ($taskStatus) {
'succeeded', 'completed' => [
'message' => '实例已创建完成。', 'tone' => 'success',
],
'refunded' => [
'message' => '实例创建失败,款项已退回账户余额。',
'tone' => 'error',
],
'failed', 'expired', 'cancelled', 'canceled' => [
'message' => '实例开通未完成,请在账单详情查看任务状态。',
'tone' => 'error',
],
default => null,
};
}
return [
'message' => $purpose === 'renewal'
? '账单支付成功,服务期限已延长。' : '账单支付成功。',
'tone' => 'success',
];
}
if (in_array($status, ['void', 'expired'], true)) {
return [
'message' => '账单已失效,到账金额会保留在账户余额中。',
'tone' => 'error',
];
}
if ($status === 'refunded') {
return [
'message' => '实例创建失败,款项已退回账户余额。',
'tone' => 'error',
];
}
if (($invoice['payable'] ?? false) !== true
&& in_array($status, ['open', 'overdue'], true)) {
return [
'message' => match ($purpose) {
'provision' => '开通账单已超过支付截止时间。',
'renewal' => '续费宽限期已经结束,到账金额会保留在账户余额中。',
default => '账单已超过支付截止时间。',
},
'tone' => 'error',
];
}
return null;
}
/**
* @param array<string, mixed> $invoice
* @return array<int, array{label: string, value: string}>

File diff suppressed because it is too large Load Diff

@ -31,6 +31,9 @@ $invoicePageService = file_get_contents($root . '/app/Services/Cloud/CloudInvoic
$invoiceDetailPageService = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoiceDetailPageService.php'
);
$invoicePresentation = file_get_contents(
$root . '/app/Services/Cloud/CloudInvoicePresentation.php'
);
$invoiceDetailTemplate = file_get_contents(
$root . '/resources/views/venix/cloud/pages/invoice-detail.tpl'
);
@ -116,7 +119,7 @@ $assert(str_contains($lineItemRuntime, "byId('invoice-line-items-panel')")
&& str_contains($lineItemRuntime, 'replaceChildren(')
&& !str_contains($lineItemRuntime, 'innerHTML')
&& !str_contains($lineItemRuntime, 'snapshot_json')
&& str_contains($invoiceDetailRuntime, 'renderInvoiceLineItems(invoice);'),
&& str_contains($invoiceDetailRuntime, 'renderInvoiceLineItems(presentation);'),
'Invoice-detail refresh must replace safe text-only line items.');
$assert(str_contains($invoiceDetailTemplate, 'id="invoice-payment-title"')
&& str_contains($invoiceDetailTemplate, 'id="invoice-payment-description"')
@ -128,12 +131,11 @@ $assert(str_contains($invoiceDetailTemplate, 'id="invoice-payment-title"')
&& str_contains($invoiceDetailRuntime,
'state.activePayment = payload.active_payment')
&& str_contains($invoiceDetailRuntime,
'renderActiveInvoicePayment(activePayment, result);'),
'renderActiveInvoicePayment(activePayment, presentation, result);'),
'Invoice detail must restore durable payment attempts while retaining payment choices.');
$assert(str_contains($pageController,
$assert(str_contains($invoicePresentation,
"\$invoice['renews_expires_at'] ?? \$invoice['due_at'] ?? null")
&& str_contains($invoiceDetailRuntime,
'invoice.renews_expires_at ?? invoice.due_at'),
&& str_contains($invoiceDetailRuntime, 'payload.presentation'),
'Renewal invoice details must render their authoritative target expiry.');
$listMethod = $section($apiController, 'public function invoices(',
@ -203,10 +205,11 @@ $assert(!str_contains($invoiceDetailRuntime, '/api/v1/jobs/')
'/api/v1/invoices/${encodeURIComponent(invoice.id)}/status') === 1
&& str_contains($invoiceDetailRuntime, "actionButton('刷新账单状态'")
&& str_contains($invoiceDetailRuntime,
'const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);'),
'const nextPresentation = mergePresentationPatch(state.presentation, patch);'),
'Manual creation-progress refresh must use one invoice-scoped lightweight request.');
$manualProgress = $section($invoiceDetailRuntime,
'function appendProvisionInvoiceActions(', ' if (data.instanceId) {');
'function appendProvisionInvoiceActions(',
'function renderInvoiceFulfillment(');
$manualProgressCatch = $section($manualProgress,
'} catch (error) {', ' }');
$assert(str_contains($manualProgress, 'const readSequence = ++state.readSequence;')
@ -215,6 +218,7 @@ $assert(str_contains($manualProgress, 'const readSequence = ++state.readSequence
< strpos($manualProgress, 'try {')
&& str_contains($manualProgressCatch,
'if (readSequence < state.appliedReadSequence) return;')
&& str_contains($manualProgress, 'applyActivePaymentPatch(patch, result);')
&& !str_contains($manualProgressCatch, 'state.invoiceJobProgress.set('),
'Manual creation-progress errors must ignore stale reads and remain transient.');
$assert(substr_count($invoiceDetailPageService, '->sharedLock()') >= 4
@ -247,34 +251,29 @@ $assert(str_contains($apiMiddleware, 'CloudAccess::actor(!$databaseOnly)')
'Invoice-only API calls must authenticate without a cloud_sessions lookup.');
$pollMethod = $section($invoiceDetailRuntime, 'async function pollInvoiceStatus(',
'function scheduleInvoicePoll(');
$activePaymentPatch = $section($invoiceDetailRuntime,
'function applyActivePaymentPatch(', 'async function pollInvoiceStatus(');
$assert(str_contains($pollMethod,
'api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`')
&& substr_count($pollMethod, 'api(') === 1
&& str_contains($pollMethod,
"Object.prototype.hasOwnProperty.call(result || {}, 'active_payment')")
&& str_contains($pollMethod,
'state.activePayment = result.active_payment')
&& str_contains($pollMethod, 'clearOnlinePaymentState(true);')
&& str_contains($pollMethod, 'const patch = result?.presentation_patch;')
&& str_contains($pollMethod, 'applyActivePaymentPatch(patch, result);')
&& str_contains($activePaymentPatch, 'state.activePayment = source.active_payment')
&& str_contains($activePaymentPatch, 'clearOnlinePaymentState(true);')
&& str_contains($pollMethod, 'entersProvisioningAfterPayment(')
&& str_contains($pollMethod, 'resetProvisioningPollWindow();')
&& !str_contains($pollMethod, 'refreshInvoiceDetail('),
'Each invoice poll must issue one lightweight request and preserve the provisioning window.');
&& str_contains($pollMethod,
'const refreshed = await refreshInvoiceDetail(nextInvoice.id);')
&& str_contains($pollMethod, 'if (refreshed !== null)')
&& str_contains($pollMethod, 'renderInvoiceDetail(nextPresentation);'),
'Each invoice poll must consume one lightweight presentation patch and fully refresh terminal state.');
$needsPolling = $section($invoiceDetailRuntime, 'function invoiceNeedsPolling(',
'function stopInvoicePoll(');
$provisionFinished = $section($invoiceDetailRuntime, 'function provisionFinished(',
'function invoiceFact(');
$assert(str_contains($needsPolling, 'state.onlinePaymentPending')
$assert(str_contains($needsPolling, 'state.presentation?.polling_required === true')
&& str_contains($needsPolling, '!onlinePaymentHasExpired()')
&& str_contains($needsPolling, 'invoiceCanPay(invoice)')
&& str_contains($needsPolling, "['creating', 'pending', 'review'].includes(")
&& str_contains($needsPolling, 'return false;')
&& !str_contains($needsPolling, 'provisionFinished(invoice)')
&& str_contains($provisionFinished,
"['succeeded', 'failed', 'expired', 'refunded', 'cancelled'].includes(status)")
&& !str_contains($provisionFinished, "'active'")
&& !str_contains($provisionFinished, "'uncertain'")
&& !str_contains($provisionFinished, "'needs_attention'"),
'Invoice polling must be bounded to active provider payment while task receipts expose provisioning outcome.');
&& !str_contains($needsPolling, "['creating', 'pending', 'review'].includes(")
&& !str_contains($invoiceDetailRuntime, 'function provisionFinished('),
'Invoice polling must consume the server projection instead of rebuilding task state.');
$paymentExpiry = $section($invoiceDetailRuntime,
'function onlinePaymentFallbackExpiresAt(', 'function invoiceNeedsPolling(');
$onlinePaymentRender = $section($invoiceDetailRuntime,
@ -289,7 +288,7 @@ $assert(!str_contains($invoiceDetailRuntime, 'function hasPendingInvoicePaymentK
'state.onlinePaymentPending = Boolean(serverPendingPayment);')
&& str_contains($invoiceDetailRuntime, 'resumeInvoicePolling();')
&& str_contains($paymentExpiry, 'STATUS_POLL_MAX_LIFETIME_MS')
&& str_contains($paymentExpiry, 'invoicePaymentDeadlineTimestamp(invoice)')
&& str_contains($paymentExpiry, 'serviceTimestamp(')
&& str_contains($paymentExpiry, 'function onlinePaymentHasExpired(')
&& str_contains($paymentExpiry, 'function expireOnlinePaymentInstructions(')
&& str_contains($paymentExpiry, 'clearOnlinePaymentState(true);')
@ -355,16 +354,21 @@ $balanceRequest = strpos($balancePayment,
'api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`');
$assert(str_contains($balancePayment,
'state.appliedReadSequence = ++state.readSequence;')
&& strpos($balancePayment,
'state.appliedReadSequence = ++state.readSequence;')
< strpos($balancePayment, 'renderInvoiceDetail(paid,'),
&& str_contains($balancePayment, 'await refreshInvoiceDetail(invoice.id);'),
'A successful balance payment must invalidate every older in-flight read.');
$balanceReset = strpos($balancePayment, 'resetProvisioningPollWindow();');
$balanceRefreshAfterReset = $balanceReset === false ? false : strpos(
$balancePayment,
'await refreshInvoiceDetail(invoice.id);',
$balanceReset
);
$assert(str_contains($balancePayment,
"const startsProvisioning = invoicePurpose(paid) === 'provision';")
"String(paid?.purpose || '').toLowerCase() === 'provision'")
&& str_contains($balancePayment,
'if (startsProvisioning) resetProvisioningPollWindow();')
&& strpos($balancePayment, 'resetProvisioningPollWindow();')
< strpos($balancePayment, 'renderInvoiceDetail(paid,'),
&& $balanceReset !== false
&& $balanceRefreshAfterReset !== false
&& $balanceReset < $balanceRefreshAfterReset,
'Balance payment must start a fresh provisioning poll window before rendering paid state.');
$assert(str_contains($balancePayment,
'if ([403, 409].includes(Number(error.status || 0)))')
@ -416,17 +420,17 @@ $assert(!str_contains($providerPayment, 'confirm(')
$assert(str_contains($onlinePaymentRender, 'container.replaceChildren(box);'),
'Rendered provider instructions must replace stale task-status notices.');
$paymentChoices = $section($invoiceDetailRuntime,
'function renderInvoicePaymentMethods(', 'function invoiceProgressText(');
'function renderInvoicePaymentMethods(',
'function appendProvisionInvoiceActions(');
$activePaymentRender = strpos($paymentChoices,
'renderActiveInvoicePayment(activePayment, result);');
$choicesStart = strpos($paymentChoices, 'const choices = [];');
$assert(str_contains($invoiceDetailRuntime, 'balancePaymentAllowed: false')
&& str_contains($invoiceDetailRuntime,
'state.balancePaymentAllowed = payload?.balance_payment_allowed === true')
&& str_contains($paymentChoices, 'if (state.balancePaymentAllowed)')
'renderActiveInvoicePayment(activePayment, presentation, result);');
$choicesStart = strpos($paymentChoices,
'Array.isArray(presentation?.payment_methods)');
$assert(str_contains($paymentChoices, 'if (!choices.length)')
&& str_contains($paymentChoices, "id === 'balance' ? 'balance' : 'online'")
&& str_contains($paymentChoices, 'if (!choices.length)')
&& str_contains($paymentChoices,
'state.selectedInvoicePaymentMethod = String(choices[0].id);')
'choices.find(choice => choice.selected === true) || choices[0]')
&& $activePaymentRender !== false
&& $choicesStart !== false
&& $activePaymentRender < $choicesStart,
@ -506,11 +510,10 @@ $assert(str_contains($statusService,
"->where('user_id', \$invoice->user_id)")
&& str_contains($statusService, '$instanceId = $linkedInstance?->id;'),
'Polling must validate the linked instance owner before exposing its id.');
$assert(str_contains($displayMethod, "'recharge' => '余额充值'")
&& str_contains($displayMethod, "'provision' => '实例开通'")
&& str_contains($displayMethod, "'renewal' => '实例续费'")
&& str_contains($displayMethod, "'title' => \$title")
&& str_contains($displayMethod, "'type_label' => \$title"),
$assert(str_contains($invoicePresentation, "'recharge' => '余额充值'")
&& str_contains($invoicePresentation, "'provision' => '实例开通'")
&& str_contains($invoicePresentation, "'renewal' => '实例续费'")
&& str_contains($invoicePresentation, "'title' => self::invoiceTitle("),
'Invoice purpose labels are incomplete.');
$assert(!str_contains($displayMethod, "'invoice_no' =>"),
'The internal invoice number is still exposed to users.');

@ -172,7 +172,12 @@ $assert(($creating['active_payment']['status'] ?? null) === 'creating'
&& ($creating['active_payment']['payment'] ?? null) === null
&& ($creating['active_payment']['can_submit'] ?? false) === true
&& $creating['payment_methods'] === []
&& $creating['balance_payment_allowed'] === true,
&& $creating['balance_payment_allowed'] === true
&& ($creating['presentation']['show_payment'] ?? false) === true
&& str_contains(
(string) ($creating['presentation']['active_payment_message'] ?? ''),
'仍可选择其他支付方式'
),
'A durable payment-create task blocked a new payment choice.');
Capsule::table('cloud_jobs')->where('id', 31)->update([
@ -223,7 +228,11 @@ $pendingStatus = CloudInvoiceDetailPageService::statusForUser(21, 1);
$assert(($pendingStatus['invoice']['id'] ?? null) === '21'
&& ($pendingStatus['active_payment']['status'] ?? null) === 'pending'
&& ($pendingStatus['active_payment']['payment']['payment_value'] ?? null)
=== 'https://checkout.stripe.test/resume-safe',
=== 'https://checkout.stripe.test/resume-safe'
&& ($pendingStatus['presentation_patch']['payment']['message'] ?? null)
=== '已有待支付订单;可继续原订单或选择其他支付方式。'
&& ($pendingStatus['presentation_patch']['polling']['required'] ?? false)
=== true,
'Lightweight invoice polling omitted the active provider payment.');
Capsule::table('cloud_invoice_payments')->where('id', 41)->update([

@ -6,6 +6,27 @@ import { createRequire } from 'node:module';
import { join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
const publicRoot = fileURLToPath(new URL('../public/', import.meta.url))
.replace(/\/+$/, '');
const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js');
const runtimeSource = await readFile(runtimePath, 'utf8');
for (const legacyFunction of [
'formatOrderDate', 'formatServiceDate', 'formatUsd', 'formatMemoryGiB',
'formatBytes', 'formatTrafficQuota', 'invoicePurpose', 'invoiceTitle',
'invoiceStatusInfo', 'paymentLabel', 'invoiceSpecification',
'provisionStatusInfo', 'upgradeStatusInfo', 'ipChangeStatusInfo',
'invoiceProgressText', 'pollCompletionMessage',
]) {
assert.doesNotMatch(runtimeSource, new RegExp(`function ${legacyFunction}\\(`),
`Invoice detail runtime still rebuilds presentation in ${legacyFunction}().`);
}
assert.match(runtimeSource, /payload\.presentation/,
'Invoice detail runtime does not consume the full server presentation.');
assert.match(runtimeSource, /function renderInvoiceDetail\(presentation\)/,
'Invoice detail renderer does not use the server presentation as its sole display input.');
assert.match(runtimeSource, /result\?\.presentation_patch/,
'Invoice polling does not consume the server presentation patch.');
const require = createRequire(import.meta.url);
let chromium;
try {
@ -25,13 +46,17 @@ if (!browserExecutable) {
console.log('Cloud invoice payment runtime browser checks skipped: Chromium is unavailable.');
process.exit(0);
}
const publicRoot = fileURLToPath(new URL('../public/', import.meta.url))
.replace(/\/+$/, '');
const runtimePath = join(publicRoot, 'cloud/invoice-detail-runtime.js');
const runtimeSource = await readFile(runtimePath, 'utf8');
const ids = [...runtimeSource.matchAll(/byId\('([^']+)'\)/g)]
.map(match => match[1])
.filter((id, index, all) => all.indexOf(id) === index);
for (const id of [
'invoice-detail-kind', 'invoice-detail-number', 'invoice-detail-created',
'invoice-detail-subtitle', 'invoice-detail-amount', 'invoice-payment-title',
'invoice-payment-description', 'invoice-fulfillment-title',
'invoice-fulfillment-description', 'current-username',
]) {
if (!ids.includes(id)) ids.push(id);
}
const html = `<!doctype html><html><body data-invoice-id="21">${ids.map(id => {
if (['invoice-payment-submit', 'invoice-detail-refresh'].includes(id)) {
@ -87,7 +112,10 @@ try {
const path = new URL(String(input), location.href).pathname;
if (path === '/api/v1/invoices/21/status') {
return new Promise(resolve => {
window.__resolveOldStatus = payload => resolve(jsonResponse(200, payload));
window.__resolveOldStatus = payload => {
window.__resolveOldStatus = null;
resolve(jsonResponse(200, payload));
};
});
}
if (path === '/api/v1/invoices/21/payments') {
@ -112,11 +140,12 @@ try {
const invoice = {
id: '21',
purpose: 'renewal',
title: '实例续费',
title: '原始标题不应显示',
status: 'open',
display_status: 'open',
payable: true,
amount: '10.00',
available_action: 'pay',
amount: '999.00',
currency: 'USD',
created_at: now - 60,
due_at: now + 86400,
@ -125,6 +154,41 @@ try {
traffic_quota_bytes: 0,
items: [],
};
const presentation = {
id: '21',
title: '服务端账单标题',
number_text: '服务端账单编号',
created_text: '服务端创建时间',
subtitle: '服务端账单副标题',
amount_display: '$10.00',
status_label: '服务端待支付',
status_class: 'warning',
facts: [{ label: '服务端事实', value: '服务端事实值' }],
show_line_items: false,
line_items: [],
show_specification: false,
specification: [],
show_payment: true,
payment_title: '服务端支付标题',
payment_description: '服务端支付说明',
active_payment_message: '服务端待支付订单',
active_payment_class: 'invoice-payment-note',
payment_methods: [
{ id: 'stripe_card', name: 'Stripe Card', description: 'Card', selected: true },
{ id: 'usdt', name: 'USDT', description: 'USDT', selected: false },
],
show_fulfillment: false,
fulfillment_title: '',
fulfillment_description: '',
fulfillment_message: '',
fulfillment_label: '',
fulfillment_class: 'other',
fulfillment_failed: false,
task_id: '',
instance_id: '',
polling_required: true,
completion_notice: null,
};
const oldPayment = {
invoice_id: '21',
method: 'stripe_card',
@ -155,7 +219,7 @@ try {
{ id: 'usdt', name: 'USDT' },
],
};
await page.evaluate(async ({ base, invoice, oldPayment, newPayment }) => {
await page.evaluate(async ({ base, invoice, presentation, oldPayment, newPayment }) => {
window.__newPayment = newPayment;
window.__invoiceRuntime = await import(
`/cloud/invoice-detail-runtime.js?behavior=${Date.now()}`
@ -163,6 +227,7 @@ try {
window.__invoicePayload = {
...base,
invoice,
presentation,
active_payment: {
status: 'pending',
task_id: null,
@ -171,12 +236,57 @@ try {
},
};
window.__invoiceRuntime.hydrateInvoiceDetail(window.__invoicePayload, '21');
}, { base, invoice, oldPayment, newPayment });
}, { base, invoice, presentation, oldPayment, newPayment });
assert.equal(await page.locator('#invoice-detail-kind').textContent(),
'服务端账单标题');
assert.equal(await page.locator('#invoice-detail-amount').textContent(), '$10.00');
assert.equal(await page.locator('#invoice-detail-status').textContent(),
'服务端待支付');
assert.match(await page.locator('#invoice-detail-facts').textContent(),
/服务端事实值/);
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);
assert.equal(await page.locator('#invoice-payment-submit').isEnabled(), true);
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 1);
await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function',
null, { timeout: 5000 });
await page.evaluate(({ invoice, oldPayment }) => {
window.__resolveOldStatus({
invoice,
active_payment: {
status: 'pending', task_id: null, payment: oldPayment, can_submit: true,
},
presentation_patch: {
invoice: {
id: '21', status: 'raw-status-must-not-render',
display_status: 'raw-status-must-not-render', payable: true,
available_action: 'pay',
},
active_payment: {
status: 'pending', task_id: null, payment: oldPayment, can_submit: true,
},
status: { code: 'open', label: '服务端轮询状态', class: 'warning' },
payment: {
payable: true, active: { status: 'pending' },
message: '服务端待支付订单', message_class: 'invoice-payment-note',
},
fulfillment: {
show_fulfillment: false, fulfillment_title: '',
fulfillment_description: '', fulfillment_message: '',
fulfillment_label: '', fulfillment_class: 'other',
fulfillment_failed: false, task_id: '', instance_id: '', status_code: '',
},
polling: { required: true, task_id: '', job_status: '' },
completion_notice: null,
},
});
}, { invoice, oldPayment });
await page.waitForFunction(() => document.querySelector(
'#invoice-detail-status'
)?.textContent === '服务端轮询状态', null, { timeout: 5000 });
assert.equal(await page.locator('#invoice-detail-status').textContent(),
'服务端轮询状态');
await page.waitForFunction(() => typeof window.__resolveOldStatus === 'function',
null, { timeout: 5000 });
await page.locator('.invoice-payment-method-card[data-method-id="usdt"]').click();
@ -195,6 +305,29 @@ try {
payment: oldPayment,
can_submit: true,
},
presentation_patch: {
invoice: {
id: '21', status: 'raw-stale-status',
display_status: 'raw-stale-status', payable: true,
available_action: 'pay',
},
active_payment: {
status: 'pending', task_id: null, payment: oldPayment, can_submit: true,
},
status: { code: 'open', label: '过期轮询状态不应显示', class: 'failed' },
payment: {
payable: true, active: { status: 'pending' },
message: '过期支付状态', message_class: 'invoice-payment-error',
},
fulfillment: {
show_fulfillment: false, fulfillment_title: '',
fulfillment_description: '', fulfillment_message: '',
fulfillment_label: '', fulfillment_class: 'other',
fulfillment_failed: false, task_id: '', instance_id: '', status_code: '',
},
polling: { required: true, task_id: '', job_status: '' },
completion_notice: null,
},
});
await page.waitForTimeout(50);
assert.match(
@ -202,9 +335,11 @@ try {
/USDT/,
'A late status response replaced the newer provider order.',
);
assert.equal(await page.locator('#invoice-detail-status').textContent(),
'服务端轮询状态', 'A stale raw/status patch replaced the newer presentation.');
assert.equal(await page.locator('a[href="https://checkout.stripe.test/old"]').count(), 0);
await page.evaluate(({ base, invoice }) => {
await page.evaluate(({ base, invoice, presentation }) => {
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:stripe_card',
'stripe-runtime-stale-key-0001');
sessionStorage.setItem('virt-cloud:invoice-payment:1:21:usdt',
@ -213,9 +348,10 @@ try {
window.__invoiceRuntime.hydrateInvoiceDetail({
...base,
invoice,
presentation,
active_payment: null,
}, '21');
}, { base, invoice });
}, { base, invoice, presentation });
assert.equal(await page.locator('.cloud-payment-instructions').count(), 0);
assert.equal(await page.locator('.invoice-payment-method-card').count(), 2);

@ -71,7 +71,10 @@ $assert($detail['show_line_items'] === true
'amount_display' => '$2.50',
],
]
&& $detail['amount_display'] === '$12.51',
&& $detail['amount_display'] === '$12.51'
&& $detail['number_text'] === '账单 #17'
&& str_starts_with($detail['created_text'], '创建于 ')
&& $detail['polling_required'] === false,
'Detail projection changed frozen line-item labels or authoritative total.');
$switchable = CloudInvoicePresentation::detail([
@ -94,7 +97,8 @@ $assert($switchable['show_payment'] === true
&& str_contains($switchable['active_payment_message'], '可选择其他支付方式')
&& count($switchable['payment_methods']) === 2
&& $switchable['payment_methods'][0]['id'] === 'balance'
&& $switchable['payment_methods'][0]['selected'] === true,
&& $switchable['payment_methods'][0]['selected'] === true
&& $switchable['polling_required'] === true,
'Unfinished payment did not remain switchable through the public module.');
$ipChange = [
@ -124,7 +128,9 @@ $assert($ipView['show_fulfillment'] === true
&& $ipView['instance_id'] === '41'
&& $ipRow['show_fulfillment'] === true
&& $ipRow['fulfillment_label'] === '待人工核对'
&& $ipRow['context_display'] === '目标实例 vm-audit',
&& $ipRow['context_display'] === '目标实例 vm-audit'
&& ($ipView['completion_notice']['message'] ?? null)
=== '公网 IP 更换结果待人工核对,请勿重复提交。',
'IP-change presentation lost its target or review-only fulfillment state.');
$unknown = CloudInvoicePresentation::summaries([[
@ -155,11 +161,14 @@ $patch = CloudInvoicePresentation::statusPatch([
'can_submit' => true,
],
]);
$assert($patch['status'] === ['label' => '已支付', 'class' => 'running']
$assert($patch['status']['code'] === 'paid'
&& $patch['status']['label'] === '已支付'
&& $patch['status']['class'] === 'running'
&& $patch['payment']['message']
=== '已有待支付订单;可继续原订单或选择其他支付方式。'
&& $patch['fulfillment']['fulfillment_label'] === '待人工核对'
&& $patch['polling']['task_id'] === '82'
&& $patch['polling']['required'] === false
&& $patch['polling']['job_attempts'] === 2
&& !array_key_exists('amount', $patch['invoice']),
'Sparse status projection did not isolate mutable payment and polling fields.');
@ -173,6 +182,9 @@ $controllerSource = file_get_contents(
$pageServiceSource = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePageService.php'
);
$detailServiceSource = file_get_contents(
dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceDetailPageService.php'
);
$assert(is_string($source)
&& !str_contains($source, 'App\\Models')
&& !preg_match('/\\btime\\s*\\(/', $source)
@ -180,11 +192,16 @@ $assert(is_string($source)
&& !str_contains($source, 'CloudInvoiceService::'),
'Presentation module acquired an ORM, clock, payment-provider or domain-service dependency.');
$assert(is_string($controllerSource) && is_string($pageServiceSource)
&& is_string($detailServiceSource)
&& str_contains($pageServiceSource,
'CloudInvoicePresentation::summaries(')
&& str_contains($controllerSource, "\$rows = \$payload['invoices'];")
&& str_contains($detailServiceSource,
'CloudInvoicePresentation::detail($payload)')
&& str_contains($detailServiceSource,
'CloudInvoicePresentation::statusPatch($payload)')
&& str_contains($controllerSource,
'CloudInvoicePresentation::detail($payload)'),
"'cloud_invoice_detail_view' => \$payload['presentation']"),
'Invoice SSR adapters do not consume the unified presentation module.');
echo "Cloud invoice presentation module checks passed.\n";

@ -136,14 +136,23 @@ $detailRuntime = file_get_contents(
);
$listRuntime = file_get_contents(dirname(__DIR__) . '/public/cloud/invoices.js');
$assert(is_string($detailRuntime) && is_string($listRuntime)
&& str_contains($detailRuntime,
&& str_contains($detailRuntime, 'payload.presentation')
&& str_contains($detailRuntime, 'result?.presentation_patch')
&& str_contains($detailRuntime, 'presentation?.status_label')
&& str_contains($detailRuntime, 'presentation?.status_class')
&& str_contains($detailRuntime, 'presentation?.fulfillment_label')
&& str_contains($detailRuntime, 'presentation?.polling_required')
&& str_contains($detailRuntime, 'function renderInvoiceDetail(presentation)')
&& !str_contains($detailRuntime,
'function renderInvoiceDetail(invoice, presentation)')
&& !str_contains($detailRuntime, 'function invoiceTitle(')
&& !str_contains($detailRuntime, 'function invoiceStatusInfo(')
&& !str_contains($detailRuntime, 'function paymentLabel(')
&& !str_contains($detailRuntime, 'function provisionStatusInfo(')
&& !str_contains($detailRuntime, 'function upgradeStatusInfo(')
&& !str_contains($detailRuntime, 'function ipChangeStatusInfo(')
&& !str_contains($detailRuntime,
"renewal_grace: ['已到期,宽限期内可续费', 'warning']")
&& str_contains($detailRuntime,
'invoice.display_status ?? invoice.status')
&& str_contains($detailRuntime,
"review: ['待人工核对', 'warning']")
&& str_contains($detailRuntime,
"invoicePurpose(invoice) === 'ip_change'")
&& str_contains($listRuntime, 'invoice?.status_label')
&& str_contains($listRuntime, 'invoice?.status_class')
&& str_contains($listRuntime, 'invoice?.fulfillment_label')

Loading…
Cancel
Save