diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 5d16db55..e7ef0e3f 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -160,7 +160,7 @@ libvirt 的持久 pool 定义就是 Agent 后续使用的映射,不另写存 公网网络接入在宿主机的“网络接入”中按资源池线路独立配置,可使用 `bridge:br0`、其他 Linux 网桥或 `network:default` 这样的 libvirt network。名称以字母或数字开头,后续只能包含字母、数字、点、下划线和短横线,bridge 名称为 1~15 字符,libvirt network 名称为 1~64 字符。宿主机上的公网网桥或 libvirt network 必须由运维预先准备。Agent 只发现、验证和使用现有公网网络,不创建公网网桥、不启动 libvirt network,也不修改公网地址、上游网关或挂载。`cloud_hosts.default_network` 仅保留为兼容展示值,不参与 Agent 就绪、调度、恢复、迁移或换 IP 决策;真正的运行时权威是资源池线路、当前 Agent 代次已验证的网络接入,以及绑定该接入的公网地址池。VPC 使用下述独立的 Agent 受管 bridge 和 L3 路由,不改变这一公网边界。 -当前完整 schema 版本为 `go-agent-wss-v46-abuse-alert-delivery`。从 v44 升级时,必须先停止滥用观测与投影 worker,为既有 finding 回填 `occurrence_generation = 1` 与 `transition_revision = 1`,再创建 `cloud_abuse_alert_events` 和 `cloud_abuse_alert_event_items`;从 v45 升级还必须停止通知 worker,创建 `cloud_abuse_alert_deliveries`、`administrator_telegram_delivery_gate` 并写入唯一 gate 行。历史 finding 不反向合成事件;事件只从升级后主库事务内真实发生的 `opened`、`escalated` 和 `evidence_clear` 解决转移产生。完成列、约束、索引、外键和 gate 核对后,先恢复滥用观测,再恢复通知 worker。 +当前完整 schema 版本为 `go-agent-wss-v47-offer-billing-cycles`。v47 为 `cloud_offers` 增加季度、年度及对应自动备份价格;既有方案升级时必须在恢复销售前显式回填 90/365 天价格,不能让数据库默认零价进入购买目录。从 v44 升级时,必须先停止滥用观测与投影 worker,为既有 finding 回填 `occurrence_generation = 1` 与 `transition_revision = 1`,再创建 `cloud_abuse_alert_events` 和 `cloud_abuse_alert_event_items`;从 v45 升级还必须停止通知 worker,创建 `cloud_abuse_alert_deliveries`、`administrator_telegram_delivery_gate` 并写入唯一 gate 行。历史 finding 不反向合成事件;事件只从升级后主库事务内真实发生的 `opened`、`escalated` 和 `evidence_clear` 解决转移产生。完成列、约束、索引、外键和 gate 核对后,先恢复滥用观测,再恢复通知 worker。 事件 header 与 projection receipt 在同一个主库事务中写入,且事件先于 receipt;同一实例同一采样桶的多规则、双协议族转移合并为一个 header 和多个 item。`continued` 不产生事件,`policy_replaced` 与 `owner_changed` 只关闭 finding,不能伪造“恢复”事件。item 已冻结当时的聚合 evidence、规则身份和 finding 代次,后续投递不得回读会变化的 finding。v46 为每个事件建立至多一条 Telegram 投递决策;远端调用开始后的中断或回执不确定统一进入 `unknown`,禁止自动重放。删除用户时按事件冻结的 `user_id` 显式删除 header,item 与投递账本按当前外键和账户清理规则收敛,避免实例转交后遗留原租户数据。 diff --git a/docs/SERVICE_COMPENSATION.md b/docs/SERVICE_COMPENSATION.md index 5e7668d3..0efc58ae 100644 --- a/docs/SERVICE_COMPENSATION.md +++ b/docs/SERVICE_COMPENSATION.md @@ -47,7 +47,7 @@ ## 部署 -全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v46-abuse-alert-delivery` 完整 schema;其中补偿模块包括: +全新数据库必须由当前 `CloudSetup` 创建并验证 `go-agent-wss-v47-offer-billing-cycles` 完整 schema;其中补偿模块包括: - `cloud_service_compensations`; - `cloud_service_compensation_items`; diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index d4e9a239..1eb04664 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -8,7 +8,7 @@ use App\Services\Config; /** Initializes only the clean-break PHP business and Agent log schemas. */ final class CloudSetup { - private const SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'; + private const SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'; /** Tables installed by ss.sql before cloudInit and owned by this schema. */ private const PREINSTALLED_MAIN_TABLES = [ 'ui_copy_locales', 'ui_copy_entries', 'ui_copy_drafts', @@ -266,7 +266,9 @@ final class CloudSetup 'created_at', 'updated_at', ], 'cloud_offers' => [ - 'backup_price', + 'price', 'quarterly_price', 'annual_price', + 'backup_price', 'backup_quarterly_price', + 'backup_annual_price', ], 'cloud_jobs' => [ 'id', 'operation_id', 'request_idempotency_key', diff --git a/web/app/Controllers/Admin/ShopController.php b/web/app/Controllers/Admin/ShopController.php index 25379ade..f4d64b20 100644 --- a/web/app/Controllers/Admin/ShopController.php +++ b/web/app/Controllers/Admin/ShopController.php @@ -26,7 +26,7 @@ class ShopController extends AdminController 'op' => '操作', 'id' => 'ID', 'name' => '基础套餐', 'cpu_cores' => 'CPU 核数', 'memory_gb' => '内存 GB', 'bandwidth_mbps' => '带宽 Mbps', 'disk_gib' => '磁盘 GB', - 'validity_days' => '每期天数', 'traffic_tb' => '每期流量 TB', + 'traffic_tb' => '每个服务周期流量 TB', 'offer_count' => '销售方案', 'active_offer_count' => '已上架方案', 'price_range' => '美元价格区间', 'status' => '套餐状态', 'sort' => '排序', ]; @@ -187,7 +187,7 @@ class ShopController extends AdminController $input = []; foreach ([ 'name', 'cpu_cores', 'memory_gb', 'bandwidth_mbps', 'disk_gib', - 'validity_days', 'traffic_tb', 'status', 'sort', + 'traffic_tb', 'status', 'sort', ] as $field) { $default = $shop->exists ? match ($field) { @@ -198,6 +198,11 @@ class ShopController extends AdminController : null; $input[$field] = $request->getParam($field, $default); } + // Service length is selected from the offer's fixed 30/90/365-day + // cycles. Keep the legacy base-plan column canonical and hidden; + // it is no longer an administrator-controlled billing term. + $input['validity_days'] = + CloudOffer::BILLING_CYCLES['monthly']['days']; $values = Shop::validatePlan($input); $now = time(); foreach ($values as $field => $value) { @@ -244,8 +249,10 @@ class ShopController extends AdminController } $input = []; foreach ([ - 'resource_pool_id', 'name', 'price', 'backup_price', 'stock', - 'status', 'sort', + 'resource_pool_id', 'name', + 'price', 'quarterly_price', 'annual_price', + 'backup_price', 'backup_quarterly_price', + 'backup_annual_price', 'stock', 'status', 'sort', ] as $field) { $input[$field] = $request->getParam($field, $offer === null ? null : $offer->$field); } @@ -315,10 +322,18 @@ class ShopController extends AdminController throw new \InvalidArgumentException('销售方案系统标识已被使用'); } - $priceChanged = $locked->exists - && ((string) $locked->price !== (string) $values['price'] - || (string) $locked->backup_price - !== (string) $values['backup_price']); + $priceChanged = false; + if ($locked->exists) { + foreach ([ + 'price', 'quarterly_price', 'annual_price', + 'backup_price', 'backup_quarterly_price', + 'backup_annual_price', + ] as $priceField) { + $priceChanged = $priceChanged + || (string) $locked->$priceField + !== (string) $values[$priceField]; + } + } foreach ($values as $field => $value) { if ($locked->exists && $field === 'code') { continue; @@ -468,13 +483,17 @@ class ShopController extends AdminController $lineFeatureEnabled ? (string) $offer->line_name : '', (string) $offer->pool_name, ], static fn ($value) => $value !== ''))), - 'price' => '$' . number_format((float) $offer->price, 2, '.', ''), - 'backup_price' => '$' . number_format( - (float) $offer->backup_price, - 2, - '.', - '' - ), + 'prices' => [ + '30 天' => '$' . number_format( + (float) $offer->price, 2, '.', '' + ), + '90 天' => '$' . number_format( + (float) $offer->quarterly_price, 2, '.', '' + ), + '365 天' => '$' . number_format( + (float) $offer->annual_price, 2, '.', '' + ), + ], 'price_version' => (int) $offer->price_version, 'stock' => (int) $offer->stock, 'status' => (bool) $offer->status, @@ -520,7 +539,7 @@ class ShopController extends AdminController $table = new Datatables(new DatatablesHelper()); $table->query('SELECT shop.id AS op,shop.id,shop.name,shop.cpu_cores,' . 'ROUND(shop.memory_mib/1024,1) AS memory_gb,shop.bandwidth_mbps,shop.disk_gib,' - . 'shop.validity_days,CASE WHEN shop.traffic_quota_bytes=0 THEN 0 ' + . 'CASE WHEN shop.traffic_quota_bytes=0 THEN 0 ' . 'ELSE ROUND(shop.traffic_quota_bytes/1099511627776,10) END AS traffic_tb,' . '(SELECT COUNT(*) FROM cloud_offers offer WHERE offer.plan_id=shop.id) AS offer_count,' . '(SELECT COUNT(*) FROM cloud_offers offer WHERE offer.plan_id=shop.id AND offer.status=1) AS active_offer_count,' diff --git a/web/app/Controllers/CloudPageController.php b/web/app/Controllers/CloudPageController.php index caec1803..dad648fe 100644 --- a/web/app/Controllers/CloudPageController.php +++ b/web/app/Controllers/CloudPageController.php @@ -166,6 +166,28 @@ final class CloudPageController break; } } + $defaultCyclePrices = []; + foreach (($defaultOffer['billing_cycles'] ?? []) as $cycle) { + if (is_array($cycle) && isset($cycle['code'], $cycle['price'])) { + $defaultCyclePrices[(string) $cycle['code']] = + (float) $cycle['price']; + } + } + $formatCyclePrice = static function ( + array $prices, + string $cycle, + int $divisor = 1 + ): string { + if (!array_key_exists($cycle, $prices)) { + return ''; + } + return '$' . number_format( + $prices[$cycle] / $divisor, + 2, + '.', + '' + ) . ' USD'; + }; $payload = [ 'user' => $this->userBootstrap($user, $actor), 'regions' => $regions, @@ -195,8 +217,28 @@ final class CloudPageController 'cloud_deploy_default_region_id' => $defaultRegionId, 'cloud_deploy_default_line_id' => $defaultLineId, 'cloud_deploy_default_offer_id' => $defaultOfferId, - 'cloud_deploy_price' => $defaultOffer === null ? '' - : '$' . number_format((float) $defaultOffer['price'], 2, '.', '') . ' USD', + 'cloud_deploy_price' => $formatCyclePrice( + $defaultCyclePrices, + 'monthly' + ), + 'cloud_deploy_quarterly_price' => $formatCyclePrice( + $defaultCyclePrices, + 'quarterly' + ), + 'cloud_deploy_quarterly_equivalent' => $formatCyclePrice( + $defaultCyclePrices, + 'quarterly', + 3 + ), + 'cloud_deploy_annual_price' => $formatCyclePrice( + $defaultCyclePrices, + 'annual' + ), + 'cloud_deploy_annual_equivalent' => $formatCyclePrice( + $defaultCyclePrices, + 'annual', + 12 + ), 'cloud_deploy_backup_price' => $defaultOffer === null ? '' : '$' . number_format((float) $defaultOffer['backup_price'], 2, '.', '') . ' USD', 'cloud_deploy_snapshot' => $cloudSnapshot, diff --git a/web/app/Models/CloudOffer.php b/web/app/Models/CloudOffer.php index fafa15ed..a160e493 100644 --- a/web/app/Models/CloudOffer.php +++ b/web/app/Models/CloudOffer.php @@ -4,6 +4,24 @@ namespace App\Models; final class CloudOffer extends Model { + public const BILLING_CYCLES = [ + 'monthly' => [ + 'days' => 30, + 'price_field' => 'price', + 'backup_price_field' => 'backup_price', + ], + 'quarterly' => [ + 'days' => 90, + 'price_field' => 'quarterly_price', + 'backup_price_field' => 'backup_quarterly_price', + ], + 'annual' => [ + 'days' => 365, + 'price_field' => 'annual_price', + 'backup_price_field' => 'backup_annual_price', + ], + ]; + protected $connection = 'default'; protected $table = 'cloud_offers'; @@ -12,7 +30,11 @@ final class CloudOffer extends Model 'plan_id' => 'int', 'resource_pool_id' => 'int', 'price' => 'decimal:2', + 'quarterly_price' => 'decimal:2', + 'annual_price' => 'decimal:2', 'backup_price' => 'decimal:2', + 'backup_quarterly_price' => 'decimal:2', + 'backup_annual_price' => 'decimal:2', 'price_version' => 'int', 'revision' => 'int', 'status' => 'boolean', @@ -45,22 +67,25 @@ final class CloudOffer extends Model throw new \InvalidArgumentException('销售名称需为 1 至 128 个字符'); } - $normalizedPrice = self::normalizePrice( - $input['price'] ?? '', - '实例价格' - ); - $normalizedBackupPrice = self::normalizePrice( - $input['backup_price'] ?? '', - '自动备份价格' - ); $data = [ 'resource_pool_id' => (int) $poolId, 'code' => $code, 'name' => $name, - 'price' => $normalizedPrice, - 'backup_price' => $normalizedBackupPrice, 'currency' => 'USD', ]; + foreach ([ + 'price' => '实例月付价格', + 'quarterly_price' => '实例季度价格', + 'annual_price' => '实例年付价格', + 'backup_price' => '自动备份月付价格', + 'backup_quarterly_price' => '自动备份季度价格', + 'backup_annual_price' => '自动备份年付价格', + ] as $field => $label) { + $data[$field] = self::normalizePrice( + $input[$field] ?? '', + $label + ); + } foreach ([ 'status' => [0, 1, 1, '销售状态'], 'stock' => [-1, 2147483647, -1, '库存'], @@ -80,6 +105,56 @@ final class CloudOffer extends Model return $data; } + public static function normalizeBillingCycle($value): string + { + if (!is_string($value) || !isset(self::BILLING_CYCLES[$value])) { + throw new \InvalidArgumentException('请选择有效的购买周期'); + } + return $value; + } + + public static function billingCycleForDays(int $days): string + { + foreach (self::BILLING_CYCLES as $code => $definition) { + if ($definition['days'] === $days) { + return $code; + } + } + throw new \InvalidArgumentException('实例服务周期不受销售方案支持'); + } + + /** + * Return the exact mutable offer prices selected by a stable cycle code. + * Callers must freeze this snapshot into their order or instance ledger. + */ + public function billingCycle(string $code): array + { + $code = self::normalizeBillingCycle($code); + $definition = self::BILLING_CYCLES[$code]; + $priceField = $definition['price_field']; + $backupPriceField = $definition['backup_price_field']; + return [ + 'code' => $code, + 'days' => $definition['days'], + 'price' => (string) $this->$priceField, + 'backup_price' => (string) $this->$backupPriceField, + ]; + } + + public function billingCycleForServiceDays(int $days): array + { + return $this->billingCycle(self::billingCycleForDays($days)); + } + + public function billingCycles(): array + { + $cycles = []; + foreach (array_keys(self::BILLING_CYCLES) as $code) { + $cycles[] = $this->billingCycle($code); + } + return $cycles; + } + private static function normalizePrice($value, string $label): string { if ((!is_string($value) && !is_int($value)) diff --git a/web/app/Services/Cloud/CloudAutomaticBackupBillingService.php b/web/app/Services/Cloud/CloudAutomaticBackupBillingService.php index 4f655014..ed8528d2 100644 --- a/web/app/Services/Cloud/CloudAutomaticBackupBillingService.php +++ b/web/app/Services/Cloud/CloudAutomaticBackupBillingService.php @@ -493,8 +493,25 @@ final class CloudAutomaticBackupBillingService throw new CloudError('自动备份周期权益账本不一致', 409); } } - $fullPriceCents = CloudMoney::cents((string) ($subscription === null - ? $offer->backup_price : $subscription->price)); + if ($subscription === null) { + try { + $billingCycle = $offer->billingCycleForServiceDays( + (int) $instance->renewal_days + ); + } catch (\InvalidArgumentException $exception) { + throw new CloudError( + '实例续费周期不受自动备份销售方案支持', + 409 + ); + } + $fullPriceCents = CloudMoney::cents( + $billingCycle['backup_price'] + ); + } else { + $fullPriceCents = CloudMoney::cents( + (string) $subscription->price + ); + } $priceVersion = $subscription === null ? (int) $offer->price_version : (int) $subscription->price_version; diff --git a/web/app/Services/Cloud/CloudAutomaticBackupService.php b/web/app/Services/Cloud/CloudAutomaticBackupService.php index 5ed8e38f..10c991df 100644 --- a/web/app/Services/Cloud/CloudAutomaticBackupService.php +++ b/web/app/Services/Cloud/CloudAutomaticBackupService.php @@ -142,7 +142,14 @@ final class CloudAutomaticBackupService || strtoupper((string) $offer->currency) !== 'USD') { throw new CloudError('升级后的自动备份价格账本不一致', 409); } - $price = self::moneySnapshot($offer->backup_price); + try { + $billingCycle = $offer->billingCycleForServiceDays( + (int) $instance->renewal_days + ); + } catch (\InvalidArgumentException $exception) { + throw new CloudError('实例续费周期不受自动备份销售方案支持', 409); + } + $price = self::moneySnapshot($billingCycle['backup_price']); $subscription->offer_id = (int) $offer->id; $subscription->price = $price; $subscription->price_version = (int) $offer->price_version; diff --git a/web/app/Services/Cloud/CloudDeploymentPageService.php b/web/app/Services/Cloud/CloudDeploymentPageService.php index 95f41bee..31594977 100644 --- a/web/app/Services/Cloud/CloudDeploymentPageService.php +++ b/web/app/Services/Cloud/CloudDeploymentPageService.php @@ -47,9 +47,11 @@ final class CloudDeploymentPageService ->get([ 'offer.id as offer_id', 'offer.name as offer_name', 'offer.price as offer_price', 'offer.stock as offer_stock', - 'offer.backup_price', + 'offer.quarterly_price', 'offer.annual_price', + 'offer.backup_price', 'offer.backup_quarterly_price', + 'offer.backup_annual_price', 'plan.cpu_cores', 'plan.memory_mib', 'plan.bandwidth_mbps', - 'plan.disk_gib', 'plan.validity_days', 'plan.traffic_quota_bytes', + 'plan.disk_gib', 'plan.traffic_quota_bytes', 'pool.id as internal_pool_id', 'line.id as line_id', 'line.name as line_name', 'line.is_default', 'region.id as region_id', 'region.name as region_name', @@ -101,6 +103,28 @@ final class CloudDeploymentPageService $trafficBytes = max(0, (int) $row->traffic_quota_bytes); $trafficGiB = intdiv($trafficBytes, self::GIB); $offerCapacityKey = $capacityKey($row); + $billingCycles = []; + foreach (CloudOffer::BILLING_CYCLES as $code => $definition) { + $priceField = $definition['price_field'] === 'price' + ? 'offer_price' : $definition['price_field']; + $backupPriceField = $definition['backup_price_field']; + $billingCycles[] = [ + 'code' => $code, + 'days' => (int) $definition['days'], + 'price' => number_format( + (float) $row->$priceField, + 2, + '.', + '' + ), + 'backup_price' => number_format( + (float) $row->$backupPriceField, + 2, + '.', + '' + ), + ]; + } $offers[] = [ 'id' => (int) $row->offer_id, 'name' => trim((string) $row->offer_name), @@ -111,6 +135,7 @@ final class CloudDeploymentPageService '.', '' ), + 'billing_cycles' => $billingCycles, 'currency' => 'USD', 'region_id' => $regionId, 'line_id' => $lineId, @@ -118,7 +143,7 @@ final class CloudDeploymentPageService 'memory_mib' => (int) $row->memory_mib, 'bandwidth_mbps' => (int) $row->bandwidth_mbps, 'disk_gib' => (int) $row->disk_gib, - 'validity_days' => (int) $row->validity_days, + 'validity_days' => 30, 'traffic_quota_bytes' => $trafficBytes, 'traffic_gib' => $trafficGiB, 'traffic_tib' => self::formatDecimalUnit($trafficGiB, 1024, 10), diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index be019284..4cf7f9ba 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -101,6 +101,23 @@ final class CloudInvoiceService || $itemTotal !== CloudMoney::cents((string) $order->amount)) { throw new CloudError('开通订单费用明细合计不一致', 409); } + $spec = json_decode((string) $order->spec_json, true); + if (!is_array($spec) || array_is_list($spec)) { + throw new CloudError('开通订单计费快照无效', 409); + } + try { + $billingCycle = CloudOffer::normalizeBillingCycle( + $spec['billing_cycle'] ?? null + ); + $cycleForDays = CloudOffer::billingCycleForDays( + (int) ($spec['validity_days'] ?? 0) + ); + } catch (\InvalidArgumentException $exception) { + throw new CloudError('开通订单计费周期无效', 409); + } + if ($billingCycle !== $cycleForDays) { + throw new CloudError('开通订单计费周期不一致', 409); + } $invoice = new CloudInvoice(); $invoice->invoice_no = self::invoiceNumber(); $invoice->purpose = 'provision'; @@ -115,7 +132,7 @@ final class CloudInvoiceService + CloudProvisioningBillingConfig::paymentWindowSeconds(); $invoice->amount = $order->amount; $invoice->currency = 'USD'; - $invoice->validity_days = (int) $plan->validity_days; + $invoice->validity_days = (int) $spec['validity_days']; $invoice->traffic_quota_bytes = max(0, (int) $plan->traffic_quota_bytes); $invoice->status = 'open'; $invoice->paid_via = null; diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index b753c9c7..60a44341 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -28,7 +28,7 @@ final class CloudOrderService CloudInput::only($input, [ 'offer_id', 'source', 'template_id', 'cloud_snapshot_key', 'guest_ssh_key_id', 'root_password', 'name', - 'automatic_backup', 'idempotency_key', + 'automatic_backup', 'billing_cycle', 'idempotency_key', ]); $requestedName = CloudInput::optionalName($input['name'] ?? null); $automaticBackup = $input['automatic_backup'] ?? false; @@ -39,6 +39,14 @@ final class CloudOrderService // fingerprint stable without storing a generated name in the request. $input['name'] = $requestedName ?? ''; $input['automatic_backup'] = $automaticBackup; + try { + $billingCycleCode = CloudOffer::normalizeBillingCycle( + $input['billing_cycle'] ?? null + ); + } catch (\InvalidArgumentException $exception) { + throw new CloudError($exception->getMessage()); + } + $input['billing_cycle'] = $billingCycleCode; $idempotency = $input['idempotency_key'] ?? ''; if (!is_string($idempotency) || preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $idempotency) !== 1) { throw new CloudError('请提供 16 至 128 字符的请求幂等标识'); @@ -73,7 +81,7 @@ final class CloudOrderService } ksort($input); $requestHash = hash_hmac('sha256', json_encode($input, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), CloudSecrets::key('order-request-hash')); - return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $snapshotKey, $automaticBackup, $idempotency, $requestHash) { + return (new User())->getConnection()->transaction(function () use ($input, $actor, $offerId, $source, $requestedName, $template, $snapshotKey, $automaticBackup, $billingCycleCode, $idempotency, $requestHash) { $user = User::where('id', $actor['user_id'])->lockForUpdate()->first(); if ($user === null || (int) $user->enable !== 1) { throw new CloudError('账户不可用', 403); @@ -147,9 +155,10 @@ final class CloudOrderService $line, (int) $plan->traffic_quota_bytes ); - $instancePrice = CloudMoney::cents($offer->price); + $billingCycle = $offer->billingCycle($billingCycleCode); + $instancePrice = CloudMoney::cents($billingCycle['price']); $backupPrice = $automaticBackup - ? CloudMoney::cents($offer->backup_price) : 0; + ? CloudMoney::cents($billingCycle['backup_price']) : 0; $totalPrice = $instancePrice + $backupPrice; $payload = ['source' => $source === 'cloud' ? 'cloud' : '', 'name' => $name, 'vcpu' => (int) $plan->cpu_cores, @@ -237,7 +246,8 @@ final class CloudOrderService $safeSpec['price_version'] = (int) $offer->price_version; $safeSpec['stock_mode'] = (int) $offer->stock === -1 ? 'unlimited' : 'finite'; - $safeSpec['validity_days'] = (int) $plan->validity_days; + $safeSpec['billing_cycle'] = $billingCycleCode; + $safeSpec['validity_days'] = (int) $billingCycle['days']; $safeSpec['traffic_quota_bytes'] = (int) $plan->traffic_quota_bytes; $safeSpec['traffic_pool_group_id'] = $trafficPoolBinding['traffic_pool_group_id']; @@ -284,7 +294,9 @@ final class CloudOrderService $offer, $instancePrice, $automaticBackup, - $backupPrice + $backupPrice, + $billingCycleCode, + (int) $billingCycle['days'] ); CloudInvoiceService::issueProvision($order, $plan, $offer, time()); return $order; @@ -356,7 +368,9 @@ final class CloudOrderService CloudOffer $offer, int $instancePrice, bool $automaticBackup, - int $backupPrice + int $backupPrice, + string $billingCycleCode, + int $validityDays ): void { $now = time(); $items = [[ @@ -368,7 +382,8 @@ final class CloudOrderService 'offer_id' => (int) $offer->id, 'offer_name' => (string) $offer->name, 'price_version' => (int) $offer->price_version, - 'validity_days' => (int) $plan->validity_days, + 'billing_cycle' => $billingCycleCode, + 'validity_days' => $validityDays, ], ]]; if ($automaticBackup) { @@ -379,7 +394,8 @@ final class CloudOrderService 'snapshot' => [ 'offer_id' => (int) $offer->id, 'price_version' => (int) $offer->price_version, - 'validity_days' => (int) $plan->validity_days, + 'billing_cycle' => $billingCycleCode, + 'validity_days' => $validityDays, ], ]; } diff --git a/web/app/Services/Cloud/CloudPlanUpgradeService.php b/web/app/Services/Cloud/CloudPlanUpgradeService.php index d5585b1c..accaa93f 100644 --- a/web/app/Services/Cloud/CloudPlanUpgradeService.php +++ b/web/app/Services/Cloud/CloudPlanUpgradeService.php @@ -546,6 +546,7 @@ final class CloudPlanUpgradeService $spec['offer_name'] = (string) $target['offer_name']; $spec['price_version'] = (int) $target['price_version']; $spec['stock_mode'] = (string) $target['stock_mode']; + $spec['billing_cycle'] = (string) $target['billing_cycle']; $spec['validity_days'] = (int) $target['validity_days']; $spec['traffic_quota_bytes'] = (int) $target['traffic_quota_bytes']; @@ -892,10 +893,16 @@ final class CloudPlanUpgradeService || strtoupper((string) $offer->currency) !== 'USD' || (int) $offer->plan_id !== (int) $plan->id || (int) $offer->resource_pool_id - !== (int) $source['resource_pool_id'] - || (int) $plan->validity_days !== (int) $source['renewal_days']) { + !== (int) $source['resource_pool_id']) { throw new CloudError('目标套餐不符合当前实例的升级条件', 409); } + try { + $billingCycle = $offer->billingCycleForServiceDays( + (int) $source['renewal_days'] + ); + } catch (\InvalidArgumentException $exception) { + throw new CloudError('目标套餐不支持当前实例的续费周期', 409); + } $resources = [ 'cpu_cores' => self::positiveInt($plan->cpu_cores), 'memory_mib' => self::positiveInt($plan->memory_mib), @@ -932,7 +939,7 @@ final class CloudPlanUpgradeService )) { throw new CloudError('套餐升级不能降低当前或续费流量额度', 409); } - $priceCents = CloudMoney::cents((string) $offer->price); + $priceCents = CloudMoney::cents($billingCycle['price']); if ($priceCents <= CloudMoney::cents( (string) $source['renewal_price'] )) { @@ -947,12 +954,13 @@ final class CloudPlanUpgradeService 'price' => CloudMoney::decimal($priceCents), 'price_version' => (int) $offer->price_version, 'backup_price' => CloudMoney::decimal( - CloudMoney::cents((string) $offer->backup_price) + CloudMoney::cents($billingCycle['backup_price']) ), 'revision' => (int) $offer->revision, 'stock_mode' => (int) $offer->stock === -1 ? 'unlimited' : 'finite', - 'validity_days' => (int) $plan->validity_days, + 'billing_cycle' => (string) $billingCycle['code'], + 'validity_days' => (int) $billingCycle['days'], 'traffic_quota_bytes' => $traffic, 'resources' => $resources, ]; diff --git a/web/public/cloud/runtime.js b/web/public/cloud/runtime.js index 654debba..b302b0f8 100644 --- a/web/public/cloud/runtime.js +++ b/web/public/cloud/runtime.js @@ -25,7 +25,7 @@ const { // address, token, host credential or unrestricted create API exists in this UI. const byId = (id) => document.getElementById(id); const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false); -const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployCloudSnapshotKey: '', deployCloudSnapshotName: '', rescueActive: false, rescueStaged: false }; +const state = { csrfToken: '', userId: '', username: '', admin: false, vms: [], offers: [], regions: [], lines: [], linesEnabled: false, sshKeys: [], templates: [], templateCatalogUnavailable: false, resources: null, selectedRegionId: '', selectedLineId: '', 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, reinstallPassword: '', reinstallPasswordDismissed: false, rfb: null, consoleToken: 0, loadingVMs: false, selectedKeys: { create: '', reinstall: '' }, resourceController: null, mutationBusy: false, powerMutation: null, provisionIdempotency: '', provisionFingerprint: '', deployCloudSnapshotKey: '', deployCloudSnapshotName: '', deployBillingCycle: 'monthly', rescueActive: false, rescueStaged: false }; function vmPageText(detailKey, reinstallKey, parameters = {}) { return t(state.view === 'reinstall' ? reinstallKey : detailKey, parameters); } @@ -733,6 +733,59 @@ function setDeploymentStepEnabled(id, enabled) { function selectedSaleOffer() { return saleOffers().find(item => String(item.id) === byId('vm-offer')?.value) || null; } +const DEPLOY_BILLING_CYCLES = Object.freeze({ + monthly: { days: 30, divisor: 1, labelKey: 'deploy.summary.cycle_monthly' }, + quarterly: { days: 90, divisor: 3, labelKey: 'deploy.summary.cycle_quarterly' }, + annual: { days: 365, divisor: 12, labelKey: 'deploy.summary.cycle_annual' }, +}); +function offerBillingCycles(offer) { + const cycles = {}; + if (!Array.isArray(offer?.billing_cycles)) return cycles; + offer.billing_cycles.forEach(item => { + const code = String(item?.code || ''); + const definition = DEPLOY_BILLING_CYCLES[code]; + const price = Number(item?.price); + const backupPrice = Number(item?.backup_price); + if (!definition || Number(item?.days) !== definition.days + || !Number.isFinite(price) || price < 0 + || !Number.isFinite(backupPrice) || backupPrice < 0) return; + cycles[code] = { code, days: definition.days, price, backupPrice }; + }); + return cycles; +} +function syncDeploymentBillingCycles(offer, backupSelected) { + const fieldset = byId('vm-billing-cycles'); + const cycles = offerBillingCycles(offer); + const complete = Object.keys(DEPLOY_BILLING_CYCLES) + .every(code => Boolean(cycles[code])); + let selectedCode = state.deployBillingCycle; + if (!cycles[selectedCode]) selectedCode = cycles.monthly ? 'monthly' : ''; + state.deployBillingCycle = selectedCode; + if (fieldset) { + fieldset.hidden = !offer; + fieldset.disabled = !offer || !complete || state.mutationBusy; + fieldset.querySelectorAll('input[name="billing_cycle"]').forEach(input => { + input.checked = input.value === selectedCode; + input.closest('.deployment-billing-cycle')?.classList.toggle( + 'is-selected', input.checked + ); + }); + } + Object.entries(DEPLOY_BILLING_CYCLES).forEach(([code, definition]) => { + const cycle = cycles[code]; + const total = cycle + ? cycle.price + (backupSelected ? cycle.backupPrice : 0) : NaN; + const price = byId(`vm-billing-${code}-price`); + if (price) price.textContent = formatUsd(total); + const equivalent = byId(`vm-billing-${code}-equivalent`); + if (equivalent) equivalent.textContent = Number.isFinite(total) + ? t('deploy.summary.cycle_equivalent_monthly', { + price: formatUsd(total / definition.divisor), + }) + : '—'; + }); + return selectedCode ? cycles[selectedCode] || null : null; +} function deploymentTemplates() { const offerId = String(selectedSaleOffer()?.id ?? ''); if (!offerId) return []; @@ -758,21 +811,33 @@ function syncDeploymentPricing() { const summary = byId('vm-order-summary'); const empty = byId('vm-order-summary-empty'); if (!offer) { + syncDeploymentBillingCycles(null, false); if (summary) summary.hidden = true; if (empty) empty.hidden = false; if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice'); return; } - const instancePrice = Number(offer.price); - const backupPrice = Number(offer.backup_price); const backupSelected = backupAvailable && checkbox?.checked === true; + const billingCycle = syncDeploymentBillingCycles(offer, backupSelected); + if (!billingCycle) { + if (summary) summary.hidden = true; + if (empty) empty.hidden = false; + if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice'); + return; + } + const instancePrice = billingCycle.price; + const backupPrice = billingCycle.backupPrice; const total = Math.max(0, Number.isFinite(instancePrice) ? instancePrice : 0) + (backupSelected && Number.isFinite(backupPrice) ? Math.max(0, backupPrice) : 0); if (byId('vm-order-instance-price')) byId('vm-order-instance-price').textContent = formatUsd(instancePrice); if (byId('vm-order-backup-price')) byId('vm-order-backup-price').textContent = formatUsd(backupPrice); if (byId('vm-order-backup-row')) byId('vm-order-backup-row').hidden = !backupSelected; if (byId('vm-order-total-price')) byId('vm-order-total-price').textContent = formatUsd(total); - if (byId('vm-order-renewal-price')) byId('vm-order-renewal-price').textContent = t('deploy.summary.period_price', { price: formatUsd(total) }); + if (byId('vm-order-service-period')) byId('vm-order-service-period').textContent = t('deploy.summary.cycle_days', { days: billingCycle.days }); + if (byId('vm-order-renewal-price')) byId('vm-order-renewal-price').textContent = t('deploy.summary.cycle_price', { + price: formatUsd(total), + cycle: t(DEPLOY_BILLING_CYCLES[billingCycle.code].labelKey), + }); if (summary) summary.hidden = false; if (empty) empty.hidden = true; if (byId('create-submit')) byId('create-submit').textContent = t('deploy.submit.invoice_amount', { price: formatUsd(total) }); @@ -819,6 +884,17 @@ function initializeDeploymentOptions(bootstrap = null) { updateCreateAvailability(); }); } + const billingCycles = byId('vm-billing-cycles'); + if (billingCycles && billingCycles.dataset.bound !== 'true') { + billingCycles.dataset.bound = 'true'; + billingCycles.addEventListener('change', event => { + const input = event.target.closest('input[name="billing_cycle"]'); + if (!input || !DEPLOY_BILLING_CYCLES[input.value]) return; + state.deployBillingCycle = input.value; + showError('create-error', ''); + updateCreateAvailability(); + }); + } applyDeploymentSource(); syncDeploymentPricing(); } @@ -827,7 +903,8 @@ function updateCreateAvailability() { const selectedTemplate = String(byId('vm-template')?.value || ''); const validTemplate = deploymentTemplates().some(item => String(item?.id) === selectedTemplate); const validMedia = Boolean(state.deployCloudSnapshotKey || validTemplate); - if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia; + const validBillingCycle = Boolean(offerBillingCycles(offer)[state.deployBillingCycle]); + if (byId('create-submit')) byId('create-submit').disabled = state.mutationBusy || !isOfferSellable(offer) || !validMedia || !validBillingCycle; syncDeploymentPricing(); } function strongPassword(value) { return !value || (value.length >= 12 && value.length <= 128 && /^[\x21-\x7e]+$/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value) && /[0-9]/.test(value) && /[^A-Za-z0-9]/.test(value)); } @@ -1111,12 +1188,14 @@ async function buy(event) { const selectedOffer = saleOffers().find(offer => String(offer.id) === byId('vm-offer').value); if (!selectedOffer) return showError('create-error', t('deploy.error.offer_mismatch')); if (!isOfferSellable(selectedOffer)) return showError('create-error', t('deploy.error.offer_sold_out')); + if (!offerBillingCycles(selectedOffer)[state.deployBillingCycle]) return showError('create-error', t('deploy.error.billing_cycle_required')); state.mutationBusy = true; const formBody = byId('create-form')?.querySelector('.workspace-form-body'); if (formBody) { formBody.inert = true; formBody.setAttribute('aria-busy', 'true'); } byId('create-submit').disabled = true; showError('create-error', ''); const body = { offer_id: Number(byId('vm-offer').value), name: byId('vm-name').value.trim(), source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud', + billing_cycle: state.deployBillingCycle, automatic_backup: byId('vm-automatic-backup')?.checked === true }; if (state.deployCloudSnapshotKey) body.cloud_snapshot_key = state.deployCloudSnapshotKey; else body.template_id = byId('vm-template').value; diff --git a/web/public/cloud/styles.css b/web/public/cloud/styles.css index bf0c9868..9be2a5a3 100644 --- a/web/public/cloud/styles.css +++ b/web/public/cloud/styles.css @@ -241,6 +241,7 @@ tbody tr:hover{background:#fcfefe} .deployment-addon-option{display:flex;align-items:flex-start;gap:13px;padding:17px 18px;border:1px solid #dce7ec;border-radius:11px;background:#fff;cursor:pointer;transition:border-color .18s,background .18s,box-shadow .18s} .deployment-addon-option:hover{border-color:#acdadd;background:#f8fcfc}.deployment-addon-option:has(input:checked){border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.deployment-addon-option.is-disabled{cursor:not-allowed;opacity:.62;background:#f7f9fa}.deployment-addon-option input{margin:3px 0 0;accent-color:#18a6b0}.deployment-addon-option span{display:grid;gap:4px}.deployment-addon-option strong{color:#30485d;font-size:13px}.deployment-addon-option small{color:#7f91a0;font-size:10px;line-height:1.6} .deployment-order-summary>dl{margin:0;border:1px solid #dfe9ed;border-radius:11px;background:#fbfdfd;overflow:hidden}.deployment-order-summary>dl>div{display:flex;align-items:center;justify-content:space-between;gap:18px;padding:13px 17px;border-bottom:1px solid #e7edef}.deployment-order-summary>dl>div:last-child{border-bottom:0}.deployment-order-summary dt{color:#718496;font-size:11px;font-weight:700}.deployment-order-summary dd{margin:0;color:#30475b;font-size:12px;font-weight:800}.deployment-order-summary .deployment-order-total{background:#eef9fa}.deployment-order-summary .deployment-order-total dt{color:#286f75}.deployment-order-summary .deployment-order-total dd{color:#0d929d;font-size:17px} +.deployment-billing-cycles{display:grid;gap:9px;margin:0 0 17px;padding:0;border:0}.deployment-billing-cycles[hidden]{display:none}.deployment-billing-cycles legend{width:100%;margin:0 0 3px;color:#5f7486;font-size:11px;font-weight:800}.deployment-billing-cycle{position:relative;display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:13px;min-height:66px;padding:12px 15px;border:1px solid #dce7ec;border-radius:11px;background:#fff;cursor:pointer;transition:border-color .18s,background .18s}.deployment-billing-cycle:hover{border-color:#acdadd;background:#f8fcfc}.deployment-billing-cycle.is-selected{border-color:#2eabb4;background:#eef9fa;box-shadow:inset 0 0 0 1px #2eabb4}.deployment-billing-cycle input{width:17px;height:17px;margin:0;accent-color:#18a6b0}.deployment-billing-cycle-copy,.deployment-billing-cycle-price{display:grid;min-width:0;gap:3px}.deployment-billing-cycle-copy strong{color:#2c4458;font-size:13px}.deployment-billing-cycle-copy small,.deployment-billing-cycle-price small{color:#8293a1;font-size:10px}.deployment-billing-cycle-price{text-align:right}.deployment-billing-cycle-price strong{color:#1698a2;font-size:14px}.deployment-billing-cycles:disabled .deployment-billing-cycle{cursor:not-allowed;opacity:.6}.deployment-billing-cycles:disabled .deployment-billing-cycle:hover{border-color:#dce7ec;background:#fff}@media(max-width:510px){.deployment-billing-cycle{grid-template-columns:auto minmax(0,1fr);gap:10px 12px;min-height:72px;padding:13px}.deployment-billing-cycle-price{grid-column:2;text-align:left}.deployment-billing-cycle-price strong{font-size:13px}.deployment-order-summary>dl>div{align-items:flex-start;padding:12px 14px}.deployment-order-summary dd{text-align:right}} /* Keep every user-facing button control free of browser or hover underlines. Plain content and navigation links intentionally keep their own styling. */ body[data-cloud-page] :is(button, [role="button"], .button, .row-button, .icon-button, .vu-btn, .vu-icon-btn), diff --git a/web/resources/user-copy/entries/instances-deploy.entries.php b/web/resources/user-copy/entries/instances-deploy.entries.php index fc465507..8e3fd4e8 100644 --- a/web/resources/user-copy/entries/instances-deploy.entries.php +++ b/web/resources/user-copy/entries/instances-deploy.entries.php @@ -164,11 +164,19 @@ return [ $entry('deploy.backup.help_available', 'deploy', 'cloud.deploy', '购买后可在实例详情的“自动备份”中管理备份计划。', 'help'), $entry('deploy.summary.title', 'deploy', 'cloud.deploy', '确认费用', 'title'), $entry('deploy.summary.empty', 'deploy', 'cloud.deploy', '选择实例规格后显示本次最终金额。', 'help'), + $entry('deploy.summary.cycle_title', 'deploy', 'cloud.deploy', '选择购买周期', 'title'), + $entry('deploy.summary.cycle_monthly', 'deploy', 'cloud.deploy', '月付'), + $entry('deploy.summary.cycle_quarterly', 'deploy', 'cloud.deploy', '季度'), + $entry('deploy.summary.cycle_annual', 'deploy', 'cloud.deploy', '一年'), + $entry('deploy.summary.cycle_days', 'deploy', 'cloud.deploy', '{days} 天', 'status', ['days' => 'integer']), + $entry('deploy.summary.cycle_total', 'deploy', 'cloud.deploy', '周期总价', 'status'), + $entry('deploy.summary.cycle_equivalent_monthly', 'deploy', 'cloud.deploy', '约 {price} / 月', 'status', ['price' => 'currency']), $entry('deploy.summary.instance', 'deploy', 'cloud.deploy', '实例费用'), $entry('deploy.summary.backup', 'deploy', 'cloud.deploy', '自动备份'), $entry('deploy.summary.total', 'deploy', 'cloud.deploy', '本次应付'), + $entry('deploy.summary.service_period', 'deploy', 'cloud.deploy', '服务周期'), $entry('deploy.summary.renewal', 'deploy', 'cloud.deploy', '下次续费'), - $entry('deploy.summary.period_price', 'deploy', 'cloud.deploy', '{price} / 期', 'status', ['price' => 'currency']), + $entry('deploy.summary.cycle_price', 'deploy', 'cloud.deploy', '{price} / {cycle}', 'status', ['price' => 'currency', 'cycle' => 'string']), $entry('deploy.submit.create', 'deploy', 'cloud.deploy', '创建实例', 'button'), $entry('deploy.submit.invoice', 'deploy', 'cloud.deploy', '生成账单', 'button'), $entry('deploy.submit.invoice_amount', 'deploy', 'cloud.deploy', '生成 {price} 账单', 'button', ['price' => 'currency']), @@ -179,6 +187,7 @@ return [ $entry('deploy.error.offer_required', 'deploy', 'cloud.deploy', '请先选择可用实例规格。', 'warning'), $entry('deploy.error.offer_mismatch', 'deploy', 'cloud.deploy', '地区、线路与实例规格不匹配,请重新选择。', 'warning'), $entry('deploy.error.offer_sold_out', 'deploy', 'cloud.deploy', '该实例规格暂时售罄,请选择其他规格。', 'warning'), + $entry('deploy.error.billing_cycle_required', 'deploy', 'cloud.deploy', '请选择购买周期。', 'warning'), $entry('deploy.error.initialize', 'deploy', 'cloud.deploy', '部署页面初始化失败,请刷新后重试。', 'warning'), $entry('deploy.error.invoice_missing', 'deploy', 'cloud.deploy', '开通账单已生成,但账单编号缺失,请刷新账单页面查看。', 'warning'), $entry('deploy.error.recovered_invoice_missing', 'deploy', 'cloud.deploy', '已找到开通账单,但账单编号缺失,请刷新账单页面查看。', 'warning'), diff --git a/web/resources/views/venix/admin/shop/create.tpl b/web/resources/views/venix/admin/shop/create.tpl index ab44ffed..8ca94af2 100755 --- a/web/resources/views/venix/admin/shop/create.tpl +++ b/web/resources/views/venix/admin/shop/create.tpl @@ -5,7 +5,7 @@
基础套餐只定义 CPU、内存、磁盘、带宽、账期和流量;保存后再为不同资源池添加独立的美元价格与库存。
+基础套餐只定义 CPU、内存、磁盘、带宽和流量;保存后再按资源池配置 30、90、365 天价格与库存。