Add renewal billing and traffic views

dev
admin 2 months ago
parent c27fab1cff
commit 9689e386f0

@ -108,7 +108,7 @@ cd /home/virt-cloud/web
sudo -u apache php xcat cloudWorker --policy-only
```
账期、到期和流量限额前台调试:
账单提醒、账期、到期和流量限额前台调试:
```bash
cd /home/virt-cloud/web
@ -132,7 +132,7 @@ journalctl -u virt-cloud-engine -u virt-cloud-worker -u virt-cloud-lifecycle \
-u 'virt-cloud-policy-worker@*' -n 100 --no-pager
```
worker 使用 `/usr/bin/php`,须为 PHP 8.5,否则修改 unit。引擎使用一个 Uvicorn worker。普通 worker 负责购买、重装等任务,并可在策略 worker 缺失时兜底;两个策略 worker 专门处理到期停机、断网与恢复,不能省略。购买排队不执行时先检查 `virt-cloud-worker`;流量用尽不断网、账期不切换或到期不停机时同时检查 `virt-cloud-lifecycle` 与 `virt-cloud-policy-worker@1/@2`。PHP 网站由你现有的 Web/FPM 服务提供。`virt-cloud-update.service` 是按需启动的一次性服务,不要 `enable` 或手动常驻运行。
worker 使用 `/usr/bin/php`,须为 PHP 8.5,否则修改 unit。引擎使用一个 Uvicorn worker。普通 worker 负责购买、重装等任务和续费账单邮件投递,并可在策略 worker 缺失时兜底;两个策略 worker 专门处理到期停机、断网与恢复,不能省略。`virt-cloud-lifecycle` 只负责到期前 7 天生成续费账单和账期/流量策略;SMTP 发送与其隔离,不会阻塞到期停机。购买排队或提醒邮件不执行时先检查 `virt-cloud-worker`;账单不生成、流量用尽不断网、账期不切换或到期不停机时同时检查 `virt-cloud-lifecycle` 与 `virt-cloud-policy-worker@1/@2`。PHP 网站由你现有的 Web/FPM 服务提供。`virt-cloud-update.service` 是按需启动的一次性服务,不要 `enable` 或手动常驻运行。
## 6. 网站与控制台
@ -164,8 +164,8 @@ location = /engine-console {
1. 管理员添加宿主机:现有 SSH/root/私钥口令、核验指纹,设置区域、网桥、目录、地址池/网关/DNS/网卡前缀,测试连接。
2. 导入云镜像与救援模板;无已有模板不能开通云镜像 VM。云镜像 SHA-256 可留空;留空时仍会在下载后计算并保存实际摘要,填写时则会严格比对。预存其他系统图标不代表已实现其云模板导入;其他系统可用合适 ISO 安装,云镜像适配后续扩展。
3. 套餐设置规格、每期价格、账期天数、每期流量额度、库存和已启用宿主机。本版为手动余额续费,不自动扣费。
4. 测试用户注册/充值/购买/提前续费,验证任务、VM 控制台、SSH、重装、救援、删除与图表。
3. 套餐设置规格、每期价格、账期天数、每期流量额度、库存和已启用宿主机。实例到期前 7 天生成续费账单;用户可用余额支付,也可由启用的易支付、Paytaro 或 USDT 渠道直接生成支付订单。在线支付回调会自动结清对应账单,重复或晚到款保留在账户余额中。
4. 测试用户注册/充值/购买/账单支付,验证提醒邮件、到期停机与晚付恢复,以及任务、VM 控制台、SSH、重装、救援、删除与图表。
5. 日志库 `engine_vm_metric_samples` 应在所有用户退出后继续新增,`engine_vm_traffic_totals` 应持续累加 RX/TX 字节;稳定 MAC 用于跨 QEMU/tap 重启衔接计数,首批数据需等待采样间隔。
6. 用测试小额度验收:下载与上传合计达额度后 VM 仍运行但所有网卡断开;下一已付费周期开始后当期用量归零且网卡自动恢复。无下一周期时,最终到期才停机。

@ -12,7 +12,8 @@
PHP cloudWorker → 持久任务 → Python operation_id → 实例关联/核对/退款
Python 后台采集 → 日志库指标/持久流量基线 → 图表与字节计量
PHP cloudLifecycle → 独立账期/流量限额 → 幂等断网、恢复或最终到期停机
PHP cloudLifecycle → 续费账单/独立账期/流量限额 → 幂等断网、恢复或到期停机
PHP cloudWorker → 隔离投递账单提醒邮件 → SMTP 异常不阻塞到期策略
```
PHP 是唯一账户入口,所有用户页面使用原虚拟化面板 CSS;后台保留 venix。没有第二套 Python 注册、SMTP、数据库设置或审核流程。
@ -22,7 +23,7 @@ PHP 是唯一账户入口,所有用户页面使用原虚拟化面板 CSS;后
| 数据 | 权威写入方 | 存储 |
| --- | --- | --- |
| 用户、钱包、套餐、原财务/工单 | PHP | 原业务库表 |
| 宿主机索引、订单、实例、账期、续费、公钥、会话、任务 | PHP | `cloud_hosts/orders/instances/service_periods/renewals/ssh_keys/sessions/jobs` |
| 宿主机索引、订单、实例、账单、支付映射、账期、续费、公钥、会话、任务 | PHP | `cloud_hosts/orders/instances/invoices/invoice_payments/service_periods/renewals/ssh_keys/sessions/jobs` |
| 宿主机凭据、VM 元数据、镜像、操作进度 | Python | 主库 `engine_records`,敏感记录加密 |
| 引擎签名防重放 | Python | 主库 `engine_request_nonces` |
| 四项性能指标样本 | Python | 日志库 `engine_vm_metric_samples`,保留 30 天 |
@ -42,11 +43,11 @@ PHP 不直接解密 Python 记录或执行任意 virsh 命令。主库与日志
4. 成功关联实例和凭据;确认创建失败且无残留时只退款、恢复库存一次。
5. 超时、引擎中断或残留无法确认时保持待核对,只查询原操作,不重复创建或盲目退款。
金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。开通和每次手动续费都生成一个独立预付费周期;提前续费只排在已购周期末尾,不会提前刷新当期流量。每期额度为下载 RX + 上传 TX;用尽只持久断开网卡,VM 不关机;下一已付费周期开始时以新的累计基线归零当期用量并自动恢复网卡。只有无后续周期的最终到期才禁用自启并停机;到期后续费恢复服务和自启,但不会擅自开启用户已关机的 VM。
金额通过精确小数与整数最小单位换算处理,不用浮点完成扣款比较。套餐带宽转换成 libvirt 网卡双向 KiB/s 限制。到期前 7 天幂等生成一张续费账单和可重试邮件任务;账单可由余额结清,也可绑定现有在线支付订单。网关回调先入账余额并在同一事务结清账单,净余额为零;账单已结清或失效时晚到款保留为余额,不能重复续期或丢失。每次结清账单都生成一个独立预付费周期,提前支付只排在已购周期末尾,不会提前刷新当期流量。每期额度为下载 RX + 上传 TX;用尽只持久断开网卡,VM 不关机;下一已付费周期开始时以新的累计基线归零当期用量并自动恢复网卡。未支付账单不会延长到期时间,实例到期后停机;晚付后恢复服务和自启策略,但不会擅自开启用户已关机的 VM。
单台实例默认最多排队 24 个未来账期,可通过 `cloud_max_renewal_periods_ahead` 调整(服务端限制为 1–120)。这个上限在实例行锁内校验,避免免费套餐或自动化重复请求无限写入续费与账期记录。
本轮不含自动扣费、套餐升级、按日比例退款或自动删除到期 VM。流量依赖约 60 秒的宿主机采样,因此限额可能有一个采样间隔的少量超额;日志库不可读时采取 fail-open,不会因未知流量误停租户。
本轮不含免确认自动扣费、套餐升级、账单自动退款、按日比例退款或自动删除到期 VM。已生效服务账单不得通过支付渠道自动退款;需要人工审核并进行补偿记账。流量依赖约 60 秒的宿主机采样,因此限额可能有一个采样间隔的少量超额;日志库不可读时采取 fail-open,不会因未知流量误停租户。
## 安全与控制台

@ -1686,3 +1686,59 @@ def test_vm_metrics_requires_auth_validates_vm_and_isolates_host(tmp_path):
assert changed_host.status_code == 200
assert changed_host.json()["points"] == []
assert len(metric_store.calls) == before + 1
def test_vm_daily_traffic_uses_utc_days_and_validates_access_and_range(tmp_path):
state = PanelState(tmp_path / "panel-data")
manager = FakeRemoteManager()
service = FakeVMService()
class FakeMetricStore:
def __init__(self):
self.calls = []
def query_daily_traffic(self, scope, vm_id, **kwargs):
self.calls.append((scope, vm_id, kwargs))
return [{"day_start": 2_937_600, "download_bytes": 2048,
"upload_bytes": 1024, "total_bytes": 3072}]
metric_store = FakeMetricStore()
app = create_app(Settings(data_dir=state.data_dir, static_dir=STATIC_DIR),
panel_state=state, remote_manager=manager,
service_factory=lambda _profile: service,
metric_store=metric_store)
with TestClient(app, base_url=ORIGIN) as client:
endpoint = f"/api/v1/vms/{VM_ID}/traffic/daily"
assert client.get(endpoint).status_code == 401
token = state.token_file.read_text(encoding="ascii").strip()
csrf = setup_admin(client, token)
configure_host(client, csrf)
scope = host_scope(manager.current())
with patch("virsh_panel.app.time.time", return_value=3_000_000):
response = client.get(endpoint + "?days=2")
assert response.status_code == 200
body = response.json()
assert body == {
"vm_id": VM_ID, "days": 2, "timezone": "UTC",
"from": 2_851_200, "until": 3_000_000,
"points": [
{"date": "1970-02-03", "day_start": 2_851_200,
"download_bytes": None, "upload_bytes": None,
"total_bytes": None},
{"date": "1970-02-04", "day_start": 2_937_600,
"download_bytes": 2048, "upload_bytes": 1024,
"total_bytes": 3072},
],
}
assert metric_store.calls == [(scope, VM_ID, {
"host_id": None, "user_id": None,
"since": 2_851_200, "until": 3_000_000, "limit": 2,
})]
assert client.get(endpoint + "?days=0").status_code == 422
assert client.get(endpoint + "?days=31").status_code == 422
assert client.get("/api/v1/vms/not-a-uuid/traffic/daily").status_code == 400
assert client.get(
"/api/v1/vms/00000000-0000-4000-8000-000000000002/traffic/daily"
).status_code == 404

@ -37,6 +37,7 @@ class MemoryStore:
self.records = {}
self.nonces = set()
self.lock = threading.RLock()
self.daily_traffic_calls = []
def get(self, kind, key):
with self.lock:
@ -71,6 +72,12 @@ class MemoryStore:
def query_metric_samples(self, *args, **kwargs):
return [{"timestamp": 123, "cpu_percent": 20.0}]
def query_daily_traffic(self, scope, vm_id, **kwargs):
self.daily_traffic_calls.append((scope, vm_id, kwargs))
day_start = kwargs["until"] - kwargs["until"] % 86400
return [{"day_start": day_start, "download_bytes": 4096,
"upload_bytes": 1024, "total_bytes": 5120}]
def get_value(self, key):
return self.get("value", key)
@ -890,13 +897,35 @@ def test_service_suspend_does_not_stop_vm_when_running_hint_cannot_persist(
item[0] == "service_suspend" for item in services["hk"].calls)
def test_metrics_query_uses_log_store_and_owner_permission(boundary):
client, engine, *_ = boundary
client, engine, _, logs, _ = boundary
call(client, "GET", "/internal/v1/hosts/hk/vms")
component = engine.registry.components["hk"]
component.state.users.assign_vm(host_scope(component.manager.profile), VM_ID, 41)
scope = host_scope(component.manager.profile)
component.state.users.assign_vm(scope, VM_ID, 41)
response = call(client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/metrics?range=30d")
assert response.status_code == 200 and response.json()["points"][0]["cpu_percent"] == 20
with patch("virsh_panel.app.time.time", return_value=3_000_000):
traffic = call(
client, "GET",
f"/internal/v1/hosts/hk/vms/{VM_ID}/traffic/daily?days=2",
)
assert traffic.status_code == 200
assert traffic.json()["points"][-1] == {
"date": "1970-02-04", "day_start": 2_937_600,
"download_bytes": 4096, "upload_bytes": 1024, "total_bytes": 5120,
}
assert logs.daily_traffic_calls == [(scope, VM_ID, {
"host_id": "hk", "user_id": 41,
"since": 2_851_200, "until": 3_000_000, "limit": 2,
})]
denied = call(
client, "GET", f"/internal/v1/hosts/hk/vms/{VM_ID}/traffic/daily",
{**USER, "user_id": 42},
)
assert denied.status_code == 404
assert len(logs.daily_traffic_calls) == 1
def test_console_ticket_is_one_use_session_bound_and_no_url_secret(boundary):
client, engine, store, *_ = boundary

@ -4,6 +4,7 @@ from __future__ import annotations
import json
import threading
from decimal import Decimal
import pytest
@ -286,6 +287,38 @@ def test_metric_store_prunes_physically_and_queries_only_scoped_recent_data():
assert connection.commits == 2 and connection.closed
def test_daily_traffic_query_sums_scoped_owner_bytes_by_utc_day():
scope = host_scope({**HOST, "host_id": "hk"})
connection = FakeConnection([
{"day_start": Decimal(0), "download_bytes": Decimal(1500),
"upload_bytes": Decimal(250)},
{"day_start": Decimal(86400), "download_bytes": None,
"upload_bytes": None},
])
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: connection
result = store.query_daily_traffic(
scope, VM_ID, host_id="hk", user_id=41,
since=0, until=172799, limit=2,
)
assert result == [
{"day_start": 0, "download_bytes": 1500,
"upload_bytes": 250, "total_bytes": 1750},
{"day_start": 86400, "download_bytes": None,
"upload_bytes": None, "total_bytes": None},
]
query, args = connection.fake_cursor.commands[0]
assert "SUM(network_rx_bytes) AS download_bytes" in query
assert "SUM(network_tx_bytes) AS upload_bytes" in query
assert "host_scope=%s AND vm_uuid=%s" in query
assert "host_id <=> %s AND user_id <=> %s" in query
assert "GROUP BY FLOOR(sampled_at / 86400)" in query
assert args == (scope, VM_ID, "hk", 41, 0, 172799, 2)
assert connection.closed
class TrafficBackend:
"""Tiny transaction fake for durable accounting behavior tests."""
def __init__(self):
@ -527,6 +560,23 @@ def test_metric_store_rejects_invalid_host_and_uuid_before_db_query():
interval_seconds=60)
def test_daily_traffic_query_rejects_invalid_identity_owner_and_range_before_db():
store = DatabaseStore.__new__(DatabaseStore)
store._connect = lambda: pytest.fail("invalid daily query must not reach database")
scope = host_scope(HOST)
common = {"host_id": "hk", "user_id": 41, "since": 0, "until": 1}
for vm_scope, vm_id, changes in (
("bad-scope", VM_ID, {}),
(scope, "not-a-uuid", {}),
(scope, VM_ID, {"host_id": "bad host"}),
(scope, VM_ID, {"user_id": 0}),
(scope, VM_ID, {"until": 30 * 86400 + 1}),
(scope, VM_ID, {"limit": 31}),
):
with pytest.raises(ValueError):
store.query_daily_traffic(vm_scope, vm_id, **{**common, **changes})
def test_collector_prunes_when_ssh_locked_and_starts_after_db_configuration():
class Store:
def __init__(self):

@ -1870,6 +1870,54 @@ def create_app(
return {"vm_id": canonical_id, "range": range_,
"interval_seconds": interval, "points": points}
@app.get("/api/v1/vms/{vm_id}/traffic/daily")
def get_vm_daily_traffic(
vm_id: str,
days: int = Query(30, ge=1, le=30),
_session: Session = Depends(require_approved),
):
try:
canonical_id = str(uuid.UUID(vm_id))
except (TypeError, ValueError, AttributeError) as exc:
raise VMError("虚拟机 UUID 无效", 400) from exc
profile = current_profile()
require_vm_access(_session, profile, canonical_id)
# Match the metrics endpoint's live inventory check before consulting
# retained rows. The owner and host filters below isolate old tenants.
new_service(profile).get_vm(canonical_id)
backend = metric_store if metric_store is not None else data_store
if backend is None:
raise HTTPException(status_code=503, detail="指标数据库尚未就绪")
try:
scope = host_scope(profile)
except (KeyError, ValueError, TypeError) as exc:
raise HTTPException(status_code=409, detail="宿主机身份信息不完整") from exc
owner_id = (state.users.owner_of_vm(scope, canonical_id)
if database_mode else None)
configured_host_id = profile.get("host_id")
metric_host_id = configured_host_id if isinstance(configured_host_id, str) else None
now = int(time.time())
day_seconds = 24 * 60 * 60
today_start = now - now % day_seconds
since = max(0, today_start - (days - 1) * day_seconds)
rows = backend.query_daily_traffic(
scope, canonical_id, host_id=metric_host_id, user_id=owner_id,
since=since, until=now, limit=days,
)
by_day = {int(row["day_start"]): row for row in rows}
points = []
for day_start in range(since, today_start + 1, day_seconds):
row = by_day.get(day_start)
points.append({
"date": time.strftime("%Y-%m-%d", time.gmtime(day_start)),
"day_start": day_start,
"download_bytes": row.get("download_bytes") if row else None,
"upload_bytes": row.get("upload_bytes") if row else None,
"total_bytes": row.get("total_bytes") if row else None,
})
return {"vm_id": canonical_id, "days": days, "timezone": "UTC",
"from": since, "until": now, "points": points}
@app.post("/api/v1/vms", status_code=201)
def create_vm(body: CreateISOBody | CreateCloudBody,
_session: Session = Depends(require_approved_write)):

@ -23,6 +23,7 @@ import threading
import time
import uuid
from dataclasses import replace
from decimal import Decimal
from pathlib import Path
from typing import Any, Mapping
from urllib.parse import quote
@ -546,6 +547,82 @@ class DatabaseStore:
finally:
connection.close()
@staticmethod
def _daily_traffic_value(value: Any) -> int | None:
if value is None:
return None
if isinstance(value, bool):
raise DatabaseError("虚拟机流量统计数据损坏")
if isinstance(value, Decimal):
if not value.is_finite() or value != value.to_integral_value():
raise DatabaseError("虚拟机流量统计数据损坏")
result = int(value)
elif isinstance(value, int):
result = value
else:
raise DatabaseError("虚拟机流量统计数据损坏")
if result < 0 or result > _MAX_UNSIGNED_BIGINT:
raise DatabaseError("虚拟机流量统计数据损坏")
return result
def query_daily_traffic(self, host_scope: str, vm_id: str, *,
host_id: str | None, user_id: int | None,
since: int, until: int,
limit: int = 30) -> list[dict[str, Any]]:
"""Sum per-observation RX/TX byte deltas into UTC calendar days."""
vm_id = self._metric_identity(host_scope, vm_id)
if (any(isinstance(value, bool) or not isinstance(value, int)
for value in (since, until, limit))
or since < 0 or until < since or until > _MAX_UNSIGNED_BIGINT
or until - since > 30 * 24 * 60 * 60
or not 1 <= limit <= 30):
raise ValueError("Daily traffic query range is invalid")
if host_id is not None and (not isinstance(host_id, str)
or not _HOST_ID.fullmatch(host_id)):
raise ValueError("Daily traffic host ID is invalid")
if user_id is not None and (isinstance(user_id, bool)
or not isinstance(user_id, int)
or user_id < 1
or user_id > _MAX_UNSIGNED_BIGINT):
raise ValueError("Daily traffic user ID is invalid")
connection = self._connect()
try:
with connection.cursor() as cursor:
cursor.execute(
"SELECT FLOOR(sampled_at / 86400) * 86400 AS day_start, "
"SUM(network_rx_bytes) AS download_bytes, "
"SUM(network_tx_bytes) AS upload_bytes "
f"FROM {self.METRIC_TABLE} "
"WHERE host_scope=%s AND vm_uuid=%s "
"AND host_id <=> %s AND user_id <=> %s "
"AND sampled_at >= %s AND sampled_at <= %s "
"GROUP BY FLOOR(sampled_at / 86400) "
"ORDER BY day_start ASC LIMIT %s",
(host_scope, vm_id, host_id, user_id, since, until, limit),
)
rows = cursor.fetchall()
result = []
for row in rows:
if not isinstance(row, Mapping):
raise DatabaseError("虚拟机流量统计数据损坏")
day_start = self._daily_traffic_value(row.get("day_start"))
if day_start is None or day_start % 86400:
raise DatabaseError("虚拟机流量统计数据损坏")
download = self._daily_traffic_value(row.get("download_bytes"))
upload = self._daily_traffic_value(row.get("upload_bytes"))
result.append({
"day_start": day_start,
"download_bytes": download,
"upload_bytes": upload,
"total_bytes": (download + upload
if download is not None and upload is not None else None),
})
return result
except pymysql.MySQLError as exc:
raise DatabaseError("无法读取虚拟机每日流量") from exc
finally:
connection.close()
def _encrypt(self, record_type: str, record_key: str, value: str) -> bytes:
if not isinstance(value, str):
raise TypeError("Database value must be a string")

@ -39,7 +39,7 @@ VM_ID = r"[0-9a-fA-F-]{36}"
JSON_LIMIT = 1024 * 1024
READ_PATHS = (
r"host", r"resources", r"vm-templates", r"rescue-templates", r"vms",
rf"vms/{VM_ID}(?:/metrics|/rescue)?",
rf"vms/{VM_ID}(?:/metrics|/traffic/daily|/rescue)?",
r"(?:reinstall-jobs|rescue-jobs|vm-templates/import-jobs|rescue-templates/import-jobs)/[A-Za-z0-9_-]+",
)
WRITE_PATHS = {

@ -2,6 +2,6 @@
仅保留 venix 主题及通用账户、邮箱、工单、公告、充值和财务能力。
用户侧旧节点列表已经删除;管理员在 `/admin/hosts` 配置宿主机。
商城套餐现在是 CPU、内存、带宽、硬盘、账期天数和每期流量额度,通过私有 Python/libvirt 引擎开通实例。支持手动续费、到期停机以及流量用尽仅断网;生产必须同时运行账期 worker 与独立策略 worker。
商城套餐现在是 CPU、内存、带宽、硬盘、账期天数和每期流量额度,通过私有 Python/libvirt 引擎开通实例。到期前 7 天生成续费账单,可使用余额或已启用的在线支付渠道结清;支持到期停机以及流量用尽仅断网。生产必须同时运行普通 worker、账期 worker 与独立策略 worker。
部署与安全边界见上层 `docs/DEPLOYMENT.md` 和 `docs/INTEGRATION_PLAN.md`。真实数据库、宿主机与支付通道仍必须在测试环境验收后再开放销售。

@ -48,6 +48,7 @@ final class CloudSetup
});
}
self::upgradeCloudInstance($connection);
self::upgradeInvoicePayments($connection);
User::getConnectionResolver()->connection('log')->unprepared(self::schema('cloud_log.sql'));
self::exportEngineConfig();
echo "虚拟化业务表、指标日志表与私有引擎配置已准备。未连接或修改任何宿主机。\n";
@ -89,6 +90,19 @@ final class CloudSetup
. 'cloud_job_instance_state (instance_id, status, id)');
}
private static function upgradeInvoicePayments($connection): void
{
// Payment-provider tables are optional. When they are already
// installed, cloudInit only verifies that the common provider order
// identifiers required by invoice payment mapping remain available.
foreach (['yipay_orders', 'paytaro_orders', 'usdt_payment_orders'] as $table) {
if ($connection->getSchemaBuilder()->hasTable($table)
&& !$connection->getSchemaBuilder()->hasColumn($table, 'order_no')) {
throw new \RuntimeException('支付表缺少商户订单号字段:' . $table);
}
}
}
public static function exportEngineConfig(): bool
{
if (Config::get('enable_log', 'false') !== 'true') {

@ -2,6 +2,7 @@
namespace App\Command;
use App\Services\Cloud\CloudWorkerService;
use App\Services\Cloud\CloudInvoiceService;
final class CloudWorker
{
@ -20,6 +21,16 @@ final class CloudWorker
}
$worked = false;
}
// SMTP is deliberately isolated from the lifecycle process so a
// slow mail server can never delay expiry or traffic policies.
if (!$policyOnly) {
try {
CloudInvoiceService::deliverReminders(1);
} catch (\Throwable $error) {
fwrite(STDERR, 'cloud invoice mail temporarily unavailable: '
. get_class($error) . PHP_EOL);
}
}
if (!$once && !$worked) {
usleep(1000000);
}

@ -3,6 +3,7 @@ namespace App\Controllers;
use App\Models\CloudHost;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudOrder;
use App\Models\CloudServicePeriod;
@ -16,8 +17,9 @@ use App\Services\Cloud\CloudEngineClient;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInput;
use App\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudInvoiceService;
use App\Services\Cloud\CloudOrderService;
use App\Services\Cloud\CloudRenewalService;
use App\Services\Cloud\CloudSecrets;
use App\Services\Cloud\CloudSSHKeys;
@ -113,6 +115,61 @@ final class CloudApiController
return $this->json($response, ['order' => CloudOrderService::display($order)]);
}
public function invoices($request, $response)
{
$actor = $this->actor($request);
$user = Auth::getUser();
$invoices = CloudInvoice::where('user_id', $actor['user_id'])
->orderByDesc('due_at')->orderByDesc('id')->limit(200)->get()
->map(fn ($invoice) => CloudInvoiceService::display($invoice))->all();
return $this->json($response, ['invoices' => $invoices,
'payment_methods' => CloudInvoicePaymentService::methods($user),
'balance' => (string) $user->money]);
}
public function invoice($request, $response, $args)
{
$actor = $this->actor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])->first();
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
return $this->json($response, ['invoice' => CloudInvoiceService::display($invoice)]);
}
public function payInvoice($request, $response, $args)
{
$actor = $this->actor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])->first();
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
$body = CloudInput::object($request);
CloudInput::only($body, ['idempotency_key']);
$paid = CloudInvoiceService::payBalance($invoice, $actor,
trim((string) ($body['idempotency_key'] ?? '')));
$user = Auth::getUser()->fresh();
return $this->json($response, ['invoice' => CloudInvoiceService::display($paid),
'balance' => (string) $user->money]);
}
public function createInvoicePayment($request, $response, $args)
{
$actor = $this->actor($request);
$invoice = CloudInvoice::where('id', $args['id'])
->where('user_id', $actor['user_id'])->first();
if ($invoice === null) {
throw new CloudError('账单不存在', 404);
}
$payment = CloudInvoicePaymentService::create($invoice, Auth::getUser(),
CloudInput::object($request),
(string) $request->getServerParam('REMOTE_ADDR', ''),
(string) $request->getHeaderLine('User-Agent'));
return $this->json($response, ['payment' => $payment], 201);
}
public function job($request, $response, $args)
{
$actor = $this->actor($request);
@ -207,6 +264,24 @@ final class CloudApiController
'vms/' . rawurlencode($instance->uuid) . '/metrics' . $suffix, $actor));
}
public function dailyTraffic($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor);
$rawDays = $request->getQueryParams()['days'] ?? '30';
if (!is_string($rawDays) && !is_int($rawDays)) {
throw new CloudError('流量统计天数无效');
}
$days = filter_var((string) $rawDays, FILTER_VALIDATE_INT,
['options' => ['min_range' => 1, 'max_range' => 30]]);
if ($days === false) {
throw new CloudError('流量统计天数必须为 1 至 30');
}
return $this->json($response, (new CloudEngineClient())->host((int) $instance->host_id,
'GET', 'vms/' . rawurlencode($instance->uuid) . '/traffic/daily?days=' . (int) $days,
$actor));
}
public function credential($request, $response, $args)
{
$instance = CloudAccess::instance($args['id'], $this->actor($request), true);
@ -291,14 +366,6 @@ final class CloudApiController
return $this->json($response, ['job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id], 202);
}
public function renew($request, $response, $args)
{
$actor = $this->actor($request);
$instance = CloudAccess::instance($args['id'], $actor, true);
$renewal = CloudRenewalService::renew($instance, CloudInput::object($request), $actor);
return $this->json($response, ['renewal' => CloudRenewalService::display($renewal)], 201);
}
private function requireService(CloudInstance $instance, array $actor): void
{
$global = ($actor['is_super_admin'] ?? false) && ($actor['can_manage'] ?? false);

@ -2,6 +2,7 @@
namespace App\Controllers;
use App\Models\CloudInvoicePayment;
use App\Models\Configurations;
use App\Models\PaytaroOrder;
use App\Services\Auth;
@ -49,7 +50,13 @@ class PaytaroController extends BaseController
if (!$user->isLogin) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$order = PaytaroOrder::where('user_id', (int) $user->id)->orderBy('id', 'desc')->first();
$order = PaytaroOrder::where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoice_payments')
->whereColumn('cloud_invoice_payments.provider_order_no', 'paytaro_orders.order_no')
->where('cloud_invoice_payments.provider', 'paytaro');
})
->orderBy('id', 'desc')->first();
if ($order === null) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
@ -86,6 +93,10 @@ class PaytaroController extends BaseController
if (!PaytaroOrder::where('order_no', $orderNo)->exists()) {
return $this->plain($response, '订单不存在', 404);
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->where('provider', 'paytaro')->exists()) {
return $response->withRedirect('/user/cloud#invoices', 302);
}
return $response->withRedirect('/user/code?payment=paytaro', 302);
} catch (\Throwable $exception) {
error_log('Paytaro return rejected: ' . $exception->getMessage());

@ -56,6 +56,11 @@ class UsdtController extends BaseController
$order = UsdtPaymentOrder::where('business_type', 'recharge')
->where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoice_payments')
->whereColumn('cloud_invoice_payments.provider_order_no', 'usdt_payment_orders.order_no')
->where('cloud_invoice_payments.provider', 'usdt');
})
->orderBy('id', 'desc')
->first();
if ($order === null) {

@ -2,6 +2,7 @@
namespace App\Controllers;
use App\Models\CloudInvoicePayment;
use App\Models\Configurations;
use App\Models\YipayOrder;
use App\Services\Auth;
@ -53,7 +54,13 @@ class YipayController extends BaseController
if (!$user->isLogin) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
$order = YipayOrder::where('user_id', (int) $user->id)->orderBy('id', 'desc')->first();
$order = YipayOrder::where('user_id', (int) $user->id)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoice_payments')
->whereColumn('cloud_invoice_payments.provider_order_no', 'yipay_orders.order_no')
->whereIn('cloud_invoice_payments.provider', ['yipay_alipay', 'yipay_wxpay']);
})
->orderBy('id', 'desc')->first();
if ($order === null) {
return $this->json($response, ['ret' => 0, 'result' => 0, 'status' => 'not_found'], 404);
}
@ -91,6 +98,10 @@ class YipayController extends BaseController
if ($order === null) {
return $this->plain($response, '订单不存在', 404);
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->where('provider', 'yipay_' . (string) $order->payment_type)->exists()) {
return $response->withRedirect('/user/cloud#invoices', 302);
}
return $response->withRedirect('/user/code?payment=yipay', 302);
} catch (\Throwable $exception) {
error_log('Yipay return rejected: ' . $exception->getMessage());

@ -0,0 +1,9 @@
<?php
namespace App\Models;
final class CloudInvoice extends Model
{
protected $connection = 'default';
protected $table = 'cloud_invoices';
protected $casts = ['amount' => 'decimal:2'];
}

@ -0,0 +1,9 @@
<?php
namespace App\Models;
final class CloudInvoicePayment extends Model
{
protected $connection = 'default';
protected $table = 'cloud_invoice_payments';
protected $casts = ['amount' => 'decimal:2'];
}

@ -0,0 +1,8 @@
<?php
namespace App\Models;
final class CloudMailOutbox extends Model
{
protected $connection = 'default';
protected $table = 'cloud_mail_outbox';
}

@ -0,0 +1,259 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudInstance;
use App\Models\PaytaroOrder;
use App\Models\UsdtPaymentOrder;
use App\Models\User;
use App\Models\YipayOrder;
use App\Services\Config;
use App\Services\Payment\PaytaroConfig;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayPaymentService;
use App\Services\UserFeatureRestrictionService;
final class CloudInvoicePaymentService
{
public static function methods(User $user): array
{
if (UserFeatureRestrictionService::isRechargeRestricted($user)
|| UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
return [];
}
$methods = [];
foreach (YipayConfig::visibleMethods($user) as $method) {
$methods[] = ['id' => 'yipay_' . $method,
'name' => $method === 'wxpay' ? '易支付 · 微信' : '易支付 · 支付宝'];
}
if (PaytaroConfig::isUserVisible($user)) {
$methods[] = ['id' => 'paytaro', 'name' => 'Paytaro · 支付宝'];
}
if (UsdtConfig::isUserVisible($user)) {
$methods[] = ['id' => 'usdt', 'name' => 'USDT-TRC20'];
}
return $methods;
}
public static function create(CloudInvoice $invoice, User $user, array $input,
string $clientIp, string $userAgent): array
{
CloudInput::only($input, ['method', 'idempotency_key']);
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
if ((int) $invoice->user_id !== (int) $user->id
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)) {
throw new CloudError('账单不存在或已结清', 404);
}
$instance = CloudInstance::where('id', $invoice->instance_id)
->where('user_id', $user->id)->where('status', '<>', 'deleted')->first();
if ($instance === null || $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| $instance->renewal_price === null
|| CloudMoney::cents((string) $instance->renewal_price)
!== CloudMoney::cents((string) $invoice->amount)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes
!== (int) $invoice->traffic_quota_bytes) {
// Never save the controller's stale model here: a concurrent
// balance/provider settlement may already have marked it paid.
CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)
->whereIn('status', ['open', 'overdue'])
->update(['status' => 'void', 'updated_at' => time()]);
throw new CloudError('账单已失效,请刷新账单列表', 409);
}
$method = strtolower(trim((string) ($input['method'] ?? '')));
$allowed = array_column(self::methods($user), 'id');
if (!in_array($method, $allowed, true)) {
throw new CloudError('所选在线支付方式不可用', 409);
}
$idempotency = trim((string) ($input['idempotency_key'] ?? ''));
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('支付请求标识无效');
}
$existing = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if ((int) $existing->invoice_id !== (int) $invoice->id
|| (string) $existing->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
$existing = self::recoverCreatingAttempt($existing);
if ((string) $existing->status === 'creating') {
throw new CloudError('支付订单正在创建,请稍后刷新账单再试', 409);
}
if ((string) $existing->status === 'failed') {
throw new CloudError('上次支付订单创建失败,请重新发起支付', 409);
}
return self::display($existing);
}
$baseUrl = rtrim((string) Config::get('baseUrl', ''), '/');
if (filter_var($baseUrl, FILTER_VALIDATE_URL) === false
|| preg_match('#^https://#i', $baseUrl) !== 1) {
throw new CloudError('站点 HTTPS 地址未正确配置,不能创建在线支付', 409);
}
$context = ['invoice_id' => (int) $invoice->id,
'idempotency_key' => $idempotency, 'provider' => $method];
try {
if (str_starts_with($method, 'yipay_')) {
$order = (new YipayPaymentService())->createOrder($user, (string) $invoice->amount,
substr($method, 6), $clientIp, $userAgent, $baseUrl, $context);
} elseif ($method === 'paytaro') {
$order = (new PaytaroPaymentService())->createOrder($user, (string) $invoice->amount,
$clientIp, $userAgent, $baseUrl, $context);
} else {
$order = (new UsdtPaymentService())->createInvoiceOrder(
$user, (string) $invoice->amount, $context);
}
CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->where('status', 'creating')
->update(['status' => 'pending', 'updated_at' => time()]);
} catch (\Throwable $error) {
// A concurrent request with the same idempotency key may have won
// the unique insert. Never mutate that request's attempt here.
$winner = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($winner !== null) {
if ((int) $winner->invoice_id !== (int) $invoice->id
|| (string) $winner->provider !== $method) {
throw new CloudError('同一支付请求标识不能用于其他账单或渠道', 409);
}
$winner = self::recoverCreatingAttempt($winner);
if (!in_array((string) $winner->status, ['creating', 'failed'], true)) {
return self::display($winner);
}
if ((string) $winner->status === 'creating') {
throw new CloudError('支付订单正在创建,请稍后刷新账单再试', 409);
}
}
throw $error;
}
$payment = CloudInvoicePayment::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($payment === null) {
throw new \RuntimeException('在线支付关联记录创建失败');
}
return self::display($payment);
}
private static function recoverCreatingAttempt(
CloudInvoicePayment $payment
): CloudInvoicePayment {
if (!in_array((string) $payment->status, ['creating', 'pending'], true)) {
return $payment;
}
$provider = (string) $payment->provider;
if (str_starts_with($provider, 'yipay_')) {
$providerStatus = YipayOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
} elseif ($provider === 'paytaro') {
$providerStatus = PaytaroOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
} else {
$providerStatus = UsdtPaymentOrder::where(
'order_no', $payment->provider_order_no
)->value('status');
}
if (in_array((string) $providerStatus, ['pending', 'paid'], true)) {
CloudInvoicePayment::where('id', $payment->id)
->where('status', 'creating')
->update(['status' => 'pending', 'updated_at' => time()]);
} elseif (in_array((string) $providerStatus, ['failed', 'expired'], true)) {
CloudInvoicePayment::where('id', $payment->id)
->whereIn('status', ['creating', 'pending'])
->update(['status' => 'failed', 'updated_at' => time()]);
}
return $payment->fresh() ?? $payment;
}
public static function recordAttempt(array $context, string $orderNo, string $amount,
int $userId, int $now): void
{
if ($context === []) {
return;
}
$provider = (string) ($context['provider'] ?? '');
$idempotency = (string) ($context['idempotency_key'] ?? '');
$invoiceId = (int) ($context['invoice_id'] ?? 0);
if ($invoiceId < 1 || !in_array($provider,
['yipay_alipay', 'yipay_wxpay', 'paytaro', 'usdt'], true)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new \RuntimeException('账单支付上下文无效');
}
$payment = new CloudInvoicePayment();
$payment->invoice_id = $invoiceId;
$payment->user_id = $userId;
$payment->provider = $provider;
$payment->provider_order_no = $orderNo;
$payment->idempotency_key = $idempotency;
$payment->amount = $amount;
$payment->status = 'creating';
$payment->created_at = $payment->updated_at = $now;
$payment->save();
}
public static function settleForProvider(string $provider, string $orderNo): ?string
{
$payment = CloudInvoicePayment::where('provider', $provider)
->where('provider_order_no', $orderNo)->lockForUpdate()->first();
if ($payment === null) {
return null;
}
if (in_array((string) $payment->status, ['paid_invoice', 'credited_balance'], true)) {
return (string) $payment->status;
}
return CloudInvoiceService::settleCreditedPayment($payment);
}
public static function display(CloudInvoicePayment $payment): array
{
$provider = (string) $payment->provider;
$result = [
'id' => (string) $payment->id,
'invoice_id' => (string) $payment->invoice_id,
'method' => $provider,
'status' => (string) $payment->status,
'amount' => (string) $payment->amount,
'poll_url' => '/api/v1/invoices/' . (int) $payment->invoice_id,
];
if (str_starts_with($provider, 'yipay_')) {
$order = YipayOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => $provider === 'yipay_wxpay'
? '易支付 · 微信' : '易支付 · 支付宝']);
}
if ($provider === 'paytaro') {
$order = PaytaroOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('在线支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => (string) $order->payment_kind,
'payment_value' => (string) $order->payment_value,
'label' => 'Paytaro · 支付宝']);
}
$order = UsdtPaymentOrder::where('order_no', $payment->provider_order_no)->first();
if ($order === null) {
throw new CloudError('USDT 支付订单不存在', 404);
}
return array_merge($result, ['payment_kind' => 'usdt', 'label' => 'USDT-TRC20',
'actual_amount' => (string) $order->actual_amount,
'receive_address' => (string) $order->receive_address,
'expires_at' => (int) $order->expires_at]);
}
}

@ -0,0 +1,332 @@
<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudMailOutbox;
use App\Models\CloudRenewal;
use App\Models\User;
use App\Services\Config;
use App\Services\Mail;
final class CloudInvoiceService
{
public const REMINDER_SECONDS = 7 * 86400;
public static function issueDue(int $limit = 200): int
{
$now = time();
$ids = CloudInstance::where('status', '<>', 'deleted')
->where('service_status', '<>', 'exempt')
->whereNotNull('expires_at')
->whereNotNull('renewal_price')
->where('renewal_days', '>', 0)
->where('expires_at', '<=', $now + self::REMINDER_SECONDS)
->whereNotExists(function ($query) {
$query->selectRaw('1')->from('cloud_invoices')
->whereColumn('cloud_invoices.instance_id', 'cloud_instances.id')
->whereColumn('cloud_invoices.renews_expires_at', 'cloud_instances.expires_at')
->where('cloud_invoices.status', '<>', 'void');
})
->orderBy('expires_at')->orderBy('id')
->limit(max(1, min(1000, $limit)))
->pluck('id')->all();
$created = 0;
foreach ($ids as $id) {
try {
$created += self::issueOne((int) $id, $now) ? 1 : 0;
} catch (\Throwable $error) {
error_log('cloud invoice generation failed for instance ' . (int) $id
. ': ' . get_class($error));
}
}
return $created;
}
private static function issueOne(int $instanceId, int $now): bool
{
return (new CloudInstance())->getConnection()->transaction(function () use ($instanceId, $now) {
$instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first();
if ($instance === null || (string) $instance->status === 'deleted'
|| (string) $instance->service_status === 'exempt'
|| $instance->expires_at === null || $instance->renewal_price === null
|| (int) $instance->renewal_days < 1
|| (int) $instance->expires_at > $now + self::REMINDER_SECONDS) {
return false;
}
$expiry = (int) $instance->expires_at;
if (CloudInvoice::where('instance_id', $instance->id)
->where('renews_expires_at', $expiry)
->where('status', '<>', 'void')->exists()) {
return false;
}
$amount = CloudMoney::decimal(CloudMoney::cents((string) $instance->renewal_price));
$invoice = new CloudInvoice();
$invoice->invoice_no = self::invoiceNumber();
$invoice->instance_id = $instance->id;
$invoice->user_id = $instance->user_id;
$invoice->plan_id = $instance->plan_id;
$invoice->renewal_id = null;
$invoice->renews_expires_at = $expiry;
$invoice->due_at = $expiry;
$invoice->amount = $amount;
$invoice->validity_days = (int) $instance->renewal_days;
$invoice->traffic_quota_bytes = max(0, (int) $instance->renewal_traffic_bytes);
$invoice->status = 'open';
$invoice->paid_via = null;
$invoice->payment_reference = null;
$invoice->paid_at = null;
$invoice->created_at = $invoice->updated_at = $now;
$invoice->save();
$mail = new CloudMailOutbox();
$mail->invoice_id = $invoice->id;
$mail->kind = 'renewal_due';
$mail->status = 'pending';
$mail->attempts = 0;
$mail->available_at = $now;
$mail->lease_token = null;
$mail->lease_until = 0;
$mail->sent_at = null;
$mail->last_error = '';
$mail->created_at = $mail->updated_at = $now;
$mail->save();
return true;
}, 3);
}
public static function deliverReminders(int $limit = 20): int
{
$sent = 0;
for ($index = 0; $index < max(1, min(100, $limit)); $index++) {
$claimed = self::claimMail();
if ($claimed === null) {
break;
}
[$message, $token] = $claimed;
$invoice = CloudInvoice::find($message->invoice_id);
$user = $invoice === null ? null : User::find($invoice->user_id);
$instance = $invoice === null ? null : CloudInstance::find($invoice->instance_id);
$ok = false;
$error = '';
$cancel = false;
if ($invoice === null || $user === null || $instance === null
|| (string) $instance->status === 'deleted'
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)) {
$error = '账单或收件人已不可用';
$cancel = true;
} elseif (filter_var((string) $user->email, FILTER_VALIDATE_EMAIL) === false) {
$error = '用户邮箱无效';
} else {
$base = rtrim((string) Config::get('baseUrl', ''), '/');
$ok = Mail::send((string) $user->email, '云服务器续费账单提醒',
'cloud/invoice.tpl', [
'invoice_no' => (string) $invoice->invoice_no,
'instance_name' => (string) $instance->name,
'amount' => (string) $invoice->amount,
'due_at' => date('Y-m-d H:i:s', (int) $invoice->due_at),
'invoice_url' => $base . '/user/cloud#invoices',
], [], 'cloud_renewal_invoice');
if (!$ok) {
$error = '邮件服务未接受消息';
}
}
self::finishMail((int) $message->id, $token, $ok, $error, $cancel);
$sent += $ok ? 1 : 0;
}
return $sent;
}
private static function claimMail(): ?array
{
return (new CloudMailOutbox())->getConnection()->transaction(function () {
$now = time();
$message = CloudMailOutbox::where(function ($query) use ($now) {
$query->where('status', 'pending')
->orWhere(function ($leased) use ($now) {
$leased->where('status', 'sending')->where('lease_until', '<=', $now);
});
})->where('available_at', '<=', $now)
->orderBy('id')->lockForUpdate()->first();
if ($message === null) {
return null;
}
$token = bin2hex(random_bytes(16));
$message->status = 'sending';
$message->lease_token = $token;
$message->lease_until = $now + 300;
$message->updated_at = $now;
$message->save();
return [$message, $token];
}, 3);
}
private static function finishMail(int $id, string $token, bool $ok, string $error,
bool $cancel = false): void
{
(new CloudMailOutbox())->getConnection()->transaction(function () use (
$id, $token, $ok, $error, $cancel
) {
$message = CloudMailOutbox::where('id', $id)->where('lease_token', $token)
->lockForUpdate()->first();
if ($message === null) {
return;
}
$now = time();
$message->attempts = (int) $message->attempts + 1;
$message->lease_token = null;
$message->lease_until = 0;
$message->updated_at = $now;
if ($ok) {
$message->status = 'sent';
$message->sent_at = $now;
$message->last_error = '';
} elseif ($cancel) {
$message->status = 'cancelled';
$message->last_error = mb_substr($error, 0, 500);
} else {
$message->status = 'pending';
$message->available_at = $now + min(21600, 60 * (1 << min(8, (int) $message->attempts - 1)));
$message->last_error = mb_substr($error, 0, 500);
}
$message->save();
}, 3);
}
public static function display(CloudInvoice $invoice): array
{
$instance = CloudInstance::find($invoice->instance_id);
$status = (string) $invoice->status;
if ($instance === null || (string) $instance->status === 'deleted') {
if (in_array($status, ['open', 'overdue'], true)) {
$status = 'void';
}
} elseif ($status === 'open' && (int) $invoice->due_at <= time()) {
$status = 'overdue';
}
return [
'id' => (string) $invoice->id,
'invoice_no' => (string) $invoice->invoice_no,
'instance_id' => (string) $invoice->instance_id,
'instance_name' => $instance?->name ?? '已删除实例',
'amount' => (string) $invoice->amount,
'validity_days' => (int) $invoice->validity_days,
'traffic_quota_bytes' => (int) $invoice->traffic_quota_bytes,
'status' => $status,
'due_at' => (int) $invoice->due_at,
'paid_at' => $invoice->paid_at === null ? null : (int) $invoice->paid_at,
'paid_via' => $invoice->paid_via,
'created_at' => (int) $invoice->created_at,
];
}
public static function payBalance(CloudInvoice $invoice, array $actor, string $idempotency): CloudInvoice
{
if ((int) $invoice->user_id !== (int) $actor['user_id']) {
throw new CloudError('只能支付自己的账单', 403);
}
$result = self::settle($invoice, $actor, $idempotency, 'balance', '');
if ($result['outcome'] === 'stale') {
throw new CloudError('账单已失效,请刷新账单列表', 409);
}
return $result['invoice'];
}
/**
* Settle an invoice after a provider callback has already credited the
* exact payment to the wallet in the same outer database transaction.
* Expected business conflicts keep that money in the wallet.
*/
public static function settleCreditedPayment(CloudInvoicePayment $payment): string
{
$invoice = CloudInvoice::where('id', $payment->invoice_id)->first();
$amountMatches = false;
if ($invoice !== null) {
try {
$amountMatches = CloudMoney::cents((string) $payment->amount)
=== CloudMoney::cents((string) $invoice->amount);
} catch (\Throwable $error) {
$amountMatches = false;
}
}
if ($invoice === null || (int) $invoice->user_id !== (int) $payment->user_id
|| !$amountMatches) {
$payment->status = 'credited_balance';
$payment->updated_at = time();
$payment->save();
return 'credited_balance';
}
$actor = ['user_id' => (int) $payment->user_id, 'is_admin' => false,
'is_super_admin' => false, 'can_manage' => false, 'session_id' => ''];
try {
$result = self::settle($invoice, $actor,
'invoice-payment-' . (int) $payment->id,
(string) $payment->provider, (string) $payment->provider_order_no);
$payment->status = $result['outcome'] === 'paid' ? 'paid_invoice' : 'credited_balance';
} catch (CloudError $error) {
$payment->status = 'credited_balance';
}
$payment->updated_at = time();
$payment->save();
return (string) $payment->status;
}
private static function settle(CloudInvoice $source, array $actor, string $idempotency,
string $paidVia, string $reference): array
{
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) {
throw new CloudError('支付请求标识无效');
}
return (new User())->getConnection()->transaction(function () use (
$source, $actor, $idempotency, $paidVia, $reference
) {
$user = User::where('id', (int) $actor['user_id'])->lockForUpdate()->first();
if ($user === null) {
throw new CloudError('账户不存在', 404);
}
$instanceId = (int) $source->instance_id;
$instance = CloudInstance::where('id', $instanceId)->lockForUpdate()->first();
$invoice = CloudInvoice::where('id', $source->id)->lockForUpdate()->first();
if ($invoice === null || (int) $invoice->user_id !== (int) $user->id) {
throw new CloudError('账单不存在', 404);
}
if ((string) $invoice->status === 'paid') {
return ['outcome' => 'already_paid', 'invoice' => $invoice];
}
if ($instance === null || (string) $instance->status === 'deleted'
|| !in_array((string) $invoice->status, ['open', 'overdue'], true)
|| (int) $instance->user_id !== (int) $user->id
|| $instance->expires_at === null
|| (int) $instance->expires_at !== (int) $invoice->renews_expires_at
|| CloudMoney::cents((string) $instance->renewal_price) !== CloudMoney::cents((string) $invoice->amount)
|| (int) $instance->renewal_days !== (int) $invoice->validity_days
|| (int) $instance->renewal_traffic_bytes !== (int) $invoice->traffic_quota_bytes) {
$invoice->status = 'void';
$invoice->updated_at = time();
$invoice->save();
return ['outcome' => 'stale', 'invoice' => $invoice];
}
// Scope the renewal key to this bill. A client key reused in a
// later billing period must never resolve to an older renewal.
$renewal = CloudRenewalService::renew($instance, [
'idempotency_key' => 'invoice-' . (int) $invoice->id . '-'
. hash('sha256', $idempotency),
], $actor);
$invoice->status = 'paid';
$invoice->renewal_id = $renewal->id;
$invoice->paid_via = mb_substr($paidVia, 0, 32);
$invoice->payment_reference = $reference === '' ? null : mb_substr($reference, 0, 80);
$invoice->paid_at = time();
$invoice->updated_at = time();
$invoice->save();
return ['outcome' => 'paid', 'invoice' => $invoice, 'renewal' => $renewal];
}, 3);
}
private static function invoiceNumber(): string
{
return 'VC' . gmdate('YmdHis') . strtoupper(bin2hex(random_bytes(8)));
}
}

@ -10,6 +10,12 @@ final class CloudLifecycleService
public function tick(int $limit = 200): int
{
$batchSize = max(1, min(1000, $limit));
try {
CloudInvoiceService::issueDue($batchSize);
} catch (\Throwable $error) {
// Invoice creation is database-only and must not stop policy.
error_log('cloud invoice generation unavailable: ' . get_class($error));
}
try {
CloudTrafficService::sync($batchSize);
} catch (\Throwable $error) {

@ -45,6 +45,8 @@ class Smtp extends Base
}
}
$mail->Port = $config['port'];
$mail->Timeout = 15;
$mail->Timelimit = 20;
$mail->setFrom($config['sender'], $config['name']);
$mail->CharSet = 'UTF-8';
return $mail;

@ -2,17 +2,20 @@
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Paylist;
use App\Models\PaytaroCallbackEvent;
use App\Models\PaytaroOrder;
use App\Models\User;
use App\Services\Cloud\CloudInvoicePaymentService;
class PaytaroPaymentService
{
public const LEDGER_TYPE = 10005;
private const ORDER_PATTERN = '/^PT\d{14}[A-F0-9]{16}$/';
public function createOrder(User $user, $rawAmount, $clientIp, $userAgent, $returnBaseUrl)
public function createOrder(User $user, $rawAmount, $clientIp, $userAgent, $returnBaseUrl,
array $businessContext = [])
{
$settings = PaytaroConfig::runtimeForUser($user);
$amount = $this->validateAmount($rawAmount, $settings);
@ -23,7 +26,12 @@ class PaytaroPaymentService
}
$connection = (new PaytaroOrder())->getConnection();
$connection->transaction(function () use ($user, $amount, $orderNo, $now) {
$connection->transaction(function () use (
$user, $amount, $orderNo, $now, $businessContext
) {
if (User::where('id', (int) $user->id)->lockForUpdate()->first() === null) {
throw new \RuntimeException('支付账户不存在');
}
$paylist = new Paylist();
$paylist->userid = (int) $user->id;
$paylist->total = $amount;
@ -41,6 +49,10 @@ class PaytaroPaymentService
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
CloudInvoicePaymentService::recordAttempt(
$businessContext, $orderNo, $amount, (int) $user->id, $now
);
});
$baseUrl = rtrim((string) $settings['paytaro_callback_base_url'], '/');
@ -57,11 +69,22 @@ class PaytaroPaymentService
$gateway = $this->gatewayClient($settings)->createOrder($payload);
return $this->bindGatewayOrder($orderNo, $gateway);
} catch (\Throwable $exception) {
PaytaroOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
'status' => 'failed',
'error_message' => mb_substr($exception->getMessage(), 0, 500),
'updated_at' => time(),
]);
$failedAt = time();
$connection->transaction(function () use (
$orderNo, $businessContext, $exception, $failedAt
) {
PaytaroOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
'status' => 'failed',
'error_message' => mb_substr($exception->getMessage(), 0, 500),
'updated_at' => $failedAt,
]);
if ($businessContext !== []) {
CloudInvoicePayment::where('provider_order_no', $orderNo)
->where('provider', (string) ($businessContext['provider'] ?? ''))
->where('status', 'creating')
->update(['status' => 'failed', 'updated_at' => $failedAt]);
}
});
throw $exception;
}
}
@ -106,7 +129,10 @@ class PaytaroPaymentService
$duplicate = true;
return;
}
if (!in_array((string) $order->status, ['creating', 'pending'], true)) {
// A gateway request may time out after Paytaro accepted it. A
// later signed callback is the authoritative proof of payment,
// so a locally failed/ambiguous creation must still reconcile.
if (!in_array((string) $order->status, ['creating', 'pending', 'failed'], true)) {
throw new \RuntimeException('Paytaro 本地订单状态无效');
}
@ -125,6 +151,10 @@ class PaytaroPaymentService
throw new \RuntimeException('Paytaro 关联充值订单无效');
}
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true);
if (CloudInvoicePayment::where('provider', 'paytaro')
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider('paytaro', $orderNo);
}
$order->gateway_trade_no = $tradeNo;
$order->status = 'paid';
$order->paid_at = $now;

@ -6,6 +6,7 @@ use App\Models\Paylist;
use App\Models\User;
use App\Models\UsdtPaymentOrder;
use App\Models\UsdtWallet;
use App\Services\Cloud\CloudInvoicePaymentService;
class UsdtPaymentService
{
@ -18,7 +19,18 @@ class UsdtPaymentService
$settings = UsdtConfig::runtimeForUser($user);
$amount = $this->validateAmount($rawAmount, $settings['usdt_min_amount']);
$orderNo = $this->orderNo();
return $this->createOrder($orderNo, (int) $user->id, $amount, $settings);
return $this->createOrder($orderNo, (int) $user->id, $amount, $settings, []);
}
public function createInvoiceOrder(User $user, $rawAmount, array $businessContext)
{
$this->assertSchemaReady();
$settings = UsdtConfig::runtimeForUser($user);
$amount = $this->validateAmount($rawAmount, $settings['usdt_min_amount']);
$orderNo = $this->orderNo();
return $this->createOrder(
$orderNo, (int) $user->id, $amount, $settings, $businessContext
);
}
public function expire(UsdtPaymentOrder $order)
@ -44,12 +56,18 @@ class UsdtPaymentService
];
}
private function createOrder($businessOrderNo, $userId, $amount, array $settings)
private function createOrder($businessOrderNo, $userId, $amount, array $settings,
array $businessContext)
{
$now = time();
$result = null;
$connection = (new UsdtPaymentOrder())->getConnection();
$connection->transaction(function () use ($businessOrderNo, $userId, $amount, $settings, $now, &$result) {
$connection->transaction(function () use (
$businessOrderNo, $userId, $amount, $settings, $businessContext, $now, &$result
) {
if (User::where('id', (int) $userId)->lockForUpdate()->first() === null) {
throw new \RuntimeException('支付账户不存在');
}
$existing = UsdtPaymentOrder::where('business_type', 'recharge')
->where('business_order_no', $businessOrderNo)
->lockForUpdate()
@ -106,6 +124,10 @@ class UsdtPaymentService
$order->error_message = '';
$order->save();
CloudInvoicePaymentService::recordAttempt(
$businessContext, $businessOrderNo, $amount, (int) $userId, $now
);
$wallet->allocation_cursor = $cursor;
$wallet->last_assigned_at = $now;
$wallet->updated_at = $now;

@ -2,10 +2,12 @@
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Paylist;
use App\Models\UsdtChainTransaction;
use App\Models\UsdtPaymentOrder;
use App\Models\UsdtWallet;
use App\Services\Cloud\CloudInvoicePaymentService;
class UsdtScannerService
{
@ -233,8 +235,13 @@ class UsdtScannerService
try {
if ((string) $order->business_type === 'recharge') {
$credited = $this->settleRecharge($order, $event);
$stats[$credited ? 'credited' : 'duplicates']++;
$outcome = $this->settleRecharge($order, $event);
$stats[match ($outcome) {
'credited' => 'credited',
'duplicate' => 'duplicates',
'unmatched' => 'unmatched',
default => throw new \RuntimeException('USDT 结算结果无效'),
}]++;
return;
}
throw new \RuntimeException('USDT 订单业务类型无效');
@ -257,11 +264,15 @@ class UsdtScannerService
throw new \RuntimeException('USDT 充值订单或链上事件不存在');
}
if ((string) $order->status === 'paid') {
$event->status = 'credited';
$event->order_no = (string) $order->order_no;
$sameTransaction = (string) $order->txid !== ''
&& hash_equals((string) $order->txid, (string) $event->txid);
$event->status = $sameTransaction ? 'credited' : 'unmatched';
$event->order_no = $sameTransaction ? (string) $order->order_no : null;
$event->processed_at = time();
$event->error_message = '';
$event->error_message = $sameTransaction ? ''
: '同额订单已由另一笔链上交易结算,请人工核对';
$event->save();
$credited = $sameTransaction ? 'duplicate' : 'unmatched';
return;
}
@ -271,8 +282,14 @@ class UsdtScannerService
|| (int) $paylist->userid !== (int) $order->user_id) {
throw new \RuntimeException('USDT 关联充值订单无效');
}
$credited = RechargeCreditService::creditLocked($paylist, UsdtPaymentService::LEDGER_TYPE);
$walletCredited = RechargeCreditService::creditLocked(
$paylist, UsdtPaymentService::LEDGER_TYPE);
if (CloudInvoicePayment::where('provider', 'usdt')
->where('provider_order_no', (string) $order->order_no)->exists()) {
CloudInvoicePaymentService::settleForProvider('usdt', (string) $order->order_no);
}
$this->applyChainResult($order, $event, 'paid', 'credited');
$credited = $walletCredited ? 'credited' : 'duplicate';
}, 3);
return $credited;
}

@ -2,6 +2,7 @@
namespace App\Services\Payment;
use App\Models\CloudInvoicePayment;
use App\Models\Code;
use App\Models\Paylist;
use App\Models\Payback;
@ -9,12 +10,14 @@ use App\Models\User;
use App\Models\YipayCallbackEvent;
use App\Models\YipayOrder;
use App\Models\YipayRefund;
use App\Services\Cloud\CloudInvoicePaymentService;
class YipayPaymentService
{
public const LEDGER_TYPE = 10007;
public function createOrder(User $user, $rawAmount, $rawMethod, $clientIp, $userAgent, $returnBaseUrl)
public function createOrder(User $user, $rawAmount, $rawMethod, $clientIp, $userAgent,
$returnBaseUrl, array $businessContext = [])
{
$method = YipayConfig::normalizeMethod($rawMethod);
$settings = YipayConfig::runtimeForUser($user, $method);
@ -26,7 +29,12 @@ class YipayPaymentService
}
$connection = (new YipayOrder())->getConnection();
$connection->transaction(function () use ($user, $amount, $method, $orderNo, $now) {
$connection->transaction(function () use (
$user, $amount, $method, $orderNo, $now, $businessContext
) {
if (User::where('id', (int) $user->id)->lockForUpdate()->first() === null) {
throw new \RuntimeException('支付账户不存在');
}
$paylist = new Paylist();
$paylist->userid = (int) $user->id;
$paylist->total = $amount;
@ -45,6 +53,10 @@ class YipayPaymentService
$order->created_at = $now;
$order->updated_at = $now;
$order->save();
CloudInvoicePaymentService::recordAttempt(
$businessContext, $orderNo, $amount, (int) $user->id, $now
);
});
$baseUrl = rtrim((string) $settings['yipay_callback_base_url'], '/');
@ -63,11 +75,22 @@ class YipayPaymentService
$gateway = $this->gatewayClient($settings)->createOrder($payload);
return $this->bindGatewayOrder($orderNo, $gateway);
} catch (\Throwable $exception) {
YipayOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
'status' => 'failed',
'error_message' => mb_substr($exception->getMessage(), 0, 500),
'updated_at' => time(),
]);
$failedAt = time();
$connection->transaction(function () use (
$orderNo, $businessContext, $exception, $failedAt
) {
YipayOrder::where('order_no', $orderNo)->where('status', 'creating')->update([
'status' => 'failed',
'error_message' => mb_substr($exception->getMessage(), 0, 500),
'updated_at' => $failedAt,
]);
if ($businessContext !== []) {
CloudInvoicePayment::where('provider_order_no', $orderNo)
->where('provider', (string) ($businessContext['provider'] ?? ''))
->where('status', 'creating')
->update(['status' => 'failed', 'updated_at' => $failedAt]);
}
});
throw $exception;
}
}
@ -138,6 +161,11 @@ class YipayPaymentService
}
$credited = RechargeCreditService::creditLocked($paylist, self::LEDGER_TYPE, true);
$invoiceProvider = 'yipay_' . (string) $order->payment_type;
if (CloudInvoicePayment::where('provider', $invoiceProvider)
->where('provider_order_no', $orderNo)->exists()) {
CloudInvoicePaymentService::settleForProvider($invoiceProvider, $orderNo);
}
$order->gateway_trade_no = $tradeNo;
$order->status = 'paid';
$order->paid_at = $now;
@ -182,6 +210,10 @@ class YipayPaymentService
if ($adminUserId <= 0) {
throw new \RuntimeException('退款管理员身份无效');
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
}
$settings = YipayConfig::runtime(false);
$result = null;
@ -200,6 +232,10 @@ class YipayPaymentService
if ((string) $order->status !== 'paid') {
throw new \RuntimeException('只有已支付订单可以退款');
}
if (CloudInvoicePayment::where('provider_order_no', $orderNo)
->whereIn('provider', ['yipay_alipay', 'yipay_wxpay'])->exists()) {
throw new \RuntimeException('账单支付不支持自动退款,请人工核对服务期后处理');
}
$tradeNo = trim((string) $order->gateway_trade_no);
if (!preg_match('/^[A-Za-z0-9_-]{1,80}$/', $tradeNo)) {
throw new \RuntimeException('易支付平台订单号无效,不能退款');

@ -13,6 +13,13 @@ class UserDataDeletionService
['paylist', 'userid'], ['ss_invite_code', 'user_id'], ['ticket', 'userid'],
['user_survey_responses', 'user_id'],
['cloud_ssh_keys', 'user_id'], ['cloud_sessions', 'user_id'],
// Delete cloud history from dependants to parents after the active VM,
// order and payment guards above have proved the account is safe to
// remove. cloud_jobs may contain encrypted provisioning credentials.
['cloud_jobs', 'user_id'], ['cloud_service_periods', 'user_id'],
['cloud_renewals', 'user_id'], ['cloud_invoice_payments', 'user_id'],
['cloud_invoices', 'user_id'], ['cloud_orders', 'user_id'],
['cloud_instances', 'user_id'],
];
private const EMAIL_REFERENCES = [
['checkout_apply', 'email'], ['email_verify', 'email'], ['ss_password_reset', 'email'],
@ -49,15 +56,37 @@ class UserDataDeletionService
->whereIn('status', ['pending', 'queued', 'running', 'provisioning', 'uncertain'])->exists()) {
throw new \RuntimeException('用户仍有开通中的订单,请先处理订单后再删除账户');
}
foreach ([
['cloud_invoice_payments', ['creating', 'pending', 'failed']],
['yipay_orders', ['creating', 'pending', 'failed']],
['paytaro_orders', ['creating', 'pending', 'failed']],
['usdt_payment_orders', ['pending', 'expired']],
] as [$table, $statuses]) {
if ($this->hasColumns($connection, $table, ['user_id', 'status'])
&& $connection->table($table)->whereIn('user_id', $ids)
->whereIn('status', $statuses)->exists()) {
throw new \RuntimeException(
'用户仍有未核对的支付订单,请先确认网关和链上到账状态');
}
}
foreach ($users as $user) {
LoginSessionRevocationService::revokeUser($user);
}
$emails = array_values(array_unique(array_filter($emails, 'strlen')));
if ($this->hasColumns($connection, 'cloud_invoices', ['id', 'user_id'])) {
$invoiceIds = $connection->table('cloud_invoices')
->whereIn('user_id', $ids)->pluck('id')->all();
$deletedMailRows = $this->deleteWhereIn(
$connection, 'cloud_mail_outbox', 'invoice_id', $invoiceIds);
} else {
$deletedMailRows = 0;
}
// The log database has its own transaction; this is not distributed atomicity.
// Log unavailability aborts deletion before the default database is changed.
$logRows = $this->deleteLogRecords($ids, $emails);
$rows = $this->deleteRelatedRecords($connection, $ids, $emails);
$rows = $deletedMailRows + $this->deleteRelatedRecords($connection, $ids, $emails);
$deleted = (int) User::whereIn('id', $ids)->where('is_admin', 0)->delete();
if ($deleted !== count($ids)) {
throw new \RuntimeException('用户状态发生变化,删除已取消');

@ -8,6 +8,10 @@ $app->group('/api/v1', function () {
$this->get('/orders/by-request/{key:[A-Za-z0-9_.-]+}',
'App\Controllers\CloudApiController:orderRequest');
$this->get('/orders/{id:[0-9]+}', 'App\Controllers\CloudApiController:order');
$this->get('/invoices', 'App\Controllers\CloudApiController:invoices');
$this->get('/invoices/{id:[0-9]+}', 'App\Controllers\CloudApiController:invoice');
$this->post('/invoices/{id:[0-9]+}/pay-balance', 'App\Controllers\CloudApiController:payInvoice');
$this->post('/invoices/{id:[0-9]+}/payments', 'App\Controllers\CloudApiController:createInvoicePayment');
foreach (['jobs', 'reinstall-jobs', 'rescue-jobs'] as $name) {
$this->get('/' . $name . '/{id:[0-9]+}', 'App\Controllers\CloudApiController:job');
}
@ -15,10 +19,10 @@ $app->group('/api/v1', function () {
$this->get('/vms', 'App\Controllers\CloudApiController:vms');
$this->get('/vms/{id}', 'App\Controllers\CloudApiController:vm');
$this->get('/vms/{id}/metrics', 'App\Controllers\CloudApiController:metrics');
$this->get('/vms/{id}/traffic/daily', 'App\Controllers\CloudApiController:dailyTraffic');
$this->post('/vms/{id}/credential', 'App\Controllers\CloudApiController:credential');
$this->post('/vms/{id}/console-ticket', 'App\Controllers\CloudApiController:consoleTicket');
$this->post('/vms/{id}/actions', 'App\Controllers\CloudApiController:actions');
$this->post('/vms/{id}/renewals', 'App\Controllers\CloudApiController:renew');
$this->post('/vms/{id}/reinstall', 'App\Controllers\CloudApiController:reinstall');
$this->map(['GET', 'POST'], '/vms/{id}/rescue', 'App\Controllers\CloudApiController:rescue');
$this->post('/vms/{id}/rescue/force-start', 'App\Controllers\CloudApiController:rescue')->setArgument('rescue_action', '/force-start');

@ -1,9 +1,9 @@
// PHP owns authentication, authorisation, ownership and purchasing. No engine
// address, token, host credential or unrestricted create API exists in this UI.
const byId = (id) => document.getElementById(id);
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, view: 'list', selectedVmId: null, metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, orderPoll: null, mutationBusy: false, orderIdempotency: '', orderFingerprint: '', renewalIdempotency: {}, rescueActive: false, rescueStaged: false };
const RENEWAL_STORAGE_PREFIX = 'virt-cloud:pending-renewal:';
const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], sshKeys: [], templates: [], resources: null, invoices: [], invoicePaymentMethods: [], invoicePollTimers: new Map(), view: 'list', selectedVmId: null, detailTab: 'operations', metricsRange: '24h', metricsPayload: null, metricsRequest: null, metricsPollTimer: null, metricsResizeTimer: null, trafficDailyPayload: null, trafficDailyVmId: '', trafficDailyRequest: null, trafficDailyResizeTimer: null, trafficDailyLoadedAt: 0, credentialPassword: '', credentialVisible: false, credentialTimer: null, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, formEpoch: 0, resourceController: null, orderPoll: null, mutationBusy: false, orderIdempotency: '', orderFingerprint: '', rescueActive: false, rescueStaged: false };
const ORDER_STORAGE_PREFIX = 'virt-cloud:pending-order:';
const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:';
const text = (id, value) => { byId(id).textContent = value ?? '—'; };
const items = (payload) => Array.isArray(payload) ? payload : Array.isArray(payload?.items) ? payload.items : Array.isArray(payload?.plans) ? payload.plans : Array.isArray(payload?.orders) ? payload.orders : Array.isArray(payload?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : [];
function showError(id, message) { text(id, message); byId(id).hidden = !message; }
@ -38,14 +38,6 @@ function firstNumber(...values) {
}
return null;
}
function firstBoolean(...values) {
for (const value of values) {
if (value === true || value === false) return value;
if (value === 1 || value === '1' || value === 'true') return true;
if (value === 0 || value === '0' || value === 'false') return false;
}
return null;
}
function firstText(...values) {
for (const value of values) {
if (value !== null && value !== undefined && String(value).trim() !== '') return String(value).trim();
@ -69,19 +61,10 @@ function vmServiceData(vm) {
rx !== null && tx !== null ? rx + tx : null);
const remaining = firstNumber(vm?.traffic_remaining_bytes, service.traffic_remaining_bytes, period.traffic_remaining_bytes, traffic.remaining_bytes,
quota !== null && used !== null ? Math.max(0, quota - used) : null);
const validityDays = firstNumber(vm?.renewal_days, vm?.validity_days, service.renewal_days, service.validity_days, period.renewal_days, period.validity_days, billing.renewal_days, billing.validity_days);
const renewalPrice = firstNumber(vm?.renewal_price, service.renewal_price, period.renewal_price, billing.renewal_price);
const renewalQuota = firstNumber(vm?.renewal_traffic_bytes, service.renewal_traffic_bytes, period.renewal_traffic_bytes, billing.renewal_traffic_bytes, quota);
const periodStartsAt = vm?.current_period_starts_at ?? vm?.current_period_started_at ?? vm?.current_period_start ?? service.current_period_starts_at ?? service.current_period_started_at ?? service.current_period_start ?? period.started_at ?? period.starts_at ?? period.start_at ?? null;
const periodEndsAt = vm?.current_period_ends_at ?? vm?.current_period_end ?? service.current_period_ends_at ?? service.current_period_end ?? period.ends_at ?? period.end_at ?? null;
const expiresAt = vm?.service_expires_at ?? vm?.final_expires_at ?? vm?.expires_at ?? vm?.valid_until ?? service.service_expires_at ?? service.final_expires_at ?? service.expires_at ?? service.valid_until ?? period.final_expires_at ?? period.expires_at ?? billing.expires_at ?? null;
const prepaidPeriods = firstNumber(vm?.prepaid_future_periods, vm?.prepaid_periods, vm?.future_period_count, vm?.scheduled_period_count,
service.prepaid_future_periods, service.prepaid_periods, service.future_period_count, period.prepaid_future_periods, period.prepaid_periods, billing.prepaid_periods);
const status = firstText(vm?.service_status, service.status, period.status, billing.status, vm?.subscription_status);
const networkStatus = firstText(vm?.network_status, service.network_status, period.network_status, traffic.network_status);
const renewable = firstBoolean(vm?.can_renew, vm?.renewable, service.can_renew, service.renewable, period.can_renew, period.renewable, billing.can_renew, billing.renewable);
return { quota, rx, tx, used, remaining, validityDays, renewalPrice, renewalQuota, periodStartsAt, periodEndsAt, expiresAt, prepaidPeriods, status, networkStatus, renewable,
available: Boolean(status || networkStatus || expiresAt !== null || periodStartsAt !== null || periodEndsAt !== null || [quota, rx, tx, used, remaining, validityDays, renewalPrice, renewalQuota, prepaidPeriods].some(value => value !== null) || renewable !== null) };
return { quota, rx, tx, used, remaining, periodEndsAt, status, networkStatus };
}
function formatBytes(value) {
if (value === null || !Number.isFinite(value) || value < 0) return '暂未提供';
@ -108,7 +91,7 @@ function formatServiceDate(value) {
}
function serviceStatusInfo(data) {
let status = data.status.toLowerCase().replace(/[\s-]+/g, '_');
if (!status && serviceTimestamp(data.expiresAt) !== null) status = serviceTimestamp(data.expiresAt) <= Date.now() ? 'expired' : 'active';
if (!status && serviceTimestamp(data.periodEndsAt) !== null) status = serviceTimestamp(data.periodEndsAt) <= Date.now() ? 'expired' : 'active';
const labels = {
active: ['服务有效', 'active'], pending: ['待生效', 'warning'], renewing: ['续费处理中', 'warning'], grace: ['宽限期', 'warning'],
resume_pending: ['等待恢复服务', 'warning'], resuming: ['正在恢复服务', 'warning'], resume_failed: ['服务恢复失败,请联系管理员', 'stopped'], suspending: ['正在暂停', 'warning'],
@ -132,10 +115,31 @@ function networkStatusInfo(value) {
function selectedVm() { return state.vms.find(vm => vm.uuid === state.selectedVmId); }
function vmPath(vm = selectedVm()) { if (!vm) throw new Error('请先选择虚拟机。'); return `/api/v1/vms/${encodeURIComponent(vm.api_id)}`; }
function clearCredential() { clearTimeout(state.credentialTimer); state.credentialPassword = ''; state.credentialVisible = false; text('vm-detail-root-password', '********'); byId('vm-detail-password-reveal').setAttribute('aria-pressed', 'false'); }
const VM_DETAIL_TABS = ['operations', 'performance', 'traffic'];
function setVmDetailTab(tab, focus = false) {
const next = VM_DETAIL_TABS.includes(tab) ? tab : 'operations';
state.detailTab = next;
for (const name of VM_DETAIL_TABS) {
const button = byId(`vm-detail-tab-${name}`);
const active = name === next;
button.classList.toggle('active', active);
button.setAttribute('aria-selected', String(active));
button.tabIndex = active ? 0 : -1;
byId(`vm-detail-${name}-panel`).hidden = !active;
}
stopVmMetrics();
stopVmTrafficDaily();
if (state.view === 'detail') {
if (next === 'performance') startVmMetrics();
if (next === 'traffic') startVmTrafficDaily();
}
if (focus) byId(`vm-detail-tab-${next}`).focus();
}
function showView(view) {
clearCredential(); stopVmMetrics(); state.view = view;
byId('vm-workspace').hidden = ['keys', 'orders'].includes(view);
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('orders-workspace').hidden = view !== 'orders';
clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); state.view = view;
if (view !== 'invoices' && state.invoicePollTimers.size) stopInvoicePoll();
byId('vm-workspace').hidden = ['keys', 'orders', 'invoices'].includes(view);
byId('ssh-keys-workspace').hidden = view !== 'keys'; byId('orders-workspace').hidden = view !== 'orders'; byId('invoices-workspace').hidden = view !== 'invoices';
const sections = { list: 'vm-list-view', detail: 'vm-detail-view', create: 'create-view', reinstall: 'reinstall-view', rescue: 'rescue-view' };
for (const [name, id] of Object.entries(sections)) byId(id).hidden = view !== name;
const navigationView = ['detail', 'reinstall', 'rescue'].includes(view) ? 'list' : view;
@ -145,13 +149,13 @@ function showView(view) {
if (active) button.setAttribute('aria-current', 'page');
else button.removeAttribute('aria-current');
});
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', orders: '开通订单' })[view]);
const hash = ({ list: '', create: 'plans', keys: 'keys', orders: 'orders' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
text('breadcrumb-current', ({ list: '实例管理', detail: '虚拟机详情', create: '部署实例', reinstall: '重装系统', rescue: '紧急救援', keys: 'SSH 公钥', orders: '开通订单', invoices: '续费账单' })[view]);
const hash = ({ list: '', create: 'plans', keys: 'keys', orders: 'orders', invoices: 'invoices' })[view] ?? (selectedVm() ? `vm=${encodeURIComponent(selectedVm().api_id)}` : '');
history.replaceState(null, '', `${location.pathname}${location.search}${hash ? '#' + hash : ''}`);
window.scrollTo({ top: 0, behavior: 'auto' });
if (view === 'detail') startVmMetrics();
if (view === 'detail') setVmDetailTab(state.detailTab);
}
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders') { showView('orders'); await loadOrders(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
async function routeHash(hash = location.hash) { const target = hash.replace(/^#/, ''); try { if (target === 'plans') await openCreate(); else if (target === 'keys') { showView('keys'); await loadKeys(); } else if (target === 'orders') { showView('orders'); await loadOrders(); } else if (target === 'invoices') { showView('invoices'); await loadInvoices(); } else if (target.startsWith('vm=')) { const id = decodeURIComponent(target.slice(3)); const vm = state.vms.find(item => item.api_id === id); if (vm) openVmDetail(vm.uuid); else showView('list'); } else showView('list'); } catch (error) { showError('cloud-page-error', error.message); } }
async function loadVms() {
if (state.loadingVMs) return;
state.loadingVMs = true;
@ -159,7 +163,7 @@ async function loadVms() {
catch (error) { showError('cloud-page-error', error.message); if (!state.vms.length) renderVMs(true); }
finally { state.loadingVMs = false; }
}
function openVmDetail(uuid) { const vm = state.vms.find(item => item.uuid === String(uuid)); if (!vm) return toast('虚拟机不存在,请刷新。', 'error'); state.selectedVmId = vm.uuid; renderVmDetail(vm); showView('detail'); clearVmMetrics('正在加载监控数据…'); }
function openVmDetail(uuid) { const vm = state.vms.find(item => item.uuid === String(uuid)); if (!vm) return toast('虚拟机不存在,请刷新。', 'error'); state.selectedVmId = vm.uuid; state.detailTab = 'operations'; clearVmMetrics('打开“性能监控”页签后加载监控数据。'); clearVmTrafficDaily('打开“流量信息”页签后加载最近 30 天数据。'); renderVmDetail(vm); showView('detail'); }
function renderVmDetail(vm) {
text('vm-detail-name', vm.name); text('vm-detail-state', stateLabel(vm.state)); byId('vm-detail-state').className = `state-pill ${stateCategory(vm.state)}`;
for (const id of ['vm-detail-region', 'vm-detail-header-region']) text(id, vmRegion(vm));
@ -179,7 +183,7 @@ function renderVmDetail(vm) {
} else {
primary.append(makeElement('p', 'muted', '这是其他用户的实例;当前管理员账户只有查看权限。'));
}
if (state.mutationBusy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button,#vm-detail-renew-button').forEach(button => { button.disabled = true; });
if (state.mutationBusy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; });
}
function renderVmService(vm) {
const data = vmServiceData(vm);
@ -191,15 +195,11 @@ function renderVmService(vm) {
const networkStatusElement = byId('vm-detail-network-status');
networkStatusElement.textContent = networkStatus.label;
networkStatusElement.className = `service-pill ${networkStatus.className}`;
text('vm-detail-period-start', formatServiceDate(data.periodStartsAt));
text('vm-detail-period-end', formatServiceDate(data.periodEndsAt));
text('vm-detail-expires-at', formatServiceDate(data.expiresAt));
text('vm-detail-prepaid-periods', data.prepaidPeriods === null ? '暂未提供' : `${Math.floor(data.prepaidPeriods)} 个`);
text('vm-detail-traffic-rx', formatBytes(data.rx));
text('vm-detail-traffic-tx', formatBytes(data.tx));
text('vm-detail-traffic-used', formatBytes(data.used));
text('vm-detail-traffic-quota', formatTrafficQuota(data.quota));
text('vm-detail-traffic-remaining', data.quota === 0 ? '不限流量' : formatBytes(data.remaining));
text('vm-detail-traffic-total-remaining', `${formatTrafficQuota(data.quota)} / ${data.quota === 0 ? '不限流量' : formatBytes(data.remaining)}`);
const progress = byId('vm-detail-traffic-progress');
const ratio = data.quota !== null && data.quota > 0 && data.used !== null ? Math.max(0, Math.min(100, data.used / data.quota * 100)) : null;
progress.hidden = ratio === null;
@ -212,64 +212,10 @@ function renderVmService(vm) {
byId('vm-detail-traffic-progress-bar').style.width = '0';
progress.classList.remove('is-exhausted');
}
const renewButton = byId('vm-detail-renew-button');
const hasRenewalMetadata = data.renewable !== null || data.validityDays !== null || data.renewalPrice !== null;
renewButton.hidden = vm.is_owner === false || !data.available || !hasRenewalMetadata;
renewButton.disabled = state.mutationBusy || data.renewable === false;
renewButton.textContent = data.renewalPrice !== null && data.validityDays !== null
? `续费 ${Math.floor(data.validityDays)} 天 · ¥${data.renewalPrice.toFixed(2)}` : '立即续费';
renewButton.title = data.renewable === false ? '当前实例暂不能续费' : '购买下一个服务周期';
let note = '接口暂未提供服务周期与流量信息。';
if (data.available) {
note = '流量按当前账期单独计算;用尽时仅暂停网络,下一账期开始流量归零并自动恢复网络。';
if (data.prepaidPeriods !== null && data.prepaidPeriods > 0) note += ` 已预付 ${Math.floor(data.prepaidPeriods)} 个未来账期。`;
if (data.renewable !== false) note += ' 续费购买的下一账期会从当前已购期限末尾开始。';
}
text('vm-detail-service-note', note);
}
async function powerAction(action, dangerous = false) { const vm = selectedVm(); if (!vm?.can_mutate) return toast('当前账户只有查看权限。', 'error'); if (state.mutationBusy) return; if (dangerous && !confirm('此操作会强制断电,可能丢失未保存的数据。确认继续?')) return; state.mutationBusy = true; setDetailBusy(true); try { const result = await api(`${vmPath()}/actions`, { method: 'POST', body: { action } }); toast('电源任务已提交,正在执行…'); if (result.job_id) await pollJob('power', result.job_id); toast('电源操作已完成。', 'success'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
async function deleteVm() { const vm = selectedVm(); if (!vm?.can_mutate) return toast('当前账户只有查看权限。', 'error'); if (state.mutationBusy) return; const confirmation = prompt(`永久删除“${vm.name}”及面板管理的虚拟磁盘,此操作不可恢复。请输入完整虚拟机名称确认:`); if (confirmation === null) return; if (confirmation !== vm.name) return toast('虚拟机名称不匹配,未执行删除。', 'error'); state.mutationBusy = true; setDetailBusy(true); try { const result = await api(vmPath(vm), { method: 'DELETE', body: { confirmation_name: vm.name, delete_disks: true } }); toast('删除任务已提交,正在执行…'); if (result.job_id) await pollJob('delete', result.job_id); toast('虚拟机删除已完成。', 'success'); state.selectedVmId = null; showView('list'); await loadVms(); } catch (error) { toast(error.message, 'error'); } finally { state.mutationBusy = false; setDetailBusy(false); } }
function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button,#vm-detail-renew-button').forEach(button => { button.disabled = true; }); }
function renewalStorageKey(vmId) { return `${RENEWAL_STORAGE_PREFIX}${vmId}`; }
function pendingRenewalKey(vmId) {
if (state.renewalIdempotency[vmId]) return state.renewalIdempotency[vmId];
let key = '';
try { key = sessionStorage.getItem(renewalStorageKey(vmId)) || ''; } catch {}
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
state.renewalIdempotency[vmId] = key;
try { sessionStorage.setItem(renewalStorageKey(vmId), key); } catch {}
return key;
}
function clearPendingRenewalKey(vmId) {
delete state.renewalIdempotency[vmId];
try { sessionStorage.removeItem(renewalStorageKey(vmId)); } catch {}
}
async function renewVm() {
const vm = selectedVm();
if (!vm || state.mutationBusy) return;
const service = vmServiceData(vm);
if (service.renewable === false) return toast('当前实例暂不能续费。', 'error');
const details = [];
if (service.renewalPrice !== null) details.push(`从账户余额支付 ¥${service.renewalPrice.toFixed(2)}`);
if (service.validityDays !== null) details.push(`购买下一个 ${Math.floor(service.validityDays)} 天账期`);
if (service.renewalQuota !== null) details.push(`下一账期流量额度 ${formatTrafficQuota(service.renewalQuota)}`);
const prompt = `${details.length ? details.join(',') : '确认购买下一个服务账期'}。下一账期将从当前已购买期限末尾生效,确认续费?`;
if (!confirm(prompt)) return;
state.mutationBusy = true;
setDetailBusy(true);
const key = pendingRenewalKey(vm.api_id);
try {
await api(`${vmPath(vm)}/renewals`, { method: 'POST', body: { idempotency_key: key } });
clearPendingRenewalKey(vm.api_id);
await loadVms();
toast('续费成功,下一账期将在当前已购期限末尾生效。已关机的虚拟机仍保持关机,需要时请手动开机。', 'success');
} catch (error) {
toast(`${error.message} 可再次点击续费安全核对同一请求。`, 'error');
} finally {
state.mutationBusy = false;
setDetailBusy(false);
}
}
function setDetailBusy(busy) { if (!busy && selectedVm()) renderVmDetail(selectedVm()); else if (busy) document.querySelectorAll('#vm-detail-primary-actions button,#vm-detail-danger-actions button').forEach(button => { button.disabled = true; }); }
async function credential(copy = false) {
const vm = selectedVm(); if (!vm?.can_view_credential || !vm.password_available) return;
if (!copy && state.credentialVisible) return clearCredential();
@ -337,6 +283,31 @@ function clearPendingOrderKey() {
state.orderFingerprint = '';
try { sessionStorage.removeItem(orderStorageKey()); } catch {}
}
function invoicePaymentStorageKey(invoiceId, methodId) {
return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`;
}
function pendingInvoicePaymentKey(invoiceId, methodId) {
const storageKey = invoicePaymentStorageKey(invoiceId, methodId);
let key = '';
try { key = String(sessionStorage.getItem(storageKey) || ''); } catch {}
if (!/^[A-Za-z0-9_.-]{16,128}$/.test(key)) key = crypto.randomUUID();
try { sessionStorage.setItem(storageKey, key); } catch {}
return key;
}
function clearInvoicePaymentKey(invoiceId, methodId) {
try { sessionStorage.removeItem(invoicePaymentStorageKey(invoiceId, methodId)); } catch {}
}
function clearInvoicePaymentKeys(invoiceId) {
const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`;
try {
const keys = [];
for (let index = 0; index < sessionStorage.length; index += 1) {
const key = sessionStorage.key(index);
if (key?.startsWith(prefix)) keys.push(key);
}
keys.forEach(key => sessionStorage.removeItem(key));
} catch {}
}
async function existingPendingOrder(key) {
try { return await api(`/api/v1/orders/by-request/${encodeURIComponent(key)}`); }
catch (error) { if (error.status === 404) return null; throw error; }
@ -349,7 +320,7 @@ async function buy(event) {
if (!byId('vm-plan').value || !state.resources) return showError('create-error', '请先选择可用套餐。');
const selectedPlan = state.plans.find(plan => String(plan.id) === byId('vm-plan').value);
const purchaseSummary = selectedPlan ? `每期 ¥${selectedPlan.price},${planBillingLabel(selectedPlan)}` : '所选套餐';
if (!confirm(`确认从账户余额支付并开通虚拟机?${purchaseSummary}。到期前可手动续费。`)) return;
if (!confirm(`确认从账户余额支付并开通虚拟机?${purchaseSummary}。到期前 7 天会自动生成续费账单。`)) return;
state.mutationBusy = true; byId('create-submit').disabled = true; showError('create-error', '');
const body = { plan_id: Number(byId('vm-plan').value), name: byId('vm-name').value.trim(), source: sourceMode() };
if (cloud) { body.template_id = byId('vm-template').value; if (state.selectedKeys.create) body.guest_ssh_key_id = state.selectedKeys.create; if (password) body.root_password = password; } else body.iso_path = byId('vm-iso').value;
@ -412,6 +383,175 @@ async function loadOrders() {
}
} catch (error) { showError('cloud-page-error', error.message); }
}
function invoiceStatusInfo(status) {
const values = {
open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'],
paid: ['已支付', 'running'], void: ['已失效', 'other'],
};
return values[String(status || '').toLowerCase()] || [String(status || '未知'), 'other'];
}
function validPaymentUrl(value) {
try {
const url = new URL(String(value || ''));
return ['https:', 'weixin:', 'alipays:', 'alipayqr:'].includes(url.protocol) ? url.href : '';
}
catch { return ''; }
}
function appendPaymentQr(container, value) {
if (!value || typeof window.QRCode !== 'function') return false;
const qr = makeElement('div', 'cloud-payment-qr');
try {
const levels = window.QRCode.CorrectLevel || { L: 1, M: 0 };
new window.QRCode(qr, {
text: String(value), width: 196, height: 196,
correctLevel: String(value).length > 1200 ? levels.L : levels.M,
});
if (!qr.children.length) return false;
container.append(qr);
return true;
} catch { return false; }
}
function stopInvoicePoll(invoiceId = null) {
if (invoiceId !== null) {
const key = String(invoiceId);
const timer = state.invoicePollTimers.get(key);
if (timer !== undefined) clearTimeout(timer);
state.invoicePollTimers.delete(key);
return;
}
for (const timer of state.invoicePollTimers.values()) clearTimeout(timer);
state.invoicePollTimers.clear();
}
function scheduleInvoicePoll(invoiceId) {
const key = String(invoiceId);
stopInvoicePoll(key);
const started = Date.now();
const poll = async () => {
if (state.view !== 'invoices') return stopInvoicePoll(key);
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}`);
if (result.invoice?.status === 'paid') {
stopInvoicePoll(key); toast('账单支付成功,服务期限已延长。', 'success'); await loadInvoices(); await loadVms(); return;
}
if (['void'].includes(result.invoice?.status)) {
stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); await loadInvoices(); return;
}
} catch {}
if (Date.now() - started < 10 * 60 * 1000) {
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
} else {
stopInvoicePoll(key);
await loadInvoices();
}
};
state.invoicePollTimers.set(key, setTimeout(poll, 3000));
}
function renderOnlinePayment(container, payment) {
let box = container.querySelector('.cloud-payment-instructions');
if (!box) { box = makeElement('div', 'cloud-payment-instructions'); container.append(box); }
box.replaceChildren();
if (payment.payment_kind === 'usdt') {
box.append(makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`),
makeElement('code', '', payment.receive_address || '收款地址不可用'),
makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`));
appendPaymentQr(box, payment.receive_address || '');
const copy = actionButton('复制收款地址', async () => {
try { await copyText(payment.receive_address || ''); toast('USDT 收款地址已复制。', 'success'); }
catch (error) { toast(error.message, 'error'); }
});
box.append(copy);
} else {
const url = validPaymentUrl(payment.payment_value);
box.append(makeElement('strong', '', `${payment.label || '在线支付'}订单已生成`));
appendPaymentQr(box, payment.payment_value || '');
if (url) {
const link = makeElement('a', 'button button-primary small', '前往支付');
link.href = url; link.target = '_blank'; link.rel = 'noopener noreferrer'; box.append(link);
} else {
box.append(makeElement('code', '', payment.payment_value || '支付信息暂不可用'));
const copy = actionButton('复制支付信息', async () => {
try { await copyText(payment.payment_value || ''); toast('支付信息已复制。', 'success'); }
catch (error) { toast(error.message, 'error'); }
});
box.append(copy);
}
box.append(makeElement('small', '', '完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。'));
}
scheduleInvoicePoll(payment.invoice_id);
}
async function payInvoiceBalance(invoice, row) {
if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 ${invoice.invoice_no},金额 ¥${invoice.amount}?`)) return;
state.mutationBusy = true;
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
try {
await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, {
method: 'POST', body: { idempotency_key: crypto.randomUUID() },
});
toast('账单已支付,服务期限已延长。', 'success'); await loadInvoices(); await loadVms();
} catch (error) { toast(error.message, 'error'); }
finally {
state.mutationBusy = false;
row.querySelectorAll('button').forEach(button => { button.disabled = false; });
}
}
async function createInvoicePayment(invoice, method, row) {
if (state.mutationBusy || !confirm(`确认通过“${method.name}”生成 ¥${invoice.amount} 的支付订单?`)) return;
state.mutationBusy = true;
row.querySelectorAll('button').forEach(button => { button.disabled = true; });
const idempotencyKey = pendingInvoicePaymentKey(invoice.id, method.id);
try {
const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`, {
method: 'POST', body: { method: method.id, idempotency_key: idempotencyKey },
});
renderOnlinePayment(row, result.payment || {});
} catch (error) {
// A transport failure may hide a successfully created provider order, so
// retain the key and recover it on the next click. Only a definite 4xx
// rejection proves no ambiguous 5xx/network outcome needs reconciling.
const status = Number(error.status || 0);
const ambiguousHttpFailure = [408, 425, 429].includes(status);
if (status >= 400 && status < 500 && !ambiguousHttpFailure
&& !String(error.message).includes('正在创建')) {
clearInvoicePaymentKey(invoice.id, method.id);
}
toast(error.message, 'error');
}
finally { state.mutationBusy = false; row.querySelectorAll('button').forEach(button => { button.disabled = false; }); }
}
function renderInvoices() {
const container = byId('invoices-list'); container.replaceChildren();
if (!state.invoices.length) return container.append(makeElement('p', 'muted', '暂无续费账单。账单会在实例到期前 7 天自动生成。'));
for (const invoice of state.invoices) {
const row = makeElement('article', 'cloud-order cloud-invoice');
const detail = makeElement('div', 'cloud-order-detail');
detail.append(makeElement('strong', '', `${invoice.instance_name || '实例'} · ¥${invoice.amount}`),
makeElement('p', 'muted', `账单 ${invoice.invoice_no} · 到期时间 ${formatOrderDate(invoice.due_at)}`),
makeElement('p', 'cloud-order-message', `支付后增加 ${invoice.validity_days} 天服务期 · 新账期流量 ${formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))}`));
const actions = makeElement('div', 'cloud-order-actions');
const [label, className] = invoiceStatusInfo(invoice.status);
actions.append(makeElement('span', `state-pill ${className}`, label));
if (['open', 'overdue'].includes(invoice.status)) {
actions.append(actionButton('余额支付', () => payInvoiceBalance(invoice, row)));
for (const method of state.invoicePaymentMethods) actions.append(actionButton(method.name, () => createInvoicePayment(invoice, method, row)));
} else if (invoice.status === 'paid') {
stopInvoicePoll(invoice.id);
clearInvoicePaymentKeys(invoice.id);
actions.append(makeElement('span', 'muted', invoice.paid_at ? `支付于 ${formatOrderDate(invoice.paid_at)}` : '已结清'));
} else if (invoice.status === 'void') {
stopInvoicePoll(invoice.id);
clearInvoicePaymentKeys(invoice.id);
}
row.append(detail, actions); container.append(row);
}
}
async function loadInvoices() {
try {
const payload = await api('/api/v1/invoices');
state.invoices = Array.isArray(payload.invoices) ? payload.invoices : [];
state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : [];
text('invoices-balance', `¥${payload.balance ?? '—'}`); renderInvoices(); showError('cloud-page-error', '');
} catch (error) { showError('cloud-page-error', error.message); }
}
async function openReinstall(vm) {
if (!vm?.can_mutate) return toast('当前账户只有查看权限。', 'error');
showView('reinstall'); text('reinstall-subtitle', `${vm.name} · 保留原有公网网络参数,重新创建系统盘。`); text('reinstall-public-ip', vmIp(vm)); byId('reinstall-confirm-name').value = ''; byId('reinstall-root-password').value = ''; byId('reinstall-template').value = ''; showError('reinstall-error', ''); byId('reinstall-progress').hidden = true; byId('reinstall-result').hidden = true; byId('reinstall-fields').hidden = false;
@ -675,7 +815,7 @@ const VM_METRIC_CHARTS = [
];
function metricViewVisible() {
return Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden
return state.view === "detail" && state.detailTab === "performance" && Boolean(state.selectedVmId) && !document.hidden && !byId("dashboard-view").hidden
&& !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden;
}
@ -898,6 +1038,180 @@ function renderVmMetrics(payload) {
setVmMetricsStatus(`${visiblePoints.length} 个采样点 · ${stale ? "最近历史记录" : "最近采样"} ${formatMetricTime(latest)} · 每分钟自动刷新${stale ? "(当前无新数据)" : ""}`, stale);
}
function trafficDailyViewVisible() {
return state.view === "detail" && state.detailTab === "traffic" && Boolean(state.selectedVmId) && !document.hidden
&& !byId("dashboard-view").hidden && !byId("vm-workspace").hidden && !byId("vm-detail-view").hidden;
}
function stopVmTrafficDaily() {
state.trafficDailyRequest?.controller.abort();
state.trafficDailyRequest = null;
if (state.trafficDailyResizeTimer) window.clearTimeout(state.trafficDailyResizeTimer);
state.trafficDailyResizeTimer = null;
}
function setVmTrafficDailyStatus(message, warning = false) {
const status = byId("vm-traffic-daily-status");
status.textContent = message;
status.classList.toggle("warning", warning);
}
function clearVmTrafficDaily(message) {
stopVmTrafficDaily();
state.trafficDailyPayload = null;
state.trafficDailyVmId = "";
state.trafficDailyLoadedAt = 0;
setVmTrafficDailyStatus(message);
byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", message));
}
function trafficDailyItems(payload) {
if (Array.isArray(payload)) return payload;
for (const value of [payload?.points, payload?.days, payload?.items, payload?.daily, payload?.data?.points, payload?.data?.days, payload?.data]) {
if (Array.isArray(value)) return value;
}
return null;
}
function trafficDailyDate(point) {
const value = point?.date ?? point?.day ?? point?.bucket_date ?? point?.observed_date ?? point?.day_start ?? point?.timestamp ?? point?.time;
const dateText = typeof value === "string" ? value.trim() : "";
if (/^\d{4}-\d{2}-\d{2}$/.test(dateText)) {
return { timestamp: Date.parse(`${dateText}T00:00:00Z`), label: dateText };
}
const timestamp = serviceTimestamp(value);
if (timestamp === null) return null;
const date = new Date(timestamp);
return { timestamp, label: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(date.getUTCDate()).padStart(2, "0")}` };
}
function normalizeTrafficDailyPoints(payload) {
const values = trafficDailyItems(payload);
if (values === null) throw new Error("每日流量数据格式无效");
const points = [];
for (const point of values) {
const date = trafficDailyDate(point);
if (!date) continue;
const download = firstNumber(point?.download_bytes, point?.rx_bytes, point?.traffic_download_bytes, point?.download, point?.rx);
const upload = firstNumber(point?.upload_bytes, point?.tx_bytes, point?.traffic_upload_bytes, point?.upload, point?.tx);
points.push({ ...date, download, upload });
}
return points.sort((a, b) => a.timestamp - b.timestamp).slice(-30);
}
function trafficDailyShortDate(point) {
return point.label.slice(5).replace("-", "/");
}
function drawVmTrafficDaily(payload) {
const plot = byId("vm-traffic-daily-plot");
const points = normalizeTrafficDailyPoints(payload);
if (!points.length) {
plot.replaceChildren(makeElement("p", "vm-metric-empty", "最近 30 天暂无每日流量记录。"));
setVmTrafficDailyStatus("最近 30 天暂无每日流量记录。", true);
return;
}
const values = points.flatMap(point => [point.download, point.upload]).filter(value => value !== null);
if (!values.length) {
plot.replaceChildren(makeElement("p", "vm-metric-empty", "最近 30 天暂无每日流量采样。"));
setVmTrafficDailyStatus("最近 30 天暂无每日流量采样。", true);
return;
}
const maximum = metricNiceMax(Math.max(...values));
const width = Math.max(300, Math.floor(plot.clientWidth || 800));
const height = Math.max(220, Math.floor(plot.clientHeight || 290));
const left = 68;
const right = 18;
const top = 18;
const bottom = 38;
const plotWidth = width - left - right;
const plotHeight = height - top - bottom;
const groupWidth = plotWidth / points.length;
const barWidth = Math.max(2, Math.min(12, groupWidth * .32));
const y = (value) => top + (1 - Math.min(value, maximum) / maximum) * plotHeight;
const totalDownload = points.reduce((sum, point) => sum + (point.download ?? 0), 0);
const totalUpload = points.reduce((sum, point) => sum + (point.upload ?? 0), 0);
const sampledDays = points.filter(point => point.download !== null || point.upload !== null).length;
const svg = metricSvgElement("svg", {
viewBox: `0 0 ${width} ${height}`,
role: "img",
"aria-label": `最近 ${points.length} 天每日流量;下载 ${formatBytes(totalDownload)},上传 ${formatBytes(totalUpload)}`,
});
for (const fraction of [1, .5, 0]) {
const lineY = top + (1 - fraction) * plotHeight;
svg.append(metricSvgElement("line", { x1: left, x2: width - right, y1: lineY, y2: lineY, class: "vm-metric-gridline" }));
const label = metricSvgElement("text", { x: left - 8, y: lineY + 4, "text-anchor": "end", class: "vm-metric-axis-label" });
label.textContent = formatBytes(fraction * maximum);
svg.append(label);
}
points.forEach((point, index) => {
const center = left + (index + .5) * groupWidth;
for (const [value, className, offset] of [[point.download, "download", -barWidth], [point.upload, "upload", 0]]) {
if (value === null) continue;
const topY = y(value);
const bar = metricSvgElement("rect", {
x: center + offset,
y: topY,
width: barWidth,
height: Math.max(1, top + plotHeight - topY),
rx: Math.min(2, barWidth / 3),
class: `vm-traffic-daily-bar ${className}`,
});
const title = metricSvgElement("title");
title.textContent = `${point.label} ${className === "download" ? "下载" : "上传"} ${formatBytes(value)}`;
bar.append(title);
svg.append(bar);
}
});
const labelIndexes = [...new Set([0, Math.floor((points.length - 1) / 2), points.length - 1])];
for (const index of labelIndexes) {
const anchor = index === 0 ? "start" : index === points.length - 1 ? "end" : "middle";
const label = metricSvgElement("text", { x: left + (index + .5) * groupWidth, y: height - 8, "text-anchor": anchor, class: "vm-metric-axis-label" });
label.textContent = trafficDailyShortDate(points[index]);
svg.append(label);
}
plot.replaceChildren(svg);
setVmTrafficDailyStatus(`最近 ${points.length} 天 · ${sampledDays} 天有采样 · 下载 ${formatBytes(totalDownload)} · 上传 ${formatBytes(totalUpload)}`);
}
async function loadVmTrafficDaily(force = false) {
if (!trafficDailyViewVisible()) return;
const vmId = state.selectedVmId;
if (!force && state.trafficDailyPayload && state.trafficDailyVmId === vmId
&& Date.now() - state.trafficDailyLoadedAt < 60000) return;
if (state.trafficDailyRequest?.vmId === vmId) return;
state.trafficDailyRequest?.controller.abort();
const request = { vmId, controller: new AbortController() };
state.trafficDailyRequest = request;
setVmTrafficDailyStatus("正在加载最近 30 天每日流量…");
try {
const payload = await api(`${vmPath()}/traffic/daily?days=30`, { signal: request.controller.signal });
if (request !== state.trafficDailyRequest || !trafficDailyViewVisible()) return;
state.trafficDailyPayload = payload;
state.trafficDailyVmId = vmId;
state.trafficDailyLoadedAt = Date.now();
drawVmTrafficDaily(payload);
} catch (error) {
if (request !== state.trafficDailyRequest || request.controller.signal.aborted || !trafficDailyViewVisible()) return;
setVmTrafficDailyStatus(`每日流量暂时无法加载:${error.message}。`, true);
if (!state.trafficDailyPayload || state.trafficDailyVmId !== vmId) {
byId("vm-traffic-daily-plot").replaceChildren(makeElement("p", "vm-metric-empty", "每日流量暂时无法加载。"));
}
} finally {
if (request === state.trafficDailyRequest) state.trafficDailyRequest = null;
}
}
function startVmTrafficDaily() {
if (!trafficDailyViewVisible()) return;
if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId) drawVmTrafficDaily(state.trafficDailyPayload);
void loadVmTrafficDaily();
}
const TEMPLATE_FAMILY_NAMES = {
almalinux: "AlmaLinux",
debian: "Debian",
@ -997,20 +1311,42 @@ function renderTemplateCatalog(inputId) {
}
container.replaceChildren(...cards);
}
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'orders') await loadOrders(); } } catch (error) { showError('cloud-page-error', error.message); } }));
for (const id of ['refresh-button', 'vm-detail-refresh-button']) byId(id).addEventListener('click', loadVms);
document.querySelectorAll('[data-view]').forEach(button => button.addEventListener('click', async event => { event.preventDefault(); const view = button.dataset.view; button.closest('details')?.removeAttribute('open'); try { if (view === 'create') await openCreate(); else { showView(view); if (view === 'keys') await loadKeys(); if (view === 'orders') await loadOrders(); if (view === 'invoices') await loadInvoices(); } } catch (error) { showError('cloud-page-error', error.message); } }));
byId('refresh-button').addEventListener('click', loadVms);
byId('vm-detail-refresh-button').addEventListener('click', async () => {
await loadVms();
if (trafficDailyViewVisible()) await loadVmTrafficDaily(true);
});
byId('create-button').addEventListener('click', openCreate); byId('create-back').addEventListener('click', () => showView('list')); byId('vm-detail-back-button').addEventListener('click', () => { state.selectedVmId = null; showView('list'); }); byId('ssh-keys-back-button').addEventListener('click', () => showView('list'));
for (const id of ['reinstall-back', 'reinstall-cancel', 'rescue-back']) byId(id).addEventListener('click', () => { if (!state.mutationBusy) { const vm = selectedVm(); if (vm) openVmDetail(vm.uuid); else showView('list'); } });
byId('search-input').addEventListener('input', () => renderVMs()); byId('state-filter').addEventListener('change', () => renderVMs()); byId('vm-plan').addEventListener('change', () => { void loadPlanResources(); }); byId('create-form').querySelectorAll('[name="source"]').forEach(radio => radio.addEventListener('change', updateSource));
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('orders-refresh').addEventListener('click', loadOrders);
byId('create-form').addEventListener('submit', buy); byId('reinstall-form').addEventListener('submit', reinstall); byId('rescue-form').addEventListener('submit', event => { event.preventDefault(); void rescueAction('load'); }); byId('rescue-force-start').addEventListener('click', () => rescueAction('force-start')); byId('rescue-exit').addEventListener('click', () => rescueAction('exit')); byId('orders-refresh').addEventListener('click', loadOrders); byId('invoices-refresh').addEventListener('click', loadInvoices);
for (const id of ['vm-open-ssh-keys', 'reinstall-open-ssh-keys']) byId(id).addEventListener('click', async () => { showView('keys'); try { await loadKeys(); } catch (error) { toast(error.message, 'error'); } });
byId('ssh-key-form').addEventListener('submit', async event => { event.preventDefault(); const button = byId('ssh-key-save-button'); button.disabled = true; showError('ssh-key-form-error', ''); try { await api('/api/v1/ssh-keys', { method: 'POST', body: { name: byId('ssh-key-name').value.trim(), public_key: byId('ssh-key-public-key').value.trim() } }); byId('ssh-key-form').reset(); await loadKeys(); toast('公钥已保存。', 'success'); } catch (error) { showError('ssh-key-form-error', error.message); } finally { button.disabled = false; } });
byId('ssh-key-file').addEventListener('change', async event => { const file = event.target.files?.[0]; if (!file) return; if (file.size > 16384) return showError('ssh-key-form-error', '公钥文件超过 16 KiB 限制。'); const content = await file.text(); if (/PRIVATE KEY/.test(content)) return showError('ssh-key-form-error', '不能导入私钥,只能导入 .pub 公钥。'); byId('ssh-key-public-key').value = content.trim(); });
byId('vm-detail-ip-copy').addEventListener('click', async () => { try { await copyText(vmIp(selectedVm())); toast('公网 IP 已复制。'); } catch (error) { toast(error.message, 'error'); } }); byId('vm-detail-password-reveal').addEventListener('click', () => credential()); byId('vm-detail-password-copy').addEventListener('click', () => credential(true));
byId('vm-detail-renew-button').addEventListener('click', renewVm);
byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange = byId('vm-metrics-range').value; state.metricsRequest?.controller.abort(); state.metricsRequest = null; void loadVmMetrics(); }); window.addEventListener('resize', () => { clearTimeout(state.metricsResizeTimer); state.metricsResizeTimer = setTimeout(() => { if (state.metricsPayload && state.view === 'detail') renderVmMetrics(state.metricsPayload); }, 150); });
document.querySelectorAll('[data-detail-tab]').forEach(button => {
button.addEventListener('click', () => setVmDetailTab(button.dataset.detailTab));
button.addEventListener('keydown', event => {
const current = VM_DETAIL_TABS.indexOf(button.dataset.detailTab);
let next = current;
if (event.key === 'ArrowRight') next = (current + 1) % VM_DETAIL_TABS.length;
else if (event.key === 'ArrowLeft') next = (current - 1 + VM_DETAIL_TABS.length) % VM_DETAIL_TABS.length;
else if (event.key === 'Home') next = 0;
else if (event.key === 'End') next = VM_DETAIL_TABS.length - 1;
else return;
event.preventDefault();
setVmDetailTab(VM_DETAIL_TABS[next], true);
});
});
byId('vm-metrics-range').addEventListener('change', () => { state.metricsRange = byId('vm-metrics-range').value; state.metricsRequest?.controller.abort(); state.metricsRequest = null; void loadVmMetrics(); }); window.addEventListener('resize', () => {
clearTimeout(state.metricsResizeTimer);
clearTimeout(state.trafficDailyResizeTimer);
state.metricsResizeTimer = setTimeout(() => { if (state.metricsPayload && metricViewVisible()) renderVmMetrics(state.metricsPayload); }, 150);
state.trafficDailyResizeTimer = setTimeout(() => { if (state.trafficDailyPayload && state.trafficDailyVmId === state.selectedVmId && trafficDailyViewVisible()) drawVmTrafficDaily(state.trafficDailyPayload); }, 150);
});
byId('console-modal').querySelector('[data-close-modal]').addEventListener('click', closeConsole); byId('console-cad').addEventListener('click', () => state.rfb?.sendCtrlAltDel()); byId('console-fullscreen').addEventListener('click', () => { byId('console-stage').requestFullscreen?.().catch(error => toast(error.message, 'error')); }); byId('console-password-form').addEventListener('submit', event => { event.preventDefault(); state.rfb?.sendCredentials({ password: byId('console-password').value }); byId('console-password').value = ''; byId('console-password-form').hidden = true; }); window.addEventListener('keydown', event => { if (event.key === 'Escape') closeConsole(); });
document.addEventListener('visibilitychange', () => { if (document.hidden) clearCredential(); else { void loadVms(); if (state.view === 'detail') startVmMetrics(); } }); window.addEventListener('pagehide', () => { clearCredential(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/user/logout'); });
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); if (link) link.hidden = !state.admin; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (state.view === 'orders') void loadOrders(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
document.addEventListener('visibilitychange', () => { if (document.hidden) { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); } else { void loadVms(); if (state.view === 'detail') setVmDetailTab(state.detailTab); if (state.view === 'invoices') void loadInvoices(); } }); window.addEventListener('pagehide', () => { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); stopInvoicePoll(); closeConsole(); state.resourceController?.abort(); }); byId('logout-button').addEventListener('click', () => { clearCredential(); closeConsole(); location.assign('/user/logout'); });
async function initialize() { const initialHash = location.hash; try { const session = await api('/api/v1/session'); if (session.authenticated === false) { location.assign('/auth/login'); return; } state.csrfToken = session.csrf_token || ''; if (!state.csrfToken) throw new Error('会话 CSRF 令牌缺失,请重新登录。'); state.userId = String(session.user_id || ''); if (!/^\d+$/.test(state.userId)) throw new Error('会话用户标识缺失,请重新登录。'); state.username = session.username || session.user_name || session.email || session.user?.email || '用户'; state.admin = session.admin === true || session.is_admin === true || Number(session.is_admin) === 1; text('current-username', state.username); for (const id of ['cloud-admin-link', 'cloud-admin-menu-link']) { const link = byId(id); if (link) link.hidden = !state.admin; } showView('list'); updateSource(); await loadVms(); await routeHash(initialHash); setInterval(() => { if (!document.hidden) { void loadVms(); if (trafficDailyViewVisible()) void loadVmTrafficDaily(); if (state.view === 'orders') void loadOrders(); if (state.view === 'invoices' && state.invoicePollTimers.size === 0) void loadInvoices(); } }, 15000); } catch (error) { showError('cloud-page-error', error.message); } }
window.addEventListener('hashchange', () => { if (state.csrfToken) void routeHash(); });
void initialize();

@ -41,18 +41,28 @@
.cloud-order-progress { font-size: 11px; overflow-wrap: anywhere; }
.cloud-order-progress.form-error { margin-top: 9px; }
.cloud-order-actions .state-pill.failed { background: #fff0f1; color: #bd4654; }
.cloud-order-actions .state-pill.warning { background: #fff4e5; color: #b98129; }
.cloud-order-actions { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
.cloud-order-actions .row-button { min-height: 36px; padding: 8px 12px; border-color: #dce7ec; background: #fff; }
.cloud-order-actions .row-button:not(:disabled):hover { border-color: #bcdadd; background: #edf8f8; }
.cloud-order:last-child { border: 0; }
.cloud-order code { overflow-wrap: anywhere; }
.invoice-balance-card { display: flex; align-items: center; gap: 14px; margin: 0 0 20px; padding: 18px 22px; border: 1px solid #e0e9ef; border-radius: 13px; background: #fff; box-shadow: 0 10px 30px rgba(19,42,65,.027); color: #77899a; font-size: 12px; font-weight: 700; }
.invoice-balance-card strong { margin-right: auto; color: #1e354d; font-size: 23px; letter-spacing: -.4px; }
.cloud-invoice { position: relative; }
.cloud-payment-instructions { grid-column: 1 / -1; display: flex; align-items: center; flex-wrap: wrap; gap: 9px 13px; margin-top: 2px; padding: 14px 16px; border-radius: 9px; background: #edf8f8; color: #3e596b; font-size: 11px; line-height: 1.6; }
.cloud-payment-instructions strong { color: #20394e; }
.cloud-payment-instructions code { max-width: 100%; padding: 5px 8px; border-radius: 5px; background: #fff; color: #25465b; font-size: 11px; }
.cloud-payment-instructions small { flex: 1 1 100%; color: #738798; }
.cloud-payment-instructions .row-button,.cloud-payment-instructions .button { min-height: 34px; padding: 7px 11px; }
.cloud-payment-qr { display: flex; width: 212px; min-height: 212px; align-items: center; justify-content: center; padding: 8px; border: 1px solid #d7e3e9; border-radius: 10px; background: #fff; }
.cloud-payment-qr img,.cloud-payment-qr canvas { display: block; max-width: 196px; height: auto; }
.cloud-plan-summary { display: flex; flex-wrap: wrap; gap: 12px; }
.cloud-page-progress { margin: 16px 0; }
.vm-detail-secret { max-width: 100%; overflow-wrap: anywhere; }
.vm-service-panel { margin-top: 18px; }
.vm-service-panel { margin-top: 0; }
.vm-service-panel .panel-heading { align-items: center; }
.vm-service-panel .panel-heading > div { min-width: 0; }
.vm-renew-button { flex: none; }
.vm-service-facts { display: grid; grid-template-columns: repeat(auto-fit, minmax(155px, 1fr)); gap: 0; margin: 0; padding: 5px 24px 13px; }
.vm-service-facts > div { min-width: 0; padding: 15px 12px 15px 0; border-bottom: 1px solid #edf1f5; }
.vm-service-facts dt { margin: 0 0 8px; color: #91a0af; font-size: 11px; font-weight: 700; }
@ -66,6 +76,20 @@
.vm-traffic-progress { height: 8px; margin: 0 24px 22px; overflow: hidden; border-radius: 999px; background: #e7eef2; }
.vm-traffic-progress > span { display: block; width: 0; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #1bb6b0, #0f9eaa); transition: width .25s ease; }
.vm-traffic-progress.is-exhausted > span { background: #d94350; }
.vm-traffic-daily { margin-top: 18px; overflow: hidden; }
.vm-traffic-daily-status { margin: 0 24px 4px; padding: 9px 12px; border-radius: 8px; background: #eaf7f7; color: #277b82; font-size: 11px; line-height: 1.5; }
.vm-traffic-daily-status.warning { background: #fff6e9; color: #946620; }
.vm-traffic-daily-plot { display: flex; align-items: center; justify-content: center; height: 300px; margin: 4px 20px 2px; overflow: hidden; }
.vm-traffic-daily-plot svg { display: block; width: 100%; height: 100%; font-family: Inter, "SF Pro Display", "PingFang SC", "Microsoft YaHei", sans-serif; }
.vm-traffic-daily-bar.download { fill: #17a685; }
.vm-traffic-daily-bar.upload { fill: #926ed0; }
.vm-traffic-daily-bar { transition: opacity .15s ease; }
.vm-traffic-daily-bar:hover { opacity: .72; }
.vm-traffic-daily-legend { display: flex; align-items: center; flex-wrap: wrap; gap: 18px; padding: 0 24px 21px; color: #728297; font-size: 10px; font-weight: 700; }
.vm-traffic-daily-legend span { display: inline-flex; align-items: center; gap: 7px; }
.vm-traffic-daily-legend i { width: 13px; height: 8px; border-radius: 2px; }
.vm-traffic-daily-legend i.download { background: #17a685; }
.vm-traffic-daily-legend i.upload { background: #926ed0; }
.ssh-key-choice-label { align-self: center; }
#vm-plan-summary { display: block; padding: 16px; }
#cloud-page-error { margin-bottom: 20px; }
@ -91,7 +115,7 @@
.cloud-order { grid-template-columns: 1fr; gap: 13px; }
.cloud-order-actions { justify-content: flex-start; }
.vm-service-panel .panel-heading { align-items: flex-start; }
.vm-service-panel .vm-renew-button { width: 100%; }
.vm-traffic-daily-plot { height: 250px; margin-inline: 12px; }
}
@media (max-width: 520px) {
@ -103,7 +127,13 @@
.cloud-order { padding: 19px 17px; }
.cloud-order-actions { width: 100%; }
.cloud-order-actions .row-button { flex: 1 1 145px; }
.invoice-balance-card { align-items: flex-start; flex-wrap: wrap; }
.invoice-balance-card strong { flex: 1 1 calc(100% - 130px); }
.vm-detail-tabs { width: 100%; }
.vm-detail-tab { flex: 1 0 auto; padding-inline: 12px; }
.vm-service-facts { grid-template-columns: 1fr 1fr; padding: 4px 17px 12px; }
.vm-service-facts > div { padding: 12px 8px 12px 0; }
.vm-traffic-progress { margin: 0 17px 18px; }
.vm-traffic-daily-status { margin-inline: 17px; }
.vm-traffic-daily-legend { padding-inline: 17px; }
}

@ -130,11 +130,11 @@ tbody tr:hover{background:#fcfefe}
.row-actions{display:flex;align-items:center;justify-content:flex-end;gap:5px;white-space:nowrap}.row-button{border:1px solid transparent;background:transparent;color:#577083;border-radius:7px;padding:7px 8px;min-height:31px;font-size:11px;font-weight:700}.row-button:not(:disabled):hover{background:#e8f7f7;color:#117f88}.row-button.primary{background:#e7f7f7;color:#118e98}.row-button.danger{color:#bf6470}.row-button.danger:not(:disabled):hover{background:#fff0f1;color:#ba3a49}
.empty-state{text-align:center;padding:65px 20px 72px}.empty-icon{margin:0 auto 16px;width:54px;height:54px;display:flex;align-items:center;justify-content:center;border-radius:16px;background:#eaf7f7;color:#17a3aa;font-size:28px}.empty-state h3{font-size:16px;color:#34465a;margin:0 0 8px}.empty-state p{font-size:12px;color:#a0aebe;margin:0}
.footer-note{text-align:right;color:#a9b4c0;font-size:10px;margin-top:18px}
.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef}
.vm-detail-back{padding-left:0;margin-bottom:22px;color:#267b86}.vm-detail-heading{align-items:center}.vm-detail-heading .heading-actions{align-items:center}.vm-detail-heading .state-pill{min-height:31px}.vm-detail-summary{display:flex;align-items:center;flex-wrap:wrap;gap:5px 18px}.vm-detail-summary span{white-space:nowrap}.vm-detail-summary strong{color:#455a70;font-weight:700;margin-left:4px}.vm-detail-tabs{display:flex;width:max-content;max-width:100%;gap:4px;margin:0 0 18px;padding:5px;overflow-x:auto;border:1px solid #dfeaec;border-radius:11px;background:#f3f8f9}.vm-detail-tab{min-height:39px;padding:9px 18px;border:0;border-radius:8px;background:transparent;color:#718497;font:inherit;font-size:12px;font-weight:800;white-space:nowrap;cursor:pointer}.vm-detail-tab:hover{color:#237f88;background:#e8f4f4}.vm-detail-tab.active{background:#fff;color:#157f88;box-shadow:0 2px 9px rgba(27,71,87,.1)}.vm-detail-tab:focus-visible{outline:2px solid #25adb4;outline-offset:2px}.vm-detail-grid{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(320px,.85fr);gap:18px;align-items:start}.vm-detail-panel{min-height:0}.vm-detail-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0;margin:0;padding:6px 24px 17px}.vm-detail-facts>div{min-width:0;padding:17px 9px 17px 0;border-bottom:1px solid #edf1f5}.vm-detail-facts dt{font-size:11px;font-weight:700;color:#91a0af;margin-bottom:9px}.vm-detail-facts dd{margin:0;color:#273c52;font-size:13px;font-weight:700;line-height:1.5;overflow-wrap:anywhere}.vm-detail-operations{display:grid;gap:18px}.vm-detail-actions{display:flex;flex-wrap:wrap;gap:10px;padding:20px 24px 23px}.vm-detail-actions .row-button{min-height:39px;padding:9px 15px;border-color:#dce9ea;font-size:12px}.vm-detail-actions .row-button.primary{border-color:#cbecee}.vm-danger-panel .panel-heading h2{color:#a4434f}.vm-danger-panel .row-button.danger{border-color:#f2dfe2;background:#fff9f9}.vm-danger-panel .row-button.danger:not(:disabled):hover{background:#ffedef}
.vm-detail-inline,.vm-ip-copy-row{display:flex;align-items:center;flex-wrap:wrap;gap:7px}.vm-detail-inline{min-height:25px}.vm-detail-secret{font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.vm-detail-mini-button,.vm-copy-icon{display:inline-flex;align-items:center;justify-content:center;flex:none;border:1px solid #d9e9ea;border-radius:6px;background:#f5fbfb;color:#1b8790;font-size:11px;font-weight:700;min-height:25px;padding:3px 7px}.vm-detail-mini-button:not(:disabled):hover,.vm-copy-icon:not(:disabled):hover{background:#e6f6f7;border-color:#b6dcdf}.vm-copy-icon{width:25px;padding:3px}.vm-copy-icon svg{display:block;width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
.vm-credential-icon{width:30px;min-height:30px}.vm-credential-icon svg{width:17px;height:17px}.vm-credential-icon .vm-eye-slash{visibility:hidden}.vm-credential-icon[aria-pressed="true"] .vm-eye-slash{visibility:visible}
.vm-detail-facts .vm-detail-credential-row{grid-column:1/-1}
.vm-metrics{margin-top:25px}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6}
.vm-metrics{margin-top:0}.vm-metrics-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}.vm-metrics-heading h2{font-size:19px;margin:7px 0 6px}.vm-metrics-heading p{font-size:11px;color:#8191a1;line-height:1.6;margin:0}.vm-metrics-range-control{display:flex;align-items:center;gap:9px;flex:none;color:#64768a;font-size:11px;font-weight:700}.vm-metrics-range-control select{height:37px;padding:0 11px;border:1px solid #dbe6ec;border-radius:8px;color:#344e60;background:#fff;font-size:12px;font-weight:700}.vm-metrics-status{margin:0 0 14px;padding:9px 12px;border-radius:8px;background:#eaf7f7;color:#277b82;font-size:11px;line-height:1.5}.vm-metrics-status.warning{background:#fff6e9;color:#946620}.vm-metrics-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:17px}.vm-metric-card{min-width:0;padding:20px 21px 16px;border:1px solid #e7ecf2;border-radius:13px;background:#fff;box-shadow:0 10px 30px rgba(19,42,65,.027)}.vm-metric-card-heading{display:flex;align-items:flex-start;gap:11px;min-height:62px}.vm-metric-card-heading>div{min-width:0}.vm-metric-card-heading h3{margin:1px 0 6px;font-size:13px;color:#32485b}.vm-metric-card-heading p{margin:0;color:#60758a;font-size:12px;line-height:1.45;overflow-wrap:anywhere}.vm-metric-icon{display:flex;align-items:center;justify-content:center;flex:none;width:34px;height:34px;border-radius:9px;font-size:18px;font-weight:700}.vm-metric-icon.cpu{background:#e8f8f8;color:#0f9eaa}.vm-metric-icon.memory{background:#edf3fb;color:#4781cf}.vm-metric-icon.disk{background:#eef3fa;color:#477dc9}.vm-metric-icon.network{background:#eaf8f2;color:#17a685}.vm-metric-plot{display:flex;align-items:center;justify-content:center;height:205px;margin:8px 0 6px;overflow:hidden}.vm-metric-plot svg{display:block;width:100%;height:100%;font-family:Inter,"SF Pro Display","PingFang SC","Microsoft YaHei",sans-serif}.vm-metric-gridline{stroke:#e5edf2;stroke-width:1;stroke-dasharray:3 4}.vm-metric-axis-label{fill:#9aabb9;font-size:10px}.vm-metric-empty{margin:0;padding:15px;text-align:center;color:#94a2af;font-size:11px;line-height:1.6}.vm-metric-legend{display:flex;align-items:center;flex-wrap:wrap;gap:15px;padding-left:7px;color:#728297;font-size:10px;font-weight:700}.vm-metric-legend span{display:inline-flex;align-items:center;gap:6px}.vm-metric-swatch{display:inline-block;width:16px;height:0;border-top:3px solid #0f9eaa;border-radius:2px}.vm-metric-swatch.cpu{border-color:#0f9eaa}.vm-metric-swatch.memory{border-color:#4781cf}.vm-metric-swatch.memory-total{border-color:#a4b7d7;border-top-style:dashed}.vm-metric-swatch.disk-read{border-color:#477dc9}.vm-metric-swatch.disk-write{border-color:#e59c46}.vm-metric-swatch.network-rx{border-color:#17a685}.vm-metric-swatch.network-tx{border-color:#926ed0}.vm-metrics-footnote{margin:12px 1px 0;color:#9ba8b6;font-size:10px;line-height:1.6}
.modal-backdrop{position:fixed;inset:0;z-index:30;background:rgba(11,25,40,.58);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(3px)}
.modal{width:min(100%,610px);max-height:min(92vh,900px);overflow:auto;border-radius:14px;background:#fff;box-shadow:0 22px 70px rgba(0,0,0,.2)}.narrow-modal{width:min(100%,460px)}
.modal-header{display:flex;align-items:flex-start;justify-content:space-between;padding:26px 29px 18px;border-bottom:1px solid #edf1f5}.modal-header h2{font-size:21px;letter-spacing:-.35px;margin:7px 0 5px}.modal-header p{font-size:12px;color:#95a1af;margin:0}.icon-button{border:0;border-radius:8px;background:transparent;color:#8a98a8;width:31px;height:31px;font-size:23px;line-height:1;display:flex;align-items:center;justify-content:center}.icon-button:hover{background:#f1f5f8;color:#30445a}

@ -0,0 +1,5 @@
<p>您好:</p>
<p>您的云服务器 <strong>{$instance_name|escape}</strong> 将于 {$due_at|escape} 到期。</p>
<p>续费账单 {$invoice_no|escape},应付金额 ¥{$amount|escape}。请在到期前完成支付,逾期未支付的实例将自动停机。</p>
<p><a href="{$invoice_url|escape}">查看并支付账单</a></p>
<p>此邮件由系统自动发送,请勿直接回复。</p>

@ -1,2 +1,2 @@
{assign var=admin_title value='开通订单'}{assign var=admin_active value='cloud_orders'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>余额开通订单</h4><p class="text-muted">开通套餐按设置的账期生效,用户可在实例详情手动续费,不自动扣款。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>订单</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>余额开通订单</h4><p class="text-muted">开通套餐按设置的账期生效;到期前 7 天生成续费账单,用户可以使用账户余额或已启用的在线支付渠道结清。失败或不确定的开通任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>订单</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}

@ -1,5 +1,5 @@
{assign var=admin_title value='新增商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'}
<div class="py-3"><h4>新增云服务器套餐</h4><p class="text-muted">绑定宿主机并设置账期、每期流量额度后,用户可用余额购买开通及手动续费。</p><a class="btn btn-light" href="/admin/shop">返回商品列表</a></div>
<div class="py-3"><h4>新增云服务器套餐</h4><p class="text-muted">绑定宿主机并设置账期、每期流量额度后,用户可用余额购买开通;到期前会生成支持余额或在线支付的续费账单。</p><a class="btn btn-light" href="/admin/shop">返回商品列表</a></div>
<form class="card" id="shopForm" data-method="POST" data-url="/admin/shop"><div class="card-body"><div class="row g-3"><div class="col-12"><label class="form-label" for="name">商品名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" value="" required></div>
<div class="col-md-6"><label class="form-label" for="cpu_cores">CPU 核数</label><input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="2" required></div>
<div class="col-md-6"><label class="form-label" for="host_id">开通宿主机</label><select class="form-select" id="host_id" name="host_id" data-selected=""><option value="">未绑定(禁止购买)</option></select></div>

@ -24,38 +24,49 @@
<section id="vm-detail-view" class="vm-detail-view" aria-labelledby="vm-detail-name" hidden>
<button id="vm-detail-back-button" class="button button-ghost vm-detail-back" type="button">← 返回虚拟机列表</button>
<div class="page-heading vm-detail-heading"><div><span class="eyebrow">VIRTUAL MACHINE DETAILS</span><h1 id="vm-detail-name" tabindex="-1">虚拟机</h1><p class="vm-detail-summary"><span><span class="sr-only">服务器 IP:</span><strong id="vm-detail-header-ip">未获取</strong></span><span><span class="sr-only">区域:</span><strong id="vm-detail-header-region">未设置</strong></span><span><strong id="vm-detail-header-created-at">未记录</strong></span></p></div><div class="heading-actions"><span id="vm-detail-state" class="state-pill other">未知</span><button id="vm-detail-refresh-button" class="button button-outline" type="button"><span aria-hidden="true">↻</span> 刷新</button></div></div>
<div class="vm-detail-grid">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-info-title"><div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div><dl class="vm-detail-facts">
<div><dt>地区</dt><dd id="vm-detail-region">未设置</dd></div><div><dt id="vm-detail-os-label">系统</dt><dd id="vm-detail-os">未识别</dd></div>
<div><dt>已配置公网 IP</dt><dd class="vm-detail-inline"><span id="vm-detail-ip">未获取</span><button id="vm-detail-ip-copy" class="vm-copy-icon" type="button" aria-label="复制公网 IP" title="复制公网 IP" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button></dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">—</dd></div>
<div><dt>硬盘大小</dt><dd id="vm-detail-disk">—</dd></div>
<div><dt>SSH 登录名</dt><dd id="vm-detail-ssh-user">未记录</dd></div>
<div class="vm-detail-credential-row"><dt>面板记录的初始 root 密码</dt><dd class="vm-detail-inline"><code id="vm-detail-root-password" class="vm-detail-secret">未记录</code>
<button id="vm-detail-password-reveal" class="vm-copy-icon vm-credential-icon" type="button" aria-label="查看初始 root 密码" title="查看初始 root 密码" aria-controls="vm-detail-root-password" aria-pressed="false" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.3 12S5.8 6.5 12 6.5s9.7 5.5 9.7 5.5-3.5 5.5-9.7 5.5S2.3 12 2.3 12Z"/><circle cx="12" cy="12" r="2.6"/><path class="vm-eye-slash" d="M3 3 21 21"/></svg></button>
<button id="vm-detail-password-copy" class="vm-copy-icon vm-credential-icon" type="button" aria-label="复制初始 root 密码" title="复制初始 root 密码" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button>
</dd></div>
</dl></section>
<div class="vm-detail-operations"><section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"></div></section></div>
<div id="vm-detail-tabs" class="vm-detail-tabs" role="tablist" aria-label="虚拟机详情页面">
<button id="vm-detail-tab-operations" class="vm-detail-tab active" type="button" role="tab" aria-selected="true" aria-controls="vm-detail-operations-panel" data-detail-tab="operations">实例操作</button>
<button id="vm-detail-tab-performance" class="vm-detail-tab" type="button" role="tab" aria-selected="false" aria-controls="vm-detail-performance-panel" data-detail-tab="performance" tabindex="-1">性能监控</button>
<button id="vm-detail-tab-traffic" class="vm-detail-tab" type="button" role="tab" aria-selected="false" aria-controls="vm-detail-traffic-panel" data-detail-tab="traffic" tabindex="-1">流量信息</button>
</div>
<section class="inventory-panel vm-service-panel" aria-labelledby="vm-service-title">
<div class="panel-heading"><div><h2 id="vm-service-title">服务周期与流量</h2><p id="vm-detail-service-note">正在读取套餐服务信息…</p></div><button id="vm-detail-renew-button" class="button button-primary vm-renew-button" type="button" hidden>立即续费</button></div>
<dl class="vm-service-facts">
<div><dt>服务状态</dt><dd><span id="vm-detail-service-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>网络状态</dt><dd><span id="vm-detail-network-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>当前账期开始</dt><dd id="vm-detail-period-start">暂未提供</dd></div>
<div><dt>当前账期结束</dt><dd id="vm-detail-period-end">暂未提供</dd></div>
<div><dt>最终服务到期</dt><dd id="vm-detail-expires-at">暂未提供</dd></div>
<div><dt>已预付未来账期</dt><dd id="vm-detail-prepaid-periods">暂未提供</dd></div>
<div><dt>本期下载(RX)</dt><dd id="vm-detail-traffic-rx">暂未提供</dd></div>
<div><dt>本期上传(TX)</dt><dd id="vm-detail-traffic-tx">暂未提供</dd></div>
<div><dt>本期合计已用</dt><dd id="vm-detail-traffic-used">暂未提供</dd></div>
<div><dt>本期流量额度</dt><dd id="vm-detail-traffic-quota">暂未提供</dd></div>
<div><dt>本期剩余流量</dt><dd id="vm-detail-traffic-remaining">暂未提供</dd></div>
</dl>
<div id="vm-detail-traffic-progress" class="vm-traffic-progress" role="progressbar" aria-label="套餐流量使用率" aria-valuemin="0" aria-valuemax="100" hidden><span id="vm-detail-traffic-progress-bar"></span></div>
</section>
<section class="vm-metrics" aria-labelledby="vm-metrics-title">
<div id="vm-detail-operations-panel" role="tabpanel" aria-labelledby="vm-detail-tab-operations">
<div class="vm-detail-grid">
<section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-info-title"><div class="panel-heading"><div><h2 id="vm-detail-info-title">虚拟机信息</h2><p>状态和配置每 15 秒自动更新;IP 是面板记录的配置,不代表系统已联网。</p></div></div><dl class="vm-detail-facts">
<div><dt>地区</dt><dd id="vm-detail-region">未设置</dd></div><div><dt id="vm-detail-os-label">系统</dt><dd id="vm-detail-os">未识别</dd></div>
<div><dt>已配置公网 IP</dt><dd class="vm-detail-inline"><span id="vm-detail-ip">未获取</span><button id="vm-detail-ip-copy" class="vm-copy-icon" type="button" aria-label="复制公网 IP" title="复制公网 IP" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button></dd></div><div><dt>计算规格</dt><dd id="vm-detail-spec">—</dd></div>
<div><dt>硬盘大小</dt><dd id="vm-detail-disk">—</dd></div>
<div><dt>SSH 登录名</dt><dd id="vm-detail-ssh-user">未记录</dd></div>
<div class="vm-detail-credential-row"><dt>面板记录的初始 root 密码</dt><dd class="vm-detail-inline"><code id="vm-detail-root-password" class="vm-detail-secret">未记录</code>
<button id="vm-detail-password-reveal" class="vm-copy-icon vm-credential-icon" type="button" aria-label="查看初始 root 密码" title="查看初始 root 密码" aria-controls="vm-detail-root-password" aria-pressed="false" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M2.3 12S5.8 6.5 12 6.5s9.7 5.5 9.7 5.5-3.5 5.5-9.7 5.5S2.3 12 2.3 12Z"/><circle cx="12" cy="12" r="2.6"/><path class="vm-eye-slash" d="M3 3 21 21"/></svg></button>
<button id="vm-detail-password-copy" class="vm-copy-icon vm-credential-icon" type="button" aria-label="复制初始 root 密码" title="复制初始 root 密码" hidden><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"/></svg></button>
</dd></div>
</dl></section>
<div class="vm-detail-operations"><section class="inventory-panel vm-detail-panel" aria-labelledby="vm-detail-actions-title"><div class="panel-heading"><div><h2 id="vm-detail-actions-title">日常操作</h2><p>在这里管理这台虚拟机的电源和控制台。</p></div></div><div id="vm-detail-primary-actions" class="vm-detail-actions"></div></section>
<section class="inventory-panel vm-detail-panel vm-danger-panel" aria-labelledby="vm-detail-danger-title"><div class="panel-heading"><div><h2 id="vm-detail-danger-title">维护与危险操作</h2><p>救援会先预挂载 ISO,再尝试正常关机并开机;强制断电可能丢失未保存的数据,重装或删除会清除数据。</p></div></div><div id="vm-detail-danger-actions" class="vm-detail-actions"></div></section></div>
</div>
</div>
<div id="vm-detail-traffic-panel" role="tabpanel" aria-labelledby="vm-detail-tab-traffic" hidden>
<section class="inventory-panel vm-service-panel" aria-labelledby="vm-service-title">
<div class="panel-heading"><div><h2 id="vm-service-title">服务周期与流量</h2><p>查看当前服务、网络状态和本期流量使用情况。</p></div></div>
<dl class="vm-service-facts">
<div><dt>服务状态</dt><dd><span id="vm-detail-service-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>网络状态</dt><dd><span id="vm-detail-network-status" class="service-pill unknown">暂未提供</span></dd></div>
<div><dt>当前账期结束</dt><dd id="vm-detail-period-end">暂未提供</dd></div>
<div><dt>本期下载(RX)</dt><dd id="vm-detail-traffic-rx">暂未提供</dd></div>
<div><dt>本期上传(TX)</dt><dd id="vm-detail-traffic-tx">暂未提供</dd></div>
<div><dt>本期合计已用</dt><dd id="vm-detail-traffic-used">暂未提供</dd></div>
<div><dt>总流量 / 剩余流量</dt><dd id="vm-detail-traffic-total-remaining">暂未提供</dd></div>
</dl>
<div id="vm-detail-traffic-progress" class="vm-traffic-progress" role="progressbar" aria-label="套餐流量使用率" aria-valuemin="0" aria-valuemax="100" hidden><span id="vm-detail-traffic-progress-bar"></span></div>
</section>
<section class="inventory-panel vm-traffic-daily" aria-labelledby="vm-traffic-daily-title">
<div class="panel-heading"><div><h2 id="vm-traffic-daily-title">最近 30 天每日流量</h2><p>按天统计虚拟机的下载和上传流量。</p></div></div>
<p id="vm-traffic-daily-status" class="vm-traffic-daily-status" role="status">打开流量信息后加载每日统计。</p>
<div id="vm-traffic-daily-plot" class="vm-traffic-daily-plot"></div>
<div class="vm-traffic-daily-legend"><span><i class="download"></i>下载</span><span><i class="upload"></i>上传</span></div>
</section>
</div>
<section id="vm-detail-performance-panel" class="vm-metrics" role="tabpanel" aria-labelledby="vm-detail-tab-performance" hidden>
<div class="vm-metrics-heading"><div><span class="eyebrow">PERFORMANCE HISTORY</span><h2 id="vm-metrics-title">性能监控</h2><p>每分钟采样并自动刷新,历史数据最长保留 30 天;长时间范围会聚合,较长的采样缺口留空。</p></div><label class="vm-metrics-range-control" for="vm-metrics-range">时间范围 <select id="vm-metrics-range"><option value="1h">最近 1 小时</option><option value="24h" selected>最近 24 小时</option><option value="7d">最近 7 天</option><option value="30d">最近 30 天</option></select></label></div>
<p id="vm-metrics-status" class="vm-metrics-status" role="status">选择虚拟机后加载监控数据。</p>
<div class="vm-metrics-grid">
@ -151,6 +162,11 @@
</div>
<section id="orders-workspace" hidden><div class="page-heading"><div><span class="eyebrow">PROVISIONING ORDERS</span><h1>开通订单</h1><p>余额支付后由后台持续开通;关闭页面不会取消任务。失败会按订单状态退款,失败原因在此显示。</p></div><button id="orders-refresh" class="button button-outline" type="button">刷新</button></div><div id="orders-list" class="inventory-panel cloud-orders" aria-live="polite"></div></section>
<section id="invoices-workspace" hidden>
<div class="page-heading"><div><span class="eyebrow">RENEWAL INVOICES</span><h1>续费账单</h1><p>实例到期前 7 天自动生成账单;可使用账户余额或已启用的在线支付渠道结清。</p></div><button id="invoices-refresh" class="button button-outline" type="button">刷新</button></div>
<div class="invoice-balance-card"><span>当前账户余额</span><strong id="invoices-balance">¥—</strong><a class="button button-outline small" href="/user/code">余额充值</a></div>
<div id="invoices-list" class="inventory-panel cloud-orders cloud-invoices" aria-live="polite"><p class="muted">正在加载…</p></div>
</section>
</main></div></div> <div id="console-modal" class="modal-backdrop console-backdrop" hidden>
<section class="modal console-modal" role="dialog" aria-modal="true" aria-labelledby="console-title"><div class="console-toolbar"><div><span class="eyebrow">VNC CONSOLE</span><h2 id="console-title">虚拟机控制台</h2><p id="console-status">正在连接…</p></div><div class="console-tools"><button id="console-cad" class="button button-outline small" type="button" disabled>发送 Ctrl+Alt+Del</button><button id="console-fullscreen" class="button button-outline small" type="button">全屏</button><button class="icon-button" type="button" data-close-modal aria-label="关闭">×</button></div></div><div id="console-stage" class="console-stage"><div id="console-placeholder" class="console-placeholder"><span class="console-spinner" aria-hidden="true"></span><span>正在连接到虚拟机画面…</span></div></div><form id="console-password-form" class="console-password" hidden><label for="console-password">VNC 密码</label><input id="console-password" type="password" autocomplete="off" required /><button class="button button-primary small" type="submit">连接</button></form></section>
</div><div id="toast" class="toast" role="status" aria-live="polite" hidden></div><script type="module" src="/cloud/app.js?v={$venix_asset_version}"></script></body></html>
</div><div id="toast" class="toast" role="status" aria-live="polite" hidden></div><script src="/theme/venix/js/qrcode.min.js?v={$venix_asset_version}"></script><script type="module" src="/cloud/app.js?v={$venix_asset_version}"></script></body></html>

@ -1 +1 @@
{assign var=venix_asset_version value='2026092707' scope='global'}
{assign var=venix_asset_version value='2026092708' scope='global'}

@ -25,6 +25,9 @@
<a class="sidebar-link" href="/user/cloud#orders"{if $panel_cloud_mode} data-view="orders"{/if}>
<i class="mdi mdi-clipboard-text-outline nav-icon" aria-hidden="true"></i><span>开通订单</span>
</a>
<a class="sidebar-link" href="/user/cloud#invoices"{if $panel_cloud_mode} data-view="invoices"{/if}>
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>续费账单</span>
</a>
<div class="sidebar-section-label">账户与支持</div>
<a class="sidebar-link{if $panel_active_key == 'home'} active{/if}" href="/user/account">

@ -98,6 +98,67 @@ CREATE TABLE IF NOT EXISTS cloud_renewals (
UNIQUE KEY uniq_cloud_renewal_request (user_id, idempotency_key),
KEY cloud_renewal_instance (instance_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_invoices (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_no VARCHAR(40) NOT NULL,
instance_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
plan_id BIGINT UNSIGNED DEFAULT NULL,
renewal_id BIGINT UNSIGNED DEFAULT NULL,
renews_expires_at BIGINT UNSIGNED NOT NULL,
due_at BIGINT UNSIGNED NOT NULL,
amount DECIMAL(12,2) NOT NULL,
validity_days INT UNSIGNED NOT NULL,
traffic_quota_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
status VARCHAR(16) NOT NULL DEFAULT 'open',
paid_via VARCHAR(32) DEFAULT NULL,
payment_reference VARCHAR(80) DEFAULT NULL,
paid_at BIGINT UNSIGNED DEFAULT NULL,
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY uniq_cloud_invoice_no (invoice_no),
KEY cloud_invoice_period (instance_id, renews_expires_at, status),
UNIQUE KEY uniq_cloud_invoice_renewal (renewal_id),
KEY cloud_invoice_owner (user_id, status, due_at),
KEY cloud_invoice_due (status, due_at, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Releases created before void invoices became replaceable used a unique
-- period key. Keep void rows as an audit trail while permitting one corrected
-- replacement bill for the same expiry.
ALTER TABLE cloud_invoices DROP INDEX IF EXISTS uniq_cloud_invoice_period;
ALTER TABLE cloud_invoices ADD INDEX IF NOT EXISTS
cloud_invoice_period (instance_id, renews_expires_at, status);
CREATE TABLE IF NOT EXISTS cloud_invoice_payments (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_id BIGINT UNSIGNED NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
provider VARCHAR(24) NOT NULL,
provider_order_no VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
amount DECIMAL(12,2) NOT NULL,
status VARCHAR(24) NOT NULL DEFAULT 'creating',
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY uniq_cloud_invoice_provider_order (provider, provider_order_no),
UNIQUE KEY uniq_cloud_invoice_payment_request (user_id, idempotency_key),
KEY cloud_invoice_payment_invoice (invoice_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_mail_outbox (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
invoice_id BIGINT UNSIGNED NOT NULL,
kind VARCHAR(32) NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'pending',
attempts INT UNSIGNED NOT NULL DEFAULT 0,
available_at BIGINT UNSIGNED NOT NULL,
lease_token CHAR(32) DEFAULT NULL,
lease_until BIGINT UNSIGNED NOT NULL DEFAULT 0,
sent_at BIGINT UNSIGNED DEFAULT NULL,
last_error VARCHAR(500) NOT NULL DEFAULT '',
created_at BIGINT UNSIGNED NOT NULL,
updated_at BIGINT UNSIGNED NOT NULL,
UNIQUE KEY uniq_cloud_invoice_mail (invoice_id, kind),
KEY cloud_mail_delivery (status, available_at, lease_until, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS cloud_jobs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
operation_id CHAR(32) NOT NULL,

@ -0,0 +1,259 @@
<?php
namespace App\Services {
final class Config
{
public static array $values = [];
public static function get($name, $default = null)
{
return self::$values[$name] ?? $default;
}
}
}
namespace App\Services\Cloud {
final class CloudSecrets
{
public static function key(string $purpose): string
{
return str_repeat('i', 32);
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudInvoicePayment;
use App\Models\CloudMailOutbox;
use App\Models\CloudRenewal;
use App\Models\CloudServicePeriod;
use App\Models\User;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudInvoicePaymentService;
use App\Services\Cloud\CloudInvoiceService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) throw new RuntimeException($message);
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id'); $table->string('money'); $table->integer('enable')->default(1);
$table->integer('restrict_recharge')->default(0);
$table->integer('restrict_balance_purchase')->default(0);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('host_id'); $table->integer('user_id');
$table->integer('order_id')->nullable(); $table->integer('plan_id')->nullable();
$table->integer('current_period_id')->nullable(); $table->string('uuid'); $table->string('name');
$table->string('status'); $table->string('service_status'); $table->string('network_status');
$table->integer('expires_at')->nullable(); $table->string('renewal_price')->nullable();
$table->integer('renewal_days')->default(0); $table->integer('renewal_traffic_bytes')->default(0);
$table->integer('traffic_quota_bytes')->default(0); $table->integer('traffic_download_bytes')->default(0);
$table->integer('traffic_upload_bytes')->default(0); $table->integer('lifetime_download_bytes')->default(0);
$table->integer('lifetime_upload_bytes')->default(0); $table->integer('traffic_synced_at')->default(0);
$table->integer('suspended_at')->nullable(); $table->integer('network_suspended_at')->nullable();
$table->text('spec_json'); $table->text('credential_cipher')->nullable();
$table->integer('created_at'); $table->integer('updated_at');
});
$schema->create('cloud_service_periods', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('instance_id'); $table->integer('user_id');
$table->integer('plan_id')->nullable(); $table->integer('order_id')->nullable();
$table->integer('renewal_id')->nullable(); $table->integer('starts_at'); $table->integer('ends_at');
$table->integer('traffic_quota_bytes'); $table->integer('download_base_bytes')->nullable();
$table->integer('upload_base_bytes')->nullable(); $table->integer('download_used_bytes')->default(0);
$table->integer('upload_used_bytes')->default(0); $table->string('status');
$table->integer('activated_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
$table->unique('order_id'); $table->unique('renewal_id');
});
$schema->create('cloud_renewals', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('instance_id'); $table->integer('user_id');
$table->integer('plan_id')->nullable(); $table->integer('period_id')->nullable();
$table->string('idempotency_key'); $table->string('request_hash'); $table->string('amount');
$table->integer('validity_days'); $table->integer('traffic_bytes_added');
$table->integer('previous_expires_at'); $table->integer('new_expires_at'); $table->integer('created_at');
$table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_jobs', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('instance_id')->nullable(); $table->string('kind');
$table->string('status'); $table->integer('updated_at')->default(0);
});
$schema->create('cloud_invoices', static function (Blueprint $table): void {
$table->increments('id'); $table->string('invoice_no')->unique(); $table->integer('instance_id');
$table->integer('user_id'); $table->integer('plan_id')->nullable(); $table->integer('renewal_id')->nullable();
$table->integer('renews_expires_at'); $table->integer('due_at'); $table->string('amount');
$table->integer('validity_days'); $table->integer('traffic_quota_bytes'); $table->string('status');
$table->string('paid_via')->nullable(); $table->string('payment_reference')->nullable();
$table->integer('paid_at')->nullable(); $table->integer('created_at'); $table->integer('updated_at');
$table->index(['instance_id', 'renews_expires_at', 'status']); $table->unique('renewal_id');
});
$schema->create('cloud_invoice_payments', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('invoice_id'); $table->integer('user_id');
$table->string('provider'); $table->string('provider_order_no'); $table->string('idempotency_key');
$table->string('amount'); $table->string('status'); $table->integer('created_at'); $table->integer('updated_at');
$table->unique(['provider', 'provider_order_no']); $table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_mail_outbox', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('invoice_id'); $table->string('kind'); $table->string('status');
$table->integer('attempts'); $table->integer('available_at'); $table->string('lease_token')->nullable();
$table->integer('lease_until'); $table->integer('sent_at')->nullable(); $table->string('last_error');
$table->integer('created_at'); $table->integer('updated_at'); $table->unique(['invoice_id', 'kind']);
});
$user = new User(); $user->id = 1; $user->money = '50.00'; $user->enable = 1;
$user->restrict_balance_purchase = 0; $user->save();
$now = time();
$instance = new CloudInstance(); $instance->host_id = 1; $instance->user_id = 1; $instance->plan_id = 8;
$instance->uuid = '11111111-2222-4333-8444-555555555555'; $instance->name = 'invoice-vm';
$instance->status = 'active'; $instance->service_status = 'active'; $instance->network_status = 'active';
$instance->expires_at = $now + CloudInvoiceService::REMINDER_SECONDS; $instance->renewal_price = '12.50';
$instance->renewal_days = 30; $instance->renewal_traffic_bytes = 4096; $instance->traffic_quota_bytes = 4096;
$instance->spec_json = '{}'; $instance->created_at = $instance->updated_at = $now; $instance->save();
$period = new CloudServicePeriod(); $period->instance_id = $instance->id; $period->user_id = 1;
$period->plan_id = 8; $period->starts_at = $now - 100; $period->ends_at = $instance->expires_at;
$period->traffic_quota_bytes = 4096; $period->download_base_bytes = 0; $period->upload_base_bytes = 0;
$period->status = 'active'; $period->activated_at = $now - 100; $period->created_at = $period->updated_at = $now;
$period->save(); $instance->current_period_id = $period->id; $instance->save();
$assert(CloudInvoiceService::issueDue() === 1 && CloudInvoiceService::issueDue() === 0,
'T-7 invoice generation was not idempotent.');
$invoice = CloudInvoice::first();
$assert($invoice !== null && CloudMailOutbox::count() === 1 && (string) $invoice->amount === '12.50',
'Invoice snapshot or reminder outbox is missing.');
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false,
'can_manage' => false, 'session_id' => ''];
$paid = CloudInvoiceService::payBalance($invoice, $actor, 'invoice-balance-test-0001');
$expiry = (int) $instance->expires_at;
$assert($paid->status === 'paid' && User::find(1)->money === '37.50'
&& CloudRenewal::count() === 1 && (int) $instance->fresh()->expires_at === $expiry + 30 * 86400,
'Balance invoice settlement was not atomic.');
CloudInvoiceService::payBalance($paid->fresh(), $actor, 'invoice-balance-test-0001');
$assert(User::find(1)->money === '37.50' && CloudRenewal::count() === 1,
'Repeated invoice payment debited or renewed twice.');
CloudInvoiceService::deliverReminders();
$assert(CloudMailOutbox::first()->status === 'cancelled',
'A settled invoice reminder remained in the retry queue.');
$currentExpiry = (int) $instance->fresh()->expires_at;
$second = new CloudInvoice(); $second->invoice_no = 'VC-GATEWAY'; $second->instance_id = $instance->id;
$second->user_id = 1; $second->plan_id = 8; $second->renews_expires_at = $currentExpiry;
$second->due_at = $currentExpiry; $second->amount = '12.50'; $second->validity_days = 30;
$second->traffic_quota_bytes = 4096; $second->status = 'open'; $second->created_at = $second->updated_at = $now;
$second->save();
$payment = new CloudInvoicePayment(); $payment->invoice_id = $second->id; $payment->user_id = 1;
$payment->provider = 'paytaro'; $payment->provider_order_no = 'PT-GATEWAY';
$payment->idempotency_key = 'invoice-gateway-test-0001'; $payment->amount = '12.50';
$payment->status = 'pending'; $payment->created_at = $payment->updated_at = $now; $payment->save();
$user = User::find(1); $user->money = '50.00'; $user->save();
$outcome = CloudInvoiceService::settleCreditedPayment($payment);
$assert($outcome === 'paid_invoice' && User::find(1)->money === '37.50'
&& $second->fresh()->status === 'paid' && CloudRenewal::count() === 2
&& (int) $instance->fresh()->expires_at === $currentExpiry + 30 * 86400,
'Provider credit was not consumed exactly once to settle the invoice.');
try {
// `$second` is deliberately the stale pre-callback model. Starting a
// provider order from it must not overwrite the freshly paid row.
CloudInvoicePaymentService::create($second, User::find(1), [
'method' => 'paytaro',
'idempotency_key' => 'stale-paid-invoice-guard-0001',
], '192.0.2.10', 'invoice-test');
throw new RuntimeException('Stale paid invoice unexpectedly created another payment.');
} catch (CloudError $error) {
$assert($error->httpStatus === 409, 'Stale paid invoice returned the wrong conflict status.');
}
$assert($second->fresh()->status === 'paid' && CloudRenewal::count() === 2,
'A stale provider-order request overwrote the paid invoice state.');
$third = new CloudInvoice(); $third->invoice_no = 'VC-STALE'; $third->instance_id = $instance->id;
$third->user_id = 1; $third->plan_id = 8; $third->renews_expires_at = $currentExpiry - 1;
$third->due_at = $currentExpiry - 1; $third->amount = '12.50'; $third->validity_days = 30;
$third->traffic_quota_bytes = 4096; $third->status = 'open'; $third->created_at = $third->updated_at = $now;
$third->save();
$late = new CloudInvoicePayment(); $late->invoice_id = $third->id; $late->user_id = 1;
$late->provider = 'paytaro'; $late->provider_order_no = 'PT-STALE';
$late->idempotency_key = 'invoice-gateway-test-0002'; $late->amount = '12.50';
$late->status = 'pending'; $late->created_at = $late->updated_at = $now; $late->save();
$user = User::find(1); $user->money = '50.00'; $user->save();
$outcome = CloudInvoiceService::settleCreditedPayment($late);
$assert($outcome === 'credited_balance' && User::find(1)->money === '50.00'
&& $third->fresh()->status === 'void' && CloudRenewal::count() === 2,
'Late provider payment was lost or renewed a stale invoice.');
$actualExpiry = (int) $instance->fresh()->expires_at;
$fourth = new CloudInvoice(); $fourth->invoice_no = 'VC-AMOUNT'; $fourth->instance_id = $instance->id;
$fourth->user_id = 1; $fourth->plan_id = 8; $fourth->renews_expires_at = $actualExpiry;
$fourth->due_at = $actualExpiry; $fourth->amount = '12.50'; $fourth->validity_days = 30;
$fourth->traffic_quota_bytes = 4096; $fourth->status = 'open'; $fourth->created_at = $fourth->updated_at = $now;
$fourth->save();
$mismatch = new CloudInvoicePayment(); $mismatch->invoice_id = $fourth->id; $mismatch->user_id = 1;
$mismatch->provider = 'paytaro'; $mismatch->provider_order_no = 'PT-AMOUNT';
$mismatch->idempotency_key = 'invoice-gateway-test-0003'; $mismatch->amount = '1.00';
$mismatch->status = 'pending'; $mismatch->created_at = $mismatch->updated_at = $now; $mismatch->save();
$user = User::find(1); $user->money = '51.00'; $user->save();
$outcome = CloudInvoiceService::settleCreditedPayment($mismatch);
$assert($outcome === 'credited_balance' && User::find(1)->money === '51.00'
&& $fourth->fresh()->status === 'open' && CloudRenewal::count() === 2,
'Mismatched provider payment amount unexpectedly settled an invoice.');
$makeDueInstance = static function (string $uuid, string $name, int $expiry) use ($now): CloudInstance {
$candidate = new CloudInstance(); $candidate->host_id = 1; $candidate->user_id = 1;
$candidate->plan_id = 8; $candidate->uuid = $uuid; $candidate->name = $name;
$candidate->status = 'active'; $candidate->service_status = 'active';
$candidate->network_status = 'active'; $candidate->expires_at = $expiry;
$candidate->renewal_price = '12.50'; $candidate->renewal_days = 30;
$candidate->renewal_traffic_bytes = 4096; $candidate->traffic_quota_bytes = 4096;
$candidate->spec_json = '{}'; $candidate->created_at = $candidate->updated_at = $now;
$candidate->save();
return $candidate;
};
$alreadyBilled = $makeDueInstance('11111111-2222-4333-8444-555555555556',
'already-billed', $now + 60);
$existingInvoice = new CloudInvoice(); $existingInvoice->invoice_no = 'VC-EXISTING';
$existingInvoice->instance_id = $alreadyBilled->id; $existingInvoice->user_id = 1;
$existingInvoice->plan_id = 8; $existingInvoice->renews_expires_at = $alreadyBilled->expires_at;
$existingInvoice->due_at = $alreadyBilled->expires_at; $existingInvoice->amount = '12.50';
$existingInvoice->validity_days = 30; $existingInvoice->traffic_quota_bytes = 4096;
$existingInvoice->status = 'open'; $existingInvoice->created_at = $existingInvoice->updated_at = $now;
$existingInvoice->save();
$nextDue = $makeDueInstance('11111111-2222-4333-8444-555555555557',
'next-due', $now + 120);
$assert(CloudInvoiceService::issueDue(1) === 1
&& CloudInvoice::where('instance_id', $nextDue->id)
->where('renews_expires_at', $nextDue->expires_at)->exists(),
'Already billed instances starved a later invoice batch.');
$corrected = $makeDueInstance('11111111-2222-4333-8444-555555555558',
'corrected-plan', $now + 180);
$assert(CloudInvoiceService::issueDue(10) === 1,
'Correctable invoice fixture was not generated.');
$oldInvoice = CloudInvoice::where('instance_id', $corrected->id)->first();
$corrected->renewal_price = '13.00';
$corrected->save();
try {
CloudInvoicePaymentService::create($oldInvoice, User::find(1), [
'method' => 'paytaro',
'idempotency_key' => 'corrected-invoice-provider-0001',
], '192.0.2.11', 'invoice-test');
throw new RuntimeException('Changed plan snapshot unexpectedly created a payment order.');
} catch (CloudError $error) {
$assert($error->httpStatus === 409, 'Changed snapshot returned the wrong conflict status.');
}
$assert($oldInvoice->fresh()->status === 'void'
&& CloudInvoiceService::issueDue(10) === 1,
'Void invoice prevented a corrected replacement from being issued.');
$replacement = CloudInvoice::where('instance_id', $corrected->id)
->where('status', 'open')->orderByDesc('id')->first();
$assert($replacement !== null && (string) $replacement->amount === '13.00'
&& CloudInvoice::where('instance_id', $corrected->id)->count() === 2,
'Corrected invoice did not retain the void audit row and current snapshot.');
echo "Cloud invoice generation, balance settlement and provider-payment safety passed.\n";
}

@ -68,6 +68,8 @@ namespace PHPMailer\PHPMailer {
public string $SMTPSecure = '';
public array $SMTPOptions = [];
public string $Port = '';
public int $Timeout = 0;
public int $Timelimit = 0;
public string $CharSet = '';
public string $Subject = '';
public string $Body = '';

@ -41,6 +41,26 @@ foreach (['yipay_callback_events', 'yipay_refunds'] as $tableName) {
$table->string('order_no');
});
}
$schema->create('cloud_instances', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id'); $table->string('status');
});
$schema->create('cloud_orders', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id'); $table->string('status');
});
foreach (['cloud_jobs', 'cloud_service_periods', 'cloud_renewals'] as $tableName) {
$schema->create($tableName, static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id');
});
}
$schema->create('cloud_invoices', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id');
});
$schema->create('cloud_invoice_payments', static function (Blueprint $table) {
$table->increments('id'); $table->integer('user_id'); $table->string('status');
});
$schema->create('cloud_mail_outbox', static function (Blueprint $table) {
$table->increments('id'); $table->integer('invoice_id');
});
$schema->create('email_verify', static function (Blueprint $table) {
$table->increments('id');
$table->string('email');
@ -69,6 +89,29 @@ foreach (['yipay_callback_events', 'yipay_refunds'] as $tableName) {
['order_no' => 'deleted-order'], ['order_no' => 'retained-order'],
]);
}
Capsule::table('cloud_instances')->insert([
['id' => 101, 'user_id' => 1, 'status' => 'deleted'],
['id' => 301, 'user_id' => 3, 'status' => 'active'],
]);
Capsule::table('cloud_orders')->insert([
['id' => 102, 'user_id' => 1, 'status' => 'completed'],
['id' => 302, 'user_id' => 3, 'status' => 'completed'],
]);
foreach (['cloud_jobs', 'cloud_service_periods', 'cloud_renewals'] as $tableName) {
Capsule::table($tableName)->insert([
['user_id' => 1], ['user_id' => 3],
]);
}
Capsule::table('cloud_invoices')->insert([
['id' => 103, 'user_id' => 1], ['id' => 303, 'user_id' => 3],
]);
Capsule::table('cloud_invoice_payments')->insert([
['user_id' => 1, 'status' => 'paid_invoice'],
['user_id' => 3, 'status' => 'paid_invoice'],
]);
Capsule::table('cloud_mail_outbox')->insert([
['invoice_id' => 103], ['invoice_id' => 303],
]);
Capsule::table('email_verify')->insert([
['email' => 'deleted@example.com'], ['email' => 'other@example.com'],
]);
@ -85,8 +128,30 @@ $assert(Capsule::table('ticket')->pluck('id')->all() === [20], 'Ticket replies f
foreach (['yipay_orders', 'yipay_callback_events', 'yipay_refunds'] as $tableName) {
$assert(Capsule::table($tableName)->pluck('order_no')->all() === ['retained-order'], 'Payment relation deletion was not isolated.');
}
foreach (['cloud_instances', 'cloud_orders', 'cloud_jobs', 'cloud_service_periods',
'cloud_renewals', 'cloud_invoices', 'cloud_invoice_payments'] as $tableName) {
$assert(Capsule::table($tableName)->pluck('user_id')->all() === [3],
'Cloud account history deletion was not isolated: ' . $tableName);
}
$assert(Capsule::table('cloud_mail_outbox')->pluck('invoice_id')->all() === [303],
'Cloud invoice mail history deletion was not isolated.');
$assert(Capsule::table('email_verify')->pluck('email')->all() === ['other@example.com'], 'Email verification cleanup was not isolated.');
$assert(Capsule::table('configurations')->where('name', 'email_blacklist')->value('value') === "deleted@example.com\n@blocked.example", 'Manual blacklist was changed.');
$assert($result['cache_error'] === false && $result['log_rows_deleted'] === 0, 'Disabled optional services were accessed.');
Capsule::table('user')->insert([
'id' => 4, 'email' => 'payment-pending@example.com', 'is_admin' => 0, 'ref_by' => 0,
]);
Capsule::table('cloud_invoice_payments')->insert([
'user_id' => 4, 'status' => 'failed',
]);
try {
(new UserDataDeletionService())->deleteUsers([4], false);
throw new RuntimeException('Account with an unresolved payment was deleted.');
} catch (RuntimeException $error) {
$assert(str_contains($error->getMessage(), '未核对的支付订单'),
'Unresolved-payment deletion returned the wrong error.');
}
$assert(User::find(4) !== null, 'Unresolved-payment deletion was not rolled back.');
echo 'Manual account deletion SQLite checks passed.' . PHP_EOL;

@ -10,6 +10,7 @@ use App\Services\Payment\PaytaroClient;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\PaytaroProtocol;
use App\Services\Payment\PaytaroSigner;
use App\Models\User;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
@ -244,6 +245,24 @@ $schema->create('paytaro_callback_events', function (Blueprint $table) {
$table->integer('received_at');
$table->integer('processed_at');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('invoice_id');
$table->integer('user_id');
$table->string('provider');
$table->string('provider_order_no');
$table->string('idempotency_key');
$table->decimal('amount', 12, 2);
$table->string('status')->default('creating');
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['provider', 'provider_order_no']);
$table->unique(['user_id', 'idempotency_key']);
});
Capsule::table('configurations')->insert([
'name' => 'paytaro_gateway_url',
@ -268,6 +287,66 @@ Capsule::table('user')->insert([
['id' => 1, 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
$invoiceCreateGateway = new class {
public function createOrder(array $payload)
{
return [
'gateway_trade_no' => '202609270000000011',
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/invoice/paytaro',
];
}
};
$invoiceCreateService = new class($invoiceCreateGateway) extends PaytaroPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
$createdInvoiceOrder = $invoiceCreateService->createOrder(
User::find(1), '42.00', '192.0.2.30', 'test', 'https://panel.example.com',
['invoice_id' => 998, 'idempotency_key' => 'paytaro-invoice-create-01', 'provider' => 'paytaro']
);
$createdAttempt = Capsule::table('cloud_invoice_payments')
->where('provider_order_no', (string) $createdInvoiceOrder->order_no)->first();
if ($createdAttempt === null
|| (string) $createdAttempt->status !== 'creating'
|| (string) $createdAttempt->provider !== 'paytaro'
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Paytaro invoice attempt was not recorded with the local order.' . PHP_EOL);
exit(1);
}
$invoiceFailGateway = new class {
public function createOrder(array $payload)
{
throw new RuntimeException('simulated Paytaro gateway failure');
}
};
$invoiceFailService = new class($invoiceFailGateway) extends PaytaroPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
try {
$invoiceFailService->createOrder(
User::find(1), '43.00', '192.0.2.31', 'test', 'https://panel.example.com',
['invoice_id' => 997, 'idempotency_key' => 'paytaro-invoice-failed-01', 'provider' => 'paytaro']
);
fwrite(STDERR, 'Paytaro invoice gateway failure unexpectedly succeeded.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: both the provider order and invoice attempt must become failed.
}
$failedAttempt = Capsule::table('cloud_invoice_payments')
->where('idempotency_key', 'paytaro-invoice-failed-01')->first();
if ($failedAttempt === null
|| (string) $failedAttempt->status !== 'failed'
|| Capsule::table('paytaro_orders')->where('order_no', $failedAttempt->provider_order_no)
->where('status', 'failed')->count() !== 1) {
fwrite(STDERR, 'Paytaro failed invoice attempt was not synchronized.' . PHP_EOL);
exit(1);
}
$orderNo = 'PT20260815120000A1B2C3D4E5F60708';
$paylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
@ -284,7 +363,9 @@ Capsule::table('paytaro_orders')->insert([
'amount' => 100,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/1',
'status' => 'pending',
// Simulate an ambiguous gateway-create timeout: a later signed callback
// must still recover the user's money.
'status' => 'failed',
]);
$callback = [
@ -337,6 +418,56 @@ try {
// Expected: a callback must belong to the configured merchant App ID.
}
$invoiceOrderNo = 'PT20260927120000B1B2C3D4E5F60708';
$invoicePaylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 25,
'status' => 0,
'tradeno' => $invoiceOrderNo,
'datetime' => time(),
]);
Capsule::table('paytaro_orders')->insert([
'order_no' => $invoiceOrderNo,
'gateway_trade_no' => null,
'paylist_id' => $invoicePaylistId,
'user_id' => 1,
'amount' => 25,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/invoice',
'status' => 'failed',
]);
Capsule::table('cloud_invoice_payments')->insert([
'invoice_id' => 999,
'user_id' => 1,
'provider' => 'paytaro',
'provider_order_no' => $invoiceOrderNo,
'idempotency_key' => 'paytaro-invoice-callback-01',
'amount' => 25,
'status' => 'failed',
'created_at' => time(),
'updated_at' => time(),
]);
$invoiceCallback = [
'pid' => 'A1B2C3D4E5F',
'type' => 'alipay',
'out_trade_no' => $invoiceOrderNo,
'money' => '25.00',
'trade_no' => '202609271234567891',
'trade_status' => 'TRADE_SUCCESS',
'sign_type' => 'MD5',
];
$invoiceCallback['sign'] = PaytaroSigner::sign($invoiceCallback, $secret);
$invoiceResult = $service->processCallback($invoiceCallback);
if (!$invoiceResult['credited']
|| (string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $invoiceOrderNo)->value('status') !== 'credited_balance'
|| (string) Capsule::table('paytaro_orders')->where('order_no', $invoiceOrderNo)
->value('status') !== 'paid'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 125.0) {
fwrite(STDERR, 'Paytaro invoice callback did not invoke invoice settlement.' . PHP_EOL);
exit(1);
}
$smartyDirectory = sys_get_temp_dir() . '/sspanel-paytaro-smarty';
if (!is_dir($smartyDirectory) && !mkdir($smartyDirectory, 0700, true) && !is_dir($smartyDirectory)) {
fwrite(STDERR, 'Could not create the Paytaro Smarty test directory.' . PHP_EOL);
@ -411,4 +542,12 @@ if ($rechargeTemplate === false
exit(1);
}
echo 'Paytaro MAPI signing, request, callback, idempotency, credit, and referral checks passed.' . PHP_EOL;
$userControllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/PaytaroController.php');
if ($userControllerSource === false
|| strpos($userControllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($userControllerSource, "withRedirect('/user/cloud#invoices', 302)") === false) {
fwrite(STDERR, 'Paytaro invoice orders are not isolated from recharge status and return handling.' . PHP_EOL);
exit(1);
}
echo 'Paytaro MAPI signing, invoice bridge, callback, idempotency, credit, and referral checks passed.' . PHP_EOL;

@ -14,6 +14,8 @@ namespace PHPMailer\PHPMailer {
public string $SMTPSecure = '';
public array $SMTPOptions = [];
public string $Port = '';
public int $Timeout = 0;
public int $Timelimit = 0;
public string $CharSet = '';
public string $Subject = '';
public string $Body = '';
@ -108,6 +110,8 @@ namespace {
expectSmtpSingleConfig($mail->Username === 'primary-user', 'Wrong SMTP username for ' . $address);
expectSmtpSingleConfig($mail->Password === 'primary-password', 'Wrong SMTP password for ' . $address);
expectSmtpSingleConfig($mail->Port === '587', 'Wrong SMTP port for ' . $address);
expectSmtpSingleConfig($mail->Timeout === 15 && $mail->Timelimit === 20,
'SMTP transport timeouts are not bounded for ' . $address);
expectSmtpSingleConfig($mail->SMTPSecure === 'tls', 'Wrong SMTP encryption for ' . $address);
expectSmtpSingleConfig($mail->fromAddress === 'sender@primary.example.com', 'Wrong sender address for ' . $address);
expectSmtpSingleConfig($mail->fromName === 'Primary sender', 'Wrong sender name for ' . $address);

@ -147,6 +147,24 @@ $schema->create('usdt_chain_transactions', function (Blueprint $table) {
$table->bigInteger('processed_at')->default(0);
$table->string('error_message')->default('');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('invoice_id');
$table->integer('user_id');
$table->string('provider');
$table->string('provider_order_no');
$table->string('idempotency_key');
$table->decimal('amount', 12, 2);
$table->string('status')->default('creating');
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['provider', 'provider_order_no']);
$table->unique(['user_id', 'idempotency_key']);
});
Capsule::table('configurations')->insert([
['name' => 'usdt_enabled', 'value' => 'true'],
@ -229,4 +247,56 @@ if ((int) $retryStats['credited'] !== 0
failUsdtTest('Native USDT recovery retry credited the same recharge twice or failed to reconcile the event.');
}
echo 'Native USDT address, order allocation and idempotent recovery checks passed.' . PHP_EOL;
$invoiceOrder = (new UsdtPaymentService())->createInvoiceOrder($user, '50.00', [
'invoice_id' => 999,
'idempotency_key' => 'usdt-invoice-payment-0001',
'provider' => 'usdt',
]);
$invoiceAttempt = Capsule::table('cloud_invoice_payments')
->where('provider_order_no', (string) $invoiceOrder->order_no)->first();
if ($invoiceAttempt === null
|| (string) $invoiceAttempt->status !== 'creating'
|| (string) $invoiceOrder->business_type !== 'recharge'
|| (string) $invoiceOrder->business_order_no !== (string) $invoiceOrder->order_no) {
failUsdtTest('Native USDT invoice order did not preserve recharge scanning semantics.');
}
Capsule::table('cloud_invoice_payments')->where('id', $invoiceAttempt->id)
->update(['status' => 'pending', 'updated_at' => time()]);
$invoiceTransfer = [
'transaction_id' => str_repeat('b', 64),
'token_info' => ['address' => UsdtConfig::CONTRACT_ADDRESS, 'decimals' => 6, 'symbol' => 'USDT'],
'from' => $senderAddress,
'to' => $walletAddress,
'value' => (string) $invoiceOrder->amount_atomic,
'block_timestamp' => (int) $invoiceOrder->created_at * 1000,
'block_number' => 123457,
];
$invoiceClient = new class($invoiceTransfer) {
private $transfer;
public function __construct(array $transfer) { $this->transfer = $transfer; }
public function transfersTo($address, $minimum, $maximum) { return [$this->transfer]; }
};
$invoiceScanner = new class($invoiceClient) extends UsdtScannerService {
private $fakeClient;
public function __construct($fakeClient) { $this->fakeClient = $fakeClient; }
protected function client(array $settings) { return $this->fakeClient; }
};
$invoiceStats = $invoiceScanner->run();
if ((int) $invoiceStats['credited'] !== 1
|| (string) Capsule::table('cloud_invoice_payments')->where('id', $invoiceAttempt->id)
->value('status') !== 'credited_balance'
|| (string) Capsule::table('usdt_payment_orders')->where('id', $invoiceOrder->id)
->value('status') !== 'paid'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 150.0
|| Capsule::table('code')->where('type', UsdtPaymentService::LEDGER_TYPE)->count() !== 2) {
failUsdtTest('Native USDT invoice settlement bridge failed.');
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/UsdtController.php');
if ($controllerSource === false
|| strpos($controllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($controllerSource, "cloud_invoice_payments.provider_order_no") === false) {
failUsdtTest('Native USDT invoice orders are exposed by the recharge status endpoint.');
}
echo 'Native USDT address, invoice bridge, order allocation and idempotent recovery checks passed.' . PHP_EOL;

@ -67,6 +67,38 @@ $assert(str_contains($adminScript, 'function unixTime(value)')
$assert(str_contains($clientScript, "makeElement('div', 'cloud-order-actions')")
&& str_contains($clientStyles, '.cloud-orders { min-height: 0;'),
'Provisioning orders must use grouped actions without inheriting the inventory minimum height');
$assert(str_contains($cloudTemplate, 'data-detail-tab="operations"')
&& str_contains($cloudTemplate, 'data-detail-tab="performance"')
&& str_contains($cloudTemplate, 'data-detail-tab="traffic"'),
'VM details must expose operations, performance and traffic tabs');
$assert(str_contains($clientScript, '/traffic/daily?days=30')
&& str_contains($cloudTemplate, '最近 30 天每日流量'),
'VM traffic view must load and display daily traffic history');
$assert(str_contains($sharedSidebar, 'data-view="invoices"')
&& str_contains($cloudTemplate, 'id="invoices-workspace"')
&& str_contains($clientScript, '/pay-balance')
&& str_contains($clientScript, '/payments'),
'Renewal invoices must support balance and online payment paths');
$assert(str_contains($cloudTemplate, '/theme/venix/js/qrcode.min.js')
&& str_contains($clientScript, "'weixin:', 'alipays:', 'alipayqr:'")
&& str_contains($clientScript, 'appendPaymentQr(box'),
'Invoice online payments must support local QR rendering and trusted payment-app links');
$assert(str_contains($clientScript, 'INVOICE_PAYMENT_STORAGE_PREFIX')
&& str_contains($clientScript, 'pendingInvoicePaymentKey(invoice.id, method.id)'),
'Invoice provider orders must reuse a session-scoped idempotency key after lost responses');
$assert(str_contains($clientScript, 'invoicePollTimers: new Map()')
&& str_contains($clientScript, 'state.invoicePollTimers.set(key, setTimeout(poll, 3000))')
&& str_contains($clientScript, 'stopInvoicePoll(key);')
&& substr_count($clientScript,
"row.querySelectorAll('button').forEach(button => { button.disabled = false; });") >= 2,
'Concurrent invoice polling and failed payment attempts must remain recoverable');
$assert(str_contains($clientScript, 'status >= 400 && status < 500')
&& str_contains($clientScript, 'const ambiguousHttpFailure = [408, 425, 429].includes(status)')
&& str_contains($clientScript, 'pendingInvoicePaymentKey(invoice.id, method.id)'),
'Ambiguous 5xx or transport failures must retain the provider idempotency key');
$assert(!str_contains($clientScript, '/renewals')
&& !str_contains($cloudTemplate, '续费周期'),
'Retired direct-renewal controls must not remain in the user UI');
$assert(str_contains($cloudAdminController, "'known_owners' => (object) CloudInstanceDiscovery::knownOwners"),
'Empty VM ownership maps must be encoded as a JSON object for engine discovery');
foreach (['hosts/index.tpl', 'cloud/orders.tpl', 'cloud/instances.tpl', 'cloud/rescue.tpl', 'cloud/templates.tpl'] as $template) {

@ -5,6 +5,7 @@ require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
use App\Models\Code;
use App\Models\User;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayCredentialCipher;
use App\Services\Payment\YipayPaymentService;
@ -135,6 +136,24 @@ $schema->create('yipay_refunds', function (Blueprint $table) {
$table->integer('completed_at');
$table->integer('updated_at');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('invoice_id');
$table->integer('user_id');
$table->string('provider');
$table->string('provider_order_no');
$table->string('idempotency_key');
$table->decimal('amount', 12, 2);
$table->string('status')->default('creating');
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['provider', 'provider_order_no']);
$table->unique(['user_id', 'idempotency_key']);
});
putenv('YIPAY_CREDENTIAL_KEY=' . str_repeat('2', 64));
$_ENV['YIPAY_CREDENTIAL_KEY'] = str_repeat('2', 64);
@ -149,6 +168,66 @@ Capsule::table('user')->insert([
['id' => 1, 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
$invoiceCreateGateway = new class {
public function createOrder(array $payload)
{
return [
'trade_no' => '202609270000000001',
'payurl' => 'https://pay.example.com/invoice/yipay',
];
}
};
$invoiceCreateService = new class($invoiceCreateGateway) extends YipayPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
$createdInvoiceOrder = $invoiceCreateService->createOrder(
User::find(1), '42.00', 'alipay', '192.0.2.20', 'test', 'https://panel.example.com',
['invoice_id' => 998, 'idempotency_key' => 'yipay-invoice-create-0001', 'provider' => 'yipay_alipay']
);
$createdAttempt = Capsule::table('cloud_invoice_payments')
->where('provider_order_no', (string) $createdInvoiceOrder->order_no)->first();
if ($createdAttempt === null
|| (string) $createdAttempt->status !== 'creating'
|| (string) $createdAttempt->provider !== 'yipay_alipay'
|| (int) $createdAttempt->user_id !== 1
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Yipay invoice attempt was not recorded with the local order.' . PHP_EOL);
exit(1);
}
$invoiceFailGateway = new class {
public function createOrder(array $payload)
{
throw new RuntimeException('simulated Yipay gateway failure');
}
};
$invoiceFailService = new class($invoiceFailGateway) extends YipayPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
try {
$invoiceFailService->createOrder(
User::find(1), '43.00', 'alipay', '192.0.2.21', 'test', 'https://panel.example.com',
['invoice_id' => 997, 'idempotency_key' => 'yipay-invoice-failed-0001', 'provider' => 'yipay_alipay']
);
fwrite(STDERR, 'Yipay invoice gateway failure unexpectedly succeeded.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: both the provider order and invoice attempt must become failed.
}
$failedAttempt = Capsule::table('cloud_invoice_payments')
->where('idempotency_key', 'yipay-invoice-failed-0001')->first();
if ($failedAttempt === null
|| (string) $failedAttempt->status !== 'failed'
|| Capsule::table('yipay_orders')->where('order_no', $failedAttempt->provider_order_no)
->where('status', 'failed')->count() !== 1) {
fwrite(STDERR, 'Yipay failed invoice attempt was not synchronized.' . PHP_EOL);
exit(1);
}
$orderNo = 'YP20260815120000A1B2C3D4E5F60708';
$paylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
@ -168,6 +247,7 @@ Capsule::table('yipay_orders')->insert([
'payment_value' => 'https://pay.example.com/order/1',
'status' => 'pending',
]);
$refundRecordId = (int) Capsule::table('yipay_orders')->where('order_no', $orderNo)->value('id');
$callback = [
'pid' => '1001',
@ -239,7 +319,7 @@ $refundService = new class($refundGateway) extends YipayPaymentService {
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
$refund = $refundService->refundById(1, 99);
$refund = $refundService->refundById($refundRecordId, 99);
if ($refund['amount'] !== '100.00'
|| $refundGateway->calls !== 1
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -100.0
@ -272,4 +352,78 @@ if (!$afterRefundCallback['duplicate']
exit(1);
}
echo 'Yipay signing, credit, referral and full-refund checks passed.' . PHP_EOL;
$invoiceOrderNo = 'YP20260927120000B1B2C3D4E5F60708';
$invoicePaylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 25,
'status' => 0,
'tradeno' => $invoiceOrderNo,
'datetime' => time(),
]);
Capsule::table('yipay_orders')->insert([
'order_no' => $invoiceOrderNo,
'gateway_trade_no' => '202609271234567890',
'paylist_id' => $invoicePaylistId,
'user_id' => 1,
'payment_type' => 'alipay',
'amount' => 25,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/invoice',
'status' => 'pending',
]);
Capsule::table('cloud_invoice_payments')->insert([
'invoice_id' => 999,
'user_id' => 1,
'provider' => 'yipay_alipay',
'provider_order_no' => $invoiceOrderNo,
'idempotency_key' => 'yipay-invoice-callback-0001',
'amount' => 25,
'status' => 'pending',
'created_at' => time(),
'updated_at' => time(),
]);
$invoiceCallback = [
'pid' => '1001',
'trade_no' => '202609271234567890',
'out_trade_no' => $invoiceOrderNo,
'type' => 'alipay',
'name' => '云服务器续费账单',
'money' => '25.00',
'trade_status' => 'TRADE_SUCCESS',
'param' => '',
'sign_type' => 'MD5',
];
$invoiceCallback['sign'] = YipaySigner::sign($invoiceCallback, $secret);
$invoiceResult = $service->processCallback($invoiceCallback);
if (!$invoiceResult['credited']
|| (string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $invoiceOrderNo)->value('status') !== 'credited_balance'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -75.0) {
fwrite(STDERR, 'Yipay invoice callback did not invoke invoice settlement.' . PHP_EOL);
exit(1);
}
try {
$refundService->refund($invoiceOrderNo, 99);
fwrite(STDERR, 'Yipay accepted an automatic refund for an invoice payment.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
if (strpos($exception->getMessage(), '账单支付不支持自动退款') === false) {
throw $exception;
}
}
if ($refundGateway->calls !== 1
|| Capsule::table('yipay_orders')->where('order_no', $invoiceOrderNo)->value('status') !== 'paid'
|| Capsule::table('yipay_refunds')->where('order_no', $invoiceOrderNo)->exists()) {
fwrite(STDERR, 'Yipay invoice refund rejection reached the gateway or mutated the order.' . PHP_EOL);
exit(1);
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/YipayController.php');
if ($controllerSource === false
|| strpos($controllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($controllerSource, "withRedirect('/user/cloud#invoices', 302)") === false) {
fwrite(STDERR, 'Yipay invoice orders are not isolated from recharge status and return handling.' . PHP_EOL);
exit(1);
}
echo 'Yipay signing, invoice bridge, credit, referral and refund checks passed.' . PHP_EOL;

Loading…
Cancel
Save