fix: display user times in browser timezone

go
codex 2 weeks ago
parent 92a6f8fdbf
commit 795c8eb8a8

@ -29,4 +29,10 @@ class Code extends Model
}
return $value;
}
public function getUsedAtTimestampAttribute()
{
$timestamp = strtotime((string) ($this->attributes['usedatetime'] ?? ''));
return $timestamp === false ? 0 : $timestamp;
}
}

@ -16,11 +16,22 @@ class Ticket extends Model
return date("Y-m-d H:i:s", $this->attributes['datetime']);
}
public function datetimeTimestamp(): int
{
return max(0, (int) ($this->attributes['datetime'] ?? 0));
}
public function lastActivity()
{
$timestamp = $this->attributes['last_activity_at'] ?? $this->attributes['datetime'];
return date("Y-m-d H:i:s", (int) $timestamp);
}
public function lastActivityTimestamp(): int
{
return max(0, (int) ($this->attributes['last_activity_at']
?? $this->attributes['datetime'] ?? 0));
}
}

@ -190,10 +190,23 @@ final class AnnouncementService
private static function dto(Ann $ann): array
{
$type = (string) $ann->type;
$publishedAt = $ann->published_at === null ? null : (string) $ann->published_at;
$updatedAt = (string) $ann->updated_at;
return ['id' => (string) $ann->id, 'title' => (string) $ann->title,
'type' => $type, 'type_label' => self::TYPES[$type] ?? '通知', 'body' => (string) $ann->body,
'status' => (string) $ann->status,
'published_at' => $ann->published_at === null ? null : (string) $ann->published_at,
'updated_at' => (string) $ann->updated_at];
'published_at' => $publishedAt,
'published_at_epoch' => self::epoch($publishedAt),
'updated_at' => $updatedAt,
'updated_at_epoch' => self::epoch($updatedAt)];
}
private static function epoch(?string $value): ?int
{
if ($value === null || trim($value) === '') {
return null;
}
$timestamp = strtotime($value);
return $timestamp === false ? null : $timestamp;
}
}

@ -53,39 +53,26 @@ final class CloudInvoicePresentation
$facts = [
['label' => '账单编号', 'value' => '#' . (string) ($invoice['id'] ?? '—')],
['label' => '创建时间', 'value' => $created],
self::timestampFact('创建时间', $invoice['created_at'] ?? null,
'时间未记录'),
];
if ($purpose === 'provision') {
$facts[] = [
'label' => '支付截止',
'value' => self::formatTimestamp(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null
),
];
$facts[] = self::timestampFact('支付截止',
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null);
} elseif ($purpose === 'renewal') {
$facts[] = [
'label' => '实例到期',
'value' => self::formatTimestamp(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null
),
];
$facts[] = self::timestampFact('实例到期',
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null);
if (($invoice['deletion_at'] ?? null) !== null) {
$facts[] = [
'label' => '最晚支付',
'value' => self::formatTimestamp($invoice['deletion_at']),
];
$facts[] = self::timestampFact('最晚支付',
$invoice['deletion_at']);
}
} elseif (($invoice['payment_deadline_at'] ?? null) !== null) {
$facts[] = [
'label' => '支付截止',
'value' => self::formatTimestamp($invoice['payment_deadline_at']),
];
$facts[] = self::timestampFact('支付截止',
$invoice['payment_deadline_at']);
}
if (($invoice['paid_at'] ?? null) !== null) {
$facts[] = [
'label' => '支付时间',
'value' => self::formatTimestamp($invoice['paid_at']),
];
$facts[] = self::timestampFact('支付时间',
$invoice['paid_at']);
}
if (trim((string) ($invoice['paid_via'] ?? '')) !== '') {
$facts[] = [
@ -118,6 +105,7 @@ final class CloudInvoicePresentation
'id' => (string) ($invoice['id'] ?? ''),
'title' => self::invoiceTitle($invoice, $purpose),
'number_text' => '账单 #' . (string) ($invoice['id'] ?? '—'),
'created_at' => self::timestampValue($invoice['created_at'] ?? null),
'created_text' => '创建于 ' . $created,
'subtitle' => '账单 #' . (string) ($invoice['id'] ?? '—')
. ' · ' . $created,
@ -286,6 +274,9 @@ final class CloudInvoicePresentation
) !== ''))
&& $fulfillmentLabel !== '';
$invoice['context_display'] = self::context($invoice, $purpose, $status);
$invoice['context_segments'] = self::contextSegments(
$invoice, $purpose, $status
);
$invoice['polling_required'] = in_array($status, ['open', 'overdue'], true)
|| (in_array($purpose, ['upgrade', 'ip_change'], true)
&& $fulfillmentStatus === 'active');
@ -325,6 +316,50 @@ final class CloudInvoicePresentation
return '';
}
/**
* Preserve the server-owned context vocabulary while exposing canonical
* timestamps for browser-local formatting.
*
* @param array<string, mixed> $invoice
* @return array<int, array{kind: string, value: int|string}>
*/
private static function contextSegments(array $invoice, string $purpose,
string $status): array
{
if ($purpose === 'renewal') {
$segments = [
['kind' => 'text', 'value' => '对应实例到期 '],
['kind' => 'timestamp', 'value' => self::timestampValue(
$invoice['renews_expires_at'] ?? $invoice['due_at'] ?? null
) ?? 0],
];
if (in_array($status, ['open', 'overdue'], true)) {
$segments[] = ['kind' => 'text', 'value' => ' · 最晚支付 '];
$segments[] = ['kind' => 'timestamp', 'value' =>
self::timestampValue($invoice['payment_deadline_at'] ?? null)
?? 0];
}
return $segments;
}
if ($purpose === 'provision') {
return [
['kind' => 'text', 'value' => '支付截止 '],
['kind' => 'timestamp', 'value' => self::timestampValue(
$invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null
) ?? 0],
];
}
if (in_array($purpose, ['upgrade', 'ip_change', 'backup_addon'], true)) {
$target = self::firstText($invoice['instance_name'] ?? null);
if ($target === '' && ($invoice['instance_id'] ?? null) !== null) {
$target = '#' . (string) $invoice['instance_id'];
}
return [['kind' => 'text', 'value' => '目标实例 '
. ($target !== '' ? $target : '实例')]];
}
return [];
}
/**
* @param array<string, mixed> $payload
* @param array<string, mixed> $invoice
@ -734,6 +769,22 @@ final class CloudInvoicePresentation
);
}
/** @return array{label: string, value: string, timestamp: int|null} */
private static function timestampFact(string $label, $value,
string $fallback = '暂未提供'): array
{
return [
'label' => $label,
'value' => self::formatTimestamp($value, $fallback),
'timestamp' => self::timestampValue($value),
];
}
private static function timestampValue($value): ?int
{
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
}
private static function formatMemory(int $memoryMiB): string
{
$memoryGiB = $memoryMiB / 1024;

@ -115,7 +115,8 @@ final class TicketReadModel
'id' => (int) $message->id,
'content' => $content,
'datetime' => date('Y-m-d H:i:s', (int) $message->datetime),
'datetime_iso' => date(DATE_ATOM, (int) $message->datetime),
'datetime_epoch' => max(0, (int) $message->datetime),
'datetime_iso' => gmdate(DATE_ATOM, (int) $message->datetime),
'author_id' => (int) $message->userid,
'author_is_admin' => $authorIsAdmin,
'viewer_is_author' => (int) $message->userid === $viewer->actorId,

@ -25,9 +25,11 @@ function setMessage(message, tone = '') {
}
function dateText(value) {
// The API supplies the publication time in the site's timezone. Do not parse
// an unzoned SQL date as UTC or substitute a browser-generated publication time.
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(value) ? value : '时间未记录';
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return '时间未记录';
const date = new Date(numeric * (numeric < 1e12 ? 1000 : 1));
return Number.isFinite(date.getTime())
? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录';
}
function renderItems() {
@ -40,11 +42,14 @@ function renderItems() {
const type = ['notice', 'maintenance', 'incident'].includes(item.type) ? item.type : 'notice';
const fallback = { notice: '通知', maintenance: '维护', incident: '故障' }[type];
meta.append(element('span', `panel-announcements-type is-${type}`, item.type_label || fallback));
const published = element('time', '', `发布于 ${dateText(item.published_at)}`);
if (dateText(item.published_at) !== '时间未记录') published.dateTime = item.published_at.replace(' ', 'T');
const published = element('time', '', `发布于 ${dateText(item.published_at_epoch)}`);
if (dateText(item.published_at_epoch) !== '时间未记录') {
published.dateTime = new Date(Number(item.published_at_epoch) * 1000).toISOString();
}
meta.append(published);
if (item.updated_at && item.updated_at !== item.published_at) {
meta.append(element('span', '', `更新于 ${dateText(item.updated_at)}`));
if (Number(item.updated_at_epoch) > 0
&& Number(item.updated_at_epoch) !== Number(item.published_at_epoch)) {
meta.append(element('span', '', `更新于 ${dateText(item.updated_at_epoch)}`));
}
article.append(meta, element('h3', '', item.title || '站点公告'), element('p', 'panel-announcements-body', item.body ?? ''));
list.append(article);
@ -129,8 +134,9 @@ function contentSignature(items) {
const type = ['notice', 'maintenance', 'incident'].includes(item.type) ? item.type : 'notice';
const fallback = { notice: '通知', maintenance: '维护', incident: '故障' }[type];
return [String(item.id), type, String(item.type_label || fallback),
String(item.title || '站点公告'), String(item.body ?? ''), dateText(item.published_at),
item.updated_at && item.updated_at !== item.published_at ? dateText(item.updated_at) : ''];
String(item.title || '站点公告'), String(item.body ?? ''), dateText(item.published_at_epoch),
Number(item.updated_at_epoch) > 0 && Number(item.updated_at_epoch) !== Number(item.published_at_epoch)
? dateText(item.updated_at_epoch) : ''];
}));
}

@ -227,11 +227,17 @@ async function load(page = 1) {
export async function initialize() {
try {
const bootstrap = readBootstrap('cloud-backups-bootstrap');
if (!await initializeSession('backups', bootstrap?.user)) return;
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.backups)) {
const hasBootstrap = Array.isArray(bootstrap?.items)
|| Array.isArray(bootstrap?.backups);
// Do not leave the panel-time SSR fallback visible while session
// confirmation is pending or unavailable; the page bootstrap already
// carries canonical owner-scoped timestamps.
if (hasBootstrap) {
applyPayload(bootstrap);
byId('cloud-backups-status').hidden = true;
} else {
}
if (!await initializeSession('backups', bootstrap?.user)) return;
if (!hasBootstrap) {
await load(1);
}
byId('cloud-backups-refresh')?.addEventListener('click', () => void load(state.page));

@ -242,11 +242,17 @@ async function deleteSnapshot(snapshot) {
export async function initialize() {
try {
const bootstrap = readBootstrap('cloud-snapshots-bootstrap');
if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return;
if (Array.isArray(bootstrap?.items) || Array.isArray(bootstrap?.snapshots)) {
const hasBootstrap = Array.isArray(bootstrap?.items)
|| Array.isArray(bootstrap?.snapshots);
// Do not leave the panel-time SSR fallback visible while session
// confirmation is pending or unavailable; the page bootstrap already
// carries canonical owner-scoped timestamps.
if (hasBootstrap) {
applyPayload(bootstrap);
byId('cloud-snapshots-status').hidden = true;
} else {
}
if (!await initializeSession('cloud-snapshots', bootstrap?.user)) return;
if (!hasBootstrap) {
await load(1);
}
byId('cloud-snapshots-refresh')?.addEventListener('click',

@ -693,8 +693,12 @@ function hydrate() {
state.liveStatsReady = state.vms.length === 0 || state.vms.every(runtimeStateReady);
state.user = payload.user && typeof payload.user === 'object' ? payload.user : {};
renderStats();
// Replace the PHP timezone fallback synchronously from the canonical
// timestamps embedded in the bootstrap. This must not wait for a live
// Agent/status request, otherwise a failed refresh leaves panel-time
// values visible to users in other timezones.
renderVms();
renderPagination();
renderCount(state.vms.length);
updatePageUrl(state.pagination.page);
return true;
} catch { return false; }

@ -216,15 +216,25 @@ function serviceTimestamp(value) {
return Number.isFinite(parsed) ? parsed : null;
}
function browserTime(value, fallback = '时间未记录') {
const timestamp = serviceTimestamp(value);
if (timestamp === null) return fallback;
const date = new Date(timestamp);
return Number.isFinite(date.getTime())
? date.toLocaleString('zh-CN', { hour12: false }) : fallback;
}
function invoiceCanPay(invoice) {
return invoice?.payable === true && invoice?.available_action === 'pay';
}
function invoiceFact(label, value) {
function invoiceFact(label, value, timestamp = null) {
const item = makeElement('div', 'invoice-detail-fact');
item.append(
makeElement('dt', '', label),
makeElement('dd', '', value === null || value === undefined || value === '' ? '—' : value),
makeElement('dd', '', timestamp === null || timestamp === undefined
? (value === null || value === undefined || value === '' ? '—' : value)
: browserTime(timestamp, value || '—')),
);
return item;
}
@ -1128,10 +1138,16 @@ function renderInvoiceFulfillment(invoice, presentation) {
function renderInvoiceDetail(presentation) {
state.presentation = presentation;
const created = browserTime(
presentation?.created_at,
firstText(presentation?.created_display, '时间未记录'),
);
text('invoice-detail-kind', firstText(presentation?.title, '账单'));
text('invoice-detail-number', firstText(presentation?.number_text, '账单'));
text('invoice-detail-created', firstText(presentation?.created_text, '时间未记录'));
text('invoice-detail-subtitle', firstText(presentation?.subtitle, '账单详情'));
text('invoice-detail-created', `创建于 ${created}`);
text('invoice-detail-subtitle', `${firstText(
presentation?.number_text, '账单',
)} · ${created}`);
text('invoice-detail-amount', firstText(presentation?.amount_display, '$—'));
const status = byId('invoice-detail-status');
if (status) {
@ -1141,7 +1157,7 @@ function renderInvoiceDetail(presentation) {
const facts = (Array.isArray(presentation?.facts) ? presentation.facts : [])
.flatMap(item => item && typeof item === 'object' && !Array.isArray(item)
? [invoiceFact(item.label, item.value)] : []);
? [invoiceFact(item.label, item.value, item.timestamp)] : []);
byId('invoice-detail-facts')?.replaceChildren(...facts);
renderInvoiceLineItems(presentation);

@ -81,6 +81,25 @@ function invoiceNeedsPolling(invoice) {
return invoice?.polling_required === true;
}
function browserTime(value, fallback = '时间未记录') {
const numeric = Number(value);
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
const date = new Date(numeric * (numeric < 1e12 ? 1000 : 1));
return Number.isFinite(date.getTime())
? date.toLocaleString('zh-CN', { hour12: false }) : fallback;
}
function presentationSegmentsText(invoice) {
const segments = Array.isArray(invoice?.context_segments)
? invoice.context_segments : [];
if (!segments.length) return String(invoice?.context_display || '').trim();
return segments.map(segment => {
if (!segment || typeof segment !== 'object' || Array.isArray(segment)) return '';
if (segment.kind === 'timestamp') return browserTime(segment.value);
return segment.kind === 'text' ? String(segment.value || '') : '';
}).join('').trim();
}
function renderInvoices() {
const container = byId('invoices-list');
if (!container) return;
@ -95,9 +114,9 @@ function renderInvoices() {
const detail = makeElement('div', 'cloud-order-detail cloud-invoice-list-copy');
detail.append(makeElement('strong', '', String(invoice?.title || '账单')),
makeElement('p', 'muted', `账单 #${invoice.id} · ${String(
invoice?.created_display || '时间未记录',
browserTime(invoice?.created_at, invoice?.created_display || '时间未记录'),
)}`));
const context = String(invoice?.context_display || '').trim();
const context = presentationSegmentsText(invoice);
if (context) detail.append(makeElement('p', 'muted cloud-invoice-context', context));
const actions = makeElement('div', 'cloud-order-actions cloud-invoice-list-actions');
actions.append(makeElement('span', `state-pill ${String(
@ -238,6 +257,7 @@ function hydrate() {
syncFilters();
state.pagination = normalizePagination(payload.pagination, 1);
state.page = state.pagination.page;
renderInvoices();
renderPagination();
return true;
} catch { return false; }

@ -270,8 +270,12 @@ async function load() {
export async function initialize() {
try {
const bootstrap = readBootstrap('cloud-traffic-bootstrap');
const hasBootstrap = Array.isArray(bootstrap?.line_pools);
// Browser-localise the SSR fallback before the asynchronous session
// handshake. The bootstrap is already owner-scoped by the page request.
if (hasBootstrap) applyPayload(bootstrap);
if (!await initializeSession('traffic', bootstrap?.user)) return;
applyPayload(bootstrap);
if (!hasBootstrap) applyPayload(bootstrap);
byId('cloud-traffic-refresh')?.addEventListener('click', () => void load());
window.addEventListener('pagehide', () => state.controller?.abort());
} catch (error) {

@ -34,6 +34,17 @@
return Array.prototype.slice.call(document.querySelectorAll(selector));
}
function renderBrowserTimes() {
qsa("[data-recharge-time]").forEach(function (node) {
var timestamp = Number(node.getAttribute("data-timestamp"));
if (!Number.isFinite(timestamp) || timestamp <= 0) return;
var date = new Date(timestamp * (timestamp < 1e12 ? 1000 : 1));
if (!Number.isFinite(date.getTime())) return;
node.textContent = date.toLocaleString("zh-CN", { hour12: false });
node.dateTime = date.toISOString();
});
}
function topWindow() {
try {
return window.top || window;
@ -426,6 +437,7 @@
priceInput.addEventListener("change", loadMethods);
}
qsa("[data-pay-close]").forEach(function (item) { item.addEventListener("click", closePayDialog); });
renderBrowserTimes();
var returnParams = new URLSearchParams(window.location.search);
if (returnParams.get("payment") === "yipay") {

@ -9,6 +9,18 @@
return Array.prototype.slice.call((root || document).querySelectorAll(selector));
}
function localizeTicketTimes(root) {
qsa("[data-ticket-time]", root).forEach(function (element) {
var seconds = Number(element.getAttribute("data-timestamp"));
var date;
if (!Number.isFinite(seconds) || seconds <= 0) return;
date = new Date(seconds * 1000);
if (!Number.isFinite(date.getTime())) return;
element.textContent = date.toLocaleString("zh-CN", { hour12: false });
if (element.tagName === "TIME") element.dateTime = date.toISOString();
});
}
function csrfHeaders() {
var token = "";
var element = qs("[data-csrf-token]");
@ -262,6 +274,7 @@
}
document.addEventListener("DOMContentLoaded", function () {
localizeTicketTimes(document);
bindCreate();
bindReply();
markThreadRead();

@ -1,2 +1,2 @@
{* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *}
{assign var=venix_asset_version value='2026110201' scope='global'}
{assign var=venix_asset_version value='2026110202' scope='global'}

@ -25,7 +25,7 @@
{if $codes->isEmpty()}<tr><td colspan="3"><div class="vu-inline-empty"><i class="mdi mdi-receipt-text-remove-outline"></i><span>暂无充值记录</span></div></td></tr>
{else}
{foreach $codes as $code}
{if $code->type!=-2}<tr><td><strong>$ {$code->number}</strong></td><td>{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005}余额充值{elseif $code->type==10006}USDT 充值{elseif $code->type==10007}在线充值{else}充值{/if}</td><td>{$code->usedatetime}</td></tr>{/if}
{if $code->type!=-2}<tr><td><strong>$ {$code->number}</strong></td><td>{if $code->type==-1 || $code->type==10003 || $code->type==10004 || $code->type==10005}余额充值{elseif $code->type==10006}USDT 充值{elseif $code->type==10007}在线充值{else}充值{/if}</td><td><time data-recharge-time data-timestamp="{$code->used_at_timestamp|escape:'html'}">{$code->usedatetime|escape:'html'}</time></td></tr>{/if}
{/foreach}
{/if}
</tbody></table></div>

@ -55,7 +55,7 @@
{elseif $ticket->priority|default:'' == 'low'}<span class="vu-ticket-tag">低优先级</span>{/if}
</div>
<h3>{$ticket->title|escape:"html"}</h3>
<p><i class="mdi mdi-clock-outline" aria-hidden="true"></i>最近活动 {$ticket->lastActivity()} · {if $ticket->waiting_for|default:''=='admin'}等待管理员{elseif $ticket->waiting_for|default:''=='user'}等待你回复{else}已关闭{/if}</p>
<p><i class="mdi mdi-clock-outline" aria-hidden="true"></i>最近活动 <time data-ticket-time data-timestamp="{$ticket->lastActivityTimestamp()|escape:'html'}">{$ticket->lastActivity()|escape:"html"}</time> · {if $ticket->waiting_for|default:''=='admin'}等待管理员{elseif $ticket->waiting_for|default:''=='user'}等待你回复{else}已关闭{/if}</p>
</div>
<div class="vu-support-ticket-side">
<span class="vu-support-status {if $ticket->status==1}is-open{else}is-closed{/if}">

@ -20,7 +20,7 @@
<div class="vu-support-message-body">
<div class="vu-support-message-head">
<strong>{$ticket->author_name|escape:"html"}</strong>
<time datetime="{$ticket->datetime_iso|escape:'html'}">{$ticket->datetime|escape:"html"}</time>
<time datetime="{$ticket->datetime_iso|escape:'html'}" data-ticket-time data-timestamp="{$ticket->datetime_epoch|escape:'html'}">{$ticket->datetime|escape:"html"}</time>
</div>
<p>{$ticket->content|escape:"html"|nl2br}</p>
{if isset($ticket->attachments) && $ticket->attachments}
@ -109,7 +109,7 @@
{elseif isset($ticket_main) && $ticket_main->instance_id|default:''}
<div><span>关联实例</span><strong>#{$ticket_main->instance_id|escape:'html'}(不可用)</strong></div>
{/if}
<div><span>创建时间</span><strong>{if isset($ticket_main)}{$ticket_main->datetime()}{else}-{/if}</strong></div>
<div><span>创建时间</span><strong>{if isset($ticket_main)}<time data-ticket-time data-timestamp="{$ticket_main->datetimeTimestamp()|escape:'html'}">{$ticket_main->datetime()|escape:'html'}</time>{else}-{/if}</strong></div>
</div>
<a class="vu-btn vu-btn-soft" href="/user/ticket/create"><i class="mdi mdi-message-plus-outline" aria-hidden="true"></i><span>创建新工单</span></a>
</div>

@ -329,7 +329,7 @@ $assert(str_contains($invoicePresentation,
&& !str_contains($invoicePresentation, 'match (strtolower($status))'),
'User invoice statuses must translate catalog tones, not rebuild semantics.');
$assert(str_contains($layoutAssets,
"venix_asset_version value='2026110201'")
"venix_asset_version value='2026110202'")
&& str_contains($template,
'/cloud/admin-billing.js?v={$venix_asset_version}'),
'Administrator billing asset changes must advance the shared cache key.');

@ -68,6 +68,10 @@ function fixture() {
assert.equal(locale, 'zh-CN'); assert.equal(options.hour12, false);
return this.toISOString().slice(11, 19);
}
toLocaleString(locale, options) {
assert.equal(locale, 'zh-CN'); assert.equal(options.hour12, false);
return this.toISOString().replace('T', ' ').slice(0, 19);
}
}
const timers = new Map(); const requests = [];
const setTimeout = (callback, delay = 0) => {
@ -114,7 +118,8 @@ function fixture() {
function announcement(id, changes = {}) {
return {
id: String(id), title: `公告 ${id}`, type: 'notice', type_label: '通知', body: `正文 ${id}`,
status: 'published', published_at: '2026-09-30 12:00:00', updated_at: '2026-09-30 12:00:00', ...changes,
status: 'published', published_at: '2026-09-30 12:00:00', updated_at: '2026-09-30 12:00:00',
published_at_epoch: 1790769600, updated_at_epoch: 1790769600, ...changes,
};
}
function page(items, number = 1, total = items.length) {
@ -135,6 +140,8 @@ function assertQuiet(test) {
await test.respond(page([unsafe]));
assert.equal(articles(test).length, 1); assert.match(test.nodes.list.textContent, /<script>alert\(1\)<\/script>/);
assert.equal(articles(test)[0].children.find(node => node.tagName === 'H3').textContent, unsafe.title);
assert.match(test.nodes.list.textContent, /发布于 2026-09-30 12:00:00/,
'Announcement publication time must be formatted from the canonical epoch in the browser.');
assertQuiet(test);
const renders = test.nodes.list.replacements;
test.nodes.scroll.scrollTop = 173; const scrollWrites = test.nodes.scroll.scrollWrites;

@ -121,6 +121,11 @@ namespace {
$page = Announcements::page($admin);
$assert($page['pagination']['total'] === 205 && count($page['items']) === 20
&& $page['filters']['status'] === 'all', 'Admin pagination lost historical announcements.');
$assert(is_int($page['items'][0]['published_at_epoch'])
&& $page['items'][0]['published_at_epoch'] > 0
&& is_int($page['items'][0]['updated_at_epoch'])
&& $page['items'][0]['updated_at_epoch'] > 0,
'Announcement DTO did not expose canonical epochs for browser-local display.');
$seen = [];
for ($pageNo = 1; $pageNo <= 21; $pageNo++) {
$published = Announcements::published($customer, ['page' => $pageNo]);
@ -142,6 +147,8 @@ namespace {
$input = ['title' => '维护通知 🛠', 'type' => 'maintenance', 'body' => "第一行\r\n第二行 <script>只是文本</script>", 'status' => 'published'];
$new = Announcements::save($super, $input);
$assert($new['type_label'] === '维护' && $new['status'] === 'published' && $new['published_at'] !== null
&& is_int($new['published_at_epoch']) && $new['published_at_epoch'] > 0
&& is_int($new['updated_at_epoch']) && $new['updated_at_epoch'] > 0
&& $new['body'] === "第一行\n第二行 <script>只是文本</script>", 'New announcement was not stored as literal plain text.');
$stored = $connection->table('announcement')->where('id', $new['id'])->first();
$assert(!property_exists($stored, 'content') && !property_exists($stored, 'markdown'), 'New schema retained legacy rich-text fields.');

@ -15,7 +15,7 @@ $assert = static function (bool $condition, string $message): void {
};
$assert(is_string($assets)
&& str_contains($assets, "venix_asset_version value='2026110201'")
&& str_contains($assets, "venix_asset_version value='2026110202'")
&& is_string($cloudShell)
&& str_contains($cloudShell, '/cloud/app.js?v={$venix_asset_version}'),
'The cloud application entry must use the shared Venix asset version.');

@ -82,6 +82,8 @@ $listStatusRefresh = $section($instances, 'async function refreshStatuses(',
'async function loadPage(');
$listPageLoad = $section($instances, 'async function loadPage(',
'function hydrate(');
$listHydrate = $section($instances, 'function hydrate()',
'function bindEvents(');
$listEvents = $section($instances, 'function bindEvents(',
'export async function initialize(');
$assert(str_contains($detail, 'hydrateVmDetailBootstrap(detailBootstrap())')
@ -152,6 +154,9 @@ $assert(str_contains($instances,
'const busy = state.loading || state.metadataLoading || state.statusLoading;')
&& str_contains($listPageLoad,
'await Promise.all([refreshMetadata(), refreshStatuses(true)]);')
&& str_contains($listHydrate, 'renderVms();')
&& strpos($listHydrate, 'renderVms();')
< strpos($listHydrate, 'updatePageUrl(state.pagination.page);')
&& str_contains($instances,
'await Promise.all([refreshMetadata(), refreshStatuses(true)]);')
&& str_contains($listStatusRefresh,
@ -176,6 +181,6 @@ $assert(str_contains($instances,
&& str_contains($instances, 'TRANSITION_POLL_INTERVAL = 3000')
&& str_contains($instances, 'Object.prototype.hasOwnProperty.call(update, field)')
&& !str_contains($instances, "api('/api/v1/vms')"),
'Each instance page must retain cache-only polling and bound live probes to shutdown convergence.');
'Each instance page must render browser-local bootstrap timestamps before retaining cache-only polling and bound live probes to shutdown convergence.');
echo "Cloud instance bulk-list and single-detail read paths passed.\n";

@ -45,6 +45,10 @@ const invoice = id => ({
status_label: `服务端状态-${id}`,
status_class: 'warning',
context_display: `服务端上下文-${id}`,
context_segments: [
{ kind: 'text', value: '对应实例到期 ' },
{ kind: 'timestamp', value: 2_000_100_000 },
],
show_fulfillment: true,
fulfillment_label: `服务端履约-${id}`,
fulfillment_class: 'running',
@ -145,14 +149,20 @@ const response = value => ({ ok: true, status: 200, json: async () => structured
assert.equal(page.state.invoices[0].id, '2');
assert.match(page.location.search, /keyword=second-vm/);
const rendered = page.nodes.get('invoices-list').textContent;
assert.match(rendered, /服务端时间-2/,
'Invoice list ignored the server-rendered creation time.');
assert.match(rendered, new RegExp(new Date(1000).toLocaleString(
'zh-CN', { hour12: false },
).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),
'Invoice list did not format the canonical creation timestamp in the browser.');
assert.doesNotMatch(rendered, /服务端时间-2/,
'Invoice list retained the panel-time creation string.');
assert.match(rendered, /\$10\.02/,
'Invoice list ignored the server-rendered amount.');
assert.match(rendered, /服务端状态-2/,
'Invoice list reinterpreted the canonical invoice status.');
assert.match(rendered, /服务端上下文-2/,
'Invoice list rebuilt its context from raw invoice fields.');
assert.match(rendered, /对应实例到期/,
'Invoice list ignored the server-owned context segments.');
assert.doesNotMatch(rendered, /服务端上下文-2/,
'Invoice list retained the panel-time context string.');
assert.match(rendered, /服务端履约-2/,
'Invoice list rebuilt its fulfillment state from raw task fields.');
assert.doesNotMatch(rendered, /\$999\.00/,

@ -49,7 +49,9 @@ $assert(count($rows) === 1
&& $rows[0]['status_class'] === 'warning'
&& $rows[0]['amount_display'] === '$12.51'
&& $rows[0]['polling_required'] === true
&& str_contains($rows[0]['context_display'], '最晚支付'),
&& str_contains($rows[0]['context_display'], '最晚支付')
&& ($rows[0]['context_segments'][1]['value'] ?? null) === 2_000_100_000
&& ($rows[0]['context_segments'][3]['value'] ?? null) === 2_000_359_200,
'Renewal grace summary did not preserve its canonical status and deadline.');
$wrongLegacyTitle = $renewal;
@ -73,6 +75,9 @@ $assert($detail['show_line_items'] === true
]
&& $detail['amount_display'] === '$12.51'
&& $detail['number_text'] === '账单 #17'
&& $detail['created_at'] === 2_000_000_000
&& ($detail['facts'][1]['timestamp'] ?? null) === 2_000_000_000
&& ($detail['facts'][2]['timestamp'] ?? null) === 2_000_100_000
&& str_starts_with($detail['created_text'], '创建于 ')
&& $detail['polling_required'] === false,
'Detail projection changed frozen line-item labels or authoritative total.');

@ -47,6 +47,10 @@ $view = CloudInvoicePresentation::detail($payload);
$assert(($view['show_line_items'] ?? false) === true,
'Invoice first paint does not expose its frozen line items.');
$assert(($view['created_at'] ?? null) === 2_000_000_000
&& ($view['facts'][1]['timestamp'] ?? null) === 2_000_000_000
&& ($view['facts'][2]['timestamp'] ?? null) === 2_000_100_000,
'Invoice presentation did not preserve canonical timestamps for browser-local display.');
$assert(($view['line_items'] ?? null) === [
['label' => '实例套餐续费', 'amount_display' => '$10.00'],
[
@ -149,6 +153,7 @@ $assert(is_string($detailRuntime) && is_string($listRuntime)
&& str_contains($detailRuntime, 'presentation?.fulfillment_label')
&& str_contains($detailRuntime, 'presentation?.polling_required')
&& str_contains($detailRuntime, 'function renderInvoiceDetail(presentation)')
&& str_contains($detailRuntime, "toLocaleString('zh-CN'")
&& !str_contains($detailRuntime,
'function renderInvoiceDetail(invoice, presentation)')
&& !str_contains($detailRuntime, 'function invoiceTitle(')
@ -163,6 +168,8 @@ $assert(is_string($detailRuntime) && is_string($listRuntime)
&& str_contains($listRuntime, 'invoice?.status_class')
&& str_contains($listRuntime, 'invoice?.fulfillment_label')
&& str_contains($listRuntime, 'invoice?.polling_required === true')
&& str_contains($listRuntime, 'invoice?.context_segments')
&& str_contains($listRuntime, "toLocaleString('zh-CN'")
&& str_contains($listRuntime, 'payload?.balance_display')
&& !str_contains($listRuntime, 'function formatUsd(')
&& !str_contains($listRuntime, 'function invoiceStatusInfo(')

@ -136,6 +136,11 @@ $assert(str_contains($script,
&& str_contains($script, 'pool.active_consumed_bytes')
&& str_contains($script, 'pool.available_bytes')
&& str_contains($script, 'pool.projection_ready === true')
&& str_contains($script,
'const hasBootstrap = Array.isArray(bootstrap?.line_pools);')
&& str_contains($script, 'if (hasBootstrap) applyPayload(bootstrap);')
&& strpos($script, 'if (hasBootstrap) applyPayload(bootstrap);')
< strpos($script, "initializeSession('traffic', bootstrap?.user)")
&& str_contains($script,
"fact('本周期总额度', formatBytes(instance.period_traffic_quota_bytes))")
&& str_contains($script,
@ -143,7 +148,7 @@ $assert(str_contains($script,
&& str_contains($script,
"fact('上传 TX', formatBytes(instance.traffic_upload_bytes))")
&& str_contains($script, "preparing: ['额度准备中', 'warning']"),
'Browser code must only refresh the server projection and must not mutate, sum or inject traffic data.');
'Browser code must immediately localise the server projection, then only refresh it without mutating, summing or injecting traffic data.');
$assert(str_contains($view, 'function trafficPools(')
&& str_contains($view, "\$payload['line_pools']")

@ -118,8 +118,18 @@ $assert(str_contains($sidebar, 'href="/user/cloud/backups"')
&& str_contains($backupScript,
"`/user/cloud/instances/\${encodeURIComponent(source.id)}?tab=settings&setting=automatic_backup`")
&& str_contains($backupScript, 'backup?.source_instance')
&& str_contains($backupScript,
'const hasBootstrap = Array.isArray(bootstrap?.items)')
&& strpos($backupScript, 'if (hasBootstrap) {')
< strpos($backupScript,
"initializeSession('backups', bootstrap?.user)")
&& str_contains($snapshotScript,
"api(`/api/v1/cloud-snapshots?page=")
&& str_contains($snapshotScript,
'const hasBootstrap = Array.isArray(bootstrap?.items)')
&& strpos($snapshotScript, 'if (hasBootstrap) {')
< strpos($snapshotScript,
"initializeSession('cloud-snapshots', bootstrap?.user)")
&& str_contains($snapshotScript,
'`/user/cloud/deploy?cloud_snapshot=${encodeURIComponent(key)}`')
&& str_contains($snapshotScript,

@ -11,6 +11,7 @@ use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\PaytaroProtocol;
use App\Services\Payment\PaytaroSigner;
use App\Services\Payment\PaymentOrderCreationException;
use App\Models\Code;
use App\Models\User;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
@ -652,6 +653,12 @@ if (strpos($adminHtml, 'action="/admin/paytaro/config"') === false
$rechargeTemplate = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/paytaro.tpl');
$userLayoutScripts = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/layout_scripts.tpl');
$rechargeScript = file_get_contents(dirname(__DIR__) . '/public/theme/venix/js/recharge.js');
$previousTimezone = date_default_timezone_get();
date_default_timezone_set('Asia/Shanghai');
$historyRecord = new Code();
$historyRecord->setRawAttributes(['usedatetime' => '2026-11-02 16:00:00']);
$historyEpoch = $historyRecord->used_at_timestamp;
date_default_timezone_set($previousTimezone);
if ($rechargeTemplate === false
|| $userLayoutScripts === false
|| $rechargeScript === false
@ -665,6 +672,11 @@ if ($rechargeTemplate === false
|| strpos($rechargeScript, 'topWindow().location.assign(mobileUrl)') === false
|| strpos($rechargeScript, 'function renderPaymentQr(') === false
|| strpos($rechargeScript, 'content.length > 1200 ? levels.L : levels.M') === false
|| strpos($rechargeTemplate, 'data-recharge-time') === false
|| strpos($rechargeTemplate, 'data-timestamp="{$code->used_at_timestamp|escape:') === false
|| strpos($rechargeScript, 'function renderBrowserTimes()') === false
|| strpos($rechargeScript, 'date.toLocaleString("zh-CN", { hour12: false })') === false
|| $historyEpoch !== 1793606400
|| strpos($userLayoutScripts, 'src="{$cdn}/theme/venix/js/qrcode.min.js?v={$vu_asset_version}"') === false) {
fwrite(STDERR, 'Paytaro mobile redirect policy failed.' . PHP_EOL);
exit(1);

@ -70,6 +70,14 @@ $assert(str_contains($userJavascript, 'window.VenixTicketUpload.mount(')
&& str_contains($userJavascript, 'window.VenixTicketUpload.submit(')
&& !str_contains($userJavascript, 'new FormData('),
'User ticket behavior bypasses the shared upload module.');
$assert(str_contains($userList, 'data-ticket-time')
&& str_contains($userList, 'lastActivityTimestamp()')
&& str_contains($userThread, 'data-timestamp="{$ticket->datetime_epoch|escape:')
&& str_contains($userThread, 'datetimeTimestamp()')
&& str_contains($userJavascript, 'localizeTicketTimes(document)')
&& str_contains($userJavascript, 'new Date(seconds * 1000)')
&& str_contains($userJavascript, 'toLocaleString("zh-CN", { hour12: false })'),
'User ticket timestamps are not localized from canonical epochs by the browser.');
$assert(str_contains($adminThreadJavascript, 'window.VenixTicketUpload.mount(')
&& str_contains($adminThreadJavascript, 'window.VenixTicketUpload.submit(')
&& str_contains($adminListJavascript, 'AbortController'),
@ -86,7 +94,7 @@ $assert(!str_contains($adminHomeCss, '.admin-ticket-thread')
&& str_contains($adminTicketCss, '.admin-ticket-thread')
&& str_contains($adminTicketCss, '.admin-ticket-preview-remove'),
'Administrator ticket-only styles are not isolated, or shared legacy primitives were removed.');
$assert(preg_match("/venix_asset_version value='2026110201'/", $assets) === 1,
$assert(preg_match("/venix_asset_version value='2026110202'/", $assets) === 1,
'Ticket asset extraction must advance the shared browser cache key.');
echo "Ticket frontend asset contract passed.\n";

@ -118,6 +118,9 @@ $assert(($adminThread['instance']->detail_url ?? null) === '/admin/cloud/instanc
$items = $thread['messages']->items();
$assert($items[0]->id === 12 && $items[0]->author_name === '管理员',
'The latest administrator reply was not projected first.');
$assert($items[0]->datetime_epoch === 112
&& $items[0]->datetime_iso === '1970-01-01T00:01:52+00:00',
'Ticket messages do not expose a canonical timestamp for browser-local display.');
$messageTwo = null;
foreach ($items as $item) {
if ($item->id === 2) {

@ -52,7 +52,7 @@ $assert(str_contains($adminCss, '.admin-ticket-table td[data-label]::before')
&& str_contains($adminCss, ':focus-visible')
&& str_contains($adminCss, 'prefers-reduced-motion: reduce'),
'Administrator ticket cards, focus treatment or reduced-motion support is missing.');
$assert(preg_match("/venix_asset_version value='2026110201'/", $assets) === 1,
$assert(preg_match("/venix_asset_version value='2026110202'/", $assets) === 1,
'Ticket workflow polish must advance the shared browser cache key.');
echo "Ticket workflow polish contract passed.\n";

@ -29,13 +29,15 @@ $now = time();
$items = [];
for ($id = 12; $id >= 1; --$id) {
$kind = $id === 12 ? 'maintenance' : ($id === 11 ? 'incident' : 'notice');
$publishedAt = '2026-09-' . str_pad((string) (17 + $id), 2, '0', STR_PAD_LEFT) . ' 10:00:00';
$items[] = ['id' => $id, 'title' => $id === 12 ? '香港区域计划维护通知' : ($id === 11 ? '区域网络故障说明' : '站点服务通知 ' . $id),
'type' => $kind, 'type_label' => ['notice' => '通知', 'maintenance' => '维护', 'incident' => '故障'][$kind],
'body' => $id === 12 ? "维护时间:2026-10-01 02:00 至 03:00(站点时间)。\n维护期间可能短暂中断,请提前保存工作。\n这是一条预览公告,不代表真实维护安排。"
: ($id === 11 ? "历史故障说明,仅用于预览。\nHTML 不执行:<img src=x onerror=alert(1)>\n<script>window.announcementUnsafe=1</script>"
: "服务通知正文。\n保持段落换行,使用原有用户页面主题。"),
'status' => 'published', 'published_at' => '2026-09-' . str_pad((string) (17 + $id), 2, '0', STR_PAD_LEFT) . ' 10:00:00',
'updated_at' => '2026-09-' . str_pad((string) (17 + $id), 2, '0', STR_PAD_LEFT) . ' 10:00:00'];
'status' => 'published', 'published_at' => $publishedAt,
'published_at_epoch' => strtotime($publishedAt),
'updated_at' => $publishedAt, 'updated_at_epoch' => strtotime($publishedAt)];
}
$pages = [];
foreach ([1, 2] as $page) {

Loading…
Cancel
Save