feat: add selectable billing cycles

go
codex 1 week ago
parent 6117d512ab
commit ba115f4aba

@ -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 与投递账本按当前外键和账户清理规则收敛,避免实例转交后遗留原租户数据。

@ -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`;

@ -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',

@ -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,'

@ -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,

@ -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))

@ -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;

@ -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;

@ -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),

@ -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;

@ -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,
],
];
}

@ -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,
];

@ -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;

@ -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),

@ -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'),

@ -5,7 +5,7 @@
<div class="py-3 d-flex align-items-xl-center flex-xl-row flex-column gap-3">
<div class="flex-grow-1">
<h1 class="fs-20 fw-semibold mb-1">新增基础套餐</h1>
<p class="text-muted mb-0">基础套餐只定义 CPU、内存、磁盘、带宽、账期和流量;保存后再为不同资源池添加独立的美元价格与库存。</p>
<p class="text-muted mb-0">基础套餐只定义 CPU、内存、磁盘、带宽和流量;保存后再按资源池配置 30、90、365 天价格与库存。</p>
</div>
<div class="admin-config-actions flex-shrink-0">
<span id="shopFormStatus" class="admin-config-status" role="status" aria-live="polite">待保存</span>
@ -22,7 +22,6 @@
<div class="col-md-6 col-xl-3"><label class="form-label" for="memory_gb">内存(GB)</label><input class="form-control" id="memory_gb" name="memory_gb" type="number" min="0.5" max="256" step="0.5" value="2" required></div>
<div class="col-md-6 col-xl-3"><label class="form-label" for="disk_gib">磁盘(GB)</label><input class="form-control" id="disk_gib" name="disk_gib" type="number" min="1" max="4096" step="1" value="20" required></div>
<div class="col-md-6 col-xl-3"><label class="form-label" for="bandwidth_mbps">带宽(Mbps)</label><input class="form-control" id="bandwidth_mbps" name="bandwidth_mbps" type="number" min="1" max="100000" step="1" value="100" required></div>
<div class="col-md-6"><label class="form-label" for="validity_days">每期天数</label><input class="form-control" id="validity_days" name="validity_days" type="number" min="1" max="3650" step="1" value="30" required><div class="form-text">购买或续费一次增加的服务天数。</div></div>
<div class="col-md-6"><label class="form-label" for="traffic_tb">每期流量额度(TB)</label><input class="form-control" id="traffic_tb" name="traffic_tb" type="number" min="0" max="1024" step="0.0009765625" value="1" required><div class="form-text">最小步进 1 GiB;填 0 表示不限流量。</div></div>
<div class="col-md-6"><label class="form-label" for="sort">排序</label><input class="form-control" id="sort" name="sort" type="number" min="-1000000" max="1000000" step="1" value="0" required></div>
<div class="col-md-6"><label class="form-label" for="status">套餐状态</label><select class="form-select" id="status" name="status"><option value="1" selected>启用</option><option value="0">停用</option></select><div class="form-text">用户只能购买已启用套餐下已上架的销售方案。</div></div>

@ -15,7 +15,7 @@
</div>
<section class="card mb-3" aria-labelledby="plan-settings-title">
<div class="card-header"><h2 class="h5 card-title mb-0" id="plan-settings-title">资源规格与账期</h2></div>
<div class="card-header"><h2 class="h5 card-title mb-0" id="plan-settings-title">资源规格与流量</h2></div>
<div class="card-body">
<form id="shopForm" data-method="PUT" data-url="/admin/shop/{$shop->id|escape:'html'}">
<div class="row g-3">
@ -24,7 +24,6 @@
<div class="col-md-6 col-xl-3"><label class="form-label" for="memory_gb">内存(GB)</label><input class="form-control" id="memory_gb" name="memory_gb" type="number" min="0.5" max="256" step="0.5" value="{$shop->memoryGB()|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="col-md-6 col-xl-3"><label class="form-label" for="disk_gib">磁盘(GB)</label><input class="form-control" id="disk_gib" name="disk_gib" type="number" min="1" max="4096" step="1" value="{$shop->disk_gib|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="col-md-6 col-xl-3"><label class="form-label" for="bandwidth_mbps">带宽(Mbps)</label><input class="form-control" id="bandwidth_mbps" name="bandwidth_mbps" type="number" min="1" max="100000" step="1" value="{$shop->bandwidth_mbps|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="col-md-6"><label class="form-label" for="validity_days">每期天数</label><input class="form-control" id="validity_days" name="validity_days" type="number" min="1" max="3650" step="1" value="{$shop->validity_days|default:30|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}><div class="form-text">修改不追溯已开通的服务周期。</div></div>
<div class="col-md-6"><label class="form-label" for="traffic_tb">每期流量额度(TB)</label><input class="form-control" id="traffic_tb" name="traffic_tb" type="number" min="0" max="1024" step="0.0009765625" value="{$shop->trafficTB()|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}><div class="form-text">最小步进 1 GiB;填 0 表示不限流量。</div></div>
<div class="col-md-6"><label class="form-label" for="sort">排序</label><input class="form-control" id="sort" name="sort" type="number" min="-1000000" max="1000000" step="1" value="{$shop->sort|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="col-md-6"><label class="form-label" for="status">套餐状态</label><select class="form-select" id="status" name="status" {if !$admin_can_manage|default:false}disabled{/if}><option value="1" {if $shop->status == 1}selected{/if}>启用</option><option value="0" {if $shop->status == 0}selected{/if}>停用</option></select></div>
@ -48,7 +47,7 @@
<tr>
<td><div class="fw-semibold">{$item.name|escape}</div><details class="mt-1"><summary class="text-muted fs-12">技术信息</summary><div class="text-muted fs-12 mt-1">系统标识 <span class="admin-mono">{$item.code|escape}</span> · 记录 #{$item.id|escape}</div></details></td>
<td class="text-muted">{$item.pool|default:'销售位置不可用'|escape}</td>
<td class="fw-semibold">{$item.price|escape}</td>
<td class="fw-semibold">{foreach $item.prices as $period => $price}<div><span class="text-muted fs-12">{$period|escape}</span> {$price|escape}</div>{/foreach}</td>
<td>{if $item.stock == -1}不限{else}{$item.stock|escape}{/if}</td>
<td>v{$item.price_version|escape}</td>
<td>{if $item.status && $item.location_active}<span class="badge text-bg-success">已上架</span>{elseif $item.status}<span class="badge text-bg-warning">当前不可售</span><div class="text-muted fs-12 mt-1">{$item.availability_reason|default:'销售位置不可用'|escape}</div>{else}<span class="badge text-bg-light">已下架</span>{/if}</td>

@ -6,7 +6,7 @@
var status = document.getElementById('shopFormStatus');
var toast = document.getElementById('shopFormToast');
var fields = ['name', 'cpu_cores', 'memory_gb', 'bandwidth_mbps', 'disk_gib',
'validity_days', 'traffic_tb', 'status', 'sort'];
'traffic_tb', 'status', 'sort'];
var submitLocked = !submit || submit.disabled;
function value(id) {

@ -1,7 +1,7 @@
{assign var=admin_title value='套餐与销售方案'}
{assign var=admin_active value='shop'}
{assign var=page_title value='基础套餐'}
{assign var=page_desc value='统一管理云服务器规格、账期和流量;每个基础套餐可按资源池配置多个独立销售方案。'}
{assign var=page_desc value='统一管理云服务器规格和流量;每个基础套餐可按资源池配置 30、90、365 天独立销售价格。'}
{assign var=page_icon value='mdi-storefront-outline'}
{assign var=admin_table_storage_key value='venix-admin-base-plans-columns-v2'}
{assign var=admin_table_ajax_url value='/admin/shop/ajax'}
@ -13,6 +13,6 @@
{assign var=admin_table_create_url value='/admin/shop/create'}
{assign var=admin_table_create_text value='新增基础套餐'}
{assign var=admin_table_create_icon value='mdi-plus-circle-outline'}
{assign var=admin_table_columns_json value='[{"key":"op","label":"操作","width":"170px","sortable":false,"action":"shopActions"},{"key":"id","label":"ID","width":"90px"},{"key":"name","label":"基础套餐","width":"180px"},{"key":"cpu_cores","label":"CPU","width":"90px"},{"key":"memory_gb","label":"内存 GB","width":"110px"},{"key":"bandwidth_mbps","label":"带宽 Mbps","width":"120px"},{"key":"disk_gib","label":"磁盘 GB","width":"110px"},{"key":"validity_days","label":"每期天数","width":"120px"},{"key":"traffic_tb","label":"每期流量 TB","width":"150px"},{"key":"offer_count","label":"销售方案","width":"110px"},{"key":"active_offer_count","label":"已上架","width":"100px"},{"key":"price_range","label":"美元价格区间","width":"180px"},{"key":"status","label":"套餐状态","width":"110px"},{"key":"sort","label":"排序","width":"90px"}]'}
{assign var=admin_table_default_columns_json value='["op","id","name","cpu_cores","memory_gb","disk_gib","validity_days","offer_count","active_offer_count","price_range","status"]'}
{assign var=admin_table_columns_json value='[{"key":"op","label":"操作","width":"170px","sortable":false,"action":"shopActions"},{"key":"id","label":"ID","width":"90px"},{"key":"name","label":"基础套餐","width":"180px"},{"key":"cpu_cores","label":"CPU","width":"90px"},{"key":"memory_gb","label":"内存 GB","width":"110px"},{"key":"bandwidth_mbps","label":"带宽 Mbps","width":"120px"},{"key":"disk_gib","label":"磁盘 GB","width":"110px"},{"key":"traffic_tb","label":"每周期流量 TB","width":"150px"},{"key":"offer_count","label":"销售方案","width":"110px"},{"key":"active_offer_count","label":"已上架","width":"100px"},{"key":"price_range","label":"月付价格区间","width":"180px"},{"key":"status","label":"套餐状态","width":"110px"},{"key":"sort","label":"排序","width":"90px"}]'}
{assign var=admin_table_default_columns_json value='["op","id","name","cpu_cores","memory_gb","disk_gib","traffic_tb","offer_count","active_offer_count","price_range","status"]'}
{include file='admin/components/table_page.tpl'}

@ -4,7 +4,11 @@
{assign var=offer_code value=$offer->code}
{assign var=offer_name value=$offer->name}
{assign var=offer_price value=$offer->price}
{assign var=offer_quarterly_price value=$offer->quarterly_price}
{assign var=offer_annual_price value=$offer->annual_price}
{assign var=offer_backup_price value=$offer->backup_price}
{assign var=offer_backup_quarterly_price value=$offer->backup_quarterly_price}
{assign var=offer_backup_annual_price value=$offer->backup_annual_price}
{assign var=offer_stock value=$offer->stock}
{assign var=offer_sort value=$offer->sort}
{else}
@ -13,7 +17,11 @@
{assign var=offer_code value=''}
{assign var=offer_name value=''}
{assign var=offer_price value='0.00'}
{assign var=offer_quarterly_price value='0.00'}
{assign var=offer_annual_price value='0.00'}
{assign var=offer_backup_price value='0.00'}
{assign var=offer_backup_quarterly_price value='0.00'}
{assign var=offer_backup_annual_price value='0.00'}
{assign var=offer_stock value=-1}
{assign var=offer_sort value=0}
{/if}
@ -62,13 +70,29 @@
</details>
<details class="card admin-config-section" open>
<summary><span><strong>价格与销售状态</strong><small>实例和自动备份价格固定使用 USD;库存为 0 或下架时停止新购。</small></span><i class="mdi mdi-chevron-down" aria-hidden="true"></i></summary>
<div class="admin-config-body"><div class="row g-3">
<div class="col-md-6 col-xl-4"><label class="form-label" for="price">每期价格(USD)</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="price" name="price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div>{if $offer}<div class="form-text">当前价格版本 v{$offer->price_version|escape};修改价格后自动递增。</div>{/if}</div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="backup_price">自动备份每期价格(USD)</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="backup_price" name="backup_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_backup_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div><div class="form-text">所有在售规格均可选购自动备份;这里只配置价格,备份频率和保留数量由用户在实例设置中选择。</div></div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="stock">可售库存</label><input class="form-control" id="stock" name="stock" type="number" min="-1" max="2147483647" step="1" value="{$offer_stock|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}><div class="form-text">-1 表示不限库存,0 表示暂停新购。</div></div>
<div class="col-md-6 col-xl-4"><label class="form-label" for="status">销售状态</label><select class="form-select" id="status" name="status" {if !$admin_can_manage|default:false}disabled{/if}><option value="1" {if !$offer || $offer->status}selected{/if}>上架销售</option><option value="0" {if $offer && !$offer->status}selected{/if}>下架停售</option></select><div class="form-text">下架不会删除历史订单或已开通实例。</div></div>
</div></div>
<summary><span><strong>周期价格与销售状态</strong><small>分别配置 30、90、365 天的实例与自动备份价格;订单会冻结用户选择的周期和价格。</small></span><i class="mdi mdi-chevron-down" aria-hidden="true"></i></summary>
<div class="admin-config-body">
<h2 class="h6 mb-3">实例价格(USD)</h2>
<div class="row g-3">
<div class="col-md-4"><label class="form-label" for="price">月付 · 30 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="price" name="price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
<div class="col-md-4"><label class="form-label" for="quarterly_price">季度 · 90 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="quarterly_price" name="quarterly_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_quarterly_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
<div class="col-md-4"><label class="form-label" for="annual_price">一年 · 365 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="annual_price" name="annual_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_annual_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
</div>
<hr class="my-4">
<h2 class="h6 mb-1">自动备份价格(USD)</h2>
<p class="text-muted fs-13 mb-3">与实例使用相同服务周期;备份频率和保留数量由用户在实例设置中选择。</p>
<div class="row g-3">
<div class="col-md-4"><label class="form-label" for="backup_price">月付 · 30 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="backup_price" name="backup_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_backup_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
<div class="col-md-4"><label class="form-label" for="backup_quarterly_price">季度 · 90 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="backup_quarterly_price" name="backup_quarterly_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_backup_quarterly_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
<div class="col-md-4"><label class="form-label" for="backup_annual_price">一年 · 365 天</label><div class="input-group"><span class="input-group-text">$</span><input class="form-control" id="backup_annual_price" name="backup_annual_price" type="number" min="0" max="9999999999.99" step="0.01" value="{$offer_backup_annual_price|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}></div></div>
</div>
{if $offer}<div class="form-text mt-3">当前价格版本 v{$offer->price_version|escape};修改任一周期价格后自动递增。</div>{/if}
<hr class="my-4">
<div class="row g-3">
<div class="col-md-6"><label class="form-label" for="stock">可售库存</label><input class="form-control" id="stock" name="stock" type="number" min="-1" max="2147483647" step="1" value="{$offer_stock|escape:'html'}" required {if !$admin_can_manage|default:false}disabled{/if}><div class="form-text">-1 表示不限库存,0 表示暂停新购。</div></div>
<div class="col-md-6"><label class="form-label" for="status">销售状态</label><select class="form-select" id="status" name="status" {if !$admin_can_manage|default:false}disabled{/if}><option value="1" {if !$offer || $offer->status}selected{/if}>上架销售</option><option value="0" {if $offer && !$offer->status}selected{/if}>下架停售</option></select><div class="form-text">下架不会删除历史订单或已开通实例。</div></div>
</div>
</div>
</details>
<details class="card admin-config-section">

@ -7,8 +7,9 @@
var toast = document.getElementById('offerFormToast');
var deleteButton = document.getElementById('offerDeleteButton');
var fields = [
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort', 'revision'
'resource_pool_id', 'name', 'price', 'quarterly_price',
'annual_price', 'backup_price', 'backup_quarterly_price',
'backup_annual_price', 'stock', 'status', 'sort', 'revision'
];
var submitLocked = !submit || submit.disabled;
var deleteArmed = false;

@ -106,11 +106,30 @@
<section id="vm-order-summary-step" class="deployment-step deployment-order-summary" aria-labelledby="deploy-order-summary-title">
<div class="deployment-step-heading"><span>{if !empty($cloud_deploy_lines_enabled)}7{else}6{/if}</span><h2 id="deploy-order-summary-title"{user_copy_binding key='deploy.summary.title'}>{user_copy key='deploy.summary.title'}</h2></div>
<p id="vm-order-summary-empty" class="muted"{if !empty($cloud_deploy_price)} hidden{/if}{user_copy_binding key='deploy.summary.empty'}>{user_copy key='deploy.summary.empty'}</p>
<fieldset id="vm-billing-cycles" class="deployment-billing-cycles"{if empty($cloud_deploy_price)} hidden disabled{/if}>
<legend{user_copy_binding key='deploy.summary.cycle_title'}>{user_copy key='deploy.summary.cycle_title'}</legend>
<label class="deployment-billing-cycle" data-billing-cycle="monthly">
<input type="radio" name="billing_cycle" value="monthly" checked>
<span class="deployment-billing-cycle-copy"><strong{user_copy_binding key='deploy.summary.cycle_monthly'}>{user_copy key='deploy.summary.cycle_monthly'}</strong><small>{user_copy key='deploy.summary.cycle_days' days=30}</small></span>
<span class="deployment-billing-cycle-price"><strong id="vm-billing-monthly-price">{$cloud_deploy_price|default:'—'|escape:'html'}</strong><small>{user_copy key='deploy.summary.cycle_total'}</small></span>
</label>
<label class="deployment-billing-cycle" data-billing-cycle="quarterly">
<input type="radio" name="billing_cycle" value="quarterly">
<span class="deployment-billing-cycle-copy"><strong{user_copy_binding key='deploy.summary.cycle_quarterly'}>{user_copy key='deploy.summary.cycle_quarterly'}</strong><small>{user_copy key='deploy.summary.cycle_days' days=90}</small></span>
<span class="deployment-billing-cycle-price"><strong id="vm-billing-quarterly-price">{$cloud_deploy_quarterly_price|default:'—'|escape:'html'}</strong><small id="vm-billing-quarterly-equivalent">{if !empty($cloud_deploy_quarterly_equivalent)}{user_copy key='deploy.summary.cycle_equivalent_monthly' price=$cloud_deploy_quarterly_equivalent}{else}—{/if}</small></span>
</label>
<label class="deployment-billing-cycle" data-billing-cycle="annual">
<input type="radio" name="billing_cycle" value="annual">
<span class="deployment-billing-cycle-copy"><strong{user_copy_binding key='deploy.summary.cycle_annual'}>{user_copy key='deploy.summary.cycle_annual'}</strong><small>{user_copy key='deploy.summary.cycle_days' days=365}</small></span>
<span class="deployment-billing-cycle-price"><strong id="vm-billing-annual-price">{$cloud_deploy_annual_price|default:'—'|escape:'html'}</strong><small id="vm-billing-annual-equivalent">{if !empty($cloud_deploy_annual_equivalent)}{user_copy key='deploy.summary.cycle_equivalent_monthly' price=$cloud_deploy_annual_equivalent}{else}—{/if}</small></span>
</label>
</fieldset>
<dl id="vm-order-summary" aria-live="polite"{if empty($cloud_deploy_price)} hidden{/if}>
<div><dt{user_copy_binding key='deploy.summary.instance'}>{user_copy key='deploy.summary.instance'}</dt><dd id="vm-order-instance-price">{$cloud_deploy_price|default:'—'|escape:'html'}</dd></div>
<div id="vm-order-backup-row" hidden><dt{user_copy_binding key='deploy.summary.backup'}>{user_copy key='deploy.summary.backup'}</dt><dd id="vm-order-backup-price">{$cloud_deploy_backup_price|default:'—'|escape:'html'}</dd></div>
<div class="deployment-order-total"><dt{user_copy_binding key='deploy.summary.total'}>{user_copy key='deploy.summary.total'}</dt><dd id="vm-order-total-price">{$cloud_deploy_price|default:'—'|escape:'html'}</dd></div>
<div><dt{user_copy_binding key='deploy.summary.renewal'}>{user_copy key='deploy.summary.renewal'}</dt><dd id="vm-order-renewal-price">{user_copy key='deploy.summary.period_price' price=$cloud_deploy_price|default:'—'}</dd></div>
<div><dt{user_copy_binding key='deploy.summary.service_period'}>{user_copy key='deploy.summary.service_period'}</dt><dd id="vm-order-service-period">{user_copy key='deploy.summary.cycle_days' days=30}</dd></div>
<div><dt{user_copy_binding key='deploy.summary.renewal'}>{user_copy key='deploy.summary.renewal'}</dt><dd id="vm-order-renewal-price">{$cloud_deploy_price|default:'—'|escape:'html'} / {user_copy key='deploy.summary.cycle_monthly'}</dd></div>
</dl>
</section>
<p id="create-error" class="form-error" role="alert" hidden></p>

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

@ -493,7 +493,11 @@ CREATE TABLE cloud_offers (
code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
name VARCHAR(128) NOT NULL,
price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
quarterly_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
annual_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
backup_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
backup_quarterly_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
backup_annual_price DECIMAL(12,2) NOT NULL DEFAULT 0.00,
currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD',
price_version INT UNSIGNED NOT NULL DEFAULT 1,
revision INT UNSIGNED NOT NULL DEFAULT 1,

@ -18,13 +18,20 @@ namespace {
$valid = [
'resource_pool_id' => '8', 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '019.9', 'backup_price' => '003.5', 'stock' => '-1',
'price' => '019.9', 'quarterly_price' => '056.7',
'annual_price' => '199', 'backup_price' => '003.5',
'backup_quarterly_price' => '009.5',
'backup_annual_price' => '35', 'stock' => '-1',
'status' => '1', 'sort' => '-20',
];
$normalized = CloudOffer::validateOffer($valid);
$assert($normalized === [
'resource_pool_id' => 8, 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '19.90', 'backup_price' => '3.50', 'currency' => 'USD',
'currency' => 'USD',
'price' => '19.90', 'quarterly_price' => '56.70',
'annual_price' => '199.00', 'backup_price' => '3.50',
'backup_quarterly_price' => '9.50',
'backup_annual_price' => '35.00',
'status' => 1,
'stock' => -1, 'sort' => -20,
], 'Offer input was not normalized into the expected pool, USD price, inventory and status fields.');
@ -37,7 +44,10 @@ namespace {
foreach ([
['resource_pool_id' => 0], ['code' => 'Tokyo Premium'], ['code' => ''],
['name' => ''], ['price' => '-1'], ['price' => '1.999'],
['quarterly_price' => '-1'], ['annual_price' => '1.999'],
['backup_price' => '-1'], ['backup_price' => '1.999'], ['stock' => -2],
['backup_quarterly_price' => '-1'],
['backup_annual_price' => '1.999'],
['status' => 2], ['sort' => 1000001],
] as $invalid) {
try {
@ -60,8 +70,11 @@ namespace {
$assert(!str_contains($planViews, 'name="host_id"')
&& !str_contains($planViews, 'name="price"')
&& !str_contains($planViews, 'name="stock"')
&& !str_contains($planViews, 'name="validity_days"')
&& !str_contains($controller, "foreach (['name', 'host_id'")
&& str_contains($controller, "'name', 'cpu_cores', 'memory_gb'")
&& str_contains($controller,
"CloudOffer::BILLING_CYCLES['monthly']['days']")
&& str_contains($controller, 'CloudOffer::validateOffer($input)')
&& str_contains($controller, "\$input['code'] = \$offer === null")
&& str_contains($controller, '$this->availableOfferSystemCode()')
@ -99,7 +112,8 @@ namespace {
&& str_contains($controller, "(string) \$locked->code !== (string) \$values['code']")
&& str_contains($controller, "\$locked->exists && \$field === 'code'")
&& str_contains($controller, '销售方案系统标识创建后不可修改,请新建方案')
&& str_contains($controller, '$priceChanged = $locked->exists')
&& str_contains($controller, '$priceChanged = false')
&& str_contains($controller, "'quarterly_price', 'annual_price'")
&& str_contains($controller, '} elseif ($priceChanged) {')
&& str_contains($controller, '$locked->price_version = max(1, (int) $locked->price_version) + 1;')
&& str_contains($controller, '$locked->delete()')
@ -107,14 +121,18 @@ namespace {
'Offer mutation lacks server authorization, price versioning, or reference-aware deletion.');
foreach ([
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort', 'revision',
'resource_pool_id', 'name', 'price', 'quarterly_price',
'annual_price', 'backup_price', 'backup_quarterly_price',
'backup_annual_price', 'stock', 'status', 'sort', 'revision',
] as $field) {
$assert(str_contains($offerView, 'name="' . $field . '"'),
'Offer editor is missing field: ' . $field);
}
$assert(str_contains($offerView, '每期价格(USD)')
&& str_contains($offerView, '自动备份每期价格(USD)')
$assert(str_contains($offerView, '实例价格(USD)')
&& str_contains($offerView, '自动备份价格(USD)')
&& str_contains($offerView, '月付 · 30 天')
&& str_contains($offerView, '季度 · 90 天')
&& str_contains($offerView, '一年 · 365 天')
&& !str_contains($offerView, 'name="backup_available"')
&& str_contains($offerView, '备份频率和保留数量由用户在实例设置中选择')
&& str_contains($offerView, '当前价格版本')

@ -18,7 +18,10 @@ $offer = new CloudOffer();
$offer->setRawAttributes([
'id' => 11, 'plan_id' => 71, 'resource_pool_id' => 8,
'code' => 'tokyo-standard', 'name' => '东京标准云服务器',
'price' => '19.90', 'backup_price' => '3.50',
'price' => '19.90', 'quarterly_price' => '56.70',
'annual_price' => '199.00', 'backup_price' => '3.50',
'backup_quarterly_price' => '9.50',
'backup_annual_price' => '35.00',
'price_version' => 3, 'revision' => 4,
'stock' => 25, 'status' => 1, 'sort' => 10,
]);
@ -93,8 +96,9 @@ $assert($editForm->getAttribute('data-method') === 'PUT'
'Edit form lost its PUT endpoint.');
foreach ([
'resource_pool_id', 'name', 'price', 'backup_price', 'stock',
'status', 'sort', 'revision',
'resource_pool_id', 'name', 'price', 'quarterly_price',
'annual_price', 'backup_price', 'backup_quarterly_price',
'backup_annual_price', 'stock', 'status', 'sort', 'revision',
] as $field) {
$one($create, '//*[@name="' . $field . '"]');
$one($edit, '//*[@name="' . $field . '"]');
@ -107,8 +111,12 @@ $assert($namePosition !== false && $poolPosition !== false && $sortPosition !==
&& strpos($createHtml, 'id="code"') === false,
'Create must lead with name/location and must not expose a system-identifier field.');
$assert(str_contains($createHtml, '销售名称与位置')
&& str_contains($createHtml, '价格与销售状态')
&& str_contains($createHtml, '自动备份每期价格(USD)')
&& str_contains($createHtml, '周期价格与销售状态')
&& str_contains($createHtml, '实例价格(USD)')
&& str_contains($createHtml, '自动备份价格(USD)')
&& str_contains($createHtml, '月付 · 30 天')
&& str_contains($createHtml, '季度 · 90 天')
&& str_contains($createHtml, '一年 · 365 天')
&& !str_contains($createHtml, 'name="backup_available"')
&& str_contains($createHtml, '备份频率和保留数量由用户在实例设置中选择')
&& str_contains($createHtml, '高级设置')

@ -41,7 +41,11 @@ const nodes = new Map([
['resource_pool_id', new Element('1')],
['name', new Element('Tokyo standard')],
['price', new Element('19.90')],
['quarterly_price', new Element('56.70')],
['annual_price', new Element('199.00')],
['backup_price', new Element('4.25')],
['backup_quarterly_price', new Element('12.00')],
['backup_annual_price', new Element('42.00')],
['stock', new Element('-1')],
['status', new Element('1')],
['sort', new Element('0')],
@ -86,7 +90,11 @@ assert.deepEqual(
resource_pool_id: '1',
name: 'Tokyo standard',
price: '19.90',
quarterly_price: '56.70',
annual_price: '199.00',
backup_price: '4.25',
backup_quarterly_price: '12.00',
backup_annual_price: '42.00',
stock: '-1',
status: '1',
sort: '0',
@ -95,4 +103,4 @@ assert.deepEqual(
'Non-zero automatic-backup price was omitted from the administrator request.',
);
console.log('Administrator offer submit preserves the automatic-backup price.');
console.log('Administrator offer submit preserves every instance and automatic-backup cycle price.');

@ -87,7 +87,11 @@ $schema->create('cloud_offers', function (Blueprint $table): void {
$table->string('code')->unique();
$table->string('name');
$table->decimal('price', 12, 2);
$table->decimal('quarterly_price', 12, 2);
$table->decimal('annual_price', 12, 2);
$table->decimal('backup_price', 12, 2)->default(0);
$table->decimal('backup_quarterly_price', 12, 2)->default(0);
$table->decimal('backup_annual_price', 12, 2)->default(0);
$table->string('currency');
$table->integer('price_version');
$table->integer('revision');
@ -187,7 +191,11 @@ $baseInput = [
'resource_pool_id' => '1',
'name' => '东京标准云服务器',
'price' => '19.90',
'quarterly_price' => '56.70',
'annual_price' => '199.00',
'backup_price' => '3.50',
'backup_quarterly_price' => '9.50',
'backup_annual_price' => '35.00',
'stock' => '-1',
'status' => '1',
'sort' => '0',

@ -40,7 +40,11 @@ $render = static function (Shop $shop, ?bool $canManage = true,
'pool' => $linesEnabled
? '香港 → 默认线路 → 通用资源池'
: '香港 → 通用资源池',
'price' => '$12.34',
'prices' => [
'30 天' => '$12.34',
'90 天' => '$34.00',
'365 天' => '$120.00',
],
'price_version' => 2, 'stock' => 25, 'status' => true,
'location_active' => true, 'availability_reason' => '', 'sort' => 0,
]]);
@ -84,7 +88,7 @@ $assert($form->getAttribute('data-method') === 'PUT'
&& $form->getAttribute('data-url') === '/admin/shop/71',
'Restyling changed the existing update method or resource URL.');
$expectedNames = ['name', 'cpu_cores', 'memory_gb', 'disk_gib', 'bandwidth_mbps',
'validity_days', 'traffic_tb', 'sort', 'status'];
'traffic_tb', 'sort', 'status'];
$actualNames = [];
foreach ($xpath->query('//form[@id="shopForm"]//*[@name and (self::input or self::select or self::textarea)]') as $control) {
$actualNames[] = $control->getAttribute('name');
@ -109,7 +113,6 @@ $numbers = [
'memory_gb' => ['0.5', '256', '0.5', '2.5'],
'disk_gib' => ['1', '4096', '1', '80'],
'bandwidth_mbps' => ['1', '100000', '1', '200'],
'validity_days' => ['1', '3650', '1', '45'],
'traffic_tb' => ['0', '1024', '0.0009765625', '1.5'],
'sort' => ['-1000000', '1000000', '1', '-2'],
];
@ -122,8 +125,8 @@ foreach ($numbers as $id => [$minimum, $maximum, $step, $value]) {
&& $control->getAttribute('value') === $value,
'Existing numeric field semantics changed: ' . $id);
}
$assert($xpath->query('//*[@id="host_id" or @id="price" or @id="stock"]')->length === 0,
'The base-plan editor still exposes host placement, offer pricing, or offer stock.');
$assert($xpath->query('//*[@id="host_id" or @id="price" or @id="stock" or @id="validity_days"]')->length === 0,
'The base-plan editor still exposes host placement, offer pricing, stock, or a mutable billing term.');
$one($xpath, '//select[@id="status"]');
$statusOptions = [];
foreach ($xpath->query('//select[@id="status"]/option') as $option) {
@ -161,9 +164,8 @@ $off = $parse($render($makeShop([
])));
$assert($one($off, '//select[@id="status"]/option[@selected]')->getAttribute('value') === '0'
&& $one($off, '//input[@id="memory_gb"]')->getAttribute('value') === '0.5'
&& $one($off, '//input[@id="traffic_tb"]')->getAttribute('value') === '0'
&& $one($off, '//input[@id="validity_days"]')->getAttribute('value') === '30',
'Disabled, unlimited-traffic, or default-period plan values were lost.');
&& $one($off, '//input[@id="traffic_tb"]')->getAttribute('value') === '0',
'Disabled or unlimited-traffic plan values were lost.');
$smallQuota = $parse($render($makeShop(['traffic_quota_bytes' => Shop::GIB])));
$assert($one($smallQuota, '//input[@id="traffic_tb"]')->getAttribute('value') === '0.0009765625',
'Rendering rounded away the supported one-GiB traffic increment.');

@ -378,7 +378,7 @@ $assert(str_contains(
$assert(str_contains(
$setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'"
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'"
), 'CloudSetup schema version was not advanced for abuse observation.');
foreach (array_keys($mainTables + $logTables) as $table) {

@ -96,7 +96,7 @@ foreach ($defaults->rules() as $code => $rule) {
'The fresh schema rule seed drifted from PHP: ' . $code);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($service, "->where('active_slot', 1)->lockForUpdate()")
&& str_contains($service, "->where('active_slot', 1)->update")
&& str_contains($service, 'insertGetId'),

@ -258,7 +258,7 @@ $assert(str_contains($projection, '->snapshotByIdentity($revision, $hash)')
&& !str_contains($projection, '->activeSnapshot()'),
'Projection can drift from the outbox identity to the current policy.');
$assert(str_contains($deployment,
'`go-agent-wss-v46-abuse-alert-delivery`')
'`go-agent-wss-v47-offer-billing-cycles`')
&& str_contains($deployment,
'`occurrence_generation = 1` 与 `transition_revision = 1`')
&& str_contains($deployment,

@ -50,7 +50,11 @@ $schema->create('cloud_offers', static function (Blueprint $table): void {
$table->string('code');
$table->string('name');
$table->string('price');
$table->string('quarterly_price');
$table->string('annual_price');
$table->string('backup_price');
$table->string('backup_quarterly_price');
$table->string('backup_annual_price');
$table->string('currency');
$table->integer('price_version');
$table->integer('revision');
@ -202,7 +206,11 @@ $capsule->table('cloud_offers')->insert([
'code' => 'half-period-offer',
'name' => 'Half period offer',
'price' => '20.00',
'quarterly_price' => '55.00',
'annual_price' => '200.00',
'backup_price' => '10.00',
'backup_quarterly_price' => '28.00',
'backup_annual_price' => '100.00',
'currency' => 'USD',
'price_version' => 3,
'revision' => 1,
@ -253,6 +261,45 @@ $assert($quote['full_period_amount'] === '10.00'
&& $quote['can_enable'] === true,
'Automatic backup quote did not expose the verified billing period.');
$quarterlyUser = new User();
$quarterlyUser->id = 17;
$quarterlyUser->enable = 1;
$quarterlyUser->money = '50.00';
$quarterlyUser->save();
$quarterlyStart = $now - (45 * 86400);
$quarterlyEnd = $now + (45 * 86400);
$quarterlyInstance = new CloudInstance();
$quarterlyInstance->id = 17;
$quarterlyInstance->user_id = 17;
$quarterlyInstance->offer_id = 9;
$quarterlyInstance->name = 'quarterly-billing-test-vm';
$quarterlyInstance->status = 'active';
$quarterlyInstance->service_status = 'active';
$quarterlyInstance->expires_at = $quarterlyEnd;
$quarterlyInstance->renewal_price = '55.00';
$quarterlyInstance->renewal_days = 90;
$quarterlyInstance->renewal_traffic_bytes = 0;
$quarterlyInstance->spec_json = '{}';
$quarterlyInstance->updated_at = $quarterlyStart;
$quarterlyInstance->save();
$quarterlyPeriodId = $capsule->table('cloud_service_periods')->insertGetId([
'instance_id' => 17, 'user_id' => 17, 'plan_id' => 4,
'order_id' => 17, 'renewal_id' => null,
'starts_at' => $quarterlyStart, 'ends_at' => $quarterlyEnd,
'status' => 'active', 'created_at' => $quarterlyStart,
'updated_at' => $quarterlyStart,
]);
$quarterlyInstance->current_period_id = $quarterlyPeriodId;
$quarterlyInstance->save();
$quarterlyQuote = CloudAutomaticBackupBillingService::quote(
$quarterlyInstance,
$quarterlyUser,
$now
);
$assert($quarterlyQuote['activation_amount'] === '14.00'
&& $quarterlyQuote['full_period_amount'] === '28.00',
'Quarterly automatic backup quote fell back to the monthly price.');
$actor = [
'user_id' => 7,
'request_idempotency_key' => 'backup-enable-test-0001',
@ -542,7 +589,11 @@ $capsule->table('cloud_offers')->insert([
'code' => 'upgraded-offer',
'name' => 'Upgraded offer',
'price' => '30.00',
'quarterly_price' => '85.00',
'annual_price' => '300.00',
'backup_price' => '12.00',
'backup_quarterly_price' => '34.00',
'backup_annual_price' => '120.00',
'currency' => 'USD',
'price_version' => 4,
'revision' => 1,

@ -64,7 +64,7 @@ foreach ([
'CloudSetup omits backup preparation contract: ' . $required);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup,
"'columns' => [\n 'create_request_actor_id',\n 'create_request_idempotency_key',")
&& str_contains($setup, "'non_unique' => 0"),

@ -73,6 +73,9 @@ $assert(str_contains($deployController, 'CloudAccess::actor(false)')
&& str_contains($deployController,
'$defaultRegionId = $regions === [] ? 0 : (int) $regions[0][\'id\']')
&& str_contains($deployController, "'default_line_id' => \$defaultLineId")
&& str_contains($deployController, "'cloud_deploy_quarterly_price'")
&& str_contains($deployController, "'cloud_deploy_annual_price'")
&& str_contains($deployController, "'cloud_deploy_annual_equivalent'")
&& str_contains($deployController, "'catalog_unavailable' => \$catalogUnavailable")
&& str_contains($deployController,
"'cloud_deploy_catalog_unavailable' => \$catalogUnavailable")
@ -105,6 +108,8 @@ $assert(str_contains($saleCatalog, "->join('shop as plan'")
&& str_contains($saleCatalog, "\$query->where('line.is_default', 1)")
&& str_contains($saleCatalog, "'lines_enabled' => \$linesEnabled")
&& str_contains($saleCatalog, "'currency' => 'USD'")
&& str_contains($saleCatalog, 'CloudOffer::BILLING_CYCLES')
&& str_contains($publicOfferDto, "'billing_cycles' => \$billingCycles")
&& str_contains($publicOfferDto, "'sellable' =>")
&& str_contains($saleCatalog, "'traffic_tib' => self::formatDecimalUnit(\$trafficGiB, 1024, 10)")
&& str_contains($service, 'private static function formatDecimalUnit(')
@ -149,6 +154,13 @@ $assert(str_contains($deployTemplate, 'id="deploy-bootstrap" type="application/j
&& str_contains($deployTemplate, '{$offer.traffic_tib|escape:"html"} TB')
&& !str_contains($deployTemplate, 'offer-option-price')
&& str_contains($deployTemplate, 'id="vm-automatic-backup"')
&& str_contains($deployTemplate, 'id="vm-billing-cycles"')
&& substr_count($deployTemplate, 'name="billing_cycle"') === 3
&& str_contains($deployTemplate, '$cloud_deploy_quarterly_price')
&& str_contains($deployTemplate, '$cloud_deploy_annual_price')
&& str_contains($deployTemplate, 'value="monthly" checked')
&& str_contains($deployTemplate, 'value="quarterly"')
&& str_contains($deployTemplate, 'value="annual"')
&& str_contains($deployTemplate, 'id="vm-order-total-price"')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_template_groups as $group}')
&& str_contains($deployTemplate, '{foreach $cloud_deploy_ssh_keys as $key}')
@ -222,6 +234,7 @@ $assert($selectRegion !== '' && $selectLine !== '' && $selectOffer !== ''
&& str_contains($runtime, 'function deploymentTemplates()')
&& str_contains($runtime, 'Array.isArray(item?.offer_ids)')
&& str_contains($buy, 'offer_id: Number(byId(\'vm-offer\').value)')
&& str_contains($buy, 'billing_cycle: state.deployBillingCycle')
&& str_contains($buy, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& str_contains($buy,
'body.cloud_snapshot_key = state.deployCloudSnapshotKey')
@ -274,6 +287,9 @@ $assert(str_contains($catalogApi, 'CloudDeploymentPageService::saleCatalog()')
'Catalog APIs must return offer-scoped deployment images or current-host reinstall images without exposing internal host identity.');
$assert(str_contains($runtime, 'return `$${amount.toFixed(2)} USD`;')
&& str_contains($runtime, 'function offerBillingCycles(offer)')
&& str_contains($runtime, 'function syncDeploymentBillingCycles(offer, backupSelected)')
&& str_contains($cloudStyles, '.deployment-billing-cycle.is-selected')
&& str_contains($runtime, 'formatTrafficTiB(offer.traffic_tib)')
&& str_contains($runtime, "amount.toFixed(10).replace(/\\.?0+\$/, '')")
&& !str_contains($runtime, "amount.toLocaleString('en-US', { minimumFractionDigits: 2"),

@ -293,7 +293,7 @@ namespace {
$schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->integer('address_family'); $t->string('cidr'); $t->string('gateway'); $t->boolean('gateway_on_link')->default(false); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('allocation_start')->nullable(); $t->string('allocation_end')->nullable(); $t->string('allocation_cursor')->nullable(); $t->integer('max_allocations')->default(0); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id'); $t->integer('address_family'); $t->string('address'); $t->binary('address_binary'); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable(); $t->integer('reservation_ip_claim_id')->nullable(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['address_family', 'address_binary']); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('backup_price')->default('0.00'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); });
$schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('quarterly_price'); $t->string('annual_price'); $t->string('backup_price')->default('0.00'); $t->string('backup_quarterly_price')->default('0.00'); $t->string('backup_annual_price')->default('0.00'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); });
$schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('catalog_key')->default('test-catalog'); $t->string('version_label')->default('test-version'); $t->boolean('is_default')->default(true); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('active_job_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); });
$schema->create('cloud_user_isos', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('active_job_id')->nullable(); });
$schema->create('cloud_template_replicas', function (Blueprint $t) { $t->integer('host_id'); $t->string('template_id'); $t->integer('job_id')->nullable(); $t->integer('revision'); $t->string('generation_token'); $t->string('state')->default('pending'); $t->integer('image_bytes')->default(0); $t->string('sha256')->default(''); $t->string('operation_id')->default(''); $t->string('error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->primary(['host_id', 'template_id']); });
@ -536,8 +536,8 @@ namespace {
}
$plan = new Shop(); $plan->name = 'plan'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->sort = 0; $plan->save();
$soldOutPlan = new Shop(); $soldOutPlan->name = 'sold-out-plan'; $soldOutPlan->cpu_cores = 2; $soldOutPlan->memory_mib = 2048; $soldOutPlan->bandwidth_mbps = 100; $soldOutPlan->disk_gib = 20; $soldOutPlan->validity_days = 30; $soldOutPlan->traffic_quota_bytes = 1024 * 1024 * 1024; $soldOutPlan->status = 1; $soldOutPlan->sort = 0; $soldOutPlan->save();
$offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->backup_price = '2.50'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save();
$soldOutOffer = new CloudOffer(); $soldOutOffer->plan_id = $soldOutPlan->id; $soldOutOffer->resource_pool_id = $pool->id; $soldOutOffer->code = 'sold-out-offer'; $soldOutOffer->name = 'Sold Out Offer'; $soldOutOffer->price = '8.99'; $soldOutOffer->backup_price = '0.00'; $soldOutOffer->currency = 'USD'; $soldOutOffer->price_version = 1; $soldOutOffer->status = 1; $soldOutOffer->stock = 0; $soldOutOffer->sort = 0; $soldOutOffer->created_at = $soldOutOffer->updated_at = $now; $soldOutOffer->save();
$offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->quarterly_price = '27.00'; $offer->annual_price = '99.00'; $offer->backup_price = '2.50'; $offer->backup_quarterly_price = '7.00'; $offer->backup_annual_price = '25.00'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save();
$soldOutOffer = new CloudOffer(); $soldOutOffer->plan_id = $soldOutPlan->id; $soldOutOffer->resource_pool_id = $pool->id; $soldOutOffer->code = 'sold-out-offer'; $soldOutOffer->name = 'Sold Out Offer'; $soldOutOffer->price = '8.99'; $soldOutOffer->quarterly_price = '25.00'; $soldOutOffer->annual_price = '89.00'; $soldOutOffer->backup_price = '0.00'; $soldOutOffer->backup_quarterly_price = '0.00'; $soldOutOffer->backup_annual_price = '0.00'; $soldOutOffer->currency = 'USD'; $soldOutOffer->price_version = 1; $soldOutOffer->status = 1; $soldOutOffer->stock = 0; $soldOutOffer->sort = 0; $soldOutOffer->created_at = $soldOutOffer->updated_at = $now; $soldOutOffer->save();
$template = new CloudTemplate();
$template->id = 'alma10-1234abcd-0123456789abcdef';
$template->name = 'AlmaLinux 10';
@ -591,7 +591,7 @@ namespace {
'updated_at' => $now,
]);
$actor = ['user_id' => 1, 'is_admin' => false, 'is_super_admin' => false, 'can_manage' => false, 'session_id' => ''];
$input = ['offer_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'idempotency_key' => 'test-request-key-0001'];
$input = ['offer_id' => 1, 'source' => 'cloud', 'name' => 'vm-one', 'template_id' => 'alma10-1234abcd-0123456789abcdef', 'billing_cycle' => 'monthly', 'idempotency_key' => 'test-request-key-0001'];
$catalogConnection = Capsule::connection('default');
$catalogConnection->flushQueryLog();
$catalogConnection->enableQueryLog();
@ -601,8 +601,52 @@ namespace {
$assert(count($catalog['offers'] ?? []) === 2
&& ($catalog['offers'][0]['sellable'] ?? null) === true
&& ($catalog['offers'][1]['sellable'] ?? null) === false
&& ($catalog['offers'][0]['billing_cycles'] ?? null) === [
['code' => 'monthly', 'days' => 30, 'price' => '9.99',
'backup_price' => '2.50'],
['code' => 'quarterly', 'days' => 90, 'price' => '27.00',
'backup_price' => '7.00'],
['code' => 'annual', 'days' => 365, 'price' => '99.00',
'backup_price' => '25.00'],
]
&& $catalogQueryCount <= 10,
'Catalog availability hid a sold-out offer, misclassified capacity, or queried per offer.');
try {
CloudOrderService::purchase(array_replace($input, [
'billing_cycle' => 'weekly',
'idempotency_key' => 'invalid-billing-cycle-0001',
]), $actor);
throw new RuntimeException('Unsupported billing cycle accepted.');
} catch (CloudError $error) {
$assert($error->httpStatus === 422,
'Unsupported billing cycle returned the wrong status.');
}
$catalogConnection->beginTransaction();
try {
$annualOrder = CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-annual',
'billing_cycle' => 'annual',
'automatic_backup' => true,
'idempotency_key' => 'annual-billing-cycle-0001',
]), $actor);
$annualSpec = json_decode(
(string) $annualOrder->spec_json,
true,
flags: JSON_THROW_ON_ERROR
);
$annualInvoice = CloudInvoice::where(
'order_id', (int) $annualOrder->id
)->firstOrFail();
$assert((string) $annualOrder->amount === '124.00'
&& ($annualSpec['billing_cycle'] ?? null) === 'annual'
&& (int) ($annualSpec['validity_days'] ?? 0) === 365
&& ($annualSpec['instance_price'] ?? null) === '99.00'
&& ($annualSpec['backup_price'] ?? null) === '25.00'
&& (int) $annualInvoice->validity_days === 365,
'Annual purchase did not freeze its exact duration and prices.');
} finally {
$catalogConnection->rollBack();
}
$host->default_network = 'public';
$host->save();
$catalogWithoutLegacyDefault = CloudDeploymentPageService::saleCatalog();
@ -852,6 +896,9 @@ namespace {
&& array_key_exists('traffic_pool_group_id', $firstSpec)
&& $firstSpec['traffic_pool_group_id'] === null
&& ($firstSpec['traffic_quota_mode'] ?? null) === 'finite'
&& ($firstSpec['billing_cycle'] ?? null) === 'monthly'
&& (int) ($firstSpec['validity_days'] ?? 0) === 30
&& (int) $openingInvoice->validity_days === 30
&& ($firstSpec['automatic_backup'] ?? null) === false
&& ($firstSpec['instance_price'] ?? null) === '9.99'
&& ($firstSpec['backup_price'] ?? null) === '0.00'
@ -1165,16 +1212,20 @@ namespace {
// queue, changing the wallet, or retaining its encrypted credential.
$abandoned = CloudOrderService::purchase(array_replace($input, [
'name' => 'vm-abandoned', 'idempotency_key' => 'test-request-key-abandoned',
'billing_cycle' => 'quarterly',
'automatic_backup' => true,
]), $actor);
$abandonedInvoice = CloudInvoice::where('order_id', $abandoned->id)->first();
$abandonedSpec = json_decode((string) $abandoned->spec_json, true,
flags: JSON_THROW_ON_ERROR);
$abandonedDisplay = CloudInvoiceService::display($abandonedInvoice);
$assert((string) $abandoned->amount === '12.49'
$assert((string) $abandoned->amount === '34.00'
&& (int) $abandonedInvoice->validity_days === 90
&& ($abandonedSpec['billing_cycle'] ?? null) === 'quarterly'
&& (int) ($abandonedSpec['validity_days'] ?? 0) === 90
&& ($abandonedSpec['automatic_backup'] ?? null) === true
&& ($abandonedSpec['instance_price'] ?? null) === '9.99'
&& ($abandonedSpec['backup_price'] ?? null) === '2.50'
&& ($abandonedSpec['instance_price'] ?? null) === '27.00'
&& ($abandonedSpec['backup_price'] ?? null) === '7.00'
&& array_column($abandonedDisplay['items'] ?? [], 'code')
=== ['instance', 'automatic_backup'],
'Automatic backup was not frozen as a separate opening-bill item.');
@ -1415,6 +1466,7 @@ namespace {
'source' => 'deployment_snapshot',
'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key,
'name' => 'vm-incompatible-backup',
'billing_cycle' => 'monthly',
'automatic_backup' => false,
'idempotency_key' => 'snapshot-source-contract-missing-0001',
], $actor);
@ -1447,6 +1499,7 @@ namespace {
'source' => 'deployment_snapshot',
'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key,
'name' => 'vm-two',
'billing_cycle' => 'monthly',
'automatic_backup' => false,
'idempotency_key' => 'test-request-key-0002',
], $actor);
@ -1455,6 +1508,7 @@ namespace {
'source' => 'deployment_snapshot',
'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key,
'name' => 'vm-two',
'billing_cycle' => 'monthly',
'automatic_backup' => false,
'idempotency_key' => 'test-request-key-0002',
], $actor);
@ -1709,6 +1763,7 @@ namespace {
'source' => 'deployment_snapshot',
'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key,
'name' => $name,
'billing_cycle' => 'monthly',
'automatic_backup' => false,
'idempotency_key' => $requestKey,
], $actor);

@ -27,10 +27,10 @@ $assert(stripos($schema, 'compatibility import') === false
$assert(!preg_match('/\bengine_[A-Za-z0-9_]*\b/', $schema),
'cloud.sql retained an engine-prefixed identifier.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& !str_contains($setup, "SCHEMA_VERSION = 'go-v1'")
&& str_contains($deployment, '`go-agent-wss-v46-abuse-alert-delivery`')
&& str_contains($compensation, '`go-agent-wss-v46-abuse-alert-delivery`'),
&& str_contains($deployment, '`go-agent-wss-v47-offer-billing-cycles`')
&& str_contains($compensation, '`go-agent-wss-v47-offer-billing-cycles`'),
'Outbound Agent schema must reject the incompatible earlier Go database.');
$assert(str_contains($schema,
"timezone VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'UTC'")
@ -131,7 +131,15 @@ $assert(str_contains($schema,
$assert(str_contains($schema,
'backup_restore_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($setup,
"'cloud_offers' => [\n 'backup_price',")
"'cloud_offers' => [\n 'price', 'quarterly_price', 'annual_price',\n 'backup_price', 'backup_quarterly_price',\n 'backup_annual_price',")
&& str_contains($schema,
'quarterly_price DECIMAL(12,2) NOT NULL DEFAULT 0.00')
&& str_contains($schema,
'annual_price DECIMAL(12,2) NOT NULL DEFAULT 0.00')
&& str_contains($schema,
'backup_quarterly_price DECIMAL(12,2) NOT NULL DEFAULT 0.00')
&& str_contains($schema,
'backup_annual_price DECIMAL(12,2) NOT NULL DEFAULT 0.00')
&& str_contains($schema,
'backup_recovery_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema,

@ -56,7 +56,7 @@ foreach ([
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'"),
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'"),
'CloudSetup schema version was not advanced for maintenance notices.');
echo "Maintenance notice schema contracts passed.\n";

@ -188,7 +188,11 @@ namespace {
$table->string('code')->unique();
$table->string('name');
$table->string('price');
$table->string('quarterly_price');
$table->string('annual_price');
$table->string('backup_price')->default('0.00');
$table->string('backup_quarterly_price')->default('0.00');
$table->string('backup_annual_price')->default('0.00');
$table->string('currency')->default('USD');
$table->integer('price_version');
$table->integer('revision');
@ -535,7 +539,10 @@ namespace {
'id' => $sourceOfferId, 'plan_id' => $sourcePlanId,
'resource_pool_id' => 1, 'code' => 'source-' . $sequence,
'name' => 'Source Offer ' . $sequence, 'price' => '10.00',
'quarterly_price' => '28.00', 'annual_price' => '100.00',
'backup_price' => '2.00',
'backup_quarterly_price' => '5.50',
'backup_annual_price' => '20.00',
'currency' => 'USD', 'price_version' => 1, 'revision' => 1,
'status' => 1, 'stock' => 5, 'sort' => 1,
'created_at' => $now, 'updated_at' => $now,
@ -544,7 +551,10 @@ namespace {
'id' => $targetOfferId, 'plan_id' => $targetPlanId,
'resource_pool_id' => 1, 'code' => 'target-' . $sequence,
'name' => 'Target Offer ' . $sequence, 'price' => '20.00',
'quarterly_price' => '55.00', 'annual_price' => '200.00',
'backup_price' => '3.00',
'backup_quarterly_price' => '8.00',
'backup_annual_price' => '30.00',
'currency' => 'USD', 'price_version' => 3, 'revision' => 4,
'status' => 1, 'stock' => 3, 'sort' => 2,
'created_at' => $now, 'updated_at' => $now,
@ -644,6 +654,54 @@ namespace {
'request_idempotency_key' => $key,
];
// The target plan's legacy validity_days must not collapse a purchased
// 90-day cycle back to monthly pricing during an in-place upgrade.
$quarterly = $fixture(10);
$quarterlyExpiresAt = $now + (45 * 86400);
$quarterlyInstance = CloudInstance::find($quarterly['instanceId']);
$quarterlySpec = json_decode(
(string) $quarterlyInstance->spec_json,
true,
flags: JSON_THROW_ON_ERROR
);
$quarterlySpec['billing_cycle'] = 'quarterly';
$quarterlySpec['validity_days'] = 90;
$quarterlySpec['renewal_price'] = '28.00';
$quarterlyInstance->expires_at = $quarterlyExpiresAt;
$quarterlyInstance->renewal_price = '28.00';
$quarterlyInstance->renewal_days = 90;
$quarterlyInstance->spec_json = json_encode(
$quarterlySpec,
JSON_THROW_ON_ERROR
);
$quarterlyInstance->save();
$connection->table('cloud_service_periods')
->where('id', $quarterly['periodId'])
->update([
'starts_at' => $now - (45 * 86400),
'ends_at' => $quarterlyExpiresAt,
]);
$connection->table('cloud_invoices')
->where('id', $quarterly['renewalInvoiceId'])
->update([
'renews_expires_at' => $quarterlyExpiresAt,
'due_at' => $quarterlyExpiresAt,
'amount' => '28.00',
'validity_days' => 90,
]);
$quarterlyOptions = CloudPlanUpgradeService::options(
$quarterlyInstance->fresh(),
User::find(1)
);
$quarterlyOption = $optionFor(
$quarterlyOptions,
$quarterly['targetOfferId']
);
$assert($quarterlyOption['amount'] === '13.50'
&& $quarterlyOption['renewal_price'] === '55.00'
&& (int) $quarterlyOption['validity_days'] === 90,
'Quarterly instance upgrade fell back to monthly duration or price.');
// A finite entitlement that already belongs to a shared pool cannot be
// converted to unlimited by an in-place upgrade. Reject it before the
// wallet, job, capacity and Agent-dispatch fences are created.

@ -53,7 +53,7 @@ $assert(is_string($schema)
'Public-pool replacement lacks durable batch, child, or claim schema.');
$assert(is_string($setup)
&& str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup,
"'cloud_public_ip_pool_replacement_batches'")
&& str_contains($setup,

@ -170,7 +170,7 @@ $assert(str_contains($setup,
'CloudSetup does not verify index uniqueness and ordered columns.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup, "'cloud_public_network_transitions'")
&& str_contains($setup, "'cloud_public_network_transition_ips'")
&& str_contains($setup, "'reservation_ip_claim_id'")

@ -57,7 +57,7 @@ $assert($replica !== ''
&& str_contains($replica, 'cleanup_resolved_at BIGINT UNSIGNED'),
'Rescue replica cannot prove exact identity or retain cleanup debt.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup, "'cloud_rescue_artifact_delete_due'")
&& str_contains($setup, "'cloud_rescue_replica_cleanup'"),
'CloudSetup version or rescue catalog indexes are incomplete.');

@ -218,7 +218,7 @@ foreach ([
'CloudSetup omits restore/migration ledger contract: ' . $required);
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($attemptModel,
"protected \$table = 'cloud_backup_restore_attempts';")
&& str_contains($attemptModel, "'active_attempt' => 'int'")

@ -105,7 +105,7 @@ $assert(str_contains($setup,
'CloudSetup lost the open-compensation fence index contract.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'"),
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'"),
'CloudSetup schema version was not advanced for service compensation.');
$appliedShape = preg_match(

@ -138,7 +138,7 @@ $assert(is_string($publicationModel)
&& str_contains($artifactModel, "'maximum_size_bytes' => 'int'"),
'Storage publication/artifact model contracts are incomplete.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'"),
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'"),
'CloudSetup schema version was not advanced for durable publications.');
echo "Storage publication schema contracts passed.\n";

@ -63,7 +63,7 @@ $assert(str_contains($schema,
&& str_contains($schema,
'CONSTRAINT chk_cloud_template_import_completion CHECK (')
&& str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'"),
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'"),
'Template imports are missing durable identity or terminal-state constraints.');
$assert(str_contains($routes, "'/admin/cloud-template-imports'")
&& str_contains($routes, "'/admin/cloud-template-imports/{id}'")

@ -71,7 +71,7 @@ $assert(str_contains($schema,
'Service-period traffic-pool identity is not frozen or indexed.');
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup, "'chk_cloud_traffic_entitlement_balance'")
&& str_contains($setup, "'cloud_traffic_ledger_sequence'"),
'CloudSetup schema version or named-object validation is incomplete.');

@ -35,7 +35,9 @@ $assert(str_contains($deploy, 'id="vm-automatic-backup"')
'Deployment must expose only the automatic-backup purchase choice and final total, never schedule controls or per-offer prices.');
$assert(str_contains($runtime, 'const backupAvailable = Boolean(offer);')
&& !str_contains($runtime, 'backup_available')
&& str_contains($runtime, 'Number(offer.backup_price)')
&& str_contains($runtime, 'function offerBillingCycles(offer)')
&& str_contains($runtime, 'const backupPrice = Number(item?.backup_price)')
&& str_contains($runtime, 'billing_cycle: state.deployBillingCycle')
&& str_contains($runtime, "automatic_backup: byId('vm-automatic-backup')?.checked === true")
&& str_contains($runtime,
"source: state.deployCloudSnapshotKey ? 'deployment_snapshot' : 'cloud'")

@ -101,7 +101,7 @@ $assert(str_contains($jobs, 'vpc_id BIGINT UNSIGNED DEFAULT NULL')
'Cloud jobs cannot be correlated to VPC or VPC-port work.');
$assert(str_contains($setup,
"private const SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"private const SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup, "'name' => 'cloud_vpc_enabled'")
&& str_contains($setup, "'value' => 'false'")
&& str_contains($setup,

@ -104,7 +104,7 @@ foreach ($models as $class => $modelTable) {
}
$assert(str_contains($setup,
"SCHEMA_VERSION = 'go-agent-wss-v46-abuse-alert-delivery'")
"SCHEMA_VERSION = 'go-agent-wss-v47-offer-billing-cycles'")
&& str_contains($setup,
"self::schema('ss.sql') . \"\\0\" . self::schema('cloud.sql')")
&& str_contains($setup,

Loading…
Cancel
Save