diff --git a/engine/tests/test_cloud_template_runtime.py b/engine/tests/test_cloud_template_runtime.py index 34324252..33938bd3 100644 --- a/engine/tests/test_cloud_template_runtime.py +++ b/engine/tests/test_cloud_template_runtime.py @@ -15,6 +15,7 @@ from unittest.mock import patch import pytest from virsh_panel.cloud_template_runtime import ( + CACHE_TOMBSTONE_KIND, CATALOG_KIND, IMPORT_JOB_KIND, CloudTemplateRuntime, @@ -395,6 +396,158 @@ def test_rename_changes_only_display_name_and_keeps_source_identity(tmp_path): assert source.name == record["volume_name"] +def test_delete_removes_global_catalog_source_and_verification_cache(tmp_path): + store = MemoryStore() + runtime = CloudTemplateRuntime(store, tmp_path) + payload = b"delete-global-cloud-image" + record = record_for(payload) + runtime.catalog.add(record) + temporary = runtime.files.directory() / ".cloud-image-delete.qcow2" + temporary.write_bytes(payload) + os.chmod(temporary, 0o600) + source = runtime.files.publish( + temporary, record["id"], expected_size=len(payload) + ) + runtime.verified_sources[record["id"]] = (1, 2, 3, 4, record["sha256"]) + try: + runtime.delete(record["id"]) + + assert not source.exists() + assert store.get(CATALOG_KIND, record["id"]) is None + assert record["id"] not in runtime.verified_sources + with pytest.raises(TemplateError) as missing: + runtime.get(record["id"]) + assert missing.value.status == 404 + finally: + runtime.close() + + +def test_delete_rejects_import_or_active_source_lease(tmp_path): + runtime = CloudTemplateRuntime(MemoryStore(), tmp_path) + payload = b"leased-global-cloud-image" + record = record_for(payload) + runtime.catalog.add(record) + temporary = runtime.files.directory() / ".cloud-image-leased.qcow2" + temporary.write_bytes(payload) + os.chmod(temporary, 0o600) + source = runtime.files.publish( + temporary, record["id"], expected_size=len(payload) + ) + try: + runtime.pending.add("active-import") + with pytest.raises(TemplateError, match="正在导入") as importing: + runtime.delete(record["id"]) + assert importing.value.status == 409 + runtime.pending.clear() + + with runtime.source(record["id"]): + with pytest.raises(TemplateError, match="正在同步") as leased: + runtime.delete(record["id"]) + assert leased.value.status == 409 + assert source.exists() + assert runtime.get(record["id"])["id"] == record["id"] + finally: + runtime.close() + + +def test_reimport_waits_for_old_host_cache_gc_then_reuses_stable_id(tmp_path): + store = MemoryStore() + runtime = CloudTemplateRuntime(store, tmp_path) + record = record_for(b"reimport-identical-image") + tombstone = { + "deletion_id": "a" * 32, + "template_id": record["id"], + "template_created_at": record["created_at"], + "source_volume_name": record["volume_name"], + "pending_hosts": ["offline-host"], + "source_deleted": True, + "created_at": 1, + } + store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone)) + try: + with pytest.raises(TemplateError, match="缓存仍在清理") as pending: + runtime._prepare_reimport(record["id"]) + assert pending.value.status == 409 + assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is not None + + tombstone["pending_hosts"] = [] + store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone)) + previous_created_at = runtime._prepare_reimport(record["id"]) + assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is None + assert previous_created_at == record["created_at"] + first_generation = runtime._next_generation( + record["id"], previous_created_at) + second_generation = runtime._next_generation(record["id"]) + assert second_generation > first_generation > previous_created_at + finally: + runtime.close() + + +def test_restore_cancels_provisional_delete_when_source_and_catalog_survive( + tmp_path): + store = MemoryStore() + runtime = CloudTemplateRuntime(store, tmp_path) + payload = b"delete-never-committed" + record = record_for(payload) + runtime.catalog.add(record) + temporary = runtime.files.directory() / ".cloud-image-delete-intact.qcow2" + temporary.write_bytes(payload) + os.chmod(temporary, 0o600) + source = runtime.files.publish( + temporary, record["id"], expected_size=len(payload) + ) + tombstone = { + "deletion_id": "c" * 32, + "template_id": record["id"], + "template_created_at": record["created_at"], + "source_volume_name": record["volume_name"], + "pending_hosts": ["host-one"], + "source_deleted": False, + "created_at": 1, + } + store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone)) + try: + runtime.restore_jobs() + + assert runtime.get(record["id"])["id"] == record["id"] + assert source.is_file() + assert store.get(CACHE_TOMBSTONE_KIND, record["id"]) is None + finally: + runtime.close() + + +def test_restore_finishes_delete_after_source_unlink_crash_window(tmp_path): + store = MemoryStore() + runtime = CloudTemplateRuntime(store, tmp_path) + payload = b"delete-unlink-committed" + record = record_for(payload) + runtime.catalog.add(record) + tombstone = { + "deletion_id": "d" * 32, + "template_id": record["id"], + "template_created_at": record["created_at"], + "source_volume_name": record["volume_name"], + "pending_hosts": ["host-one"], + "source_deleted": False, + "created_at": 1, + } + store.set(CACHE_TOMBSTONE_KIND, record["id"], json.dumps(tombstone)) + try: + assert runtime.list() == [] + runtime.restore_jobs() + + with pytest.raises(TemplateError) as missing: + runtime.get(record["id"]) + assert missing.value.status == 404 + restored = json.loads(store.get( + CACHE_TOMBSTONE_KIND, record["id"] + )) + assert restored["source_deleted"] is True + assert restored["pending_hosts"] == ["host-one"] + finally: + runtime.close() + + def test_source_rejects_permission_damage_and_content_tampering(tmp_path): store = MemoryStore() runtime = CloudTemplateRuntime(store, tmp_path) diff --git a/engine/tests/test_engine_boundary.py b/engine/tests/test_engine_boundary.py index 54315fe5..372943eb 100644 --- a/engine/tests/test_engine_boundary.py +++ b/engine/tests/test_engine_boundary.py @@ -164,6 +164,7 @@ class Service(FakeVMService): self.create_failure = False self.absent = False self.absent_checks = [] + self.cloud_template_delete_error = None self.vm.update(managed=True, os_source="iso") def create_vm(self, spec): @@ -180,6 +181,12 @@ class Service(FakeVMService): (vm_uuid, name, uuid_resources, legacy_name_collision)) return self.absent + def delete_cloud_template_replicas(self, source_volume_name): + self.calls.append(("delete_cloud_template_replicas", source_volume_name)) + if self.cloud_template_delete_error is not None: + raise self.cloud_template_delete_error + return {"source_volume_name": source_volume_name, "deleted": True} + @pytest.fixture def boundary(tmp_path): @@ -245,6 +252,36 @@ def import_user_iso_for_test(client, tmp_path, name, *, digest="e" * 64): return job["iso"]["id"] +def import_cloud_template_for_test(client, tmp_path, name="Delete Cloud Image"): + payload = name.encode("utf-8") + digest = hashlib.sha256(payload).hexdigest() + + def fake_download(_url, _sha256, directory, **_kwargs): + source = directory / ".cloud-image-delete-boundary.qcow2" + source.write_bytes(payload) + source.chmod(0o600) + return source, 2 * 1024**3, digest + + with patch( + "virsh_panel.cloud_template_runtime.download_verified_image", + side_effect=fake_download): + queued = call(client, "POST", "/internal/v1/vm-templates/import", + SUPER, {"url": OFFICIAL_CLOUD_URL, + "name": name, "sha256": ""}) + assert queued.status_code == 202, queued.text + job_id = queued.json()["job_id"] + for _ in range(100): + job = call( + client, "GET", + f"/internal/v1/vm-templates/import-jobs/{job_id}", SUPER, + ).json() + if job["status"] in {"completed", "failed"}: + break + time.sleep(0.01) + assert job["status"] == "completed", job + return job["template"], payload + + def test_global_cloud_template_is_visible_and_cached_once_per_host( boundary, tmp_path): client, engine, store, _logs, services = boundary @@ -462,6 +499,137 @@ def test_legacy_host_template_id_remains_usable_for_an_already_queued_order( assert create[2] == template_volume_name(template_id) +def test_global_cloud_template_delete_is_idempotent_and_retries_host_gc( + boundary, tmp_path): + client, engine, store, _logs, services = boundary + imported, payload = import_cloud_template_for_test(client, tmp_path) + template_id = imported["id"] + template_created_at = imported["created_at"] + source_volume_name = template_volume_name(template_id) + source_path = tmp_path / "cloud-templates" / source_volume_name + assert source_path.is_file() + + for host_id in ("hk", "jp"): + assert call( + client, "GET", f"/internal/v1/hosts/{host_id}/resources" + ).status_code == 200 + HostStore(store, host_id).set( + "cloud_template_replica", template_id, "ready-marker") + + assert call( + client, "DELETE", f"/internal/v1/vm-templates/{template_id}", + ADMIN, {"created_at": template_created_at}, + ).status_code == 403 + services["hk"].cloud_template_delete_error = VMError( + "云镜像仍被虚拟机引用,不能删除", 409) + original_store_delete = store.delete + failed_catalog_delete = False + + def fail_first_catalog_delete(kind, key): + nonlocal failed_catalog_delete + if (kind == "cloud_template" and key == template_id + and not failed_catalog_delete): + failed_catalog_delete = True + raise RuntimeError("catalog delete failed before commit") + return original_store_delete(kind, key) + + store.delete = fail_first_catalog_delete + try: + deleted = call( + client, "DELETE", f"/internal/v1/vm-templates/{template_id}", + SUPER, {"created_at": template_created_at}, + ) + finally: + store.delete = original_store_delete + assert failed_catalog_delete is True + assert deleted.status_code == 200, deleted.text + assert deleted.json() == { + "deleted": True, "cache_cleanup_pending": True, + } + assert not source_path.exists() + assert call(client, "GET", "/internal/v1/vm-templates", USER).json() == { + "templates": [], + } + + for _ in range(100): + tombstone = json.loads(store.get( + "cloud_template_tombstone", template_id)) + if tombstone["pending_hosts"] == ["hk"]: + break + time.sleep(0.01) + assert tombstone["source_deleted"] is True + assert tombstone["source_volume_name"] == source_volume_name + assert tombstone["pending_hosts"] == ["hk"] + assert HostStore(store, "jp").get( + "cloud_template_replica", template_id) is None + assert HostStore(store, "hk").get( + "cloud_template_replica", template_id) is not None + + services["hk"].cloud_template_delete_error = VMError( + "存储池 images 不存在", 404) + assert call(client, "GET", "/internal/v1/hosts/hk/resources").status_code == 200 + still_pending = json.loads(store.get( + "cloud_template_tombstone", template_id)) + assert still_pending["pending_hosts"] == ["hk"] + assert HostStore(store, "hk").get( + "cloud_template_replica", template_id) is not None + + services["hk"].cloud_template_delete_error = None + assert call(client, "GET", "/internal/v1/hosts/hk/resources").status_code == 200 + terminal = json.loads(store.get("cloud_template_tombstone", template_id)) + assert terminal["pending_hosts"] == [] + assert HostStore(store, "hk").get( + "cloud_template_replica", template_id) is None + + repeated = call( + client, "DELETE", f"/internal/v1/vm-templates/{template_id}", + SUPER, {"created_at": template_created_at}) + assert repeated.status_code == 200 + assert repeated.json() == { + "deleted": True, "cache_cleanup_pending": False, + } + + # A duplicate task from the old deletion must not touch a later deletion + # generation (or the same-ID image/replica that may exist between them). + old_deletion_id = terminal["deletion_id"] + engine.registry.cloud_templates._prepare_reimport(template_id) + reimported = { + **imported, + "volume_name": source_volume_name, + "created_at": template_created_at + 1, + } + temporary = engine.registry.cloud_templates.files.directory() \ + / ".cloud-image-reimport-boundary.qcow2" + temporary.write_bytes(payload) + temporary.chmod(0o600) + engine.registry.cloud_templates.files.publish( + temporary, template_id, expected_size=len(payload)) + engine.registry.cloud_templates.catalog.add(reimported) + stale_delete = call( + client, "DELETE", f"/internal/v1/vm-templates/{template_id}", + SUPER, {"created_at": template_created_at}) + assert stale_delete.status_code == 409 + assert engine.registry.cloud_templates.get( + template_id)["created_at"] == template_created_at + 1 + + next_tombstone = { + **terminal, + "deletion_id": "b" * 32, + "template_created_at": template_created_at + 1, + "pending_hosts": ["hk"], + } + store.set("cloud_template_tombstone", template_id, + json.dumps(next_tombstone)) + calls_before = list(services["hk"].calls) + engine._cleanup_cloud_template_tombstone_on_host_sync( + template_id, old_deletion_id, "hk", services["hk"], + engine.registry.components["hk"], + ) + assert services["hk"].calls == calls_before + assert json.loads(store.get( + "cloud_template_tombstone", template_id))["pending_hosts"] == ["hk"] + + def test_user_iso_routes_are_owner_scoped_and_create_uses_opaque_id(boundary, tmp_path): client, _engine, _store, _logs, services = boundary download = tmp_path / "download.iso" diff --git a/engine/tests/test_libvirt_service.py b/engine/tests/test_libvirt_service.py index 5684e01c..39ffa1a7 100644 --- a/engine/tests/test_libvirt_service.py +++ b/engine/tests/test_libvirt_service.py @@ -2406,6 +2406,42 @@ class VMServiceTests(unittest.TestCase): self.assertEqual(raised.exception.status, 409) self.assertIn(TEMPLATE_REPLICA_ONE, self.backend.pools["images"].volumes) + def test_template_delete_removes_source_and_every_replica_generation(self): + pool = self.backend.pools["images"] + unrelated = "panel-template-alma10-87654321-fedcba9876543210.qcow2" + for name in (TEMPLATE_NAME, TEMPLATE_REPLICA_ONE, + TEMPLATE_REPLICA_TWO, unrelated): + pool.volumes[name] = FakeVolume(pool, name, capacity=2 * 1024**3) + + result = self.service.delete_cloud_template_replicas(TEMPLATE_NAME) + + self.assertTrue(result["deleted"]) + self.assertEqual( + result["deleted_volumes"], + [TEMPLATE_REPLICA_ONE, TEMPLATE_REPLICA_TWO, TEMPLATE_NAME], + ) + self.assertEqual(set(pool.volumes), {unrelated}) + + def test_template_delete_is_all_or_nothing_when_a_replica_is_referenced(self): + pool = self.backend.pools["images"] + for name in (TEMPLATE_REPLICA_ONE, TEMPLATE_REPLICA_TWO): + pool.volumes[name] = FakeVolume(pool, name, capacity=2 * 1024**3) + self.backend.domains.append(FakeDomain(self.backend, f""" + external-template-user + 00000000-0000-4000-8000-000000000099 + + + + """, running=True)) + + with self.assertRaises(self.error_type) as raised: + self.service.delete_cloud_template_replicas(TEMPLATE_NAME) + + self.assertEqual(raised.exception.status, 409) + self.assertIn(TEMPLATE_REPLICA_ONE, pool.volumes) + self.assertIn(TEMPLATE_REPLICA_TWO, pool.volumes) + self.assertNotIn(TEMPLATE_REPLICA_ONE, self.backend.deleted_volumes) + def rescue_pool(self): pool = self.backend.pools.get("rescue") if pool is None: diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py index b1c4da72..7f02634d 100644 --- a/engine/virsh_panel/app.py +++ b/engine/virsh_panel/app.py @@ -256,6 +256,12 @@ class RenameTemplateBody(BaseModel): name: str = Field(min_length=1, max_length=64) +class DeleteTemplateBody(BaseModel): + model_config = ConfigDict(extra="forbid") + + created_at: int = Field(ge=1) + + class ReinstallBody(BaseModel): model_config = ConfigDict(extra="forbid") diff --git a/engine/virsh_panel/cloud_template_runtime.py b/engine/virsh_panel/cloud_template_runtime.py index e6ecb7b8..8d8e4745 100644 --- a/engine/virsh_panel/cloud_template_runtime.py +++ b/engine/virsh_panel/cloud_template_runtime.py @@ -53,6 +53,8 @@ GLOBAL_TEMPLATE_SCOPE = hashlib.sha256( CATALOG_KIND = "cloud_template" IMPORT_JOB_KIND = "cloud_template_import_job" +CACHE_TOMBSTONE_KIND = "cloud_template_tombstone" +GENERATION_KIND = "cloud_template_generation" SOURCE_DIRECTORY_NAME = "cloud-templates" PERSISTENT_FREE_RESERVE_BYTES = 256 * 1024**2 MIN_DOWNLOAD_BYTES = 1024 * 1024 @@ -211,6 +213,16 @@ class GlobalCloudTemplateStore: self._memory[template_id] = encoded return updated + def delete(self, template_id: str) -> None: + # Validate the opaque identifier before touching persistent storage. + template_volume_name(template_id) + with self._lock: + self.get(template_id) + if self.store is not None: + self.store.delete(CATALOG_KIND, template_id) + else: + self._memory.pop(template_id, None) + class GlobalCloudTemplateFiles: """Private engine-owned source files, never paths supplied by a caller.""" @@ -304,7 +316,10 @@ class GlobalCloudTemplateFiles: return if not stat.S_ISREG(info.st_mode) or stat.S_ISLNK(info.st_mode): raise TemplateError("云镜像源文件无法安全删除", 500) - path.unlink() + try: + path.unlink() + except OSError as exc: + raise TemplateError("云镜像源文件删除失败,请联系管理员", 500) from exc def reconcile(self, catalog: GlobalCloudTemplateStore) -> None: """Remove only provable interrupted downloads and uncataloged sources.""" @@ -344,6 +359,7 @@ class CloudTemplateRuntime: self.pending: set[str] = set() self.in_use: dict[str, int] = {} self.verified_sources: dict[str, tuple[int, int, int, int, str]] = {} + self.memory_generations: dict[str, int] = {} self._restored = False @staticmethod @@ -384,6 +400,9 @@ class CloudTemplateRuntime: "已有同名云镜像模板", "云镜像无法保存到持久目录", "面板云镜像持久目录空间不足", + "云镜像缓存清理记录损坏,请联系管理员", + "云镜像版本记录损坏,请联系管理员", + "旧云镜像缓存仍在清理,请稍后重新导入", "云镜像导入失败,请查看引擎日志", } if isinstance(value, str) and value in safe: @@ -405,7 +424,9 @@ class CloudTemplateRuntime: def list(self) -> list[dict[str, Any]]: """Return the public, host-independent template list.""" - return [self.public_record(row) for row in self.catalog.list()] + with self.lock: + self._reconcile_cache_tombstones() + return [self.public_record(row) for row in self.catalog.list()] def status(self) -> dict[str, Any]: """Return the public list plus the current import, when one exists.""" @@ -435,12 +456,187 @@ class CloudTemplateRuntime: raise TemplateError("云镜像正在导入,请稍后修改模板名称", 409) return self.public_record(self.catalog.rename(template_id, name)) + def delete(self, template_id: str) -> None: + with self.lock: + if self.pending: + raise TemplateError("云镜像正在导入,请稍后删除模板", 409) + if self.in_use.get(template_id, 0): + raise TemplateError("云镜像正在同步到宿主机,请稍后删除", 409) + self.catalog.get(template_id) + # Delete bytes first. If the catalog write then fails, a retry can + # finish the deletion without leaving unaccounted source files. + self.files.delete(template_id) + self.catalog.delete(template_id) + self.verified_sources.pop(template_id, None) + def _remaining_download_bytes(self) -> int: maximum = min(MAX_IMAGE_BYTES, self.files.available_bytes()) if maximum < MIN_DOWNLOAD_BYTES: raise TemplateError("面板云镜像持久目录空间不足", 507) return maximum + def _remember_generation(self, template_id: str, created_at: int) -> None: + if isinstance(created_at, bool) or not isinstance(created_at, int) \ + or created_at < 1: + raise TemplateError("全局云镜像目录记录损坏", 500) + if self.store is None: + self.memory_generations[template_id] = max( + created_at, self.memory_generations.get(template_id, 0)) + return + raw = self.store.get(GENERATION_KIND, template_id) + try: + previous = 0 if raw is None else int(raw) + except (TypeError, ValueError) as exc: + raise TemplateError("云镜像版本记录损坏,请联系管理员", 500) from exc + if previous < 0 or (raw is not None and str(previous) != raw): + raise TemplateError("云镜像版本记录损坏,请联系管理员", 500) + if created_at > previous: + self.store.set(GENERATION_KIND, template_id, str(created_at)) + + def _next_generation(self, template_id: str, floor: int = 0) -> int: + if self.store is None: + previous = self.memory_generations.get(template_id, 0) + else: + raw = self.store.get(GENERATION_KIND, template_id) + try: + previous = 0 if raw is None else int(raw) + except (TypeError, ValueError) as exc: + raise TemplateError( + "云镜像版本记录损坏,请联系管理员", 500 + ) from exc + if previous < 0 or (raw is not None and str(previous) != raw): + raise TemplateError("云镜像版本记录损坏,请联系管理员", 500) + generation = max(int(time.time()), previous + 1, floor + 1) + if self.store is None: + self.memory_generations[template_id] = generation + else: + self.store.set(GENERATION_KIND, template_id, str(generation)) + return generation + + @staticmethod + def _decode_cache_tombstone(template_id: str, raw: str) -> dict[str, Any]: + try: + tombstone = json.loads(raw) + deletion_id = tombstone["deletion_id"] + template_created_at = tombstone["template_created_at"] + pending_hosts = tombstone["pending_hosts"] + except (KeyError, TypeError, ValueError) as exc: + raise TemplateError( + "云镜像缓存清理记录损坏,请联系管理员", 500 + ) from exc + if (not isinstance(tombstone, dict) + or not isinstance(deletion_id, str) + or re.fullmatch(r"[0-9a-f]{32}", deletion_id) is None + or isinstance(template_created_at, bool) + or not isinstance(template_created_at, int) + or template_created_at < 1 + or tombstone.get("template_id") != template_id + or tombstone.get("source_volume_name") + != template_volume_name(template_id) + or not isinstance(tombstone.get("source_deleted"), bool) + or not isinstance(pending_hosts, list) + or any(not isinstance(host_id, str) or not host_id + for host_id in pending_hosts) + or len(set(pending_hosts)) != len(pending_hosts) + or isinstance(tombstone.get("created_at"), bool) + or not isinstance(tombstone.get("created_at"), int) + or tombstone["created_at"] < 1): + raise TemplateError( + "云镜像缓存清理记录损坏,请联系管理员", 500 + ) + return tombstone + + def _reconcile_cache_tombstone( + self, template_id: str, tombstone: dict[str, Any] + ) -> dict[str, Any] | None: + """Resolve the crash window around source/catalog removal. + + A provisional tombstone is written before unlinking the immutable + source. If the engine stops before the final flag is persisted, the + catalog and source together prove whether deletion started: a valid + pair cancels the provisional marker, while either missing half means + the requested deletion must be completed before host garbage + collection can continue. + """ + if self.store is None or tombstone["source_deleted"]: + return tombstone + try: + record = self.catalog.get(template_id) + except TemplateError as exc: + if exc.status != 404: + raise + record = None + if record is not None: + if (record["created_at"] != tombstone["template_created_at"] + or record["volume_name"] + != tombstone["source_volume_name"]): + raise TemplateError( + "云镜像缓存清理记录损坏,请联系管理员", 500 + ) + try: + self.files.path( + template_id, expected_size=record["image_bytes"]) + except TemplateError: + # The immutable source is already absent or damaged after a + # committed deletion attempt. Finish retiring the catalog. + self.files.delete(template_id) + self.catalog.delete(template_id) + self.verified_sources.pop(template_id, None) + else: + # Both durable halves still exist: deletion never committed. + self.store.delete(CACHE_TOMBSTONE_KIND, template_id) + return None + else: + # The catalog is gone, so ensure no source bytes survived an + # interrupted or externally retried database operation. + self.files.delete(template_id) + self.verified_sources.pop(template_id, None) + tombstone["source_deleted"] = True + self.store.set( + CACHE_TOMBSTONE_KIND, + template_id, + json.dumps(tombstone, separators=(",", ":")), + ) + return tombstone + + def _prepare_reimport(self, template_id: str) -> int | None: + """Retire a completed deletion marker before reusing a stable ID. + + Template IDs are content-derived, so importing identical bytes after + a deletion intentionally produces the same identifier. Reuse is safe + only after every old host replica has been reclaimed; otherwise a + delayed cleanup task could delete a newly-created replica. + """ + if self.store is None: + return None + raw = self.store.get(CACHE_TOMBSTONE_KIND, template_id) + if raw is None: + return None + tombstone = self._decode_cache_tombstone(template_id, raw) + tombstone = self._reconcile_cache_tombstone( + template_id, tombstone) + if tombstone is None: + return None + template_created_at = tombstone["template_created_at"] + pending_hosts = tombstone["pending_hosts"] + if tombstone["source_deleted"] is not True: + raise TemplateError( + "云镜像缓存清理记录损坏,请联系管理员", 500 + ) + if pending_hosts: + raise TemplateError("旧云镜像缓存仍在清理,请稍后重新导入", 409) + self.store.delete(CACHE_TOMBSTONE_KIND, template_id) + return template_created_at + + def _reconcile_cache_tombstones(self) -> None: + """Advance provisional delete records after a crash or lost DB ack.""" + if self.store is None: + return + for template_id, raw in self.store.list( + CACHE_TOMBSTONE_KIND).items(): + tombstone = self._decode_cache_tombstone(template_id, raw) + self._reconcile_cache_tombstone(template_id, tombstone) + def queue_import(self, url: str, name: str, expected_sha256: str = "") -> dict[str, str]: os_family, version = image_metadata_for(url) @@ -536,11 +732,18 @@ class CloudTemplateRuntime: "created_at": int(time.time()), } with self.lock: - if any(row["id"] == template_id for row in self.catalog.list()): + existing = self.catalog.list() + if any(row["id"] == template_id for row in existing): raise TemplateError("此云镜像已经导入", 409) if any(row["name"].casefold() == name.casefold() - for row in self.catalog.list()): + for row in existing): raise TemplateError("已有同名云镜像模板", 409) + previous_created_at = self._prepare_reimport(template_id) + # created_at doubles as the public deletion generation. A + # durable counter prevents reuse even when an earlier import + # reserved a generation and failed before catalog commit. + record["created_at"] = self._next_generation( + template_id, previous_created_at or 0) job = self.jobs[job_id] job["phase"] = "正在保存云镜像源文件" # Persist the deterministic candidate before publishing. If @@ -721,6 +924,10 @@ class CloudTemplateRuntime: if self._restored: return self.files.reconcile(self.catalog) + self._reconcile_cache_tombstones() + for record in self.catalog.list(): + self._remember_generation( + record["id"], record["created_at"]) source = self.store.list(IMPORT_JOB_KIND) if self.store is not None else {} for job_id, raw in source.items(): try: diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index bc6a07e2..fbf8b39f 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -26,8 +26,8 @@ from urllib.request import (HTTPRedirectHandler, ProxyHandler, Request as URLReq build_opener) -from .cloud_templates import TemplateError -from .cloud_template_runtime import CloudTemplateRuntime +from .cloud_templates import TemplateError, template_volume_name +from .cloud_template_runtime import CACHE_TOMBSTONE_KIND, CloudTemplateRuntime from .engine_context import (EngineComponents, HostStore, LogStore, MainStore, TRUSTED_ACTOR, actor_session) from .engine_security import (EngineAuthError, authenticate, decode_secret, @@ -56,7 +56,8 @@ WRITE_PATHS = { rf"vms/{VM_ID}/rescue/(?:exit|force-start)", r"reinstall-jobs/[A-Za-z0-9_-]+/ack-password"), "PUT": (r"host",), "PATCH": (r"vm-templates/[A-Za-z0-9_-]+",), - "DELETE": (rf"vms/{VM_ID}", r"rescue-templates/[A-Za-z0-9_-]+", + "DELETE": (rf"vms/{VM_ID}", r"vm-templates/[A-Za-z0-9_-]+", + r"rescue-templates/[A-Za-z0-9_-]+", r"user-isos/[0-9a-f]{32}"), } @@ -433,10 +434,12 @@ class EngineApplication: async with self._update_lock(): if not await asyncio.to_thread(self.updater.active_job): await self._cleanup_host_user_iso_tombstones(host_id) + await self._cleanup_host_cloud_template_tombstones(host_id) else: # Every host write reached this method while holding _update_lock # and after the active-update gate in _dispatch(). await self._cleanup_host_user_iso_tombstones(host_id) + await self._cleanup_host_cloud_template_tombstones(host_id) if resource.endswith("/console-ticket"): vm_id = resource.split("/")[1] await self._ticket(host_id, vm_id, delegated, send) @@ -534,6 +537,13 @@ class EngineApplication: try: if method == "GET" and resource == "vm-templates": records = await asyncio.to_thread(runtime.list) + # A normal catalog read also repairs the narrow crash/lost-ack + # window between source deletion and its final tombstone flag. + # Once repaired, immediately resume cache GC on every loaded + # host instead of requiring an engine restart. + for host_id in tuple(self.registry.components): + self._background( + self._cleanup_host_cloud_template_tombstones(host_id)) await json_response(send, 200, {"templates": records}) return if method == "POST" and resource == "vm-templates/import": @@ -567,6 +577,26 @@ class EngineApplication: runtime.rename, template_match[1], value.name) await json_response(send, 200, {"template": record}) return + if method == "DELETE" and template_match is not None: + from .app import DeleteTemplateBody + from pydantic import ValidationError + try: + value = DeleteTemplateBody.model_validate_json(body or b"") + except ValidationError as exc: + raise TemplateError("云镜像删除参数无效", 422) from exc + template_id = template_match[1] + tombstone_key, tombstone = await asyncio.to_thread( + self._delete_cloud_template_source, + template_id, value.created_at) + for host_id in tombstone["pending_hosts"]: + self._background( + self._cleanup_cloud_template_tombstone_on_host( + tombstone_key, tombstone, host_id)) + await json_response(send, 200, { + "deleted": True, + "cache_cleanup_pending": bool(tombstone["pending_hosts"]), + }) + return raise EngineAuthError("内部资源不存在", 404) except TemplateError as exc: await json_response(send, exc.status, {"error": str(exc)}) @@ -622,6 +652,190 @@ class EngineApplication: except TemplateError as exc: await json_response(send, exc.status, {"error": str(exc)}) + def _delete_cloud_template_source( + self, template_id: str, + expected_created_at: int) -> tuple[str, dict]: + """Commit global source deletion and durable per-host cache GC.""" + runtime = self.registry.cloud_templates + with runtime.lock: + raw = self.store.get(CACHE_TOMBSTONE_KIND, template_id) + if raw is not None: + tombstone = self._decode_cloud_template_tombstone( + template_id, raw) + if tombstone["template_created_at"] != expected_created_at: + raise TemplateError( + "云镜像版本已变化,请刷新后重试", 409) + if tombstone["source_deleted"]: + return template_id, tombstone + + try: + record = runtime.get(template_id) + except TemplateError as exc: + if raw is None or exc.status != 404: + raise + tombstone["source_deleted"] = True + self.store.set( + CACHE_TOMBSTONE_KIND, template_id, + json.dumps(tombstone, separators=(",", ":")), + ) + return template_id, tombstone + + source_volume_name = record.get("volume_name") + if source_volume_name != template_volume_name(template_id): + raise TemplateError("云镜像目录记录损坏,无法安全删除", 500) + if record.get("created_at") != expected_created_at: + raise TemplateError("云镜像版本已变化,请刷新后重试", 409) + host_ids = sorted( + set(self.store.list("engine_host")) + | set(self.registry.components) + ) + tombstone = { + "deletion_id": uuid.uuid4().hex, + "template_id": template_id, + "template_created_at": expected_created_at, + "source_volume_name": source_volume_name, + "pending_hosts": host_ids, + "source_deleted": False, + "created_at": int(time.time()), + } + encoded = json.dumps(tombstone, separators=(",", ":")) + self.store.set(CACHE_TOMBSTONE_KIND, template_id, encoded) + try: + # Re-enters runtime.lock, which is intentionally an RLock. + runtime.delete(template_id) + except Exception: + # A database DELETE acknowledgement can be lost before or + # after commit. The catalog alone is not sufficient proof of + # rollback because source unlink happens first. Reconcile both + # durable halves: only an intact catalog+source pair cancels + # this marker; a missing source completes retirement and keeps + # host GC durable. + if self.store.get( + CACHE_TOMBSTONE_KIND, template_id) == encoded: + reconciled = runtime._reconcile_cache_tombstone( + template_id, tombstone.copy()) + if (reconciled is not None + and reconciled["source_deleted"]): + return template_id, reconciled + raise + tombstone["source_deleted"] = True + self.store.set( + CACHE_TOMBSTONE_KIND, template_id, + json.dumps(tombstone, separators=(",", ":")), + ) + return template_id, tombstone + + @staticmethod + def _decode_cloud_template_tombstone(key: str, raw: str) -> dict: + try: + value = json.loads(raw) + deletion_id = value["deletion_id"] + template_id = value["template_id"] + template_created_at = value["template_created_at"] + pending = value["pending_hosts"] + except (KeyError, TypeError, ValueError) as exc: + raise ValueError("cloud template tombstone is corrupt") from exc + try: + expected_volume_name = template_volume_name(template_id) + except TemplateError as exc: + raise ValueError("cloud template tombstone is corrupt") from exc + if (not isinstance(deletion_id, str) + or not re.fullmatch(r"[0-9a-f]{32}", deletion_id) + or key != template_id + or isinstance(template_created_at, bool) + or not isinstance(template_created_at, int) + or template_created_at < 1 + or value.get("source_volume_name") != expected_volume_name + or not isinstance(pending, list) + or any(not isinstance(host_id, str) + or not HOST_ID.fullmatch(host_id) + for host_id in pending) + or len(set(pending)) != len(pending) + or not isinstance(value.get("source_deleted"), bool)): + raise ValueError("cloud template tombstone is corrupt") + return value + + async def _cleanup_cloud_template_tombstone_on_host( + self, key: str, tombstone: dict, host_id: str) -> None: + if (not tombstone.get("source_deleted") + or host_id not in tombstone["pending_hosts"]): + return + try: + await self.registry.get(host_id) + components = self.registry.components[host_id] + profile = await asyncio.to_thread(components.manager.current) + if profile is None or profile.get("key_locked"): + return + service = self._service(profile) + await asyncio.to_thread( + self._cleanup_cloud_template_tombstone_on_host_sync, + key, tombstone["deletion_id"], host_id, service, components) + except Exception as exc: + LOG.info( + "Cloud template cache cleanup deferred: host=%s type=%s", + host_id, type(exc).__name__) + + def _cleanup_cloud_template_tombstone_on_host_sync( + self, key: str, deletion_id: str, host_id: str, + service, components: EngineComponents) -> None: + """Revalidate the deletion generation at the libvirt commit point. + + Duplicate cleanup tasks can outlive the tombstone snapshot that + scheduled them. Holding the shared runtime lock across the final + re-read, libvirt deletion and marker update prevents an obsolete task + from deleting a replica created by a same-content reimport. + """ + runtime = self.registry.cloud_templates + with runtime.lock: + raw = self.store.get(CACHE_TOMBSTONE_KIND, key) + if raw is None: + return + value = self._decode_cloud_template_tombstone(key, raw) + if (value["deletion_id"] != deletion_id + or not value["source_deleted"] + or host_id not in value["pending_hosts"]): + return + try: + service.delete_cloud_template_replicas( + value["source_volume_name"]) + except Exception as exc: + from .libvirt_service import VMError + # Only an accessible pool with no matching volumes is an + # idempotent success. A missing/misconfigured storage pool is + # also reported as 404 by libvirt_service and must keep this + # host pending so an old replica cannot escape reclamation. + if (not isinstance(exc, VMError) + or exc.status != 404 + or str(exc) != "云镜像宿主机缓存不存在"): + raise + components.store.delete( + "cloud_template_replica", value["template_id"]) + value["pending_hosts"] = [ + candidate for candidate in value["pending_hosts"] + if candidate != host_id + ] + # Retain the terminal record so a response lost after source + # deletion remains retryable until an intentional reimport. + self.store.set( + CACHE_TOMBSTONE_KIND, key, + json.dumps(value, separators=(",", ":")), + ) + + async def _cleanup_host_cloud_template_tombstones( + self, host_id: str) -> None: + rows = await asyncio.to_thread( + self.store.list, CACHE_TOMBSTONE_KIND) + for key, raw in rows.items(): + try: + tombstone = self._decode_cloud_template_tombstone(key, raw) + except ValueError: + LOG.error( + "Corrupt cloud template cache cleanup record: key=%s", key) + continue + if host_id in tombstone["pending_hosts"]: + await self._cleanup_cloud_template_tombstone_on_host( + key, tombstone, host_id) + def _delete_user_iso_source( self, user_id: int, iso_id: str) -> tuple[str, dict]: """Commit one source deletion and its remote-GC tombstone atomically. @@ -1413,6 +1627,9 @@ class EngineApplication: for host_id in tuple(self.registry.components): self._background( self._cleanup_host_user_iso_tombstones(host_id)) + self._background( + self._cleanup_host_cloud_template_tombstones( + host_id)) await send({"type": "lifespan.startup.complete"}) except Exception: LOG.exception("Engine startup failed") diff --git a/engine/virsh_panel/libvirt_service.py b/engine/virsh_panel/libvirt_service.py index 1a6d08db..6350dd2b 100644 --- a/engine/virsh_panel/libvirt_service.py +++ b/engine/virsh_panel/libvirt_service.py @@ -37,13 +37,15 @@ PANEL_NS = "urn:virsh-panel:1" NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,62}\Z") INTERNAL_RESOURCE_PREFIX_LENGTHS = (16, 20, 24, 28, 32) BRIDGE_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z") -TEMPLATE_VOLUME_RE = re.compile( +TEMPLATE_VOLUME_STEM = ( r"panel-template-(?:alma(?:8|9|10)|debian(?:11|12|13)|" r"ubuntu(?:2004|2204|2404|2504|2510|2604)|" r"centosstream(?:9|10))-" r"[0-9a-f]{8}-[0-9a-f]{16}" - r"(?:-[0-9a-f]{16})?\.qcow2\Z" ) +TEMPLATE_SOURCE_VOLUME_RE = re.compile(TEMPLATE_VOLUME_STEM + r"\.qcow2\Z") +TEMPLATE_VOLUME_RE = re.compile( + TEMPLATE_VOLUME_STEM + r"(?:-[0-9a-f]{16})?\.qcow2\Z") RESCUE_VOLUME_RE = re.compile(r"panel-rescue-[0-9a-f]{32}\.iso\Z") _CREATE_LOCK = threading.RLock() REINSTALL_SHUTDOWN_TIMEOUT = 120 @@ -1274,6 +1276,53 @@ class VMService: LOG.warning("Template cache upload failed for %s: %s", volume_name, exc) raise VMError("云镜像缓存到宿主机失败", 502) from exc + def delete_cloud_template_replicas( + self, source_volume_name: str) -> dict[str, Any]: + """Delete every host-local generation derived from one global image. + + A failed identity check can intentionally leave an older generation + beside the current ready replica. Deletion therefore scans the + tightly validated source-name namespace instead of trusting only the + latest marker. All candidates are checked for domain references + before any is removed, so the operation is safe to retry. + """ + if (not isinstance(source_volume_name, str) + or not TEMPLATE_SOURCE_VOLUME_RE.fullmatch(source_volume_name)): + raise VMError("云镜像源卷名称无效") + replica_prefix = source_volume_name.removesuffix(".qcow2") + "-" + replica_re = re.compile( + re.escape(replica_prefix) + r"[0-9a-f]{16}\.qcow2\Z" + ) + with _CREATE_LOCK, self._connect() as conn: + pool = self._active_pool(conn, self.storage_pool) + self._refresh_directory_pool(pool) + candidates = sorted( + name for name in pool.listVolumes() + if name == source_volume_name or replica_re.fullmatch(name) + ) + if not candidates: + raise VMError("云镜像宿主机缓存不存在", 404) + volumes = [] + for name in candidates: + if not TEMPLATE_VOLUME_RE.fullmatch(name): + raise VMError("云镜像宿主机缓存名称无效", 500) + volume = pool.storageVolLookupByName(name) + try: + path = volume.path() + except (AttributeError, libvirt.libvirtError) as exc: + raise VMError("无法核对宿主机模板卷路径", 502) from exc + if self._other_domain_uses_volume( + conn, "", pool.name(), name, path): + raise VMError("云镜像仍被虚拟机引用,不能删除", 409) + volumes.append((name, volume)) + for _name, volume in volumes: + volume.delete(0) + return { + "source_volume_name": source_volume_name, + "deleted": True, + "deleted_volumes": [name for name, _volume in volumes], + } + @staticmethod def _check_user_iso_volume_name(volume_name: str) -> None: if not isinstance(volume_name, str) or not USER_ISO_VOLUME_RE.fullmatch(volume_name): diff --git a/web/app/Controllers/CloudAdminController.php b/web/app/Controllers/CloudAdminController.php index 27db631a..2738f1c7 100644 --- a/web/app/Controllers/CloudAdminController.php +++ b/web/app/Controllers/CloudAdminController.php @@ -8,6 +8,7 @@ use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInput; use App\Services\Cloud\CloudInstanceDiscovery; +use App\Services\Cloud\CloudTemplateDeletionService; use App\Services\Cloud\CloudUserIsoFeature; final class CloudAdminController @@ -167,6 +168,20 @@ final class CloudAdminController $body = in_array($method, ['POST', 'PATCH', 'PUT'], true) ? CloudInput::object($request) : null; $kind = $args['kind']; if ($kind === 'cloud') { + $templateId = isset($args['id']) + ? CloudInput::template((string) $args['id']) : null; + $templateCreatedAt = null; + if ($method === 'DELETE') { + $body = CloudInput::object($request); + CloudInput::only($body, ['created_at']); + $templateCreatedAt = $body['created_at'] ?? null; + if (!is_int($templateCreatedAt) || $templateCreatedAt < 1) { + throw new CloudError('云镜像版本无效,请刷新目录后重试'); + } + CloudTemplateDeletionService::begin( + (string) $templateId, $templateCreatedAt + ); + } if ($body !== null) { unset($body['host_id']); if ($method === 'POST' && isset($body['sha256']) @@ -175,19 +190,87 @@ final class CloudAdminController } } $path = '/internal/v1/vm-templates'; - if (isset($args['id'])) { - $path .= '/' . rawurlencode($args['id']); + if ($templateId !== null) { + $path .= '/' . rawurlencode($templateId); } elseif ($method === 'POST') { $path .= '/import'; } if (isset($args['job_id'])) { $path .= '/import-jobs/' . rawurlencode($args['job_id']); } - $result = (new CloudEngineClient())->request($method, $path, $actor, $body); - if ($method === 'GET' && !isset($args['job_id']) && !isset($args['id'])) { - CloudDeploymentPageService::rememberTemplateCatalog($result); + $engine = new CloudEngineClient(); + $fullCatalogRead = $method === 'GET' + && !isset($args['job_id']) && !isset($args['id']); + try { + if ($method === 'POST') { + $result = CloudTemplateDeletionService::queueImport( + static fn (): array => $engine->request( + $method, $path, $actor, $body + ) + ); + } elseif ($fullCatalogRead) { + $result = CloudTemplateDeletionService::fetchAuthoritativeCatalog( + static fn (): array => $engine->request( + $method, $path, $actor, $body + ), + static function (array $catalog): void { + CloudDeploymentPageService::rememberTemplateCatalog( + $catalog + ); + } + ); + } else { + $result = $engine->request( + $method, $path, $actor, $body + ); + } + } catch (CloudError $error) { + if ($method === 'DELETE' && $templateId !== null + && $templateCreatedAt !== null) { + if ($error->httpStatus === 404 + && $error->getMessage() === '云镜像模板不存在') { + CloudTemplateDeletionService::complete( + $templateId, + $templateCreatedAt, + static function () use ($templateId): void { + CloudDeploymentPageService::forgetTemplate( + $templateId + ); + } + ); + return $response->withJson([ + 'deleted' => true, + 'cache_cleanup_pending' => false, + ]); + } elseif ($error->httpStatus === 409 + && $error->getMessage() + === '云镜像版本已变化,请刷新后重试') { + CloudTemplateDeletionService::cancel( + $templateId, $templateCreatedAt + ); + } + } + throw $error; + } + if ($method === 'DELETE' && $templateId !== null) { + CloudTemplateDeletionService::complete( + $templateId, + (int) $templateCreatedAt, + static function () use ($templateId): void { + CloudDeploymentPageService::forgetTemplate($templateId); + } + ); } elseif (is_array($result['template'] ?? null)) { - CloudDeploymentPageService::rememberTemplate($result['template']); + CloudTemplateDeletionService::reactivateImportedTemplate( + CloudInput::template($result['template']['id'] ?? ''), + filter_var($result['template']['created_at'] ?? null, + FILTER_VALIDATE_INT) ?: 0, + static function () use ($result): void { + CloudDeploymentPageService::rememberTemplate( + $result['template'] + ); + } + ); } return $response->withJson($result); } diff --git a/web/app/Controllers/CloudApiController.php b/web/app/Controllers/CloudApiController.php index ee869e26..20d42a83 100644 --- a/web/app/Controllers/CloudApiController.php +++ b/web/app/Controllers/CloudApiController.php @@ -21,6 +21,7 @@ use App\Services\Cloud\CloudInput; use App\Services\Cloud\CloudInstanceMetadata; use App\Services\Cloud\CloudInstancePageService; use App\Services\Cloud\CloudJobService; +use App\Services\Cloud\CloudInvoiceDetailPageService; use App\Services\Cloud\CloudInvoicePageService; use App\Services\Cloud\CloudInvoicePaymentService; use App\Services\Cloud\CloudInvoiceService; @@ -240,37 +241,20 @@ final class CloudApiController public function invoice($request, $response, $args) { $actor = $this->billingActor($request); - $invoice = CloudInvoice::where('id', $args['id']) - ->where('user_id', $actor['user_id'])->first(); - if ($invoice === null) { - throw new CloudError('账单不存在', 404); - } $user = $this->user($request); - $detail = CloudInvoiceService::display($invoice); - return $this->json($response, [ - 'invoice' => $detail, - 'payment_methods' => ($detail['payable'] ?? false) - ? CloudInvoicePaymentService::methods($user) : [], - 'balance' => (string) $user->money, - 'csrf_token' => AdminCsrf::token(), - 'user_id' => (string) $user->id, - 'username' => (string) ($user->user_name ?: $user->email), - 'admin' => (bool) $actor['is_admin'], - ]); + return $this->json($response, CloudInvoiceDetailPageService::forUser( + (int) $args['id'], (int) $actor['user_id'], $user, + (bool) $actor['is_admin'] + )); } public function invoiceStatus($request, $response, $args) { $actor = $this->billingActor($request); - $invoice = CloudInvoice::where('id', $args['id']) - ->where('user_id', $actor['user_id']) - ->first(['id', 'purpose', 'instance_id', 'order_id', 'user_id', - 'due_at', 'status', 'paid_at', 'paid_via', 'created_at']); - if ($invoice === null) { - throw new CloudError('账单不存在', 404); - } return $this->json($response, [ - 'invoice' => CloudInvoiceService::status($invoice), + 'invoice' => CloudInvoiceDetailPageService::statusForUser( + (int) $args['id'], (int) $actor['user_id'] + ), ]); } diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index 8dcc0b7c..46a43458 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -8,6 +8,7 @@ use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudDeploymentPageService; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudInstancePageService; +use App\Services\Cloud\CloudInvoiceDetailPageService; use App\Services\Cloud\CloudInvoicePageService; use App\Services\Cloud\CloudUserIsoFeature; use App\Services\View; @@ -145,11 +146,29 @@ final class CloudPageController public function invoiceDetail($request, $response, $args) { $invoiceId = isset($args['id']) ? (string) $args['id'] : ''; - if (!preg_match('/^[1-9][0-9]*$/', $invoiceId)) { + if (preg_match('/^[1-9][0-9]*$/D', $invoiceId) !== 1) { return $response->withHeader('Location', '/user/cloud/invoices')->withStatus(302); } - return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId); + $actor = CloudAccess::actor(false); + $user = $request->getAttribute('auth_user') ?? Auth::getUser(); + try { + $payload = CloudInvoiceDetailPageService::forUser( + (int) $invoiceId, (int) $actor['user_id'], $user, + (bool) $actor['is_admin'] + ); + } catch (CloudError $error) { + if ($error->httpStatus === 404) { + return $response->withHeader('Location', '/user/cloud/invoices') + ->withStatus(302); + } + throw $error; + } + + return $this->render($response, 'invoice-detail', '账单详情', '', $invoiceId, [ + 'cloud_invoice_detail_view' => $this->invoiceDetailView($payload), + 'cloud_invoice_detail_bootstrap_json' => $this->safeJson($payload), + ]); } public function reinstall($request, $response, $args) @@ -226,6 +245,8 @@ final class CloudPageController ]); $smarty->assign('cloud_invoice_balance', '$—'); $smarty->assign('cloud_invoice_bootstrap_json', '{}'); + $smarty->assign('cloud_invoice_detail_view', []); + $smarty->assign('cloud_invoice_detail_bootstrap_json', '{}'); $smarty->assign('cloud_vm_rows', []); $smarty->assign('cloud_vm_stats', [ 'total' => 0, 'running' => 0, 'stopped' => 0, 'other' => 0, @@ -254,14 +275,196 @@ final class CloudPageController } $response->getBody()->write($smarty->fetch('cloud/page.tpl')); // Every cloud page is authenticated and may contain account- or - // tenant-specific data. In particular, the invoice list is now - // server-rendered, so intermediaries must never cache its HTML. + // tenant-specific data. Invoice list and detail pages are rendered + // with user data, so intermediaries must never cache their HTML. return $response->withHeader('Cache-Control', 'private, no-store'); } private function invoiceListRow(array $invoice): array { - [$statusLabel, $statusClass] = match (strtolower((string) ($invoice['status'] ?? ''))) { + [$statusLabel, $statusClass] = $this->invoiceStatus( + (string) ($invoice['status'] ?? '') + ); + $fulfillment = strtolower((string) ($invoice['fulfillment_status'] + ?? $invoice['job_status'] ?? $invoice['order_status'] ?? '')); + [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( + $fulfillment + ); + + $invoice['created_display'] = (int) ($invoice['created_at'] ?? 0) > 0 + ? date('Y/m/d H:i:s', (int) $invoice['created_at']) : '时间未记录'; + $invoice['amount_display'] = $this->formatUsd($invoice['amount'] ?? null); + $invoice['status_label'] = $statusLabel; + $invoice['status_class'] = $statusClass; + $invoice['fulfillment_label'] = $fulfillmentLabel; + $invoice['fulfillment_class'] = $fulfillmentClass; + $invoice['show_fulfillment'] = (string) ($invoice['purpose'] ?? '') === 'provision' + && in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true) + && $fulfillmentLabel !== ''; + return $invoice; + } + + private function invoiceDetailView(array $payload): array + { + $invoice = is_array($payload['invoice'] ?? null) ? $payload['invoice'] : []; + $purpose = strtolower((string) ($invoice['purpose'] ?? '')); + [$statusLabel, $statusClass] = $this->invoiceStatus( + (string) ($invoice['status'] ?? '') + ); + $created = $this->formatTimestamp($invoice['created_at'] ?? null, + '时间未记录'); + $facts = [ + ['label' => '账单编号', 'value' => '#' . (string) ($invoice['id'] ?? '—')], + ['label' => '创建时间', 'value' => $created], + ]; + if ($purpose === 'provision') { + $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( + $invoice['payment_deadline_at'] ?? $invoice['due_at'] ?? null + )]; + } elseif ($purpose === 'renewal') { + $facts[] = ['label' => '实例到期', 'value' => $this->formatTimestamp( + $invoice['due_at'] ?? null + )]; + if (($invoice['deletion_at'] ?? null) !== null) { + $facts[] = ['label' => '最晚支付', 'value' => $this->formatTimestamp( + $invoice['deletion_at'] + )]; + } + } elseif (($invoice['payment_deadline_at'] ?? null) !== null) { + $facts[] = ['label' => '支付截止', 'value' => $this->formatTimestamp( + $invoice['payment_deadline_at'] + )]; + } + if (($invoice['paid_at'] ?? null) !== null) { + $facts[] = ['label' => '支付时间', 'value' => $this->formatTimestamp( + $invoice['paid_at'] + )]; + } + if (trim((string) ($invoice['paid_via'] ?? '')) !== '') { + $facts[] = ['label' => '支付方式', 'value' => $this->paymentLabel( + (string) $invoice['paid_via'] + )]; + } + + $specification = []; + if (in_array($purpose, ['provision', 'renewal'], true)) { + $subject = $this->firstText($invoice['requested_name'] ?? null, + $invoice['instance_name'] ?? null); + $specification[] = ['label' => '实例', 'value' => $subject !== '' + ? $subject : ($purpose === 'provision' ? '待创建实例' : '实例')]; + $planName = trim((string) ($invoice['plan_name'] ?? '')); + $specification[] = ['label' => '套餐', 'value' => $planName !== '' + ? $planName : '云服务器套餐']; + if (($invoice['cpu_cores'] ?? null) !== null) { + $specification[] = ['label' => 'CPU', + 'value' => (string) $invoice['cpu_cores'] . ' 核']; + } + if (($invoice['memory_mib'] ?? null) !== null) { + $specification[] = ['label' => '内存', + 'value' => $this->formatMemory((int) $invoice['memory_mib'])]; + } + if (($invoice['disk_gib'] ?? null) !== null) { + $specification[] = ['label' => '系统盘', + 'value' => (string) $invoice['disk_gib'] . ' GB']; + } + if (($invoice['bandwidth_mbps'] ?? null) !== null) { + $specification[] = ['label' => '带宽', + 'value' => (string) $invoice['bandwidth_mbps'] . ' Mbps']; + } + $specification[] = ['label' => '服务周期', + 'value' => max(0, (int) ($invoice['validity_days'] ?? 0)) . ' 天']; + $specification[] = ['label' => '周期流量', 'value' => $this->formatBytes( + max(0, (int) ($invoice['traffic_quota_bytes'] ?? 0)), true + )]; + } + + $paymentMethods = []; + $payable = ($invoice['payable'] ?? false) === true; + $balancePaymentAllowed = ($payload['balance_payment_allowed'] ?? false) === true; + if ($payable && $balancePaymentAllowed) { + $paymentMethods[] = [ + 'id' => 'balance', + 'name' => '账户余额', + 'description' => '可用余额 ' . $this->formatUsd($payload['balance'] ?? null), + 'selected' => true, + ]; + } + if ($payable) { + foreach (is_array($payload['payment_methods'] ?? null) + ? $payload['payment_methods'] : [] as $method) { + if (!is_array($method) || !isset($method['id'], $method['name'])) { + continue; + } + $paymentMethods[] = [ + 'id' => (string) $method['id'], + 'name' => (string) $method['name'], + 'description' => trim((string) ($method['description'] + ?? $method['label'] ?? '')) ?: '在线支付', + 'selected' => false, + ]; + } + } + if ($paymentMethods !== [] + && !in_array(true, array_column($paymentMethods, 'selected'), true)) { + $paymentMethods[0]['selected'] = true; + } + + $fulfillment = is_array($invoice['fulfillment'] ?? null) + ? $invoice['fulfillment'] : []; + $fulfillmentStatus = strtolower($this->firstText( + $fulfillment['job_status'] ?? null, + $invoice['job_status'] ?? null, + $invoice['fulfillment_status'] ?? null, + $fulfillment['order_status'] ?? null, + $invoice['order_status'] ?? null + )); + [$fulfillmentLabel, $fulfillmentClass] = $this->invoiceFulfillmentStatus( + $fulfillmentStatus + ); + $showFulfillment = $purpose === 'provision' + && (in_array(strtolower((string) ($invoice['status'] ?? '')), + ['paid', 'refunded'], true) + || $this->firstText($fulfillment['job_id'] ?? null, + $invoice['job_id'] ?? null) !== ''); + $fulfillmentError = $this->firstText($fulfillment['error'] ?? null, + $invoice['error'] ?? null); + $fulfillmentMessage = $fulfillmentError; + if ($fulfillmentMessage === '') { + $fulfillmentMessage = $fulfillmentStatus === 'uncertain' + ? '后台正在核对实例创建结果,请勿重复提交。' + : ($fulfillmentLabel !== '' ? $fulfillmentLabel : '等待创建'); + } + + return [ + 'id' => (string) ($invoice['id'] ?? ''), + 'title' => (string) ($invoice['title'] ?? $invoice['type_label'] ?? '账单'), + 'created_display' => $created, + 'amount_display' => $this->formatUsd($invoice['amount'] ?? null), + 'status_label' => $statusLabel, + 'status_class' => $statusClass, + 'facts' => $facts, + 'show_specification' => $specification !== [], + 'specification' => $specification, + 'show_payment' => $payable && $paymentMethods !== [], + 'payment_methods' => $paymentMethods, + 'show_fulfillment' => $showFulfillment, + 'fulfillment_message' => $fulfillmentMessage, + 'fulfillment_label' => $fulfillmentLabel, + 'fulfillment_class' => $fulfillmentClass, + 'fulfillment_failed' => $fulfillmentMessage !== '' + && ($fulfillmentError !== '' + || in_array($fulfillmentStatus, + ['failed', 'refunded', 'needs_attention'], true)), + 'job_id' => $this->firstText($fulfillment['job_id'] ?? null, + $invoice['job_id'] ?? null), + 'instance_id' => $this->firstText($fulfillment['instance_id'] ?? null, + $invoice['instance_id'] ?? null), + ]; + } + + private function invoiceStatus(string $status): array + { + return match (strtolower($status)) { 'open' => ['待支付', 'warning'], 'overdue' => ['已逾期', 'failed'], 'paid' => ['已支付', 'running'], @@ -274,11 +477,13 @@ final class CloudPageController 'delete_failed' => ['自动删除失败', 'failed'], 'purge_stop_failed' => ['删除前关机失败', 'failed'], 'purge_failed' => ['自动删除失败', 'failed'], - default => [(string) ($invoice['status'] ?? '未知'), 'other'], + default => [$status !== '' ? $status : '未知', 'other'], }; - $fulfillment = strtolower((string) ($invoice['fulfillment_status'] - ?? $invoice['job_status'] ?? $invoice['order_status'] ?? '')); - [$fulfillmentLabel, $fulfillmentClass] = match ($fulfillment) { + } + + private function invoiceFulfillmentStatus(string $status): array + { + return match (strtolower($status)) { 'awaiting_payment', 'payment_pending', 'draft' => ['等待支付', 'warning'], 'queued', 'pending' => ['等待创建', 'warning'], 'provisioning', 'running' => ['创建中', 'warning'], @@ -289,18 +494,58 @@ final class CloudPageController 'uncertain' => ['正在核对结果', 'warning'], default => ['', ''], }; + } - $invoice['created_display'] = (int) ($invoice['created_at'] ?? 0) > 0 - ? date('Y/m/d H:i:s', (int) $invoice['created_at']) : '时间未记录'; - $invoice['amount_display'] = $this->formatUsd($invoice['amount'] ?? null); - $invoice['status_label'] = $statusLabel; - $invoice['status_class'] = $statusClass; - $invoice['fulfillment_label'] = $fulfillmentLabel; - $invoice['fulfillment_class'] = $fulfillmentClass; - $invoice['show_fulfillment'] = (string) ($invoice['purpose'] ?? '') === 'provision' - && in_array(strtolower((string) ($invoice['status'] ?? '')), ['paid', 'refunded'], true) - && $fulfillmentLabel !== ''; - return $invoice; + private function formatTimestamp($value, string $fallback = '暂未提供'): string + { + return is_numeric($value) && (int) $value > 0 + ? date('Y/m/d H:i:s', (int) $value) : $fallback; + } + + private function formatMemory(int $memoryMiB): string + { + $memoryGiB = $memoryMiB / 1024; + return number_format($memoryGiB, $memoryGiB === floor($memoryGiB) ? 0 : 1, + '.', ',') . ' GB'; + } + + private function formatBytes(int $bytes, bool $unlimitedZero = false): string + { + if ($bytes === 0 && $unlimitedZero) { + return '不限流量'; + } + $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + $amount = (float) $bytes; + $unit = 0; + while ($amount >= 1024 && $unit < count($units) - 1) { + $amount /= 1024; + ++$unit; + } + $precision = $unit === 0 ? 0 : ($amount >= 100 ? 0 : ($amount >= 10 ? 1 : 2)); + return number_format($amount, $precision, '.', '') . ' ' . $units[$unit]; + } + + private function paymentLabel(string $paidVia): string + { + return match (strtolower(trim($paidVia))) { + 'balance' => '账户余额', + 'yipay_alipay' => '易支付 · 支付宝', + 'yipay_wxpay' => '易支付 · 微信', + 'paytaro' => 'Paytaro · 支付宝', + 'usdt' => 'USDT-TRC20', + default => $paidVia, + }; + } + + private function firstText(...$values): string + { + foreach ($values as $value) { + $text = trim((string) ($value ?? '')); + if ($text !== '') { + return $text; + } + } + return ''; } private function formatUsd($value): string diff --git a/web/app/Models/CloudTemplateCatalogLock.php b/web/app/Models/CloudTemplateCatalogLock.php new file mode 100644 index 00000000..e8c6638f --- /dev/null +++ b/web/app/Models/CloudTemplateCatalogLock.php @@ -0,0 +1,10 @@ +request( - 'GET', '/internal/v1/vm-templates', $actor + $engine = new CloudEngineClient(null, $timeoutSeconds); + $payload = CloudTemplateDeletionService::fetchAuthoritativeCatalog( + static fn (): array => $engine->request( + 'GET', '/internal/v1/vm-templates', $actor + ), + static function (array $catalog): void { + self::rememberTemplateCatalog($catalog); + } + ); + $payload['templates'] = self::availableTemplates( + self::sanitizeTemplates($payload['templates'] ?? []) ); - $payload['templates'] = self::sanitizeTemplates($payload['templates'] ?? []); - self::rememberTemplateCatalog($payload); return $payload; } /** Persist only the public subset needed to draw an image picker. */ public static function rememberTemplateCatalog(array $payload): void { - $templates = self::sanitizeTemplates($payload['templates'] ?? []); + $templates = self::availableTemplates( + self::sanitizeTemplates($payload['templates'] ?? []) + ); $snapshot = [ 'version' => self::TEMPLATE_SNAPSHOT_VERSION, 'updated_at' => time(), @@ -217,6 +226,48 @@ final class CloudDeploymentPageService self::rememberTemplateCatalog(['templates' => $templates]); } + /** Remove a deleted template from the first-paint snapshot immediately. */ + public static function forgetTemplate(string $templateId): void + { + $snapshot = self::templateSnapshot(); + if ($snapshot === null) { + return; + } + $templates = array_values(array_filter( + $snapshot['templates'], + static fn (array $template): bool => + (string) ($template['id'] ?? '') !== $templateId + )); + self::rememberTemplateCatalog(['templates' => $templates]); + } + + /** Filter templates retired by PHP even if an engine retry is pending. */ + private static function availableTemplates(array $templates): array + { + try { + $retired = array_fill_keys( + CloudTemplateRetirement::query() + ->whereIn('state', ['deleting', 'deleted']) + ->pluck('template_id')->map( + static fn ($id): string => (string) $id + )->all(), + true + ); + } catch (\Throwable $error) { + // cloudInit creates the gate before the new code is started. Keep + // read-only first paint usable during tests or manual recovery. + $retired = []; + } + if ($retired === []) { + return array_values($templates); + } + return array_values(array_filter( + $templates, + static fn (array $template): bool => + !isset($retired[(string) ($template['id'] ?? '')]) + )); + } + public static function templateGroups(array $templates): array { $groups = []; @@ -286,6 +337,7 @@ final class CloudDeploymentPageService { $templates = is_array($snapshot['templates'] ?? null) ? $snapshot['templates'] : []; + $templates = self::availableTemplates($templates); $failed = ($snapshot['refresh_failed'] ?? false) === true; return [ 'templates' => $templates, diff --git a/web/app/Services/Cloud/CloudEngineClient.php b/web/app/Services/Cloud/CloudEngineClient.php index b857d2f5..eacdd715 100644 --- a/web/app/Services/Cloud/CloudEngineClient.php +++ b/web/app/Services/Cloud/CloudEngineClient.php @@ -165,6 +165,16 @@ final class CloudEngineClient 'SHA-256 可留空;填写时必须为 64 位十六进制校验值', '云镜像导入任务不存在', '云镜像模板不存在', '云镜像正在导入,请稍后修改模板名称', + '云镜像正在导入,请稍后删除模板', + '云镜像正在同步到宿主机,请稍后删除', + '云镜像删除参数无效', + '云镜像版本已变化,请刷新后重试', + '云镜像目录记录损坏,无法安全删除', + '云镜像源文件无法安全删除', + '云镜像源文件删除失败,请联系管理员', + '云镜像缓存清理记录损坏,请联系管理员', + '云镜像版本记录损坏,请联系管理员', + '旧云镜像缓存仍在清理,请稍后重新导入', '此云镜像已经导入', '已有同名云镜像模板', '该云镜像正在导入', '已有云镜像正在导入,请等待完成后再提交', '引擎正在停止,无法开始云镜像导入', diff --git a/web/app/Services/Cloud/CloudInvoiceDetailPageService.php b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php new file mode 100644 index 00000000..febfd0cf --- /dev/null +++ b/web/app/Services/Cloud/CloudInvoiceDetailPageService.php @@ -0,0 +1,75 @@ +id !== $userId) { + throw new CloudError('账单不存在', 404); + } + + // The invoice and its order/job/instance snapshot must agree. Holding + // a shared lock prevents a concurrent payment transaction from + // returning an old invoice status with newly-updated associations. + $detail = (new CloudInvoice())->getConnection()->transaction( + function () use ($invoiceId, $userId) { + $invoice = CloudInvoice::where('id', $invoiceId) + ->where('user_id', $userId) + ->sharedLock() + ->first(); + if ($invoice === null) { + throw new CloudError('账单不存在', 404); + } + return CloudInvoiceService::display($invoice); + }, 3 + ); + return [ + 'invoice' => $detail, + 'payment_methods' => ($detail['payable'] ?? false) + ? CloudInvoicePaymentService::methods($user) : [], + 'balance_payment_allowed' => (int) $user->enable === 1 + && !UserFeatureRestrictionService::isBalancePurchaseRestricted($user), + 'balance' => (string) $user->money, + 'csrf_token' => AdminCsrf::token(), + 'user_id' => (string) $user->id, + 'username' => (string) ($user->user_name ?: $user->email), + 'admin' => $isAdmin, + ]; + } + + /** Return one owner-scoped, transactionally consistent polling snapshot. */ + public static function statusForUser(int $invoiceId, int $userId): array + { + if ($invoiceId <= 0 || $userId <= 0) { + throw new CloudError('账单不存在', 404); + } + + return (new CloudInvoice())->getConnection()->transaction( + function () use ($invoiceId, $userId) { + $invoice = CloudInvoice::where('id', $invoiceId) + ->where('user_id', $userId) + ->sharedLock() + ->first(['id', 'purpose', 'instance_id', 'order_id', 'user_id', + 'due_at', 'status', 'paid_at', 'paid_via', 'created_at']); + if ($invoice === null) { + throw new CloudError('账单不存在', 404); + } + return CloudInvoiceService::status($invoice); + }, 3 + ); + } +} diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index 6a729603..b076e7af 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -475,15 +475,7 @@ final class CloudInvoiceService $instance = $purpose === 'renewal' && $invoice->instance_id !== null ? ($instances[self::listKey($ownerId, (int) $invoice->instance_id)] ?? null) : null; - $status = (string) $invoice->status; - if ($purpose === 'renewal' - && ($instance === null || (string) $instance->status === 'deleted')) { - if (in_array($status, ['open', 'overdue'], true)) { - $status = 'void'; - } - } elseif ($status === 'open' && (int) $invoice->due_at <= $now) { - $status = 'overdue'; - } + $status = self::publicStatus($invoice, $purpose, $instance, $now); $summaries[] = [ 'id' => (string) $invoice->id, 'title' => $title, @@ -505,6 +497,51 @@ final class CloudInvoiceService return $userId . ':' . $recordId; } + /** Derive the user-visible status shared by list, detail and polling. */ + private static function publicStatus(CloudInvoice $invoice, string $purpose, + $instance, int $now): string + { + $status = (string) $invoice->status; + if ($purpose === 'renewal' + && ($instance === null || (string) $instance->status === 'deleted')) { + if (in_array($status, ['open', 'overdue'], true)) { + return 'void'; + } + } elseif ($status === 'open' && (int) $invoice->due_at <= $now) { + return 'overdue'; + } + return $status; + } + + /** + * Derive the public invoice state once for both full detail responses and + * lightweight polling responses. The callers deliberately load different + * columns, but payment eligibility must never drift between them. + * + * @return array{status: string, deadline: int, payable: bool} + */ + private static function publicState(CloudInvoice $invoice, string $purpose, + $order, $instance, int $now): array + { + $status = self::publicStatus($invoice, $purpose, $instance, $now); + + $deadline = self::paymentDeadline($invoice); + if ($purpose === 'provision') { + $payable = in_array($status, ['open', 'overdue'], true) + && $order !== null + && (string) $order->status === 'awaiting_payment' + && $deadline > $now; + } else { + $payable = in_array($status, ['open', 'overdue'], true) + && $instance !== null + && !self::instanceDeleting($instance) + && $deadline > $now; + } + + return ['status' => $status, 'deadline' => $deadline, + 'payable' => $payable]; + } + /** * Return only the mutable fields needed while a browser waits for an * invoice payment or a provisioning job. This deliberately avoids plan @@ -535,28 +572,10 @@ final class CloudInvoiceService ->first(['id', 'user_id', 'status', 'service_status']); } - $status = (string) $invoice->status; - if ($purpose === 'renewal' - && ($instance === null || (string) $instance->status === 'deleted')) { - if (in_array($status, ['open', 'overdue'], true)) { - $status = 'void'; - } - } elseif ($status === 'open' && (int) $invoice->due_at <= $now) { - $status = 'overdue'; - } - - $deadline = self::paymentDeadline($invoice); - if ($purpose === 'provision') { - $payable = in_array($status, ['open', 'overdue'], true) - && $order !== null - && (string) $order->status === 'awaiting_payment' - && $deadline > $now; - } else { - $payable = in_array($status, ['open', 'overdue'], true) - && $instance !== null - && !self::instanceDeleting($instance) - && $deadline > $now; - } + $publicState = self::publicState($invoice, $purpose, $order, $instance, $now); + $status = $publicState['status']; + $deadline = $publicState['deadline']; + $payable = $publicState['payable']; $decodedJobResult = $job === null || $job->result_json === null ? null : json_decode((string) $job->result_json, true); @@ -564,9 +583,15 @@ final class CloudInvoiceService ? CloudInput::safeResult($decodedJobResult) : null; $jobPhase = is_string($safeJobResult['phase'] ?? null) ? mb_substr($safeJobResult['phase'], 0, 120) : null; - $instanceId = $purpose === 'provision' + $linkedInstanceId = $purpose === 'provision' ? ($order?->instance_id ?? $invoice->instance_id) : $invoice->instance_id; + $linkedInstance = $purpose === 'renewal' ? $instance + : ($linkedInstanceId === null ? null + : CloudInstance::where('id', $linkedInstanceId) + ->where('user_id', $invoice->user_id) + ->first(['id', 'user_id'])); + $instanceId = $linkedInstance?->id; $fulfillmentStatus = $job?->status ?? $order?->status; return [ @@ -613,16 +638,21 @@ final class CloudInvoiceService }; $order = $purpose !== 'provision' || $invoice->order_id === null ? null : CloudOrder::where('id', $invoice->order_id) - ->where('user_id', $invoice->user_id)->first(); + ->where('user_id', $invoice->user_id) + ->first(['id', 'user_id', 'instance_id', 'status', 'spec_json']); $linkedInstanceId = $purpose === 'provision' ? ($order?->instance_id ?? $invoice->instance_id) : $invoice->instance_id; $instance = $linkedInstanceId === null ? null : CloudInstance::where('id', $linkedInstanceId) - ->where('user_id', $invoice->user_id)->first(); + ->where('user_id', $invoice->user_id) + ->first(['id', 'user_id', 'name', 'status', 'service_status', + 'spec_json']); $job = $order === null ? null : CloudJob::where('order_id', $order->id) - ->where('user_id', $invoice->user_id)->first(); + ->where('user_id', $invoice->user_id) + ->first(['id', 'order_id', 'user_id', 'status', 'attempts', + 'updated_at', 'error_code']); // Successful workers persist both links. Keep the invoice-side link // as a defensive fallback for an interrupted upgrade or a repaired // order row so the unified bill can still open the created instance. @@ -644,27 +674,10 @@ final class CloudInvoiceService $memoryMiB = $memoryMiB > 0 ? $memoryMiB : null; $diskGiB = $diskGiB > 0 ? $diskGiB : null; $bandwidthMbps = $bandwidthMbps > 0 ? $bandwidthMbps : null; - $status = (string) $invoice->status; - if ($purpose === 'renewal' - && ($instance === null || (string) $instance->status === 'deleted')) { - if (in_array($status, ['open', 'overdue'], true)) { - $status = 'void'; - } - } elseif ($status === 'open' && (int) $invoice->due_at <= $now) { - $status = 'overdue'; - } - $deadline = self::paymentDeadline($invoice); - if ($purpose === 'provision') { - $payable = in_array($status, ['open', 'overdue'], true) - && $order !== null - && (string) $order->status === 'awaiting_payment' - && $deadline > $now; - } else { - $payable = in_array($status, ['open', 'overdue'], true) - && $instance !== null - && !self::instanceDeleting($instance) - && $deadline > $now; - } + $publicState = self::publicState($invoice, $purpose, $order, $instance, $now); + $status = $publicState['status']; + $deadline = $publicState['deadline']; + $payable = $publicState['payable']; return [ 'id' => (string) $invoice->id, 'title' => $title, diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index 5725d54c..5e0c0092 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -11,6 +11,11 @@ final class CloudJobService { CloudAccess::vmActor($instance, $actor); return $instance->getConnection()->transaction(function () use ($instance, $actor, $kind, $method, $suffix, $body, $credential) { + if ($kind === 'reinstall') { + CloudTemplateDeletionService::assertAvailable( + CloudInput::template($body['template_id'] ?? '') + ); + } $locked = CloudInstance::where('id', $instance->id)->lockForUpdate()->first(); if ($locked === null || (string) $locked->status === 'deleted') { throw new CloudError('虚拟机不存在', 404); diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index d86befdc..ccbeca3f 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -39,6 +39,7 @@ final class CloudOrderService ksort($input); $requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('payload_key')); return (new User())->getConnection()->transaction(function () use ($input, $actor, $planId, $source, $requestedName, $template, $idempotency, $requestHash) { + CloudTemplateDeletionService::assertAvailable($template); $user = User::where('id', $actor['user_id'])->lockForUpdate()->first(); if ($user === null || (int) $user->enable !== 1) { throw new CloudError('账户不可用', 403); diff --git a/web/app/Services/Cloud/CloudTemplateDeletionService.php b/web/app/Services/Cloud/CloudTemplateDeletionService.php new file mode 100644 index 00000000..105da486 --- /dev/null +++ b/web/app/Services/Cloud/CloudTemplateDeletionService.php @@ -0,0 +1,400 @@ +insertOrIgnore([ + 'template_id' => $templateId, + 'state' => 'active', + 'template_created_at' => 0, + 'created_at' => $now, + 'updated_at' => $now, + ]); + $state = CloudTemplateRetirement::where('template_id', $templateId) + ->lockForUpdate()->first(); + if ($state === null) { + throw new CloudError('无法锁定云镜像状态', 503); + } + if ((string) $state->state !== 'active') { + throw new CloudError('云镜像模板正在删除或已停用', 409); + } + } + + /** + * Hold one durable catalog row until the engine has accepted the import. + * The engine queues downloads asynchronously, so this transaction never + * spans the large image transfer itself. + */ + public static function queueImport(callable $queue): array + { + return (new CloudTemplateCatalogLock())->getConnection()->transaction( + static function () use ($queue): array { + self::lockCatalog(); + self::assertImportAllowed(); + $result = $queue(); + if (!is_array($result)) { + throw new CloudError('云镜像导入响应无效', 502); + } + return $result; + }, + 3 + ); + } + + /** Fetch, reconcile and optionally publish one full catalog atomically. */ + public static function fetchAuthoritativeCatalog( + callable $fetch, ?callable $publish = null + ): array + { + return (new CloudTemplateCatalogLock())->getConnection()->transaction( + static function () use ($fetch, $publish): array { + self::lockCatalog(); + $result = $fetch(); + if (!is_array($result) + || !is_array($result['templates'] ?? null)) { + throw new CloudError('云镜像目录响应无效', 502); + } + self::reconcileAuthoritativeCatalogLocked( + $result['templates'] + ); + if ($publish !== null) { + $publish($result); + } + return $result; + }, + 3 + ); + } + + /** Persist the retirement gate before scanning every durable reference. */ + public static function begin(string $templateId, int $templateCreatedAt): void + { + if ($templateCreatedAt < 1) { + throw new CloudError('云镜像版本无效,请刷新目录后重试'); + } + (new CloudTemplateRetirement())->getConnection()->transaction( + function () use ($templateId, $templateCreatedAt): void { + self::lockCatalog(); + $now = time(); + CloudTemplateRetirement::query()->insertOrIgnore([ + 'template_id' => $templateId, + 'state' => 'deleting', + 'template_created_at' => $templateCreatedAt, + 'created_at' => $now, + 'updated_at' => $now, + ]); + $retirement = CloudTemplateRetirement::where( + 'template_id', $templateId + )->lockForUpdate()->first(); + if ($retirement === null) { + throw new CloudError('无法锁定云镜像删除状态', 503); + } + $state = (string) $retirement->state; + $storedGeneration = max(0, (int) $retirement->template_created_at); + if (!in_array($state, ['active', 'deleting', 'deleted'], true)) { + throw new CloudError('云镜像删除状态异常,请联系管理员', 503); + } + if ($storedGeneration > 0 && $storedGeneration !== $templateCreatedAt + && $state !== 'deleted') { + throw new CloudError('云镜像版本已变化,请刷新后重试', 409); + } + $retirement->state = 'deleting'; + $retirement->template_created_at = $templateCreatedAt; + $retirement->updated_at = $now; + $retirement->save(); + self::assertNoReferences($templateId); + }, + 3 + ); + } + + /** Called under the catalog lock by queueImport(). */ + public static function assertImportAllowed(): void + { + if (CloudTemplateRetirement::where('state', 'deleting')->exists()) { + throw new CloudError( + '有云镜像删除尚未完成,请刷新目录确认后再导入', 409 + ); + } + } + + /** Re-enable one stable ID only when a newer engine generation exists. */ + public static function reactivateImportedTemplate( + string $templateId, int $templateCreatedAt, + ?callable $publish = null + ): bool { + if ($templateCreatedAt < 1) { + throw new CloudError('云镜像导入结果缺少版本信息', 502); + } + return (new CloudTemplateRetirement())->getConnection()->transaction( + static function () use ( + $templateId, $templateCreatedAt, $publish + ): bool { + self::lockCatalog(); + $row = CloudTemplateRetirement::where('template_id', $templateId) + ->lockForUpdate()->first(); + if ($row === null) { + $now = time(); + CloudTemplateRetirement::query()->insert([ + 'template_id' => $templateId, + 'state' => 'active', + 'template_created_at' => $templateCreatedAt, + 'created_at' => $now, + 'updated_at' => $now, + ]); + if ($publish !== null) { + $publish(); + } + return true; + } + if ((string) $row->state === 'deleting') { + // A deletion requested after this import was queued wins. + return false; + } + $storedGeneration = max(0, (int) $row->template_created_at); + if ($templateCreatedAt < $storedGeneration) { + return false; + } + if ($templateCreatedAt === $storedGeneration) { + // A same-generation PATCH/GET is current only while that + // generation is active. A deleted row must never be + // revived by a delayed import-job response. + $current = (string) $row->state === 'active'; + if ($current && $publish !== null) { + $publish(); + } + return $current; + } + $row->state = 'active'; + $row->template_created_at = $templateCreatedAt; + $row->updated_at = time(); + $row->save(); + if ($publish !== null) { + $publish(); + } + return true; + }, + 3 + ); + } + + /** Reconcile response-loss states against one authoritative full catalog. */ + public static function reconcileAuthoritativeCatalog(array $templates): void + { + (new CloudTemplateRetirement())->getConnection()->transaction( + static function () use ($templates): void { + self::lockCatalog(); + self::reconcileAuthoritativeCatalogLocked($templates); + }, + 3 + ); + } + + private static function reconcileAuthoritativeCatalogLocked( + array $templates + ): void { + $catalog = []; + foreach ($templates as $template) { + $id = is_array($template) ? ($template['id'] ?? null) : null; + $generation = is_array($template) ? ($template['created_at'] ?? null) : null; + if (!is_string($id) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $id) !== 1 + || !is_int($generation) || $generation < 1 + || isset($catalog[$id])) { + throw new CloudError('云镜像目录响应无效', 502); + } + $catalog[$id] = $generation; + } + $rows = CloudTemplateRetirement::query()->lockForUpdate()->get(); + foreach ($rows as $row) { + $id = (string) $row->template_id; + $state = (string) $row->state; + $stored = max(0, (int) $row->template_created_at); + $active = $catalog[$id] ?? null; + if ($state === 'deleting') { + if ($active === null) { + $row->state = 'deleted'; + } elseif ($stored === 0) { + $row->template_created_at = $active; + } elseif ($active !== $stored) { + $row->state = 'active'; + $row->template_created_at = $active; + } else { + continue; + } + } elseif ($state === 'deleted') { + if ($active === null) { + continue; + } + // The engine catalog is authoritative. This also repairs a + // gate written by an older PHP process that mistook an + // unsupported DELETE route for a missing template while the + // engine service was restarting. All DELETE completion paths + // take the same catalog lock, so this cannot revive a newer + // committed deletion from an older GET snapshot. + $row->state = 'active'; + $row->template_created_at = $active; + } elseif ($state === 'active') { + if ($active === null) { + $row->state = 'deleted'; + } elseif ($active === $stored) { + continue; + } else { + $row->template_created_at = $active; + } + } else { + throw new CloudError('云镜像状态异常,请联系管理员', 503); + } + $row->updated_at = time(); + $row->save(); + } + } + + public static function complete( + string $templateId, int $templateCreatedAt, + ?callable $publish = null + ): void + { + (new CloudTemplateRetirement())->getConnection()->transaction( + static function () use ( + $templateId, $templateCreatedAt, $publish + ): void { + self::lockCatalog(); + $row = CloudTemplateRetirement::where( + 'template_id', $templateId + )->lockForUpdate()->first(); + if ($row === null + || (int) $row->template_created_at !== $templateCreatedAt + || !in_array((string) $row->state, + ['deleting', 'deleted'], true)) { + throw new CloudError( + '云镜像删除状态无法确认', 503 + ); + } + if ((string) $row->state === 'deleting') { + $row->state = 'deleted'; + $row->updated_at = time(); + $row->save(); + } + if ($publish !== null) { + $publish(); + } + }, + 3 + ); + } + + /** Remove only a gate proven to belong to a rejected engine generation. */ + public static function cancel(string $templateId, int $templateCreatedAt): void + { + (new CloudTemplateRetirement())->getConnection()->transaction( + static function () use ($templateId, $templateCreatedAt): void { + self::lockCatalog(); + $row = CloudTemplateRetirement::where( + 'template_id', $templateId + )->lockForUpdate()->first(); + if ($row !== null && (string) $row->state === 'deleting' + && (int) $row->template_created_at + === $templateCreatedAt) { + $row->delete(); + } + }, + 3 + ); + } + + private static function lockCatalog(): void + { + CloudTemplateCatalogLock::query()->insertOrIgnore([ + 'id' => 1, 'updated_at' => 0, + ]); + $lock = CloudTemplateCatalogLock::where('id', 1) + ->lockForUpdate()->first(); + if ($lock === null) { + throw new CloudError('无法锁定云镜像目录', 503); + } + } + + private static function assertNoReferences(string $templateId): void + { + foreach (CloudOrder::whereIn('status', self::ACTIVE_STATUSES) + ->lockForUpdate()->get(['id', 'spec_json']) as $order) { + try { + $spec = json_decode((string) $order->spec_json, true, 32, + JSON_THROW_ON_ERROR); + } catch (\JsonException $error) { + throw new CloudError( + '未完成开通订单的数据无法核对,暂不能删除云镜像', 503 + ); + } + if (!is_array($spec) || array_is_list($spec) + || !is_string($spec['source'] ?? null)) { + throw new CloudError( + '未完成开通订单的数据无法核对,暂不能删除云镜像', 503 + ); + } + if ($spec['source'] !== 'cloud') { + continue; + } + $referenced = $spec['template_id'] ?? null; + if (!is_string($referenced) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $referenced) !== 1) { + throw new CloudError( + '未完成开通订单的云镜像无法核对,暂不能删除', 503 + ); + } + if ($referenced === $templateId) { + throw new CloudError( + '云镜像仍被未完成的开通账单或创建任务使用,暂不能删除', 409 + ); + } + } + + foreach (CloudJob::whereIn('kind', ['create', 'reinstall']) + ->whereIn('status', ['queued', 'running', 'uncertain']) + ->lockForUpdate()->get(['id', 'kind', 'payload_cipher']) as $job) { + $payload = CloudSecrets::decrypt((string) $job->payload_cipher); + $body = $payload['body'] ?? null; + if (!is_array($body) || array_is_list($body)) { + throw new CloudError( + '未完成虚拟机任务的数据无法核对,暂不能删除云镜像', 503 + ); + } + if ((string) $job->kind === 'create' + && ($body['source'] ?? null) !== 'cloud') { + if (!is_string($body['source'] ?? null)) { + throw new CloudError( + '未完成开通任务的数据无法核对,暂不能删除云镜像', 503 + ); + } + continue; + } + $referenced = $body['template_id'] ?? null; + if (!is_string($referenced) + || preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/D', $referenced) !== 1) { + throw new CloudError( + '未完成虚拟机任务的云镜像无法核对,暂不能删除', 503 + ); + } + if ($referenced === $templateId) { + throw new CloudError( + '云镜像仍被未完成的创建或重装任务使用,暂不能删除', 409 + ); + } + } + } +} diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index eee4f301..25935990 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -55,7 +55,7 @@ $app->group('/api/v1', function () { foreach (['cloud' => 'cloud-templates', 'rescue' => 'rescue-templates'] as $kind => $name) { $this->map(['GET', 'POST'], '/admin/' . $name, 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); $this->get('/admin/' . $name . '/import-jobs/{job_id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); - $this->map($kind === 'cloud' ? ['PATCH'] : ['DELETE'], '/admin/' . $name . '/{id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); + $this->map($kind === 'cloud' ? ['PATCH', 'DELETE'] : ['DELETE'], '/admin/' . $name . '/{id}', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', $kind); } $this->post('/admin/cloud-templates/import', 'App\Controllers\CloudAdminController:templates')->setArgument('kind', 'cloud'); $this->post('/admin/rescue-templates/upload', 'App\Controllers\CloudAdminController:rescueUpload'); diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index f2efcc8c..cee50930 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -103,12 +103,32 @@ async function loadCatalog() { try { const entries = collection(await api(url), 'templates'); if (epoch !== state.epoch) return; if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。')); for (const entry of entries) { const row = element('form', 'cloud-admin-row'); const name = element('input', 'form-control'); name.value = entry.name || ''; name.maxLength = 64; name.required = true; name.setAttribute('aria-label', '模版名称'); name.disabled = !canManage; const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage; const remove = element('button', 'btn btn-outline-danger', '删除'); remove.type = 'button'; remove.disabled = !canManage; const imageBytes = Number(entry.image_bytes || entry.size_bytes || 0); - row.append(name, save); - if (rescue) row.append(remove); + row.append(name, save, remove); row.append(element('small', 'cloud-admin-meta', `${entry.os_family || '镜像'} ${entry.os_version || ''} · ${imageBytes > 0 ? (imageBytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`)); if (rescue) { name.readOnly = true; save.hidden = true; save.disabled = true; } row.addEventListener('submit', async event => { event.preventDefault(); if (rescue) return; save.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, { method: 'PATCH', body: { name: name.value.trim() } }); notice('名称已保存。'); } catch (error) { notice(error.message, true); } finally { save.disabled = !canManage; } }); - remove.addEventListener('click', async () => { if (!rescue || !confirm(`删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。`)) return; remove.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`, { method: 'DELETE' }); await loadCatalog(); } catch (error) { notice(error.message, true); remove.disabled = !canManage; } }); list.append(row); + remove.addEventListener('click', async () => { + const message = rescue + ? `删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。` + : `删除全局云镜像模版“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`; + if (!confirm(message)) return; + remove.disabled = true; + const deleteUrl = rescue + ? `${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}` + : `${catalogPath()}/${encodeURIComponent(entry.id)}`; + try { + const result = await api(deleteUrl, rescue + ? { method: 'DELETE' } + : { method: 'DELETE', body: { created_at: Number(entry.created_at) } }); + await loadCatalog(); + notice(result?.cache_cleanup_pending + ? '云镜像模版已删除,宿主机缓存正在后台清理;离线宿主机会在恢复连接后继续清理。' + : '镜像模版已删除。'); + } catch (error) { + notice(error.message, true); + remove.disabled = !canManage; + } + }); list.append(row); } notice(rescue ? `已加载 ${entries.length} 个模版。` : `已加载 ${entries.length} 个全局云镜像。`); } catch (error) { notice(error.message, true); } } diff --git a/web/public/cloud/client.css b/web/public/cloud/client.css index 240a0e9c..912b0f3e 100644 --- a/web/public/cloud/client.css +++ b/web/public/cloud/client.css @@ -105,8 +105,12 @@ .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 .cloud-payment-qr-note { color: #a16f24; } +.cloud-payment-instructions.cloud-payment-expired { background: #fff5e8; color: #8c6427; } .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 { display: flex; width: 212px; min-height: 212px; flex: 0 0 212px; align-items: center; justify-content: center; padding: 8px; border: 1px solid #d7e3e9; border-radius: 10px; background: #fff; } +.cloud-payment-qr-loading { color: #7b8f9f; font-size: 11px; font-weight: 700; } +.cloud-payment-qr-error { padding: 24px; text-align: center; } .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; } @@ -196,7 +200,7 @@ .invoice-payment-actions { padding: 16px 18px 20px; } .invoice-payment-actions .button { width: 100%; } .invoice-payment-result { padding: 0 18px 20px; } - .invoice-payment-result .cloud-payment-qr { width: 100%; } + .invoice-payment-result .cloud-payment-qr { width: 100%; flex-basis: 100%; } .invoice-fulfillment-content { padding: 19px 18px 21px; } .vm-detail-tabs { width: 100%; } .vm-detail-tab { flex: 1 0 auto; padding-inline: 12px; } diff --git a/web/public/cloud/invoice-detail-runtime.js b/web/public/cloud/invoice-detail-runtime.js new file mode 100644 index 00000000..c134e62d --- /dev/null +++ b/web/public/cloud/invoice-detail-runtime.js @@ -0,0 +1,1384 @@ +// Lightweight invoice-detail runtime. This module deliberately contains no VM, +// deployment, metrics or console code so the bill is interactive without +// downloading the all-feature cloud runtime. +const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:'; +const REQUEST_TIMEOUT_MS = 15_000; +const STATUS_POLL_INTERVAL_MS = 3_000; +const STATUS_POLL_SLOW_INTERVAL_MS = 30_000; +const STATUS_POLL_WINDOW_MS = 10 * 60 * 1_000; +const STATUS_POLL_MAX_LIFETIME_MS = 24 * 60 * 60 * 1_000; + +const byId = id => document.getElementById(id); +const state = { + view: '', + csrfToken: '', + userId: '', + username: '', + admin: false, + selectedInvoice: null, + selectedInvoicePaymentMethod: '', + invoicePaymentMethods: [], + balancePaymentAllowed: false, + invoiceBalance: '0.00', + invoiceJobProgress: new Map(), + mutationBusy: false, + onlinePaymentPending: false, + onlinePaymentExpiresAt: 0, + onlinePaymentInvoiceId: '', + onlinePaymentMethodId: '', + onlinePaymentExpiryTimer: null, + paymentRenderGeneration: 0, + refreshPromise: null, + refreshController: null, + readSequence: 0, + appliedReadSequence: 0, + pollInvoiceId: '', + pollTimer: null, + pollController: null, + pollStartedAt: 0, + pollUntil: 0, + pollGeneration: 0, +}; + +const text = (id, value) => { + const element = byId(id); + if (element) element.textContent = value ?? '—'; +}; + +function firstText(...values) { + for (const value of values) { + if (value !== null && value !== undefined && String(value).trim() !== '') { + return String(value).trim(); + } + } + return ''; +} + +function firstNumber(...values) { + for (const value of values) { + if (value === null || value === undefined || value === '') continue; + const number = Number(value); + if (Number.isFinite(number) && number >= 0) return number; + } + return null; +} + +function makeElement(tag, className = '', content) { + const element = document.createElement(tag); + if (className) element.className = className; + if (content !== undefined) element.textContent = String(content); + return element; +} + +function showError(id, message) { + const element = byId(id); + if (!element) return; + element.textContent = message || ''; + element.hidden = !message; +} + +let toastTimer = null; +function toast(message, kind = '') { + const element = byId('toast'); + if (!element) return; + element.textContent = message; + element.className = `toast ${kind}`; + element.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { element.hidden = true; }, 5_000); +} + +function readInvoiceDetailBootstrap() { + const source = byId('invoice-detail-bootstrap'); + if (!source) throw new Error('账单首屏数据缺失,请刷新页面后重试。'); + let payload; + try { + payload = JSON.parse(source.textContent || '{}'); + } catch { + throw new Error('账单首屏数据无效,请刷新页面后重试。'); + } + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + throw new Error('账单首屏数据无效,请刷新页面后重试。'); + } + return payload; +} + +function requireSecureTransport() { + if (location.protocol !== 'https:' + && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) { + throw new Error('请通过 HTTPS 使用账单支付功能。'); + } +} + +async function api(path, options = {}) { + const method = String(options.method || 'GET').toUpperCase(); + if (!['GET', 'HEAD'].includes(method)) requireSecureTransport(); + const timeoutMs = Math.max(1_000, Number(options.timeoutMs) || REQUEST_TIMEOUT_MS); + const controller = new AbortController(); + const externalSignal = options.signal; + let timedOut = false; + const abortFromExternal = () => controller.abort(); + if (externalSignal?.aborted) controller.abort(); + else externalSignal?.addEventListener('abort', abortFromExternal, { once: true }); + const timeout = setTimeout(() => { + timedOut = true; + controller.abort(); + }, timeoutMs); + + const headers = new Headers(options.headers || {}); + if (!headers.has('Accept')) headers.set('Accept', 'application/json'); + if (!['GET', 'HEAD'].includes(method)) { + headers.set('X-CSRF-Token', state.csrfToken); + if (options.body !== undefined) headers.set('Content-Type', 'application/json'); + } + + try { + const response = await fetch(path, { + method, + headers, + credentials: 'same-origin', + cache: 'no-store', + signal: controller.signal, + body: options.body === undefined ? undefined : JSON.stringify(options.body), + }); + let payload = null; + if (response.status !== 204) { + try { + payload = await response.json(); + } catch { + throw new Error('服务返回了非 JSON 数据,请检查 PHP 及反代配置。'); + } + } + if (response.status === 401) { + location.assign('/auth/login'); + throw new Error('登录已过期。'); + } + if (!response.ok || payload?.ret === 0) { + const detail = Array.isArray(payload?.detail) + ? payload.detail.map(item => item.msg || '输入错误').join(';') + : payload?.detail; + const error = new Error(String(detail || payload?.message || payload?.msg + || payload?.error || `请求失败 (${response.status})`)); + error.status = response.status; + throw error; + } + return payload; + } catch (error) { + if (error?.name === 'AbortError') { + const aborted = new Error(timedOut ? '请求超时,请稍后重试。' : '请求已取消。'); + aborted.code = timedOut ? 'REQUEST_TIMEOUT' : 'REQUEST_ABORTED'; + throw aborted; + } + if (error instanceof TypeError) throw new Error('网络请求失败,请检查连接后重试。'); + throw error; + } finally { + clearTimeout(timeout); + externalSignal?.removeEventListener('abort', abortFromExternal); + } +} + +function applySession(payload) { + const nested = payload?.user && typeof payload.user === 'object' ? payload.user : {}; + const csrfToken = String(payload?.csrf_token ?? nested.csrf_token ?? ''); + const userId = String(payload?.user_id ?? nested.user_id ?? nested.id ?? ''); + if (!/^[a-f0-9]{64}$/.test(csrfToken) || !/^[1-9]\d*$/.test(userId)) { + throw new Error('账单会话信息不完整,请重新登录。'); + } + state.csrfToken = csrfToken; + state.userId = userId; + state.username = firstText(payload?.username, nested.username, nested.name, state.username, '用户'); + state.admin = payload?.admin === true || Number(payload?.admin) === 1 + || nested.admin === true || Number(nested.admin) === 1; + state.invoiceBalance = String(payload?.balance ?? state.invoiceBalance); + state.balancePaymentAllowed = payload?.balance_payment_allowed === true; + 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; + } +} + +function serviceTimestamp(value) { + if (value === null || value === undefined || value === '') return null; + if (typeof value === 'number' || /^\d+$/.test(String(value).trim())) { + const numeric = Number(value); + if (!Number.isFinite(numeric) || numeric <= 0) return null; + return numeric < 1e12 ? numeric * 1_000 : numeric; + } + const parsed = Date.parse(String(value)); + return Number.isFinite(parsed) ? parsed : null; +} + +function formatOrderDate(value) { + const timestamp = serviceTimestamp(value); + const date = new Date(timestamp ?? Number.NaN); + return Number.isFinite(date.getTime()) + ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; +} + +function formatServiceDate(value) { + const timestamp = serviceTimestamp(value); + return timestamp === null ? '暂未提供' + : new Date(timestamp).toLocaleString('zh-CN', { hour12: false }); +} + +function formatUsd(value) { + const amount = Number(value); + if (!Number.isFinite(amount) || amount < 0) return '$—'; + return `$${amount.toLocaleString('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + })}`; +} + +function formatMemoryGiB(memoryMib) { + const amount = Number(memoryMib); + if (!Number.isFinite(amount) || amount < 0) return '— GB'; + return `${(amount / 1024).toLocaleString('en-US', { maximumFractionDigits: 1 })} GB`; +} + +function formatBytes(value) { + if (value === null || !Number.isFinite(value) || value < 0) return '暂未提供'; + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + let amount = value; + let unit = 0; + while (amount >= 1024 && unit < units.length - 1) { + amount /= 1024; + unit += 1; + } + const precision = unit === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2; + return `${amount.toFixed(precision)} ${units[unit]}`; +} + +function formatTrafficQuota(value) { + return value === 0 ? '不限流量' : formatBytes(value); +} + +function invoicePurpose(invoice) { + const value = firstText(invoice?.purpose, invoice?.kind, + invoice?.invoice_type, invoice?.type).toLowerCase(); + if (['recharge', 'topup', 'top_up', 'balance', 'deposit'].includes(value)) return 'recharge'; + if (['provision', 'provisioning', 'initial', 'create'].includes(value)) return 'provision'; + if (['renewal', 'renew', 'subscription'].includes(value)) return 'renewal'; + return ''; +} + +function invoiceTitle(invoice) { + const purpose = invoicePurpose(invoice); + return firstText(invoice?.type_label, invoice?.title, { + recharge: '余额充值', + provision: '实例开通', + renewal: '实例续费', + }[purpose], '账单'); +} + +function invoiceStatusInfo(status) { + const values = { + open: ['待支付', 'warning'], + overdue: ['已逾期', 'failed'], + paid: ['已支付', 'running'], + refunded: ['已退款', 'other'], + void: ['已失效', 'other'], + expired: ['已失效', 'failed'], + deleting: ['实例删除中', 'failed'], + delete_failed: ['自动删除失败', 'failed'], + purge_pending: ['等待永久删除', 'failed'], + purge_stopping: ['删除前正在关机', 'failed'], + purge_deleting: ['实例删除中', 'failed'], + purge_stop_failed: ['删除前关机失败', 'failed'], + purge_failed: ['自动删除失败', 'failed'], + }; + return values[String(status || '').toLowerCase()] + || [String(status || '未知'), 'other']; +} + +function paymentLabel(value) { + const method = String(value || '').trim(); + const labels = { + balance: '账户余额', + yipay_alipay: '易支付 · 支付宝', + yipay_wxpay: '易支付 · 微信', + paytaro: 'Paytaro · 支付宝', + usdt: 'USDT-TRC20', + }; + return labels[method.toLowerCase()] || method; +} + +function invoiceDeletionTimestamp(invoice) { + return serviceTimestamp(invoice?.deletion_at ?? invoice?.delete_at + ?? invoice?.grace_ends_at ?? null); +} + +function invoicePaymentDeadlineTimestamp(invoice) { + return serviceTimestamp(invoice?.payment_deadline_at ?? invoice?.payable_until + ?? invoice?.payment_due_at ?? null); +} + +function invoiceCanPay(invoice) { + if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false; + if (invoice?.payable === false) return false; + if (invoice?.payable === true) return true; + const deadline = invoicePurpose(invoice) === 'renewal' + ? invoiceDeletionTimestamp(invoice) : invoicePaymentDeadlineTimestamp(invoice); + return deadline === null || Date.now() < deadline; +} + +function provisionInvoiceData(invoice) { + const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' + ? invoice.fulfillment : {}; + return { + status: firstText(fulfillment.status, fulfillment.fulfillment_status, + invoice?.fulfillment_status, fulfillment.job_status, invoice?.job_status, + fulfillment.order_status, invoice?.order_status).toLowerCase(), + jobId: firstText(fulfillment.job_id, invoice?.job_id), + jobStatus: firstText(fulfillment.job_status, invoice?.job_status).toLowerCase(), + instanceId: firstText(fulfillment.instance_id, invoice?.instance_id), + instanceUuid: firstText(fulfillment.instance_uuid, fulfillment.vm_uuid, + invoice?.instance_uuid, invoice?.vm_uuid), + phase: firstText(fulfillment.phase, invoice?.phase), + error: firstText(fulfillment.error, invoice?.error), + }; +} + +function provisionStatusInfo(invoice) { + const data = provisionInvoiceData(invoice); + const status = data.status || data.jobStatus; + const values = { + awaiting_payment: ['等待支付', 'warning'], + payment_pending: ['等待支付', 'warning'], + draft: ['等待支付', 'warning'], + queued: ['等待创建', 'warning'], + pending: ['等待创建', 'warning'], + provisioning: ['创建中', 'warning'], + running: ['创建中', 'warning'], + completed: ['已开通', 'running'], + succeeded: ['已开通', 'running'], + active: ['已开通', 'running'], + failed: ['创建失败', 'failed'], + refunded: ['开通失败,已退款', 'failed'], + needs_attention: ['需要管理员核查', 'failed'], + uncertain: ['正在核对结果', 'warning'], + }; + return { data, status, display: values[status] || [status || '等待支付', 'warning'] }; +} + +function provisionFinished(invoice) { + const { status } = provisionStatusInfo(invoice); + return ['completed', 'succeeded', 'active', 'failed', 'refunded', + 'needs_attention'].includes(status); +} + +function invoiceFact(label, value) { + const item = makeElement('div', 'invoice-detail-fact'); + item.append( + makeElement('dt', '', label), + makeElement('dd', '', value === null || value === undefined || value === '' ? '—' : value), + ); + return item; +} + +function invoiceSpecification(invoice) { + const candidates = [invoice?.specification, invoice?.spec, invoice?.plan_snapshot, + invoice?.order_snapshot, invoice?.fulfillment?.specification, + invoice?.fulfillment?.spec]; + const spec = candidates.find(value => value && typeof value === 'object') || {}; + return { + cpu: firstNumber(invoice?.cpu_cores, invoice?.vcpu, spec.cpu_cores, spec.vcpu), + memoryMib: firstNumber(invoice?.memory_mib, spec.memory_mib), + memoryGib: firstNumber(invoice?.memory_gib, spec.memory_gib), + diskGib: firstNumber(invoice?.disk_gib, invoice?.disk_size_gib, + spec.disk_gib, spec.disk_size_gib), + bandwidthMbps: firstNumber(invoice?.bandwidth_mbps, spec.bandwidth_mbps), + }; +} + +function renderInvoiceSpecification(invoice) { + const panel = byId('invoice-specification-panel'); + const container = byId('invoice-specification'); + if (!panel || !container) return; + const purpose = invoicePurpose(invoice); + if (!['provision', 'renewal'].includes(purpose)) { + panel.hidden = true; + container.replaceChildren(); + return; + } + const spec = invoiceSpecification(invoice); + const subject = firstText(invoice.requested_name, invoice.instance_name, + purpose === 'provision' ? '待创建实例' : '实例'); + const facts = [ + invoiceFact('实例', subject), + invoiceFact('套餐', firstText(invoice.plan_name, '云服务器套餐')), + ]; + if (spec.cpu !== null) facts.push(invoiceFact('CPU', `${spec.cpu} 核`)); + if (spec.memoryMib !== null) facts.push(invoiceFact('内存', formatMemoryGiB(spec.memoryMib))); + else if (spec.memoryGib !== null) facts.push(invoiceFact('内存', `${spec.memoryGib} GB`)); + if (spec.diskGib !== null) facts.push(invoiceFact('系统盘', `${spec.diskGib} GB`)); + if (spec.bandwidthMbps !== null) facts.push(invoiceFact('带宽', `${spec.bandwidthMbps} Mbps`)); + facts.push( + invoiceFact('服务周期', `${Number(invoice.validity_days || 0)} 天`), + invoiceFact('周期流量', formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0))), + ); + container.replaceChildren(...facts); + panel.hidden = false; +} + +function invoicePaymentStorageKey(invoiceId, methodId) { + return `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:${methodId}`; +} + +function randomRequestId() { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + const bytes = new Uint8Array(24); + crypto.getRandomValues(bytes); + return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); +} + +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 = randomRequestId(); + 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 {} +} + +function hasPendingInvoicePaymentKey(invoiceId) { + const prefix = `${INVOICE_PAYMENT_STORAGE_PREFIX}${state.userId || 'unknown'}:${invoiceId}:`; + try { + for (let index = 0; index < sessionStorage.length; index += 1) { + const storageKey = sessionStorage.key(index); + if (!storageKey?.startsWith(prefix)) continue; + if (/^[A-Za-z0-9_.-]{16,128}$/.test(String(sessionStorage.getItem(storageKey) || ''))) { + return true; + } + } + } catch {} + return false; +} + +async function copyText(value) { + if (navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(value); + return; + } catch {} + } + const area = document.createElement('textarea'); + area.value = value; + area.style.position = 'fixed'; + area.style.opacity = '0'; + document.body.append(area); + area.select(); + try { + if (!document.execCommand('copy')) throw new Error('浏览器无法复制,请手动选择文本。'); + } finally { + area.value = ''; + area.remove(); + } +} + +function actionButton(label, handler) { + const button = makeElement('button', 'row-button', label); + button.type = 'button'; + button.addEventListener('click', async () => { + if (button.getAttribute('aria-busy') === 'true') return; + button.disabled = true; + button.setAttribute('aria-busy', 'true'); + try { + await handler(); + } finally { + button.disabled = false; + button.removeAttribute('aria-busy'); + } + }); + return button; +} + +function validPaymentUrl(value) { + try { + const url = new URL(String(value || '')); + return ['https:', 'weixin:', 'alipays:', 'alipayqr:'].includes(url.protocol) + ? url.href : ''; + } catch { + return ''; + } +} + +let qrCodePromise = null; +function loadQrCode() { + if (typeof window.QRCode === 'function') return Promise.resolve(window.QRCode); + if (qrCodePromise) return qrCodePromise; + qrCodePromise = new Promise((resolve, reject) => { + const script = document.createElement('script'); + const url = new URL('/theme/venix/js/qrcode.min.js', location.origin); + const version = document.body.dataset.assetVersion; + if (version) url.searchParams.set('v', version); + const timer = setTimeout(() => { + script.remove(); + reject(new Error('二维码组件加载超时')); + }, 10_000); + script.src = url.href; + script.async = true; + script.dataset.invoiceQr = 'true'; + script.onload = () => { + clearTimeout(timer); + if (typeof window.QRCode === 'function') resolve(window.QRCode); + else reject(new Error('二维码组件不可用')); + }; + script.onerror = () => { + clearTimeout(timer); + script.remove(); + reject(new Error('二维码组件加载失败')); + }; + document.head.append(script); + }).catch(error => { + qrCodePromise = null; + throw error; + }); + return qrCodePromise; +} + +async function appendPaymentQr(container, value, generation) { + if (!value) return false; + const qr = makeElement('div', 'cloud-payment-qr cloud-payment-qr-loading'); + qr.setAttribute('role', 'status'); + qr.setAttribute('aria-label', '正在生成支付二维码'); + qr.append(makeElement('span', '', '二维码生成中…')); + container.append(qr); + try { + const QRCode = await loadQrCode(); + if (!container.isConnected || !qr.isConnected || !state.onlinePaymentPending + || generation !== state.paymentRenderGeneration) { + qr.remove(); + return false; + } + qr.classList.remove('cloud-payment-qr-loading'); + qr.removeAttribute('role'); + qr.removeAttribute('aria-label'); + qr.replaceChildren(); + const levels = QRCode.CorrectLevel || { L: 1, M: 0 }; + new QRCode(qr, { + text: String(value), + width: 196, + height: 196, + correctLevel: String(value).length > 1200 ? levels.L : levels.M, + }); + if (!qr.children.length) throw new Error('二维码组件未生成内容'); + return true; + } catch { + if (container.isConnected && qr.isConnected && state.onlinePaymentPending + && generation === state.paymentRenderGeneration) { + qr.className = 'cloud-payment-qr cloud-payment-qr-error'; + qr.setAttribute('role', 'status'); + qr.setAttribute('aria-label', '支付二维码暂时无法显示'); + qr.replaceChildren(makeElement('span', 'cloud-payment-qr-note', + '二维码暂时无法显示,请使用支付按钮或复制支付信息。')); + } else { + qr.remove(); + } + return false; + } +} + +function selectInvoicePaymentMethod(methodId) { + state.selectedInvoicePaymentMethod = String(methodId || ''); + byId('invoice-payment-methods')?.querySelectorAll('.invoice-payment-method-card') + .forEach(card => { + const selected = card.dataset.methodId === state.selectedInvoicePaymentMethod; + card.setAttribute('aria-pressed', String(selected)); + card.setAttribute('aria-checked', String(selected)); + }); + const submit = byId('invoice-payment-submit'); + if (submit) submit.disabled = !state.selectedInvoicePaymentMethod; +} + +function mergeInvoiceStatus(invoice, update) { + const current = invoice && typeof invoice === 'object' ? invoice : {}; + const next = update && typeof update === 'object' ? update : {}; + const merged = { ...current, ...next }; + if (current.fulfillment && typeof current.fulfillment === 'object' + && next.fulfillment && typeof next.fulfillment === 'object') { + merged.fulfillment = { ...current.fulfillment, ...next.fulfillment }; + } + return merged; +} + +function onlinePaymentFallbackExpiresAt(invoice = state.selectedInvoice) { + const now = Date.now(); + const maximum = now + STATUS_POLL_MAX_LIFETIME_MS; + const invoiceDeadline = invoicePurpose(invoice) === 'renewal' + ? invoiceDeletionTimestamp(invoice) : invoicePaymentDeadlineTimestamp(invoice); + return invoiceDeadline !== null && invoiceDeadline > now + ? Math.min(invoiceDeadline, maximum) : maximum; +} + +function clearOnlinePaymentExpiryTimer() { + if (state.onlinePaymentExpiryTimer !== null) { + clearTimeout(state.onlinePaymentExpiryTimer); + } + state.onlinePaymentExpiryTimer = null; +} + +function onlinePaymentHasExpired() { + return state.onlinePaymentPending && state.onlinePaymentExpiresAt > 0 + && Date.now() >= state.onlinePaymentExpiresAt; +} + +function clearOnlinePaymentState(clearStoredKey = false) { + clearOnlinePaymentExpiryTimer(); + const invoiceId = state.onlinePaymentInvoiceId || state.selectedInvoice?.id; + const methodId = state.onlinePaymentMethodId; + if (clearStoredKey && invoiceId) { + if (methodId) clearInvoicePaymentKey(invoiceId, methodId); + else clearInvoicePaymentKeys(invoiceId); + } + state.onlinePaymentPending = false; + state.onlinePaymentExpiresAt = 0; + state.onlinePaymentInvoiceId = ''; + state.onlinePaymentMethodId = ''; + state.paymentRenderGeneration += 1; +} + +function expireOnlinePaymentInstructions(generation = state.paymentRenderGeneration) { + if (!state.onlinePaymentPending || generation !== state.paymentRenderGeneration) { + return false; + } + const invoiceId = String(state.onlinePaymentInvoiceId + || state.selectedInvoice?.id || ''); + clearOnlinePaymentState(true); + const result = byId('invoice-payment-result'); + if (result) { + const notice = makeElement('div', + 'cloud-payment-instructions cloud-payment-expired'); + notice.append( + makeElement('strong', '', '支付订单已过期'), + makeElement('small', '', '请重新选择支付方式并确认,以生成新的支付订单。'), + ); + result.replaceChildren(notice); + } + stopInvoicePoll(); + if (/^[1-9]\d*$/.test(invoiceId) && !state.refreshPromise) { + void refreshInvoiceDetail(invoiceId); + } else if (invoiceNeedsPolling()) { + scheduleInvoicePoll(state.selectedInvoice?.id); + } + return true; +} + +function scheduleOnlinePaymentExpiry(generation) { + clearOnlinePaymentExpiryTimer(); + if (!state.onlinePaymentPending || state.onlinePaymentExpiresAt <= 0) return; + const remaining = state.onlinePaymentExpiresAt - Date.now(); + if (remaining <= 0) { + expireOnlinePaymentInstructions(generation); + return; + } + state.onlinePaymentExpiryTimer = setTimeout(() => { + state.onlinePaymentExpiryTimer = null; + expireOnlinePaymentInstructions(generation); + }, remaining); +} + +function invoiceNeedsPolling(invoice = state.selectedInvoice) { + if (!invoice?.id) return false; + if (state.onlinePaymentPending && !onlinePaymentHasExpired() + && invoiceCanPay(invoice)) return true; + return invoicePurpose(invoice) === 'provision' + && String(invoice.status || '').toLowerCase() === 'paid' + && !provisionFinished(invoice); +} + +function entersProvisioningAfterPayment(previousInvoice, nextInvoice, + wasAwaitingOnlinePayment) { + return wasAwaitingOnlinePayment + && invoiceCanPay(previousInvoice) + && invoicePurpose(nextInvoice) === 'provision' + && String(nextInvoice?.status || '').toLowerCase() === 'paid' + && !provisionFinished(nextInvoice); +} + +function resetProvisioningPollWindow() { + state.pollStartedAt = Date.now(); + state.pollUntil = state.pollStartedAt + STATUS_POLL_WINDOW_MS; +} + +function stopInvoicePoll() { + state.pollGeneration += 1; + if (state.pollTimer !== null) clearTimeout(state.pollTimer); + state.pollTimer = null; + state.pollController?.abort(); + state.pollController = null; + state.pollInvoiceId = ''; + state.pollStartedAt = 0; + state.pollUntil = 0; +} + +function queueInvoicePoll(generation, delay = STATUS_POLL_INTERVAL_MS) { + if (generation !== state.pollGeneration) return; + state.pollTimer = setTimeout(() => { + state.pollTimer = null; + void pollInvoiceStatus(generation); + }, delay); +} + +function nextInvoicePollDelay() { + return Date.now() - state.pollStartedAt < STATUS_POLL_WINDOW_MS + ? STATUS_POLL_INTERVAL_MS : STATUS_POLL_SLOW_INTERVAL_MS; +} + +function pollCompletionMessage(invoice) { + const status = String(invoice?.status || '').toLowerCase(); + if (status === 'paid') { + if (invoicePurpose(invoice) !== 'provision') { + return [invoicePurpose(invoice) === 'renewal' + ? '账单支付成功,服务期限已延长。' : '账单支付成功。', 'success']; + } + if (provisionFinished(invoice)) { + const provisionStatus = provisionStatusInfo(invoice).status; + if (['succeeded', 'completed', 'active'].includes(provisionStatus)) { + return ['实例已创建完成。', 'success']; + } + if (provisionStatus === 'refunded') { + return ['实例创建失败,款项已退回账户余额。', 'error']; + } + return ['实例开通未完成,请在账单详情查看任务状态。', 'error']; + } + } + if (['void', 'expired'].includes(status)) { + return ['账单已失效,到账金额会保留在账户余额中。', 'error']; + } + if (status === 'refunded') { + return ['实例创建失败,款项已退回账户余额。', 'error']; + } + if (!invoiceCanPay(invoice) && status !== 'paid') { + return [invoicePurpose(invoice) === 'provision' + ? '开通账单已超过支付截止时间。' + : invoicePurpose(invoice) === 'renewal' + ? '续费宽限期已经结束,到账金额会保留在账户余额中。' + : '账单已超过支付截止时间。', 'error']; + } + return null; +} + +async function pollInvoiceStatus(generation) { + if (generation !== state.pollGeneration) return; + if (onlinePaymentHasExpired()) { + expireOnlinePaymentInstructions(); + return; + } + if (document.hidden || !state.pollInvoiceId || !invoiceNeedsPolling()) { + stopInvoicePoll(); + return; + } + const controller = new AbortController(); + const readSequence = ++state.readSequence; + const previousInvoice = state.selectedInvoice; + const wasAwaitingOnlinePayment = state.onlinePaymentPending; + state.pollController = controller; + try { + const result = await api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`, { + signal: controller.signal, + timeoutMs: 10_000, + }); + if (generation !== state.pollGeneration) return; + const update = result?.invoice; + if (readSequence >= state.appliedReadSequence + && update?.id && String(update.id) === String(state.selectedInvoice?.id || '')) { + state.appliedReadSequence = readSequence; + const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update); + if (entersProvisioningAfterPayment(previousInvoice, nextInvoice, + wasAwaitingOnlinePayment)) { + resetProvisioningPollWindow(); + } + renderInvoiceDetail(nextInvoice, { + balance: state.invoiceBalance, + payment_methods: state.invoicePaymentMethods, + }); + } + if (generation !== state.pollGeneration) return; + const completion = pollCompletionMessage(state.selectedInvoice); + if (completion) { + stopInvoicePoll(); + toast(completion[0], completion[1]); + return; + } + } catch (error) { + if (error?.code === 'REQUEST_ABORTED' || generation !== state.pollGeneration) return; + } finally { + if (generation === state.pollGeneration) state.pollController = null; + } + + if (generation !== state.pollGeneration) return; + if (onlinePaymentHasExpired()) { + expireOnlinePaymentInstructions(); + } else if (invoiceNeedsPolling() && Date.now() < state.pollUntil) { + queueInvoicePoll(generation, nextInvoicePollDelay()); + } else { + stopInvoicePoll(); + } +} + +function scheduleInvoicePoll(invoiceId) { + const key = String(invoiceId || ''); + if (!key || document.hidden || state.refreshPromise) return; + if (onlinePaymentHasExpired()) { + expireOnlinePaymentInstructions(); + return; + } + if (!invoiceNeedsPolling()) return; + if (state.pollInvoiceId === key && (state.pollTimer !== null || state.pollController)) { + state.pollUntil = Math.max(state.pollUntil, state.onlinePaymentExpiresAt); + return; + } + stopInvoicePoll(); + state.pollInvoiceId = key; + state.pollStartedAt = Date.now(); + state.pollUntil = Math.max(state.pollStartedAt + STATUS_POLL_WINDOW_MS, + state.onlinePaymentExpiresAt); + const generation = ++state.pollGeneration; + queueInvoicePoll(generation); +} + +function resumeInvoicePolling() { + if (onlinePaymentHasExpired()) { + expireOnlinePaymentInstructions(); + return; + } + if (invoiceNeedsPolling()) scheduleInvoicePoll(state.selectedInvoice.id); +} + +function renderOnlinePayment(container, payment) { + clearOnlinePaymentExpiryTimer(); + const generation = ++state.paymentRenderGeneration; + let box = container.querySelector('.cloud-payment-instructions'); + if (!box) { + box = makeElement('div', 'cloud-payment-instructions'); + container.append(box); + } + box.className = 'cloud-payment-instructions'; + box.replaceChildren(); + state.onlinePaymentPending = true; + state.onlinePaymentInvoiceId = String(payment.invoice_id || state.selectedInvoice?.id || ''); + state.onlinePaymentMethodId = firstText(payment.method, + state.selectedInvoicePaymentMethod); + const paymentExpiresAt = serviceTimestamp(payment.expires_at); + state.onlinePaymentExpiresAt = paymentExpiresAt === null + ? onlinePaymentFallbackExpiresAt(state.selectedInvoice) + : Math.min(paymentExpiresAt, Date.now() + STATUS_POLL_MAX_LIFETIME_MS); + + let qrValue = ''; + if (payment.payment_kind === 'usdt') { + qrValue = payment.receive_address || ''; + box.append( + makeElement('strong', '', `请支付 ${payment.actual_amount} USDT(TRC20)`), + makeElement('code', '', qrValue || '收款地址不可用'), + makeElement('small', '', `支付订单有效至 ${formatOrderDate(payment.expires_at)};链上确认后自动结清账单。`), + ); + box.append(actionButton('复制收款地址', async () => { + try { + await copyText(qrValue); + toast('USDT 收款地址已复制。', 'success'); + } catch (error) { + toast(error.message, 'error'); + } + })); + } else { + qrValue = payment.payment_value || ''; + const url = validPaymentUrl(qrValue); + box.append(makeElement('strong', '', `${payment.label || '在线支付'}订单已生成`)); + 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', '', qrValue || '支付信息暂不可用')); + box.append(actionButton('复制支付信息', async () => { + try { + await copyText(qrValue); + toast('支付信息已复制。', 'success'); + } catch (error) { + toast(error.message, 'error'); + } + })); + } + box.append(makeElement('small', '', + '完成付款后本页会自动核对账单状态。请勿同时使用多个渠道重复付款。')); + } + void appendPaymentQr(box, qrValue, generation); + scheduleOnlinePaymentExpiry(generation); + if (generation === state.paymentRenderGeneration && state.onlinePaymentPending) { + scheduleInvoicePoll(state.onlinePaymentInvoiceId); + } +} + +async function payInvoiceBalance(invoice, container) { + if (!invoiceCanPay(invoice)) { + toast(invoicePurpose(invoice) === 'provision' + ? '开通账单已失效,不能支付。' + : invoicePurpose(invoice) === 'renewal' + ? '续费宽限期已经结束,账单不可支付。' + : '账单已失效,不能支付。', 'error'); + return; + } + if (state.mutationBusy + || !confirm(`确认使用账户余额支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) return; + state.mutationBusy = true; + container.querySelectorAll('button').forEach(button => { button.disabled = true; }); + try { + const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, { + method: 'POST', + body: { idempotency_key: randomRequestId() }, + timeoutMs: 20_000, + }); + state.invoiceBalance = String(result?.balance ?? state.invoiceBalance); + const paid = mergeInvoiceStatus(invoice, result?.invoice || {}); + const startsProvisioning = invoicePurpose(paid) === 'provision'; + // A successful mutation is newer than every GET that was already in + // flight. Prevent a late pre-payment response from restoring old payment + // controls over this authoritative paid state. + state.appliedReadSequence = ++state.readSequence; + if (startsProvisioning) resetProvisioningPollWindow(); + renderInvoiceDetail(paid, { + balance: state.invoiceBalance, + payment_methods: state.invoicePaymentMethods, + }); + if (startsProvisioning) { + toast('账单已支付,实例已进入创建队列。', 'success'); + resumeInvoicePolling(); + } else if (invoicePurpose(paid) === 'renewal') { + toast('账单已支付,服务期限已延长。', 'success'); + } else { + toast('账单已支付。', 'success'); + } + } catch (error) { + toast(error.message, 'error'); + if ([403, 409].includes(Number(error.status || 0))) { + await refreshInvoiceDetail(invoice.id); + } + } finally { + state.mutationBusy = false; + container.querySelectorAll('button').forEach(button => { button.disabled = false; }); + } +} + +async function createInvoicePayment(invoice, method, container, paymentResult) { + if (!invoiceCanPay(invoice)) { + toast(invoicePurpose(invoice) === 'provision' + ? '开通账单已失效,不能再生成支付订单。' + : invoicePurpose(invoice) === 'renewal' + ? '续费宽限期已经结束,不能再生成支付订单。' + : '账单已失效,不能再生成支付订单。', 'error'); + return; + } + if (state.mutationBusy + || !confirm(`确认通过“${method.name}”支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) return; + state.mutationBusy = true; + container.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 }, + timeoutMs: 20_000, + }); + renderOnlinePayment(paymentResult, result.payment || {}); + } catch (error) { + const status = Number(error.status || 0); + const ambiguousHttpFailure = [408, 425, 429].includes(status); + const creationStillInProgress = String(error.message).includes('正在创建'); + if (status >= 400 && status < 500 && !ambiguousHttpFailure + && !creationStillInProgress) { + clearInvoicePaymentKey(invoice.id, method.id); + } + toast(error.message, 'error'); + if ([403, 409].includes(status) && !creationStillInProgress) { + await refreshInvoiceDetail(invoice.id); + } + } finally { + state.mutationBusy = false; + container.querySelectorAll('button').forEach(button => { button.disabled = false; }); + } +} + +function renderInvoicePaymentMethods(invoice, balance, methods) { + const panel = byId('invoice-payment-panel'); + const container = byId('invoice-payment-methods'); + const result = byId('invoice-payment-result'); + if (!panel || !container || !result) return; + if (!invoiceCanPay(invoice)) { + clearInvoicePaymentKeys(invoice.id); + clearOnlinePaymentState(); + panel.hidden = true; + container.replaceChildren(); + result.replaceChildren(); + state.selectedInvoicePaymentMethod = ''; + return; + } + + const choices = []; + if (state.balancePaymentAllowed) { + choices.push({ + id: 'balance', + name: '账户余额', + description: `可用余额 ${formatUsd(balance)}`, + kind: 'balance', + }); + } + for (const method of methods) { + if (method?.id === null || method?.id === undefined || !firstText(method.name)) continue; + choices.push({ ...method, id: String(method.id), kind: 'online' }); + } + if (!choices.length) { + clearInvoicePaymentKeys(invoice.id); + clearOnlinePaymentState(); + panel.hidden = true; + container.replaceChildren(); + result.replaceChildren(); + state.selectedInvoicePaymentMethod = ''; + return; + } + const available = new Set(choices.map(choice => String(choice.id))); + if (!available.has(state.selectedInvoicePaymentMethod)) { + state.selectedInvoicePaymentMethod = String(choices[0].id); + } + const cards = choices.map(choice => { + const card = makeElement('button', 'invoice-payment-method-card'); + card.type = 'button'; + card.dataset.methodId = String(choice.id); + card.setAttribute('role', 'radio'); + const selected = String(choice.id) === state.selectedInvoicePaymentMethod; + card.setAttribute('aria-pressed', String(selected)); + card.setAttribute('aria-checked', String(selected)); + card.append( + makeElement('strong', '', choice.name), + makeElement('small', '', firstText(choice.description, choice.label, + choice.kind === 'balance' ? `可用余额 ${formatUsd(balance)}` : '在线支付')), + makeElement('span', 'invoice-payment-method-check', '✓'), + ); + card.addEventListener('click', () => selectInvoicePaymentMethod(choice.id)); + return card; + }); + container.replaceChildren(...cards); + panel.hidden = false; + const submit = byId('invoice-payment-submit'); + if (!submit) return; + submit.disabled = !state.selectedInvoicePaymentMethod; + submit.onclick = async () => { + showError('invoice-payment-error', ''); + const choice = choices.find(item => String(item.id) === state.selectedInvoicePaymentMethod); + if (!choice) { + showError('invoice-payment-error', '请选择支付方式。'); + return; + } + if (choice.kind === 'balance') await payInvoiceBalance(invoice, panel); + else await createInvoicePayment(invoice, choice, panel, result); + }; +} + +function invoiceProgressText(job) { + const status = firstText(job?.status).toLowerCase(); + const labels = { + queued: '等待创建', + pending: '等待创建', + running: '正在创建', + provisioning: '正在创建', + uncertain: '正在核对创建结果', + succeeded: '实例创建完成', + completed: '实例创建完成', + failed: '实例创建失败', + refunded: '创建失败,已退款', + needs_attention: '需要管理员核查', + }; + const resultMessage = typeof job?.result === 'object' + ? firstText(job.result.message, job.result.status) : ''; + return firstText(job?.error, job?.phase, resultMessage, labels[status], + status ? `任务状态:${status}` : '', '等待创建'); +} + +async function findInstanceByUuid(uuid) { + const payload = await api('/api/v1/vms', { timeoutMs: 20_000 }); + const values = Array.isArray(payload) ? payload + : Array.isArray(payload?.items) ? payload.items + : Array.isArray(payload?.vms) ? payload.vms : []; + return values.find(vm => String(vm?.uuid || vm?.id || '') === String(uuid)); +} + +function appendProvisionInvoiceActions(invoice, detail, actions) { + const { data, status, display } = provisionStatusInfo(invoice); + if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); + if (data.jobId) { + actions.append(actionButton('查看创建进度', async () => { + if (state.refreshPromise) { + toast('账单正在刷新,请稍候。'); + return; + } + let progress = detail.querySelector('.cloud-order-progress'); + if (!progress) { + progress = makeElement('p', 'cloud-order-progress muted'); + detail.append(progress); + } + const readSequence = ++state.readSequence; + try { + const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/status`, { + timeoutMs: 12_000, + }); + const update = result?.invoice; + if (!update?.id || String(update.id) !== String(invoice.id)) { + throw new Error('创建进度与当前账单不匹配,请刷新后重试。'); + } + if (readSequence < state.appliedReadSequence) return; + state.appliedReadSequence = readSequence; + const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update); + const jobStatus = firstText(update.job_status, + update.fulfillment_status).toLowerCase(); + const failed = ['failed', 'refunded', 'needs_attention'].includes(jobStatus) + || Boolean(update.error); + state.invoiceJobProgress.set(String(invoice.id), { + message: invoiceProgressText({ status: jobStatus, + error: update.error, phase: update.phase }), + failed, + }); + renderInvoiceDetail(nextInvoice, { + balance: state.invoiceBalance, + payment_methods: state.invoicePaymentMethods, + }); + } catch (error) { + if (readSequence < state.appliedReadSequence) return; + progress.className = 'cloud-order-progress form-error'; + progress.textContent = error.message; + } + })); + } + if (data.instanceId) { + const link = makeElement('a', 'row-button', '查看实例'); + link.href = `/user/cloud/instances/${encodeURIComponent(data.instanceId)}`; + actions.append(link); + } else if (data.instanceUuid) { + actions.append(actionButton('查看实例', async () => { + try { + const vm = await findInstanceByUuid(data.instanceUuid); + const id = firstText(vm?.api_id, vm?.id); + if (id) location.assign(`/user/cloud/instances/${encodeURIComponent(id)}`); + else toast('实例尚未出现在列表,请稍后刷新。'); + } catch (error) { + toast(error.message, 'error'); + } + })); + } +} + +function renderInvoiceFulfillment(invoice) { + const panel = byId('invoice-fulfillment-panel'); + const content = byId('invoice-fulfillment-content'); + if (!panel || !content) return; + const invoiceStatus = firstText(invoice.status).toLowerCase(); + const visible = invoicePurpose(invoice) === 'provision' + && (['paid', 'refunded'].includes(invoiceStatus) + || Boolean(provisionInvoiceData(invoice).jobId)); + if (!visible) { + panel.hidden = true; + content.replaceChildren(); + return; + } + + const detail = makeElement('div', 'invoice-fulfillment-detail'); + const actions = makeElement('div', 'cloud-order-actions invoice-fulfillment-actions'); + const { data, status, display } = provisionStatusInfo(invoice); + const cached = state.invoiceJobProgress.get(String(invoice.id)); + const terminal = provisionFinished(invoice); + const failed = Boolean(data.error) || ['failed', 'refunded', 'needs_attention'].includes(status) + || (!terminal && cached?.failed === true); + const progress = makeElement('p', `cloud-order-progress ${failed ? 'form-error' : 'muted'}`, + firstText(data.error, data.phase, terminal ? display[0] : cached?.message, + status === 'uncertain' ? '后台正在核对实例创建结果,请勿重复提交。' : display[0])); + detail.append(progress); + appendProvisionInvoiceActions(invoice, detail, actions); + content.replaceChildren(detail, actions); + panel.hidden = false; + if (invoiceStatus === 'paid' && !terminal) scheduleInvoicePoll(invoice.id); + else if (terminal) { + state.invoiceJobProgress.delete(String(invoice.id)); + if (state.pollInvoiceId === String(invoice.id) && !state.pollController) stopInvoicePoll(); + } +} + +function renderInvoiceDetail(invoice, payload) { + state.selectedInvoice = invoice; + text('invoice-detail-kind', invoiceTitle(invoice)); + text('invoice-detail-number', `账单 #${invoice.id}`); + text('invoice-detail-created', `创建于 ${formatOrderDate(invoice.created_at)}`); + text('invoice-detail-subtitle', `账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`); + text('invoice-detail-amount', formatUsd(invoice.amount)); + const [statusLabel, statusClass] = invoiceStatusInfo(invoice.status); + const status = byId('invoice-detail-status'); + if (status) { + status.className = `state-pill ${statusClass}`; + status.textContent = statusLabel; + } + + const purpose = invoicePurpose(invoice); + const facts = [ + invoiceFact('账单编号', `#${invoice.id}`), + invoiceFact('创建时间', formatOrderDate(invoice.created_at)), + ]; + if (purpose === 'provision') { + facts.push(invoiceFact('支付截止', formatServiceDate( + invoicePaymentDeadlineTimestamp(invoice) ?? invoice.due_at, + ))); + } else if (purpose === 'renewal') { + facts.push(invoiceFact('实例到期', formatOrderDate(invoice.due_at))); + if (invoiceDeletionTimestamp(invoice) !== null) { + facts.push(invoiceFact('最晚支付', formatServiceDate(invoiceDeletionTimestamp(invoice)))); + } + } else if (invoicePaymentDeadlineTimestamp(invoice) !== null) { + facts.push(invoiceFact('支付截止', + formatServiceDate(invoicePaymentDeadlineTimestamp(invoice)))); + } + if (invoice.paid_at) facts.push(invoiceFact('支付时间', formatOrderDate(invoice.paid_at))); + if (invoice.paid_via) facts.push(invoiceFact('支付方式', paymentLabel(invoice.paid_via))); + byId('invoice-detail-facts')?.replaceChildren(...facts); + + renderInvoiceSpecification(invoice); + renderInvoicePaymentMethods(invoice, payload.balance, + Array.isArray(payload.payment_methods) ? payload.payment_methods : []); + renderInvoiceFulfillment(invoice); +} + +function hydrateInvoiceDetail(payload, expectedInvoiceId = document.body.dataset.invoiceId) { + if (!payload?.invoice || typeof payload.invoice !== 'object') { + throw new Error('账单信息不完整,请刷新页面后重试。'); + } + const expected = String(expectedInvoiceId || ''); + if (!/^[1-9]\d*$/.test(expected) + || String(payload.invoice.id || '') !== expected) { + throw new Error('账单初始数据与当前地址不匹配,请返回账单列表重试。'); + } + const previousInvoice = state.selectedInvoice; + const wasAwaitingOnlinePayment = state.onlinePaymentPending; + applySession(payload); + if (state.selectedInvoice + && String(state.selectedInvoice.id) !== String(payload.invoice.id)) { + state.selectedInvoicePaymentMethod = ''; + clearOnlinePaymentState(); + byId('invoice-payment-result')?.replaceChildren(); + } + state.invoicePaymentMethods = Array.isArray(payload.payment_methods) + ? payload.payment_methods : []; + if (onlinePaymentHasExpired()) expireOnlinePaymentInstructions(); + const restoredProviderPayment = hasPendingInvoicePaymentKey(payload.invoice.id); + state.onlinePaymentPending = invoiceCanPay(payload.invoice) + && (state.onlinePaymentPending || restoredProviderPayment); + if (state.onlinePaymentPending) { + state.onlinePaymentInvoiceId = String(payload.invoice.id); + if (state.onlinePaymentExpiresAt <= 0) { + state.onlinePaymentExpiresAt = onlinePaymentFallbackExpiresAt(payload.invoice); + } + } + if (entersProvisioningAfterPayment(previousInvoice, payload.invoice, + wasAwaitingOnlinePayment)) { + resetProvisioningPollWindow(); + } + renderInvoiceDetail(payload.invoice, payload); + if (state.onlinePaymentPending) { + scheduleOnlinePaymentExpiry(state.paymentRenderGeneration); + } + resumeInvoicePolling(); + showError('cloud-page-error', ''); + return payload.invoice; +} + +async function refreshInvoiceDetail(invoiceId = document.body.dataset.invoiceId) { + const id = String(invoiceId || ''); + if (!/^[1-9]\d*$/.test(id)) { + showError('cloud-page-error', '账单编号无效。'); + return null; + } + if (state.refreshPromise) return state.refreshPromise; + // A status response is intentionally sparse. Do not let it overtake this + // full read and cause balance, payment methods or a rotated CSRF token to be + // discarded as though the whole response were stale. + stopInvoicePoll(); + const button = byId('invoice-detail-refresh'); + const workspace = byId('invoice-detail-workspace'); + const controller = new AbortController(); + state.refreshController = controller; + const readSequence = ++state.readSequence; + if (button) { + button.disabled = true; + button.setAttribute('aria-busy', 'true'); + } + workspace?.setAttribute('aria-busy', 'true'); + + const request = (async () => { + try { + const payload = await api(`/api/v1/invoices/${encodeURIComponent(id)}`, { + signal: controller.signal, + timeoutMs: 12_000, + }); + if (readSequence < state.appliedReadSequence) return state.selectedInvoice; + state.appliedReadSequence = readSequence; + return hydrateInvoiceDetail(payload, id); + } catch (error) { + if (error?.code !== 'REQUEST_ABORTED') { + showError('cloud-page-error', error.message || '账单刷新失败,请稍后重试。'); + } + return null; + } finally { + if (state.refreshController === controller) state.refreshController = null; + state.refreshPromise = null; + if (button) { + button.disabled = false; + button.removeAttribute('aria-busy'); + } + workspace?.removeAttribute('aria-busy'); + if (!controller.signal.aborted) resumeInvoicePolling(); + } + })(); + state.refreshPromise = request; + return request; +} + +let cleanupBound = false; +function bindInvoiceDetailCleanup() { + if (cleanupBound) return; + cleanupBound = true; + window.addEventListener('pagehide', () => { + state.refreshController?.abort(); + stopInvoicePoll(); + clearTimeout(toastTimer); + toastTimer = null; + const element = byId('toast'); + if (element) element.hidden = true; + clearOnlinePaymentExpiryTimer(); + }); +} + +export { + bindInvoiceDetailCleanup, + byId, + hydrateInvoiceDetail, + readInvoiceDetailBootstrap, + refreshInvoiceDetail, + resumeInvoicePolling, + showError, + state, + stopInvoicePoll, +}; diff --git a/web/public/cloud/invoice-detail.js b/web/public/cloud/invoice-detail.js index 80987d52..66ab42dd 100644 --- a/web/public/cloud/invoice-detail.js +++ b/web/public/cloud/invoice-detail.js @@ -1,43 +1,42 @@ -const runtimeUrl = new URL('/cloud/runtime.js', location.origin); +const runtimeUrl = new URL('/cloud/invoice-detail-runtime.js', location.origin); const assetVersion = new URL(import.meta.url).searchParams.get('v'); if (assetVersion) runtimeUrl.searchParams.set('v', assetVersion); const { - bindPageCleanup, byId, loadInvoiceDetail, showError, state, - scheduleInvoicePoll, stopInvoicePoll, + bindInvoiceDetailCleanup, + byId, + hydrateInvoiceDetail, + readInvoiceDetailBootstrap, + refreshInvoiceDetail, + resumeInvoicePolling, + showError, + state, + stopInvoicePoll, } = await import(runtimeUrl.href); -export async function initialize() { +export function initialize() { try { state.view = 'invoice-detail'; - bindPageCleanup(); + bindInvoiceDetailCleanup(); byId('logout-button')?.addEventListener('click', () => location.assign('/user/logout')); + const invoiceId = String(document.body.dataset.invoiceId || ''); - if (!/^\d+$/.test(invoiceId)) throw new Error('账单编号无效。'); - const refresh = () => loadInvoiceDetail(invoiceId); - const safeRefresh = async () => { try { await refresh(); } catch {} }; - const resumeActivePoll = () => { - const paymentOpen = Boolean(document.querySelector('.cloud-payment-instructions')); - const invoice = state.selectedInvoice; - const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' - ? invoice.fulfillment : {}; - const purpose = String(invoice?.purpose || '').toLowerCase(); - const invoiceStatus = String(invoice?.status || '').toLowerCase(); - const progressStatus = String(fulfillment.job_status || invoice?.job_status - || invoice?.fulfillment_status || invoice?.order_status || '').toLowerCase(); - const provisioning = purpose === 'provision' && invoiceStatus === 'paid' - && !['succeeded', 'failed', 'refunded', 'needs_attention'].includes(progressStatus); - if ((paymentOpen || provisioning) && invoice?.id) scheduleInvoicePoll(invoice.id); - }; - byId('invoice-detail-refresh')?.addEventListener('click', () => { void safeRefresh(); }); - await refresh(); + if (!/^[1-9]\d*$/.test(invoiceId)) throw new Error('账单编号无效。'); + + const bootstrap = readInvoiceDetailBootstrap(); + hydrateInvoiceDetail(bootstrap, invoiceId); + + byId('invoice-detail-refresh')?.addEventListener('click', () => { + void refreshInvoiceDetail(invoiceId); + }); window.addEventListener('pageshow', event => { - if (!event.persisted) return; - void safeRefresh(); + if (event.persisted) void refreshInvoiceDetail(invoiceId); }); document.addEventListener('visibilitychange', () => { if (document.hidden) stopInvoicePoll(); - else resumeActivePoll(); + else resumeInvoicePolling(); }); - } catch (error) { showError('cloud-page-error', error.message); } + } catch (error) { + showError('cloud-page-error', error?.message || '账单详情初始化失败,请刷新后重试。'); + } } diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 8a44b304..247f76c5 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -1,11 +1,10 @@ // 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: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', invoices: [], invoicePage: 1, invoicePagination: { page: 1, per_page: 10, total: 0, total_pages: 1, has_previous: false, has_next: false, from: 0, to: 0 }, invoiceLoading: false, invoiceLoadPromise: null, invoicePaymentMethods: [], invoiceBalance: '0.00', selectedInvoice: null, selectedInvoicePaymentMethod: '', invoiceJobProgress: new Map(), 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: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], plans: [], regions: [], sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionHostId: '', 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: '' }, resourceController: null, mutationBusy: false, provisionIdempotency: '', provisionFingerprint: '', rescueActive: false, rescueStaged: false }; // Keep the historical storage key so an interrupted deployment made just // before an online update can still reconcile to the same opening invoice. const PROVISION_INVOICE_STORAGE_PREFIX = 'virt-cloud:pending-order:'; -const INVOICE_PAYMENT_STORAGE_PREFIX = 'virt-cloud:invoice-payment:'; const CLOUD_PATHS = Object.freeze({ instances: '/user/cloud/instances', deploy: '/user/cloud/deploy', @@ -13,7 +12,6 @@ const CLOUD_PATHS = Object.freeze({ invoices: '/user/cloud/invoices', }); const vmPagePath = (id, child = '') => `${CLOUD_PATHS.instances}/${encodeURIComponent(String(id))}${child ? `/${child}` : ''}`; -const invoicePagePath = (id) => `${CLOUD_PATHS.invoices}/${encodeURIComponent(String(id))}`; const navigate = (path) => location.assign(path); 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?.templates) ? payload.templates : Array.isArray(payload?.keys) ? payload.keys : Array.isArray(payload?.vms) ? payload.vms : []; @@ -627,31 +625,6 @@ function clearPendingProvisionInvoiceKey() { state.provisionFingerprint = ''; try { sessionStorage.removeItem(provisionInvoiceStorageKey()); } 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 existingProvisionInvoice(key) { try { return await api(`/api/v1/invoices/by-request/${encodeURIComponent(key)}`); } catch (error) { if (error.status === 404) return null; throw error; } @@ -702,573 +675,6 @@ async function buy(event) { updateCreateAvailability(); } } -function formatOrderDate(value) { const timestamp = serviceTimestamp(value); const date = new Date(timestamp ?? Number.NaN); return Number.isFinite(date.getTime()) ? date.toLocaleString('zh-CN', { hour12: false }) : '时间未记录'; } -function invoicePurpose(invoice) { - const value = firstText(invoice?.purpose, invoice?.kind, invoice?.invoice_type, invoice?.type).toLowerCase(); - if (['recharge', 'topup', 'top_up', 'balance', 'deposit'].includes(value)) return 'recharge'; - if (['provision', 'provisioning', 'initial', 'create'].includes(value)) return 'provision'; - if (['renewal', 'renew', 'subscription'].includes(value)) return 'renewal'; - return ''; -} -function invoiceTitle(invoice) { - const purpose = invoicePurpose(invoice); - return firstText(invoice?.type_label, invoice?.title, { - recharge: '余额充值', provision: '实例开通', renewal: '实例续费', - }[purpose], '账单'); -} -function provisionInvoiceData(invoice) { - const fulfillment = invoice?.fulfillment && typeof invoice.fulfillment === 'object' ? invoice.fulfillment : {}; - return { - orderId: firstText(fulfillment.order_id, invoice?.order_id), - status: firstText(fulfillment.status, fulfillment.fulfillment_status, invoice?.fulfillment_status, - fulfillment.job_status, invoice?.job_status, fulfillment.order_status, invoice?.order_status).toLowerCase(), - jobId: firstText(fulfillment.job_id, invoice?.job_id), - jobStatus: firstText(fulfillment.job_status, invoice?.job_status).toLowerCase(), - instanceId: firstText(fulfillment.instance_id, invoice?.instance_id), - instanceUuid: firstText(fulfillment.instance_uuid, fulfillment.vm_uuid, invoice?.instance_uuid, invoice?.vm_uuid), - phase: firstText(fulfillment.phase, invoice?.phase), - error: firstText(fulfillment.error, invoice?.error), - }; -} -function provisionStatusInfo(invoice) { - const data = provisionInvoiceData(invoice); - const status = data.status || data.jobStatus; - const values = { - awaiting_payment: ['等待支付', 'warning'], payment_pending: ['等待支付', 'warning'], draft: ['等待支付', 'warning'], - queued: ['等待创建', 'warning'], pending: ['等待创建', 'warning'], provisioning: ['创建中', 'warning'], running: ['创建中', 'warning'], - completed: ['已开通', 'running'], succeeded: ['已开通', 'running'], active: ['已开通', 'running'], - failed: ['创建失败', 'failed'], refunded: ['开通失败,已退款', 'failed'], - needs_attention: ['需要管理员核查', 'failed'], uncertain: ['正在核对结果', 'warning'], - }; - return { data, status, display: values[status] || [status || '等待支付', 'warning'] }; -} -function provisionFinished(invoice) { - const { status } = provisionStatusInfo(invoice); - return ['succeeded', 'failed', 'refunded', 'needs_attention'].includes(status); -} -function invoiceStatusInfo(status) { - const values = { - open: ['待支付', 'warning'], overdue: ['已逾期', 'failed'], - paid: ['已支付', 'running'], refunded: ['已退款', 'other'], void: ['已失效', 'other'], expired: ['已失效', 'failed'], - deleting: ['实例删除中', 'failed'], delete_failed: ['自动删除失败', 'failed'], - purge_pending: ['等待永久删除', 'failed'], purge_stopping: ['删除前正在关机', 'failed'], - purge_deleting: ['实例删除中', 'failed'], purge_stop_failed: ['删除前关机失败', 'failed'], purge_failed: ['自动删除失败', 'failed'], - }; - return values[String(status || '').toLowerCase()] || [String(status || '未知'), 'other']; -} -function invoiceDeletionTimestamp(invoice) { - return serviceTimestamp(invoice?.deletion_at ?? invoice?.delete_at ?? invoice?.grace_ends_at ?? null); -} -function invoicePaymentDeadlineTimestamp(invoice) { - return serviceTimestamp(invoice?.payment_deadline_at ?? invoice?.payable_until ?? invoice?.payment_due_at ?? null); -} -function invoiceCanPay(invoice) { - if (!['open', 'overdue'].includes(String(invoice?.status || '').toLowerCase())) return false; - if (invoice?.payable === false) return false; - if (invoice?.payable === true) return true; - const deadline = invoicePurpose(invoice) === 'renewal' - ? invoiceDeletionTimestamp(invoice) : invoicePaymentDeadlineTimestamp(invoice); - return deadline === null || Date.now() < deadline; -} -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(); -} -async function refreshInvoiceView(invoiceId) { - if (state.view === 'invoice-detail') return loadInvoiceDetail(invoiceId); - if (state.view === 'invoices') return loadInvoices(); -} -function mergeInvoiceStatus(invoice, update) { - const current = invoice && typeof invoice === 'object' ? invoice : {}; - const next = update && typeof update === 'object' ? update : {}; - const merged = { ...current, ...next }; - if (current.fulfillment && typeof current.fulfillment === 'object' - && next.fulfillment && typeof next.fulfillment === 'object') { - merged.fulfillment = { ...current.fulfillment, ...next.fulfillment }; - } - return merged; -} -function applyInvoiceStatus(update) { - if (!update?.id) return null; - const key = String(update.id); - if (state.view === 'invoice-detail' && String(state.selectedInvoice?.id || '') === key) { - const invoice = mergeInvoiceStatus(state.selectedInvoice, update); - renderInvoiceDetail(invoice, { - balance: state.invoiceBalance, - payment_methods: state.invoicePaymentMethods, - }); - return invoice; - } - if (state.view === 'invoices') { - const index = state.invoices.findIndex(invoice => String(invoice.id) === key); - if (index >= 0) { - state.invoices[index] = mergeInvoiceStatus(state.invoices[index], update); - renderInvoices(); - return state.invoices[index]; - } - } - return update; -} -function scheduleInvoicePoll(invoiceId) { - const key = String(invoiceId); - stopInvoicePoll(key); - const started = Date.now(); - const poll = async () => { - if (!['invoices', 'invoice-detail'].includes(state.view)) return stopInvoicePoll(key); - try { - const result = await api(`/api/v1/invoices/${encodeURIComponent(key)}/status`); - const invoice = applyInvoiceStatus(result.invoice || {}) || {}; - const status = String(invoice.status || '').toLowerCase(); - if (status === 'paid') { - if (invoicePurpose(invoice) !== 'provision') { - const message = invoicePurpose(invoice) === 'renewal' - ? '账单支付成功,服务期限已延长。' : '账单支付成功。'; - stopInvoicePoll(key); toast(message, 'success'); return; - } - if (provisionFinished(invoice)) { - const { status: provisionStatus } = provisionStatusInfo(invoice); - stopInvoicePoll(key); - if (provisionStatus === 'succeeded') toast('实例已创建完成。', 'success'); - else if (provisionStatus === 'refunded') toast('实例创建失败,款项已退回账户余额。', 'error'); - else toast('实例开通未完成,请在账单详情查看任务状态。', 'error'); - return; - } - } - if (['void', 'expired'].includes(status)) { - stopInvoicePoll(key); toast('账单已失效,到账金额会保留在账户余额中。', 'error'); return; - } - if (status === 'refunded') { - stopInvoicePoll(key); toast('实例创建失败,款项已退回账户余额。', 'error'); return; - } - if (!invoiceCanPay(invoice) && status !== 'paid') { - const message = invoicePurpose(invoice) === 'provision' - ? '开通账单已超过支付截止时间。' : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,到账金额会保留在账户余额中。' : '账单已超过支付截止时间。'; - stopInvoicePoll(key); toast(message, 'error'); return; - } - } catch {} - if (Date.now() - started < 10 * 60 * 1000) { - state.invoicePollTimers.set(key, setTimeout(poll, 3000)); - } else { - stopInvoicePoll(key); - } - }; - 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, container, refresh = () => refreshInvoiceView(invoice.id)) { - if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision' - ? '开通账单已失效,不能支付。' : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,账单不可支付。' : '账单已失效,不能支付。', 'error'); - if (state.mutationBusy || !confirm(`确认使用账户余额支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) return; - state.mutationBusy = true; - container.querySelectorAll('button').forEach(button => { button.disabled = true; }); - try { - const result = await api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/pay-balance`, { - method: 'POST', body: { idempotency_key: crypto.randomUUID() }, - }); - const paid = result.invoice || invoice; - if (invoicePurpose(paid) === 'provision') { - toast('账单已支付,实例已进入创建队列。', 'success'); await refresh(paid.id || invoice.id); scheduleInvoicePoll(paid.id || invoice.id); - } else if (invoicePurpose(paid) === 'renewal') { - toast('账单已支付,服务期限已延长。', 'success'); await refresh(paid.id || invoice.id); - } else { - toast('账单已支付。', 'success'); await refresh(paid.id || invoice.id); - } - } catch (error) { toast(error.message, 'error'); } - finally { - state.mutationBusy = false; - container.querySelectorAll('button').forEach(button => { button.disabled = false; }); - } -} -async function createInvoicePayment(invoice, method, container, paymentResult = container) { - if (!invoiceCanPay(invoice)) return toast(invoicePurpose(invoice) === 'provision' - ? '开通账单已失效,不能再生成支付订单。' : invoicePurpose(invoice) === 'renewal' - ? '续费宽限期已经结束,不能再生成支付订单。' : '账单已失效,不能再生成支付订单。', 'error'); - if (state.mutationBusy || !confirm(`确认通过“${method.name}”支付账单 #${invoice.id},金额 ${formatUsd(invoice.amount)}?`)) return; - state.mutationBusy = true; - container.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(paymentResult, 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; container.querySelectorAll('button').forEach(button => { button.disabled = false; }); } -} -function invoiceFact(label, value) { - const item = makeElement('div', 'invoice-detail-fact'); - item.append(makeElement('dt', '', label), makeElement('dd', '', value === null || value === undefined || value === '' ? '—' : value)); - return item; -} -function invoiceSpecification(invoice) { - const candidates = [invoice?.specification, invoice?.spec, invoice?.plan_snapshot, - invoice?.order_snapshot, invoice?.fulfillment?.specification, invoice?.fulfillment?.spec]; - const spec = candidates.find(value => value && typeof value === 'object') || {}; - return { - cpu: firstNumber(invoice?.cpu_cores, invoice?.vcpu, spec.cpu_cores, spec.vcpu), - memoryMib: firstNumber(invoice?.memory_mib, spec.memory_mib), - memoryGib: firstNumber(invoice?.memory_gib, spec.memory_gib), - diskGib: firstNumber(invoice?.disk_gib, invoice?.disk_size_gib, spec.disk_gib, spec.disk_size_gib), - bandwidthMbps: firstNumber(invoice?.bandwidth_mbps, spec.bandwidth_mbps), - }; -} -function invoiceProgressText(job) { - const status = firstText(job?.status).toLowerCase(); - const labels = { - queued: '等待创建', pending: '等待创建', running: '正在创建', provisioning: '正在创建', - uncertain: '正在核对创建结果', succeeded: '实例创建完成', completed: '实例创建完成', - failed: '实例创建失败', refunded: '创建失败,已退款', needs_attention: '需要管理员核查', - }; - const resultMessage = typeof job?.result === 'object' ? firstText(job.result.message, job.result.status) : ''; - return firstText(job?.error, job?.phase, resultMessage, labels[status], status ? `任务状态:${status}` : '', '等待创建'); -} -function appendProvisionInvoiceActions(invoice, detail, actions) { - const { data, status, display } = provisionStatusInfo(invoice); - if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); - if (data.jobId) actions.append(actionButton('查看创建进度', async () => { - let progress = detail.querySelector('.cloud-order-progress'); - if (!progress) { progress = makeElement('p', 'cloud-order-progress muted'); detail.append(progress); } - try { - const job = await api(`/api/v1/jobs/${encodeURIComponent(data.jobId)}`); - const jobStatus = firstText(job.status).toLowerCase(); - const failed = ['failed', 'refunded', 'needs_attention'].includes(jobStatus) || Boolean(job.error); - progress.className = `cloud-order-progress ${failed ? 'form-error' : 'muted'}`; - progress.textContent = invoiceProgressText(job); - state.invoiceJobProgress.set(String(invoice.id), { message: progress.textContent, failed }); - if (!['succeeded', 'failed', 'refunded', 'needs_attention'].includes(jobStatus)) { - scheduleInvoicePoll(invoice.id); - } - } catch (error) { - progress.className = 'cloud-order-progress form-error'; progress.textContent = error.message; - state.invoiceJobProgress.set(String(invoice.id), { message: error.message, failed: true }); - } - })); - if (data.instanceId) { - const link = makeElement('a', 'row-button', '查看实例'); - link.href = vmPagePath(data.instanceId); actions.append(link); - } else if (data.instanceUuid) actions.append(actionButton('查看实例', async () => { - await loadVms(); - const vm = state.vms.find(item => item.uuid === data.instanceUuid); - if (vm) navigate(vmPagePath(vm.api_id)); else toast('实例尚未出现在列表,请稍后刷新。'); - })); -} -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 cloud-invoice-list-row'); - const detail = makeElement('div', 'cloud-order-detail cloud-invoice-list-copy'); - detail.append(makeElement('strong', '', invoiceTitle(invoice)), - makeElement('p', 'muted', `账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`)); - - const actions = makeElement('div', 'cloud-order-actions cloud-invoice-list-actions'); - const invoiceStatus = String(invoice.status || '').toLowerCase(); - const [label, className] = invoiceStatusInfo(invoiceStatus); - actions.append(makeElement('span', `state-pill ${className}`, label)); - if (invoicePurpose(invoice) === 'provision' && ['paid', 'refunded'].includes(invoiceStatus)) { - const { status, display } = provisionStatusInfo(invoice); - if (status) actions.append(makeElement('span', `state-pill ${display[1]}`, display[0])); - } - const link = makeElement('a', 'row-button', '账单详情'); - link.href = invoicePagePath(invoice.id); actions.append(link); - - const amount = makeElement('div', 'cloud-invoice-list-amount'); - amount.append(makeElement('span', '', '金额'), makeElement('strong', '', formatUsd(invoice.amount))); - row.append(detail, actions, amount); container.append(row); - } -} -function renderInvoicePagination() { - const navigation = byId('invoices-pagination'); - if (!navigation) return; - const pagination = state.invoicePagination || {}; - const page = Math.max(1, Number(pagination.page) || 1); - const totalPages = Math.max(1, Number(pagination.total_pages) || 1); - const total = Math.max(0, Number(pagination.total) || 0); - navigation.hidden = total === 0; - navigation.setAttribute('aria-busy', String(state.invoiceLoading)); - text('invoices-page-label', `第 ${page} / ${totalPages} 页 · 共 ${total} 条`); - const previous = byId('invoices-previous'); - const next = byId('invoices-next'); - if (previous) previous.disabled = state.invoiceLoading || !pagination.has_previous; - if (next) next.disabled = state.invoiceLoading || !pagination.has_next; - const refresh = byId('invoices-refresh'); - if (refresh) { - refresh.disabled = state.invoiceLoading; - refresh.setAttribute('aria-busy', String(state.invoiceLoading)); - } -} -function renderInvoiceSpecification(invoice) { - const panel = byId('invoice-specification-panel'); - const container = byId('invoice-specification'); - if (!panel || !container) return; - const purpose = invoicePurpose(invoice); - if (!['provision', 'renewal'].includes(purpose)) { - panel.hidden = true; container.replaceChildren(); return; - } - const spec = invoiceSpecification(invoice); - const subject = firstText(invoice.requested_name, invoice.instance_name, purpose === 'provision' ? '待创建实例' : '实例'); - const facts = [ - invoiceFact('实例', subject), - invoiceFact('套餐', firstText(invoice.plan_name, '云服务器套餐')), - ]; - if (spec.cpu !== null) facts.push(invoiceFact('CPU', `${spec.cpu} 核`)); - if (spec.memoryMib !== null) facts.push(invoiceFact('内存', formatMemoryGiB(spec.memoryMib))); - else if (spec.memoryGib !== null) facts.push(invoiceFact('内存', `${spec.memoryGib} GB`)); - if (spec.diskGib !== null) facts.push(invoiceFact('系统盘', `${spec.diskGib} GB`)); - if (spec.bandwidthMbps !== null) facts.push(invoiceFact('带宽', `${spec.bandwidthMbps} Mbps`)); - facts.push(invoiceFact('服务周期', `${Number(invoice.validity_days || 0)} 天`), - invoiceFact('周期流量', formatTrafficQuota(Number(invoice.traffic_quota_bytes || 0)))); - container.replaceChildren(...facts); panel.hidden = false; -} -function selectInvoicePaymentMethod(methodId) { - state.selectedInvoicePaymentMethod = String(methodId || ''); - byId('invoice-payment-methods')?.querySelectorAll('.invoice-payment-method-card').forEach(card => { - const selected = card.dataset.methodId === state.selectedInvoicePaymentMethod; - card.setAttribute('aria-pressed', String(selected)); - card.setAttribute('aria-checked', String(selected)); - }); - if (byId('invoice-payment-submit')) byId('invoice-payment-submit').disabled = !state.selectedInvoicePaymentMethod; -} -function renderInvoicePaymentMethods(invoice, balance, methods) { - const panel = byId('invoice-payment-panel'); - const container = byId('invoice-payment-methods'); - const result = byId('invoice-payment-result'); - if (!panel || !container || !result) return; - if (!invoiceCanPay(invoice)) { - clearInvoicePaymentKeys(invoice.id); - panel.hidden = true; container.replaceChildren(); result.replaceChildren(); - state.selectedInvoicePaymentMethod = ''; return; - } - const choices = [{ id: 'balance', name: '账户余额', description: `可用余额 ${formatUsd(balance)}`, kind: 'balance' }]; - for (const method of methods) { - if (method?.id === null || method?.id === undefined || !firstText(method.name)) continue; - choices.push({ ...method, id: String(method.id), kind: 'online' }); - } - const available = new Set(choices.map(choice => String(choice.id))); - if (!available.has(state.selectedInvoicePaymentMethod)) state.selectedInvoicePaymentMethod = 'balance'; - const cards = choices.map(choice => { - const card = makeElement('button', 'invoice-payment-method-card'); - card.type = 'button'; card.dataset.methodId = String(choice.id); card.setAttribute('role', 'radio'); - const selected = String(choice.id) === state.selectedInvoicePaymentMethod; - card.setAttribute('aria-pressed', String(selected)); card.setAttribute('aria-checked', String(selected)); - card.append(makeElement('strong', '', choice.name), makeElement('small', '', firstText(choice.description, - choice.label, choice.kind === 'balance' ? `可用余额 ${formatUsd(balance)}` : '在线支付')), - makeElement('span', 'invoice-payment-method-check', '✓')); - card.addEventListener('click', () => selectInvoicePaymentMethod(choice.id)); - return card; - }); - // Returning from an external payment app triggers a visibility refresh. Keep - // the already-created provider instructions while this same bill is payable; - // settlement or expiry clears them through the non-payable branch above. - container.replaceChildren(...cards); panel.hidden = false; - const submit = byId('invoice-payment-submit'); - submit.disabled = !state.selectedInvoicePaymentMethod; - submit.onclick = async () => { - showError('invoice-payment-error', ''); - const choice = choices.find(item => String(item.id) === state.selectedInvoicePaymentMethod); - if (!choice) return showError('invoice-payment-error', '请选择支付方式。'); - if (choice.kind === 'balance') await payInvoiceBalance(invoice, panel, loadInvoiceDetail); - else await createInvoicePayment(invoice, choice, panel, result); - }; -} -function renderInvoiceFulfillment(invoice) { - const panel = byId('invoice-fulfillment-panel'); - const content = byId('invoice-fulfillment-content'); - if (!panel || !content) return; - const invoiceStatus = firstText(invoice.status).toLowerCase(); - const visible = invoicePurpose(invoice) === 'provision' - && (['paid', 'refunded'].includes(invoiceStatus) || Boolean(provisionInvoiceData(invoice).jobId)); - if (!visible) { panel.hidden = true; content.replaceChildren(); return; } - const detail = makeElement('div', 'invoice-fulfillment-detail'); - const actions = makeElement('div', 'cloud-order-actions invoice-fulfillment-actions'); - const { data, status, display } = provisionStatusInfo(invoice); - const cached = state.invoiceJobProgress.get(String(invoice.id)); - const terminal = provisionFinished(invoice); - const failed = Boolean(data.error) || ['failed', 'refunded', 'needs_attention'].includes(status) - || (!terminal && cached?.failed === true); - const progress = makeElement('p', `cloud-order-progress ${failed ? 'form-error' : 'muted'}`, - firstText(data.error, data.phase, terminal ? display[0] : cached?.message, - status === 'uncertain' ? '后台正在核对实例创建结果,请勿重复提交。' : display[0])); - detail.append(progress); - appendProvisionInvoiceActions(invoice, detail, actions); - content.replaceChildren(detail, actions); panel.hidden = false; - if (invoiceStatus === 'paid' && !provisionFinished(invoice) - && !state.invoicePollTimers.has(String(invoice.id))) scheduleInvoicePoll(invoice.id); - else if (terminal) { - state.invoiceJobProgress.delete(String(invoice.id)); stopInvoicePoll(invoice.id); - } -} -function renderInvoiceDetail(invoice, payload) { - state.selectedInvoice = invoice; - text('invoice-detail-kind', invoiceTitle(invoice)); - text('invoice-detail-number', `账单 #${invoice.id}`); - text('invoice-detail-created', `创建于 ${formatOrderDate(invoice.created_at)}`); - text('invoice-detail-subtitle', `账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`); - text('invoice-detail-amount', formatUsd(invoice.amount)); - const [statusLabel, statusClass] = invoiceStatusInfo(invoice.status); - const status = byId('invoice-detail-status'); - status.className = `state-pill ${statusClass}`; status.textContent = statusLabel; - - const purpose = invoicePurpose(invoice); - const facts = [invoiceFact('账单编号', `#${invoice.id}`), invoiceFact('创建时间', formatOrderDate(invoice.created_at))]; - if (purpose === 'provision') facts.push(invoiceFact('支付截止', formatServiceDate(invoicePaymentDeadlineTimestamp(invoice) ?? invoice.due_at))); - else if (purpose === 'renewal') { - facts.push(invoiceFact('实例到期', formatOrderDate(invoice.due_at))); - if (invoiceDeletionTimestamp(invoice) !== null) facts.push(invoiceFact('最晚支付', formatServiceDate(invoiceDeletionTimestamp(invoice)))); - } else if (invoicePaymentDeadlineTimestamp(invoice) !== null) facts.push(invoiceFact('支付截止', formatServiceDate(invoicePaymentDeadlineTimestamp(invoice)))); - if (invoice.paid_at) facts.push(invoiceFact('支付时间', formatOrderDate(invoice.paid_at))); - if (invoice.paid_via) facts.push(invoiceFact('支付方式', String(invoice.paid_via))); - byId('invoice-detail-facts').replaceChildren(...facts); - - renderInvoiceSpecification(invoice); - renderInvoicePaymentMethods(invoice, payload.balance, Array.isArray(payload.payment_methods) ? payload.payment_methods : []); - renderInvoiceFulfillment(invoice); -} -async function loadInvoiceDetail(invoiceId = document.body.dataset.invoiceId) { - const id = String(invoiceId || ''); - if (!/^\d+$/.test(id)) throw new Error('账单编号无效。'); - try { - const payload = await api(`/api/v1/invoices/${encodeURIComponent(id)}`); - if (!payload?.invoice) throw new Error('账单信息不完整。'); - const csrfToken = String(payload.csrf_token || ''); - const userId = String(payload.user_id || ''); - if (!/^[a-f0-9]{64}$/.test(csrfToken) || !/^\d+$/.test(userId)) { - throw new Error('账单会话信息不完整,请重新登录。'); - } - state.csrfToken = csrfToken; - state.userId = userId; - state.username = payload.username || state.username || '用户'; - state.admin = payload.admin === true || Number(payload.admin) === 1; - state.invoiceBalance = String(payload.balance ?? state.invoiceBalance); - if (byId('current-username')) text('current-username', state.username); - for (const adminLinkId of ['cloud-admin-link', 'cloud-admin-menu-link']) { - const link = byId(adminLinkId); - if (link) link.hidden = !state.admin; - } - if (state.selectedInvoice && String(state.selectedInvoice.id) !== String(payload.invoice.id)) { - state.selectedInvoicePaymentMethod = ''; - byId('invoice-payment-result')?.replaceChildren(); - } - state.invoicePaymentMethods = Array.isArray(payload.payment_methods) ? payload.payment_methods : []; - renderInvoiceDetail(payload.invoice, payload); showError('cloud-page-error', ''); return payload.invoice; - } catch (error) { showError('cloud-page-error', error.message); throw error; } -} -async function loadInvoices(page = state.invoicePage) { - if (state.invoiceLoading) return state.invoiceLoadPromise; - const requestedPage = Math.max(1, Math.trunc(Number(page) || state.invoicePage || 1)); - state.invoiceLoading = true; - renderInvoicePagination(); - const request = (async () => { - try { - const payload = await api(`/api/v1/invoices?page=${encodeURIComponent(requestedPage)}`); - const pagination = payload?.pagination && typeof payload.pagination === 'object' - ? payload.pagination : {}; - const actualPage = Math.max(1, Math.trunc(Number(pagination.page) || requestedPage)); - const totalPages = Math.max(1, Math.trunc(Number(pagination.total_pages) || 1)); - const total = Math.max(0, Math.trunc(Number(pagination.total) || 0)); - state.invoicePage = actualPage; - state.invoicePagination = { - page: actualPage, - per_page: Math.max(1, Math.trunc(Number(pagination.per_page) || 10)), - total, - total_pages: totalPages, - has_previous: pagination.has_previous === true || actualPage > 1, - has_next: pagination.has_next === true || actualPage < totalPages, - from: Math.max(0, Math.trunc(Number(pagination.from) || 0)), - to: Math.max(0, Math.trunc(Number(pagination.to) || 0)), - }; - state.invoices = Array.isArray(payload.invoices) ? payload.invoices : []; - text('invoices-balance', formatUsd(payload.balance)); - renderInvoices(); - showError('cloud-page-error', ''); - return payload; - } catch (error) { - showError('cloud-page-error', error.message); - return null; - } - })(); - state.invoiceLoadPromise = request; - try { - return await request; - } finally { - state.invoiceLoading = false; - state.invoiceLoadPromise = null; - renderInvoicePagination(); - } -} async function openReinstall(vm, bootstrap = null) { state.view = '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; if (!vm?.can_operate) { @@ -2210,7 +1616,6 @@ function bindPageCleanup() { clearCredential(); stopVmMetrics(); stopVmTrafficDaily(); - stopInvoicePoll(); closeConsole(); state.resourceController?.abort(); }); @@ -2219,11 +1624,11 @@ function bindPageCleanup() { export { CLOUD_PATHS, VM_DETAIL_TABS, api, bindPageCleanup, buy, byId, clearCredential, clearVmMetrics, clearVmTrafficDaily, closeConsole, copyText, credential, - drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, invoicePagePath, - loadGlobalTemplates, loadInvoiceDetail, loadInvoices, loadKeys, loadVmMetrics, loadVmTrafficDaily, + drawVmTrafficDaily, hydrateVmDetailBootstrap, initializeSession, + loadGlobalTemplates, loadKeys, loadVmMetrics, loadVmTrafficDaily, loadVm, loadVmStatus, loadVms, navigate, openCreate, openReinstall, openRescue, reinstall, readBootstrap, renderVMs, renderVmDetail, renderVmMetrics, rescueAction, selectVmByApiId, selectedVm, - scheduleInvoicePoll, setVmDetailTab, showError, state, stopInvoicePoll, stopVmMetrics, + setVmDetailTab, showError, state, stopVmMetrics, stopVmTrafficDaily, toast, trafficDailyViewVisible, vmIp, vmPagePath, }; diff --git a/web/resources/views/venix/admin/cloud/templates.tpl b/web/resources/views/venix/admin/cloud/templates.tpl index 90115905..9929d0dd 100644 --- a/web/resources/views/venix/admin/cloud/templates.tpl +++ b/web/resources/views/venix/admin/cloud/templates.tpl @@ -1,5 +1,5 @@ {assign var=admin_title value='云镜像模版'}{assign var=admin_active value='cloud_templates'}{include file='admin/static_header.tpl'} -

云镜像模版

这里维护全局云镜像目录,普通用户在所有可售地区看到同一份镜像列表。宿主机副本由引擎按需准备。当前支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04 官方 x86_64 cloud-init 云镜像。升级前按宿主机导入的旧镜像不会自动进入全局目录,请重新导入一次。

正在加载…

+

云镜像模版

这里维护全局云镜像目录,普通用户在所有可售地区看到同一份镜像列表。宿主机副本由引擎按需准备。删除会同时退役全局源镜像并异步清理宿主机缓存;已创建实例使用独立克隆磁盘,不受影响。当前支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04 官方 x86_64 cloud-init 云镜像。升级前按宿主机导入的旧镜像不会自动进入全局目录,请重新导入一次。

正在加载…

导入云镜像

请粘贴受支持发行版官方镜像站的 HTTPS 文件地址,不能是下载介绍页;引擎只会跟随由官方入口返回且通过公网地址安全校验的跳转链。文件名应为 .qcow2;Ubuntu 官方 .img 也可使用,但其实际内容必须是 qcow2。

留空时面板会计算并保存实际 SHA-256,不与外部校验值比对;填写后则会在导入前核对。

已保存的模版
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/cloud/page.tpl b/web/resources/views/venix/cloud/page.tpl index ea74fe29..25477846 100644 --- a/web/resources/views/venix/cloud/page.tpl +++ b/web/resources/views/venix/cloud/page.tpl @@ -45,7 +45,6 @@ {if $cloud_page == 'detail'}{include file='cloud/console.tpl'}{/if} -{if $cloud_page == 'invoice-detail'}{/if} diff --git a/web/resources/views/venix/cloud/pages/invoice-detail.tpl b/web/resources/views/venix/cloud/pages/invoice-detail.tpl index 8506fb19..47eeccdb 100644 --- a/web/resources/views/venix/cloud/pages/invoice-detail.tpl +++ b/web/resources/views/venix/cloud/pages/invoice-detail.tpl @@ -4,7 +4,7 @@
BILL DETAIL

账单详情

-

正在读取账单信息…

+

账单 #{$cloud_invoice_detail_view.id|default:'—'|escape:"html"} · {$cloud_invoice_detail_view.created_display|default:'时间未记录'|escape:"html"}

@@ -13,35 +13,72 @@
- 账单 - 账单 #— - 创建时间 — + {$cloud_invoice_detail_view.title|default:'账单'|escape:"html"} + 账单 #{$cloud_invoice_detail_view.id|default:'—'|escape:"html"} + 创建于 {$cloud_invoice_detail_view.created_display|default:'时间未记录'|escape:"html"}
应付金额 - $— - 读取中 + {$cloud_invoice_detail_view.amount_display|default:'$—'|escape:"html"} + {$cloud_invoice_detail_view.status_label|default:'未知'|escape:"html"}
-
+
+ {foreach $cloud_invoice_detail_view.facts as $fact} +
+
{$fact.label|escape:"html"}
+
{$fact.value|default:'—'|escape:"html"}
+
+ {/foreach} +
-
diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 3c9f7779..9d8546e2 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1 +1 @@ -{assign var=venix_asset_version value='2026092823' scope='global'} +{assign var=venix_asset_version value='2026092901' scope='global'} diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 53af9dd9..14d8aeb1 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -9,6 +9,21 @@ CREATE TABLE IF NOT EXISTS cloud_hosts ( created_at BIGINT NOT NULL, updated_at BIGINT NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE IF NOT EXISTS cloud_template_retirements ( + template_id VARCHAR(80) CHARACTER SET ascii COLLATE ascii_bin NOT NULL PRIMARY KEY, + state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'deleting', + template_created_at BIGINT UNSIGNED NOT NULL DEFAULT 0, + created_at BIGINT UNSIGNED NOT NULL, + updated_at BIGINT UNSIGNED NOT NULL, + KEY cloud_template_retirement_state (state, updated_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +ALTER TABLE cloud_template_retirements ADD COLUMN IF NOT EXISTS + template_created_at BIGINT UNSIGNED NOT NULL DEFAULT 0 AFTER state; +CREATE TABLE IF NOT EXISTS cloud_template_catalog_locks ( + id TINYINT UNSIGNED NOT NULL PRIMARY KEY, + updated_at BIGINT UNSIGNED NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +INSERT IGNORE INTO cloud_template_catalog_locks (id, updated_at) VALUES (1, 0); ALTER TABLE cloud_hosts ADD COLUMN IF NOT EXISTS country_code CHAR(2) NOT NULL DEFAULT '' AFTER region; CREATE TABLE IF NOT EXISTS cloud_instances ( diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index c6099606..dde22238 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -28,6 +28,7 @@ namespace { use App\Models\CloudMailOutbox; use App\Models\CloudOrder; use App\Models\CloudJob; + use App\Models\CloudTemplateRetirement; use App\Services\Cloud\CloudInvoiceService; use App\Services\Cloud\CloudInvoicePaymentService; use App\Services\Cloud\CloudOrderService; @@ -38,6 +39,7 @@ namespace { use App\Services\Cloud\CloudInstanceDiscovery; use App\Services\Cloud\CloudError; use App\Services\Cloud\CloudMoney; + use App\Services\Cloud\CloudTemplateDeletionService; use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; @@ -53,6 +55,8 @@ namespace { $schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); }); $schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('name'); $t->string('price'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'validity_days', 'traffic_quota_bytes', 'status', 'stock', 'sort'] as $v) { $t->integer($v)->default(0); } }); $schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->integer('enabled'); $t->string('default_network'); }); + $schema->create('cloud_template_retirements', function (Blueprint $t) { $t->string('template_id')->primary(); $t->string('state')->default('deleting'); $t->integer('template_created_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_template_catalog_locks', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('updated_at'); }); $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'host_id'] as $v) { $t->integer($v); } $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('status'); $t->text('spec_json'); $t->text('payload_cipher')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); }); @@ -804,5 +808,73 @@ namespace { && preg_match('/^vm-[abcdefghjkmnpqrstuvwxyz23456789]{6}$/D', (string) ($automaticSpec['name'] ?? '')) === 1, 'Blank instance names were not generated securely or idempotently.'); + + try { + CloudTemplateDeletionService::begin($input['template_id'], 1); + throw new RuntimeException('An actively referenced cloud template was retired.'); + } catch (CloudError $error) { + $assert($error->httpStatus === 409 + && CloudTemplateRetirement::find($input['template_id'])->state === 'active', + 'A rejected template deletion did not restore the active template row.'); + } + $retiredTemplate = 'debian12-fedcba98-0123456789abcdef'; + CloudTemplateDeletionService::begin($retiredTemplate, 1); + try { + CloudTemplateDeletionService::assertImportAllowed(); + throw new RuntimeException('Import was allowed during a pending template delete.'); + } catch (CloudError $error) { + $assert($error->httpStatus === 409, + 'Pending template deletion returned the wrong import-gate status.'); + } + CloudTemplateDeletionService::complete($retiredTemplate, 1); + CloudTemplateDeletionService::assertImportAllowed(); + CloudTemplateDeletionService::begin($retiredTemplate, 1); + $assert(CloudTemplateRetirement::find($retiredTemplate)->state === 'deleting', + 'A retry did not reopen the durable engine deletion request.'); + CloudTemplateDeletionService::complete($retiredTemplate, 1); + CloudTemplateDeletionService::reactivateImportedTemplate($retiredTemplate, 2); + $assert(CloudTemplateRetirement::find($retiredTemplate)->state === 'active' + && (int) CloudTemplateRetirement::find($retiredTemplate) + ->template_created_at === 2, + 'A completed same-content reimport remained retired or reused its generation.'); + CloudTemplateRetirement::where('template_id', $retiredTemplate)->update([ + 'state' => 'deleted', 'updated_at' => time(), + ]); + CloudTemplateDeletionService::reconcileAuthoritativeCatalog([[ + 'id' => $retiredTemplate, 'created_at' => 2, + ]]); + $assert(CloudTemplateRetirement::find($retiredTemplate)->state === 'active', + 'An authoritative live catalog did not repair a stale deleted gate.'); + $staleImportAccepted = CloudTemplateDeletionService::reactivateImportedTemplate( + $retiredTemplate, 1 + ); + $assert($staleImportAccepted === false + && (int) CloudTemplateRetirement::find($retiredTemplate) + ->template_created_at === 2, + 'A delayed old import result rolled back the active template generation.'); + try { + CloudTemplateDeletionService::begin($retiredTemplate, 1); + throw new RuntimeException('A stale deletion generation was accepted.'); + } catch (CloudError $error) { + $state = CloudTemplateRetirement::find($retiredTemplate); + $assert($error->httpStatus === 409 && $state->state === 'active' + && (int) $state->template_created_at === 2, + 'A stale delete changed the active reimport generation.'); + } + $largeCatalog = []; + for ($index = 1; $index <= 257; $index++) { + $largeCatalog[] = [ + 'id' => 'bulk-template-' . $index, + 'created_at' => 1000 + $index, + ]; + } + CloudTemplateDeletionService::reactivateImportedTemplate( + 'bulk-template-257', 1257 + ); + CloudTemplateDeletionService::reconcileAuthoritativeCatalog($largeCatalog); + $largeCatalogState = CloudTemplateRetirement::find('bulk-template-257'); + $assert($largeCatalogState->state === 'active' + && (int) $largeCatalogState->template_created_at === 1257, + 'Catalog reconciliation truncated and retired a template after row 256.'); echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n"; } diff --git a/web/tests/CloudInvoiceDetailContractTest.php b/web/tests/CloudInvoiceDetailContractTest.php index b4f47b1b..c57eaff9 100644 --- a/web/tests/CloudInvoiceDetailContractTest.php +++ b/web/tests/CloudInvoiceDetailContractTest.php @@ -25,8 +25,18 @@ $apiController = file_get_contents($root . '/app/Controllers/CloudApiController. $apiMiddleware = file_get_contents($root . '/app/Middleware/CloudApi.php'); $invoiceService = file_get_contents($root . '/app/Services/Cloud/CloudInvoiceService.php'); $invoicePageService = file_get_contents($root . '/app/Services/Cloud/CloudInvoicePageService.php'); +$invoiceDetailPageService = file_get_contents( + $root . '/app/Services/Cloud/CloudInvoiceDetailPageService.php' +); +$invoiceDetailTemplate = file_get_contents( + $root . '/resources/views/venix/cloud/pages/invoice-detail.tpl' +); +$cloudShell = file_get_contents($root . '/resources/views/venix/cloud/page.tpl'); $invoiceDetailModule = file_get_contents($root . '/public/cloud/invoice-detail.js'); -$runtime = file_get_contents($root . '/public/cloud/runtime.js'); +$invoiceDetailRuntime = file_get_contents( + $root . '/public/cloud/invoice-detail-runtime.js' +); +$legacyRuntime = file_get_contents($root . '/public/cloud/runtime.js'); $jobService = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); $invoiceModel = file_get_contents($root . '/app/Models/CloudInvoice.php'); $invoiceEmail = file_get_contents($root . '/resources/email/cloud/invoice.tpl'); @@ -43,10 +53,48 @@ $assert(str_contains($apiRoutes, "'/invoices/{id:[0-9]+}/status'") $pageMethod = $section($pageController, 'public function invoiceDetail(', 'public function reinstall('); -$assert(str_contains($pageMethod, "'invoice-detail'") +$assert(str_contains($pageMethod, 'CloudAccess::actor(false)') + && str_contains($pageMethod, "getAttribute('auth_user')") + && str_contains($pageMethod, 'CloudInvoiceDetailPageService::forUser(') + && str_contains($pageMethod, "'cloud_invoice_detail_view'") + && str_contains($pageMethod, "'cloud_invoice_detail_bootstrap_json'") + && str_contains($pageMethod, '$this->safeJson($payload)') + && str_contains($pageMethod, "'invoice-detail'") && str_contains($pageMethod, "'/user/cloud/invoices'") && str_contains($pageController, "assign('cloud_invoice_id', \$invoiceId)"), - 'The detail page does not validate and pass its numeric invoice id independently.'); + 'The detail page must render an owner-scoped payload and safe bootstrap on first paint.'); +$assert(str_contains($invoiceDetailPageService, + "CloudInvoice::where('id', \$invoiceId)") + && str_contains($invoiceDetailPageService, + "->where('user_id', \$userId)") + && str_contains($invoiceDetailPageService, + '(int) $user->id !== $userId') + && str_contains($invoiceDetailPageService, + 'CloudInvoiceService::display($invoice)') + && str_contains($invoiceDetailPageService, + "CloudInvoicePaymentService::methods(\$user)") + && str_contains($invoiceDetailPageService, + "'balance_payment_allowed' =>") + && str_contains($invoiceDetailPageService, + "'balance' => (string) \$user->money"), + 'The shared invoice-detail service is not strictly owner scoped or complete.'); +$assert(str_contains($pageController, 'JSON_HEX_TAG') + && str_contains($pageController, 'JSON_HEX_AMP') + && str_contains($pageController, 'JSON_HEX_APOS') + && str_contains($pageController, 'JSON_HEX_QUOT') + && str_contains($pageController, + "withHeader('Cache-Control', 'private, no-store')"), + 'Invoice-detail HTML must embed escaped JSON and prohibit shared caching.'); +$assert(str_contains($invoiceDetailTemplate, 'id="invoice-detail-bootstrap"') + && str_contains($invoiceDetailTemplate, '$cloud_invoice_detail_bootstrap_json nofilter') + && str_contains($invoiceDetailTemplate, '$cloud_invoice_detail_view.amount_display') + && str_contains($invoiceDetailTemplate, '$cloud_invoice_detail_view.status_label') + && str_contains($invoiceDetailTemplate, '{foreach $cloud_invoice_detail_view.facts as $fact}') + && str_contains($invoiceDetailTemplate, + '{foreach $cloud_invoice_detail_view.specification as $fact}') + && !str_contains($invoiceDetailTemplate, '正在读取账单信息') + && !str_contains($invoiceDetailTemplate, '>读取中<'), + 'Invoice-detail HTML must contain meaningful first-paint content, not a client-only shell.'); $listMethod = $section($apiController, 'public function invoices(', 'private function createProvisionInvoice('); @@ -67,7 +115,9 @@ $summaryMethod = $section($invoiceService, 'public static function listSummaries 'private static function listKey('); $assert(substr_count($summaryMethod, '::whereIn(') === 3 && str_contains($summaryMethod, "->get(['id', 'user_id', 'status'])") - && str_contains($summaryMethod, "->get(['id', 'order_id', 'user_id', 'status'])"), + && str_contains($summaryMethod, "->get(['id', 'order_id', 'user_id', 'status'])") + && str_contains($summaryMethod, + 'self::publicStatus($invoice, $purpose, $instance, $now)'), 'Invoice list associations are not loaded with fixed-size batch queries.'); foreach (['id', 'title', 'type_label', 'purpose', 'amount', 'status', 'created_at', 'order_status', 'fulfillment_status', 'job_status'] as $field) { @@ -82,22 +132,43 @@ foreach (['payment_methods', 'payment_reference', 'paid_via', 'specification', $apiMethod = $section($apiController, 'public function invoice(', 'public function invoiceStatus('); -$assert(str_contains($apiMethod, "CloudInvoice::where('id', \$args['id'])") - && str_contains($apiMethod, "->where('user_id', \$actor['user_id'])") - && str_contains($apiMethod, 'CloudInvoicePaymentService::methods($user)') - && str_contains($apiMethod, "'balance' => (string) \$user->money") - && str_contains($apiMethod, "'csrf_token' => AdminCsrf::token()") - && str_contains($apiMethod, "'user_id' => (string) \$user->id"), - 'The invoice-detail API is not strictly owner-scoped or lacks payment options.'); +$assert(str_contains($apiMethod, 'CloudInvoiceDetailPageService::forUser(') + && str_contains($apiMethod, "(int) \$actor['user_id']") + && str_contains($apiMethod, '(bool) $actor[\'is_admin\']'), + 'The invoice-detail API must use the same owner-scoped payload as HTML.'); $assert(preg_match('/if\s*\([^)]*\$actor\[[\'\"]is_admin[\'\"]\]/', $apiMethod) !== 1, 'Administrator scope must not bypass invoice ownership in the user detail API.'); $statusApiMethod = $section($apiController, 'public function invoiceStatus(', 'public function payInvoice('); -$assert(str_contains($statusApiMethod, "->where('user_id', \$actor['user_id'])") - && str_contains($statusApiMethod, 'CloudInvoiceService::status($invoice)') +$assert(str_contains($statusApiMethod, 'CloudInvoiceDetailPageService::statusForUser(') + && str_contains($statusApiMethod, "(int) \$actor['user_id']") && !str_contains($statusApiMethod, 'CloudInvoicePaymentService::methods('), 'Invoice polling must use an owner-scoped lightweight response.'); +$assert(!str_contains($invoiceDetailRuntime, '/api/v1/jobs/') + && substr_count($invoiceDetailRuntime, + '/api/v1/invoices/${encodeURIComponent(invoice.id)}/status') === 1 + && str_contains($invoiceDetailRuntime, "actionButton('查看创建进度'") + && str_contains($invoiceDetailRuntime, + 'const nextInvoice = mergeInvoiceStatus(state.selectedInvoice, update);'), + 'Manual creation-progress refresh must use one invoice-scoped lightweight request.'); +$manualProgress = $section($invoiceDetailRuntime, + 'function appendProvisionInvoiceActions(', ' if (data.instanceId) {'); +$manualProgressCatch = $section($manualProgress, + '} catch (error) {', ' }'); +$assert(str_contains($manualProgress, 'const readSequence = ++state.readSequence;') + && str_contains($manualProgress, 'try {') + && strpos($manualProgress, 'const readSequence = ++state.readSequence;') + < strpos($manualProgress, 'try {') + && str_contains($manualProgressCatch, + 'if (readSequence < state.appliedReadSequence) return;') + && !str_contains($manualProgressCatch, 'state.invoiceJobProgress.set('), + 'Manual creation-progress errors must ignore stale reads and remain transient.'); +$assert(substr_count($invoiceDetailPageService, '->sharedLock()') === 2 + && str_contains($invoiceDetailPageService, 'public static function statusForUser(') + && str_contains($invoiceDetailPageService, + 'return CloudInvoiceService::status($invoice);'), + 'Full and lightweight invoice reads must use a consistent owner-scoped snapshot.'); $statusService = $section($invoiceService, 'public static function status(', 'public static function display('); $assert(str_contains($statusService, "'fulfillment' =>") @@ -108,20 +179,184 @@ $assert(str_contains($statusService, "'fulfillment' =>") $assert(str_contains($apiMiddleware, 'CloudAccess::actor(!$databaseOnly)') && str_contains($apiMiddleware, "#^/api/v1/invoices(?:/|$)#D"), 'Invoice-only API calls must authenticate without a cloud_sessions lookup.'); -$pollMethod = $section($runtime, 'function scheduleInvoicePoll(', - 'function renderOnlinePayment('); +$pollMethod = $section($invoiceDetailRuntime, 'async function pollInvoiceStatus(', + 'function scheduleInvoicePoll('); $assert(str_contains($pollMethod, - 'api(`/api/v1/invoices/${encodeURIComponent(key)}/status`)') + 'api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`') && substr_count($pollMethod, 'api(') === 1 - && !str_contains($pollMethod, 'refreshInvoiceView('), - 'Each invoice poll must issue exactly one lightweight status request.'); -$assert(!str_contains($invoiceDetailModule, 'initializeSession') + && str_contains($pollMethod, 'entersProvisioningAfterPayment(') + && str_contains($pollMethod, 'resetProvisioningPollWindow();') + && !str_contains($pollMethod, 'refreshInvoiceDetail('), + 'Each invoice poll must issue one lightweight request and preserve the provisioning window.'); +$needsPolling = $section($invoiceDetailRuntime, 'function invoiceNeedsPolling(', + 'function stopInvoicePoll('); +$provisionFinished = $section($invoiceDetailRuntime, 'function provisionFinished(', + 'function invoiceFact('); +$assert(str_contains($needsPolling, 'state.onlinePaymentPending') + && str_contains($needsPolling, "invoicePurpose(invoice) === 'provision'") + && str_contains($needsPolling, + "String(invoice.status || '').toLowerCase() === 'paid'") + && str_contains($needsPolling, '!provisionFinished(invoice)') + && str_contains($provisionFinished, + "['completed', 'succeeded', 'active', 'failed', 'refunded'") + && str_contains($provisionFinished, "'needs_attention'].includes(status)") + && !str_contains($provisionFinished, "'uncertain'"), + 'Terminal invoices must not poll while active payments and provisioning may resume.'); +$paymentExpiry = $section($invoiceDetailRuntime, + 'function onlinePaymentFallbackExpiresAt(', 'function invoiceNeedsPolling('); +$onlinePaymentRender = $section($invoiceDetailRuntime, + 'function renderOnlinePayment(', 'async function payInvoiceBalance('); +$detailHydration = $section($invoiceDetailRuntime, + 'function hydrateInvoiceDetail(', 'async function refreshInvoiceDetail('); +$assert(str_contains($invoiceDetailRuntime, 'function hasPendingInvoicePaymentKey(') + && str_contains($invoiceDetailRuntime, 'hasPendingInvoicePaymentKey(payload.invoice.id)') + && str_contains($invoiceDetailRuntime, 'resumeInvoicePolling();') + && str_contains($paymentExpiry, 'STATUS_POLL_MAX_LIFETIME_MS') + && str_contains($paymentExpiry, 'invoicePaymentDeadlineTimestamp(invoice)') + && str_contains($paymentExpiry, 'function onlinePaymentHasExpired(') + && str_contains($paymentExpiry, 'function expireOnlinePaymentInstructions(') + && str_contains($paymentExpiry, 'clearOnlinePaymentState(true);') + && str_contains($paymentExpiry, "makeElement('strong', '', '支付订单已过期')") + && str_contains($paymentExpiry, 'void refreshInvoiceDetail(invoiceId);') + && str_contains($onlinePaymentRender, 'paymentExpiresAt === null') + && str_contains($onlinePaymentRender, + 'onlinePaymentFallbackExpiresAt(state.selectedInvoice)') + && str_contains($onlinePaymentRender, 'scheduleOnlinePaymentExpiry(generation);') + && str_contains($detailHydration, + 'if (onlinePaymentHasExpired()) expireOnlinePaymentInstructions();') + && str_contains($detailHydration, 'state.onlinePaymentExpiresAt <= 0') + && !str_contains($detailHydration, 'state.onlinePaymentExpiresAt <= Date.now()') + && str_contains($invoiceDetailRuntime, 'STATUS_POLL_SLOW_INTERVAL_MS') + && str_contains($invoiceDetailRuntime, 'Date.now() < state.pollUntil'), + 'Provider payments must recover through a bounded fallback expiry and disable stale instructions.'); +$assert(str_contains($invoiceDetailRuntime, + 'function entersProvisioningAfterPayment(') + && substr_count($invoiceDetailRuntime, + 'entersProvisioningAfterPayment(') === 3 + && substr_count($invoiceDetailRuntime, + 'resetProvisioningPollWindow();') === 3 + && str_contains($invoiceDetailRuntime, + 'state.pollUntil = Math.max(state.pollUntil, state.onlinePaymentExpiresAt);'), + 'Provider and balance payment completion must preserve the correct provisioning poll window.'); +$assert(!str_contains($invoiceDetailModule, '/cloud/runtime.js') + && str_contains($invoiceDetailModule, '/cloud/invoice-detail-runtime.js') + && str_contains($invoiceDetailModule, 'readInvoiceDetailBootstrap()') + && str_contains($invoiceDetailModule, 'hydrateInvoiceDetail(bootstrap, invoiceId)') + && str_contains($invoiceDetailModule, + 'if (event.persisted) void refreshInvoiceDetail(invoiceId)') + && !str_contains($invoiceDetailModule, '/api/v1/invoices/') + && !str_contains($invoiceDetailModule, 'initializeSession') && !str_contains($invoiceDetailModule, 'setInterval(') && str_contains($invoiceDetailModule, "state.view = 'invoice-detail'"), - 'Invoice detail still creates an engine session or polls terminal bills forever.'); + 'Invoice detail must hydrate its SSR payload without the full runtime or an initial detail GET.'); +$assert(str_contains($invoiceDetailRuntime, 'readSequence: 0') + && str_contains($invoiceDetailRuntime, 'appliedReadSequence: 0') + && substr_count($invoiceDetailRuntime, + 'const readSequence = ++state.readSequence;') >= 2 + && str_contains($invoiceDetailRuntime, + 'if (readSequence < state.appliedReadSequence) return state.selectedInvoice;') + && str_contains($invoiceDetailRuntime, + 'readSequence >= state.appliedReadSequence'), + 'Invoice detail must prevent an older concurrent response from replacing newer state.'); +$schedulePoll = $section($invoiceDetailRuntime, 'function scheduleInvoicePoll(', + 'function resumeInvoicePolling('); +$refreshDetail = $section($invoiceDetailRuntime, 'async function refreshInvoiceDetail(', + 'let cleanupBound = false;'); +$assert(str_contains($schedulePoll, 'state.refreshPromise') + && str_contains($refreshDetail, 'stopInvoicePoll();') + && str_contains($refreshDetail, 'if (!controller.signal.aborted) resumeInvoicePolling();') + && strpos($refreshDetail, 'stopInvoicePoll();') + < strpos($refreshDetail, 'const readSequence = ++state.readSequence;'), + 'A full detail refresh must pause sparse status polling and resume it afterwards.'); +$balancePayment = $section($invoiceDetailRuntime, 'async function payInvoiceBalance(', + 'async function createInvoicePayment('); +$assert(str_contains($balancePayment, + 'state.appliedReadSequence = ++state.readSequence;') + && strpos($balancePayment, + 'state.appliedReadSequence = ++state.readSequence;') + < strpos($balancePayment, 'renderInvoiceDetail(paid,'), + 'A successful balance payment must invalidate every older in-flight read.'); +$assert(str_contains($balancePayment, + "const startsProvisioning = invoicePurpose(paid) === 'provision';") + && str_contains($balancePayment, + 'if (startsProvisioning) resetProvisioningPollWindow();') + && strpos($balancePayment, 'resetProvisioningPollWindow();') + < strpos($balancePayment, 'renderInvoiceDetail(paid,'), + 'Balance payment must start a fresh provisioning poll window before rendering paid state.'); +$assert(str_contains($balancePayment, + 'if ([403, 409].includes(Number(error.status || 0)))') + && str_contains($balancePayment, 'await refreshInvoiceDetail(invoice.id);'), + 'A deterministic balance-payment rejection must refresh server payable state.'); +$providerPayment = $section($invoiceDetailRuntime, + 'async function createInvoicePayment(', 'function renderInvoicePaymentMethods('); +$assert(str_contains($providerPayment, + "const creationStillInProgress = String(error.message).includes('正在创建');") + && str_contains($providerPayment, + 'if ([403, 409].includes(status) && !creationStillInProgress)') + && str_contains($providerPayment, 'await refreshInvoiceDetail(invoice.id);'), + 'A deterministic provider-payment rejection must refresh server payable state.'); +$paymentChoices = $section($invoiceDetailRuntime, + 'function renderInvoicePaymentMethods(', 'function invoiceProgressText('); +$assert(str_contains($invoiceDetailRuntime, 'balancePaymentAllowed: false') + && str_contains($invoiceDetailRuntime, + 'state.balancePaymentAllowed = payload?.balance_payment_allowed === true') + && str_contains($paymentChoices, 'if (state.balancePaymentAllowed)') + && str_contains($paymentChoices, 'if (!choices.length)') + && str_contains($paymentChoices, + 'state.selectedInvoicePaymentMethod = String(choices[0].id);'), + 'Restricted accounts must not be offered a balance-payment control.'); +$assert(!str_contains($invoiceDetailRuntime, "from '/cloud/runtime.js'") + && !str_contains($invoiceDetailRuntime, 'from "/cloud/runtime.js"') + && !str_contains($invoiceDetailRuntime, "import('/cloud/runtime.js')") + && !str_contains($invoiceDetailRuntime, 'import("/cloud/runtime.js")'), + 'The dedicated invoice runtime must not import the all-feature VM runtime.'); +$assert(!str_contains($legacyRuntime, 'function loadInvoiceDetail(') + && !str_contains($legacyRuntime, 'function renderInvoiceDetail(') + && !str_contains($legacyRuntime, 'INVOICE_PAYMENT_STORAGE_PREFIX'), + 'The all-feature VM runtime must not retain a second invoice-detail implementation.'); +$assert(!str_contains($cloudShell, '/theme/venix/js/qrcode.min.js') + && str_contains($invoiceDetailRuntime, "document.createElement('script')") + && str_contains($invoiceDetailRuntime, '/theme/venix/js/qrcode.min.js') + && str_contains($invoiceDetailRuntime, 'async function appendPaymentQr(') + && str_contains($invoiceDetailRuntime, 'paymentRenderGeneration: 0') + && str_contains($invoiceDetailRuntime, + 'generation !== state.paymentRenderGeneration') + && str_contains($invoiceDetailRuntime, + "'cloud-payment-qr cloud-payment-qr-loading'") + && str_contains($invoiceDetailRuntime, 'container.append(qr);') + && str_contains($invoiceDetailRuntime, + 'void appendPaymentQr(box, qrValue, generation)'), + 'The QR library must be loaded only after an online payment order is created.'); +$cleanup = $section($invoiceDetailRuntime, 'function bindInvoiceDetailCleanup(', + 'export {'); +$assert(str_contains($cleanup, 'clearTimeout(toastTimer);') + && str_contains($cleanup, 'toastTimer = null;') + && str_contains($cleanup, "const element = byId('toast');") + && str_contains($cleanup, 'if (element) element.hidden = true;'), + 'BFCache cleanup must not restore a visible toast after cancelling its timer.'); +$createPayment = $section($invoiceDetailRuntime, 'async function createInvoicePayment(', + 'function renderInvoicePaymentMethods('); +$paymentRequest = strpos($createPayment, + 'api(`/api/v1/invoices/${encodeURIComponent(invoice.id)}/payments`'); +$paymentRender = strpos($createPayment, + 'renderOnlinePayment(paymentResult, result.payment || {})'); +$assert($paymentRequest !== false && $paymentRender !== false + && $paymentRequest < $paymentRender, + 'QR/payment instructions must be rendered only after payment-order creation succeeds.'); $displayMethod = $section($invoiceService, 'public static function display(', 'public static function payBalance('); +$assert(str_contains($invoiceService, 'private static function publicState(') + && str_contains($invoiceService, 'private static function publicStatus(') + && substr_count($invoiceService, + 'self::publicStatus($invoice, $purpose, $instance, $now)') === 2 + && substr_count($invoiceService, + 'self::publicState($invoice, $purpose, $order, $instance, $now)') === 2, + 'Invoice list, full detail and lightweight status must share one public-state rule.'); +$assert(str_contains($statusService, + "->where('user_id', \$invoice->user_id)") + && str_contains($statusService, '$instanceId = $linkedInstance?->id;'), + 'Polling must validate the linked instance owner before exposing its id.'); $assert(str_contains($displayMethod, "'recharge' => '余额充值'") && str_contains($displayMethod, "'provision' => '实例开通'") && str_contains($displayMethod, "'renewal' => '实例续费'") @@ -130,6 +365,12 @@ $assert(str_contains($displayMethod, "'recharge' => '余额充值'") 'Invoice purpose labels are incomplete.'); $assert(!str_contains($displayMethod, "'invoice_no' =>"), 'The internal invoice number is still exposed to users.'); +$assert(!str_contains($displayMethod, "'payment_reference' =>") + && !str_contains($invoiceDetailPageService, "'invoice_no' =>") + && !str_contains($invoiceDetailPageService, "'payment_reference' =>") + && !str_contains($invoiceDetailTemplate, 'invoice_no') + && !str_contains($invoiceDetailTemplate, 'payment_reference'), + 'Invoice-detail HTML/bootstrap sources expose internal payment identifiers.'); $assert(substr_count($displayMethod, "->where('user_id', \$invoice->user_id)") >= 3, 'Invoice associations are not constrained to the invoice owner.'); $assert(str_contains($invoiceModel, "protected \$hidden = ['invoice_no', 'payment_reference']"), diff --git a/web/tests/CloudInvoiceListPerformanceContractTest.php b/web/tests/CloudInvoiceListPerformanceContractTest.php index f438ae52..f065c78f 100644 --- a/web/tests/CloudInvoiceListPerformanceContractTest.php +++ b/web/tests/CloudInvoiceListPerformanceContractTest.php @@ -40,9 +40,8 @@ $assert(!str_contains($module, '/cloud/runtime.js') && str_contains($module, "'needs_attention'].includes(fulfillmentStatus(invoice))") && !str_contains($module, 'setInterval('), 'Invoice list module must be lightweight and stop polling terminal records.'); -$assert(str_contains($shell, "if \$cloud_page == 'invoice-detail'") - && !str_contains($shell, "if \$cloud_page == 'invoices' || \$cloud_page == 'invoice-detail'"), - 'QR code assets must only load on the payment detail page.'); +$assert(!str_contains($shell, '/theme/venix/js/qrcode.min.js'), + 'The shared cloud shell must not block first paint on the QR code library.'); $assert(str_contains($topbar, "\$user->user_name|default:'账户'") && !str_contains($topbar, '{if $panel_cloud_mode}账户{else}'), 'Cloud pages must render the authenticated account name without a session API request.'); diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index a49f806c..425d3c4b 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -48,6 +48,11 @@ foreach (['instances', 'detail', 'deploy', 'iso-images', 'ssh-keys', 'invoices', $assert(is_file($path), 'Cloud page module missing: ' . $module); $clientScript .= "\n" . file_get_contents($path); } +$invoiceDetailRuntimePath = $public . '/invoice-detail-runtime.js'; +$assert(is_file($invoiceDetailRuntimePath), + 'Dedicated invoice-detail runtime missing: invoice-detail-runtime.js'); +$invoiceDetailModule = file_get_contents($public . '/invoice-detail.js'); +$invoiceDetailRuntime = file_get_contents($invoiceDetailRuntimePath); $clientStyles = file_get_contents($public . '/client.css'); $baseStyles = file_get_contents($public . '/styles.css'); $routes = file_get_contents($root . '/config/routes.php'); @@ -63,6 +68,10 @@ $templateAdmin = file_get_contents($views . '/admin/cloud/templates.tpl'); $rescueAdmin = file_get_contents($views . '/admin/cloud/rescue.tpl'); $adminScript = file_get_contents($public . '/admin.js'); $cloudAdminController = file_get_contents($root . '/app/Controllers/CloudAdminController.php'); +$cloudRoutes = file_get_contents($root . '/config/routes_cloud.php'); +$cloudSchema = file_get_contents($root . '/sql/cloud.sql'); +$templateDeletionService = file_get_contents( + $root . '/app/Services/Cloud/CloudTemplateDeletionService.php'); $assert(str_contains($cloudShell, "file='user/panel_sidebar.tpl'") && str_contains($userLayout, "file='user/panel_sidebar.tpl'"), 'Cloud and account pages must share one sidebar partial'); $assert(str_contains($cloudShell, "file='user/panel_topbar.tpl'") @@ -508,9 +517,38 @@ $globalAdmin = $globalAdminStart === false || $globalAdminEnd === false ? '' : substr($cloudAdminController, $globalAdminStart, $globalAdminEnd - $globalAdminStart); $assert(str_contains($globalAdmin, "'/internal/v1/vm-templates'") && str_contains($globalAdmin, "unset(\$body['host_id'])") - && !str_contains($globalAdmin, 'filter_var(') + && !str_contains($globalAdmin, "filter_var(\$body['host_id']") && !str_contains($globalAdmin, '->host('), 'The PHP admin proxy must use the global engine catalog without a host dependency.'); +$assert(str_contains($cloudRoutes, "['PATCH', 'DELETE']") + && str_contains($adminScript, '删除全局云镜像模版') + && str_contains($adminScript, "method: 'DELETE'") + && str_contains($templateAdmin, '已创建实例使用独立克隆磁盘') + && str_contains($globalAdmin, 'CloudTemplateDeletionService::begin') + && str_contains($globalAdmin, 'CloudTemplateDeletionService::complete') + && str_contains($globalAdmin, 'CloudTemplateDeletionService::queueImport') + && str_contains($globalAdmin, 'CloudTemplateDeletionService::fetchAuthoritativeCatalog') + && str_contains($globalAdmin, 'CloudTemplateDeletionService::reactivateImportedTemplate') + && !str_contains($globalAdmin, 'if ($currentTemplate)') + && str_contains($globalAdmin, 'CloudDeploymentPageService::rememberTemplateCatalog') + && str_contains($globalAdmin, + "\$error->getMessage() === '云镜像模板不存在'") + && str_contains($adminScript, 'created_at: Number(entry.created_at)'), + 'Global cloud templates must expose a confirmed, retryable admin deletion flow.'); +$assert(str_contains($cloudSchema, 'CREATE TABLE IF NOT EXISTS cloud_template_retirements') + && str_contains($cloudSchema, 'CREATE TABLE IF NOT EXISTS cloud_template_catalog_locks') + && str_contains($cloudSchema, 'template_created_at BIGINT UNSIGNED') + && str_contains($templateDeletionService, "'awaiting_payment', 'queued', 'running', 'uncertain'") + && str_contains($templateDeletionService, "whereIn('kind', ['create', 'reinstall'])") + && str_contains($templateDeletionService, 'lockForUpdate()') + && str_contains($templateDeletionService, "where('state', 'deleting')->exists()") + && str_contains($templateDeletionService, 'reconcileAuthoritativeCatalog') + && !str_contains($templateDeletionService, 'array_slice($templates') + && str_contains($deploymentPageService, 'availableTemplates(') + && str_contains($deploymentPageService, + 'CloudTemplateDeletionService::fetchAuthoritativeCatalog') + && str_contains($deploymentPageService, 'forgetTemplate('), + 'Template retirement must block active provisioning/reinstall references and stale SSR catalogs.'); $assert(str_contains($adminScript, 'function unixTime(value)') && str_contains($adminScript, 'orderStatus(record.status)'), 'Order diagnostics must format timestamps and localize task status'); @@ -539,15 +577,18 @@ $assert(str_contains($sharedSidebar, 'href="/user/cloud/invoices"') && str_contains($cloudTemplate, 'id="invoices-workspace"') && str_contains($cloudTemplate, 'id="invoice-detail-workspace"') && str_contains($sharedSidebar, '>账单信息') - && str_contains($clientScript, '/pay-balance') - && str_contains($clientScript, '/payments'), + && str_contains($invoiceDetailRuntime, '/pay-balance') + && str_contains($invoiceDetailRuntime, '/payments'), 'Unified invoices must support balance and online payment paths'); $assert(str_contains($clientEntry, "'invoice-detail': '/cloud/invoice-detail.js'") && str_contains($cloudShell, 'data-invoice-id=') && str_contains($cloudShell, "panel_cloud_active='invoices'") - && str_contains($clientScript, 'function loadInvoiceDetail(') - && str_contains($clientScript, 'api(`/api/v1/invoices/${encodeURIComponent(id)}`)'), - 'Invoice details must use an independent module while retaining the billing navigation state.'); + && str_contains($invoiceDetailModule, '/cloud/invoice-detail-runtime.js') + && str_contains($invoiceDetailModule, 'readInvoiceDetailBootstrap()') + && str_contains($invoiceDetailModule, 'hydrateInvoiceDetail(bootstrap, invoiceId)') + && !str_contains($invoiceDetailModule, '/cloud/runtime.js') + && !str_contains($invoiceDetailModule, '/api/v1/invoices/'), + 'Invoice details must hydrate SSR data through a dedicated lightweight module.'); $assert(str_contains($clientScript, "recharge: '余额充值', provision: '实例开通', renewal: '实例续费'") && str_contains($clientScript, '`账单 #${invoice.id} · ${formatOrderDate(invoice.created_at)}`') && str_contains($clientScript, "makeElement('div', 'cloud-invoice-list-amount')") @@ -556,6 +597,10 @@ $assert(str_contains($clientScript, "recharge: '余额充值', provision: '实 'Invoice rows must use short database IDs, type labels, a right-aligned amount and a detail link.'); $runtimeScript = file_get_contents($public . '/runtime.js'); $invoicesModule = file_get_contents($public . '/invoices.js'); +$assert(!str_contains($runtimeScript, 'function loadInvoiceDetail(') + && !str_contains($runtimeScript, 'function renderInvoiceDetail(') + && !str_contains($runtimeScript, 'INVOICE_PAYMENT_STORAGE_PREFIX'), + 'The all-feature VM runtime must not duplicate invoice-detail behavior.'); $invoiceLoaderStart = strpos($runtimeScript, 'async function loadInvoices('); $invoiceLoaderEnd = $invoiceLoaderStart === false ? false : strpos($runtimeScript, 'async function openReinstall(', $invoiceLoaderStart); @@ -582,16 +627,17 @@ $assert(str_contains($invoicesModule, "byId('invoices-previous')") 'Invoice pages must hydrate the server-rendered first page and fetch only guarded later pages.'); $assert(str_contains($cloudTemplate, 'id="invoice-payment-methods"') && str_contains($cloudTemplate, 'id="invoice-payment-submit"') - && str_contains($clientScript, "{ id: 'balance', name: '账户余额'") - && str_contains($clientScript, "card.setAttribute('aria-pressed'") + && str_contains($invoiceDetailRuntime, "id: 'balance'") + && str_contains($invoiceDetailRuntime, "name: '账户余额'") + && str_contains($invoiceDetailRuntime, "card.setAttribute('aria-pressed'") && str_contains($clientStyles, '.invoice-payment-method-card[aria-pressed="true"]') - && str_contains($clientScript, 'renderInvoiceSpecification(invoice)') - && str_contains($clientScript, 'renderInvoiceFulfillment(invoice)'), + && str_contains($invoiceDetailRuntime, 'renderInvoiceSpecification(invoice)') + && str_contains($invoiceDetailRuntime, 'renderInvoiceFulfillment(invoice)'), 'Invoice detail must isolate plan data and expose one card-based payment selector.'); -$assert(str_contains($clientScript, "uncertain: ['正在核对结果', 'warning']") - && !str_contains($clientScript, "'needs_attention', 'uncertain'].includes(status)") - && str_contains($clientScript, 'invoiceJobProgress: new Map()') - && str_contains($clientScript, 'job?.phase'), +$assert(str_contains($invoiceDetailRuntime, "uncertain: ['正在核对结果', 'warning']") + && !str_contains($invoiceDetailRuntime, "'needs_attention', 'uncertain'].includes(status)") + && str_contains($invoiceDetailRuntime, 'invoiceJobProgress: new Map()') + && str_contains($invoiceDetailRuntime, 'job?.phase'), 'Uncertain provisioning must remain non-terminal and continue reconciliation.'); $assert(!str_contains($sharedSidebar, 'data-view="orders"') && !str_contains($cloudTemplate, 'id="orders-workspace"') @@ -601,35 +647,43 @@ $assert(!str_contains($sharedSidebar, 'data-view="orders"') $assert(str_contains($cloudTemplate, '>生成开通账单') && str_contains($clientScript, "api('/api/v1/invoices', { method: 'POST', body })") && str_contains($clientScript, '/api/v1/invoices/by-request/') - && str_contains($clientScript, "invoice?.purpose") - && str_contains($clientScript, 'appendProvisionInvoiceActions(invoice, detail, actions)') - && str_contains($clientScript, "makeElement('a', 'row-button', '查看实例')"), + && str_contains($invoiceDetailRuntime, "invoice?.purpose") + && str_contains($invoiceDetailRuntime, 'appendProvisionInvoiceActions(invoice, detail, actions)') + && str_contains($invoiceDetailRuntime, "makeElement('a', 'row-button', '查看实例')"), 'Instance deployment must create a recoverable invoice and expose fulfillment inside billing'); -$assert(str_contains($cloudTemplate, "cloud_page == 'invoice-detail'") - && !str_contains($cloudTemplate, "cloud_page == 'invoices' || \$cloud_page == 'invoice-detail'") - && 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)'), +$assert(!str_contains($cloudShell, '/theme/venix/js/qrcode.min.js') + && str_contains($invoiceDetailRuntime, "document.createElement('script')") + && str_contains($invoiceDetailRuntime, '/theme/venix/js/qrcode.min.js') + && str_contains($invoiceDetailRuntime, "'weixin:', 'alipays:', 'alipayqr:'") + && str_contains($invoiceDetailRuntime, + 'void appendPaymentQr(box, qrValue, generation)'), + 'Invoice online payments must lazy-load local QR rendering after creating a payment order.'); +$assert(str_contains($invoiceDetailRuntime, 'INVOICE_PAYMENT_STORAGE_PREFIX') + && str_contains($invoiceDetailRuntime, '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, +$assert(str_contains($invoiceDetailRuntime, 'function invoiceNeedsPolling(') + && str_contains($invoiceDetailRuntime, + 'api(`/api/v1/invoices/${encodeURIComponent(state.pollInvoiceId)}/status`') + && str_contains($invoiceDetailRuntime, 'stopInvoicePoll();') + && !str_contains($invoiceDetailRuntime, 'setInterval(') + && substr_count($invoiceDetailRuntime, "container.querySelectorAll('button').forEach(button => { button.disabled = false; });") >= 2, - 'Concurrent invoice polling and failed payment attempts must remain recoverable'); -$assert(str_contains($clientScript, 'function invoiceDeletionTimestamp(invoice)') - && str_contains($clientScript, 'invoice?.deletion_at') - && str_contains($clientScript, 'function invoiceCanPay(invoice)') - && substr_count($clientScript, 'if (!invoiceCanPay(invoice))') >= 2 - && str_contains($clientScript, "panel.hidden = true; container.replaceChildren(); result.replaceChildren();") - && str_contains($clientScript, '已超过支付截止时间'), + 'Active invoice polling must use the lightweight status endpoint and remain recoverable.'); +$assert(!str_contains($invoiceDetailRuntime, '/api/v1/jobs/') + && str_contains($invoiceDetailRuntime, "actionButton('查看创建进度'") + && str_contains($invoiceDetailRuntime, + '/api/v1/invoices/${encodeURIComponent(invoice.id)}/status'), + 'Invoice creation progress must not load the general job payload or a cloud session.'); +$assert(str_contains($invoiceDetailRuntime, 'function invoiceDeletionTimestamp(invoice)') + && str_contains($invoiceDetailRuntime, 'invoice?.deletion_at') + && str_contains($invoiceDetailRuntime, 'function invoiceCanPay(invoice)') + && substr_count($invoiceDetailRuntime, 'if (!invoiceCanPay(invoice))') >= 2 + && str_contains($invoiceDetailRuntime, "panel.hidden = true; container.replaceChildren();") + && str_contains($invoiceDetailRuntime, '已超过支付截止时间'), 'Invoice UI must show the deletion deadline and hide every payment path after the cutoff'); -$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)'), +$assert(str_contains($invoiceDetailRuntime, 'status >= 400 && status < 500') + && str_contains($invoiceDetailRuntime, 'const ambiguousHttpFailure = [408, 425, 429].includes(status)') + && str_contains($invoiceDetailRuntime, 'pendingInvoicePaymentKey(invoice.id, method.id)'), 'Ambiguous 5xx or transport failures must retain the provider idempotency key'); $assert(!str_contains($clientScript, '/renewals') && !str_contains($cloudTemplate, '续费周期'),