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/CloudInvoicePaymentRuntimeB...

368 lines
13 KiB
JavaScript

import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { existsSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
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 {
({ chromium } = require('playwright'));
} catch {
console.log('Cloud invoice payment runtime browser checks skipped: Playwright is unavailable.');
process.exit(0);
}
const browserExecutable = [
process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE,
chromium.executablePath(),
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/usr/bin/google-chrome',
'/usr/bin/chromium',
].find(path => path && existsSync(path));
if (!browserExecutable) {
console.log('Cloud invoice payment runtime browser checks skipped: Chromium is unavailable.');
process.exit(0);
}
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)) {
return `<button id="${id}" type="button"></button>`;
}
return `<div id="${id}"></div>`;
}).join('')}</body></html>`;
const server = createServer(async (request, response) => {
const url = new URL(request.url || '/', 'http://127.0.0.1');
if (url.pathname === '/') {
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
response.end(html);
return;
}
if (!url.pathname.startsWith('/cloud/')) {
response.writeHead(404).end();
return;
}
const path = normalize(join(publicRoot, url.pathname));
if (!path.startsWith(`${publicRoot}/`)) {
response.writeHead(403).end();
return;
}
try {
response.writeHead(200, {
'Content-Type': 'application/javascript; charset=utf-8',
'Cache-Control': 'no-store',
});
response.end(await readFile(path));
} catch {
response.writeHead(404).end();
}
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const address = server.address();
if (!address || typeof address === 'string') throw new Error('Test server failed.');
const browser = await chromium.launch({
headless: true,
executablePath: browserExecutable,
});
try {
const page = await browser.newPage();
await page.goto(`http://127.0.0.1:${address.port}/`);
await page.evaluate(() => {
const jsonResponse = (status, payload) => new Response(
JSON.stringify(payload),
{ status, headers: { 'Content-Type': 'application/json' } },
);
window.__resolveOldStatus = null;
window.fetch = async input => {
const path = new URL(String(input), location.href).pathname;
if (path === '/api/v1/invoices/21/status') {
return new Promise(resolve => {
window.__resolveOldStatus = payload => {
window.__resolveOldStatus = null;
resolve(jsonResponse(200, payload));
};
});
}
if (path === '/api/v1/invoices/21/payments') {
return jsonResponse(202, {
task_id: '99',
status_url: '/api/v1/tasks/99',
});
}
if (path === '/api/v1/tasks/99') {
return jsonResponse(200, {
id: '99',
completed: true,
status: 'succeeded',
result: { payment: window.__newPayment },
});
}
throw new Error(`Unexpected fetch: ${path}`);
};
});
const now = Math.floor(Date.now() / 1000);
const invoice = {
id: '21',
purpose: 'renewal',
title: '原始标题不应显示',
status: 'open',
display_status: 'open',
payable: true,
available_action: 'pay',
amount: '999.00',
currency: 'USD',
created_at: now - 60,
due_at: now + 86400,
renews_expires_at: now + 86400,
validity_days: 30,
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',
status: 'pending',
payment_kind: 'payurl',
payment_value: 'https://checkout.stripe.test/old',
label: 'Stripe Card',
expires_at: now + 900,
};
const newPayment = {
invoice_id: '21',
method: 'usdt',
status: 'pending',
payment_kind: 'usdt',
actual_amount: '1.500001',
receive_address: 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t',
label: 'USDT',
expires_at: now + 900,
};
const base = {
csrf_token: 'a'.repeat(64),
user_id: '1',
username: 'runtime-test',
balance: '0.00',
balance_payment_allowed: false,
payment_methods: [
{ id: 'stripe_card', name: 'Stripe Card' },
{ id: 'usdt', name: 'USDT' },
],
};
await page.evaluate(async ({ base, invoice, presentation, oldPayment, newPayment }) => {
window.__newPayment = newPayment;
window.__invoiceRuntime = await import(
`/cloud/invoice-detail-runtime.js?behavior=${Date.now()}`
);
window.__invoicePayload = {
...base,
invoice,
presentation,
active_payment: {
status: 'pending',
task_id: null,
payment: oldPayment,
can_submit: true,
},
};
window.__invoiceRuntime.hydrateInvoiceDetail(window.__invoicePayload, '21');
}, { 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();
await page.locator('#invoice-payment-submit').click();
await page.waitForFunction(() => document.querySelector(
'.cloud-payment-instructions strong'
)?.textContent?.includes('USDT'), null, { timeout: 5000 });
await page.evaluate(oldStatus => {
window.__resolveOldStatus(oldStatus);
}, {
invoice,
active_payment: {
status: 'pending',
task_id: null,
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(
await page.locator('.cloud-payment-instructions strong').textContent(),
/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, 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',
'usdt-runtime-stale-key-0002');
window.__invoiceRuntime.stopInvoicePoll();
window.__invoiceRuntime.hydrateInvoiceDetail({
...base,
invoice,
presentation,
active_payment: null,
}, '21');
}, { base, invoice, presentation });
assert.equal(await page.locator('.cloud-payment-instructions').count(), 0);
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.evaluate(() => [...Array(sessionStorage.length).keys()]
.map(index => sessionStorage.key(index))
.filter(key => key?.startsWith('virt-cloud:invoice-payment:1:21:')).length), 0);
} finally {
await browser.close();
await new Promise(resolve => server.close(resolve));
}
console.log('Cloud invoice payment runtime browser behavior checks passed.');