feat: separate base plans from sales offers

dev
admin 2 months ago
parent 74cd779901
commit 05f42e51bf

@ -3,6 +3,14 @@
namespace App\Controllers\Admin;
use App\Controllers\AdminController;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudNetworkLine;
use App\Models\CloudOffer;
use App\Models\CloudOrder;
use App\Models\CloudRegion;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\Shop;
use App\Services\AdminPermission;
use App\Utils\DatatablesHelper;
@ -12,13 +20,19 @@ class ShopController extends AdminController
{
public function index($request, $response, $args)
{
$columns = ['op' => '操作', 'id' => 'ID', 'name' => '套餐名称', 'host_id' => '宿主机 ID',
'cpu_cores' => 'CPU 核数', 'memory_gb' => '内存 GB', 'bandwidth_mbps' => '带宽 Mbps',
'disk_gib' => '磁盘 GB', 'validity_days' => '有效期(天)', 'traffic_tb' => '每期流量 TB',
'price' => '每期价格(USD)', 'status' => '状态', 'stock' => '库存', 'sort' => '排序'];
$columns = [
'op' => '操作', 'id' => 'ID', 'name' => '基础套餐',
'cpu_cores' => 'CPU 核数', 'memory_gb' => '内存 GB',
'bandwidth_mbps' => '带宽 Mbps', 'disk_gib' => '磁盘 GB',
'validity_days' => '每期天数', 'traffic_tb' => '每期流量 TB',
'offer_count' => '销售方案', 'active_offer_count' => '已上架方案',
'price_range' => '美元价格区间', 'status' => '套餐状态', 'sort' => '排序',
];
return $this->view()->assign('table_config', [
'total_column' => $columns, 'default_show_column' => array_keys($columns), 'ajax_url' => 'shop/ajax',
'total_column' => $columns,
'default_show_column' => array_keys($columns),
'ajax_url' => 'shop/ajax',
])->display('admin/shop/index.tpl');
}
@ -34,33 +48,136 @@ class ShopController extends AdminController
public function edit($request, $response, $args)
{
$shop = Shop::find((int) $args['id']);
$shop = Shop::find((int) ($args['id'] ?? 0));
if ($shop === null) {
return $response->withStatus(404);
}
return $this->view()->assign('shop', $shop)->display('admin/shop/edit.tpl');
return $this->view()->assign([
'shop' => $shop,
'offers' => $this->offerRows((int) $shop->id),
])->display('admin/shop/edit.tpl');
}
public function update($request, $response, $args)
{
$shop = Shop::find((int) $args['id']);
$shop = Shop::find((int) ($args['id'] ?? 0));
if ($shop === null) {
return $response->withJson(['ret' => 0, 'msg' => '套餐不存在'], 404);
return $response->withJson(['ret' => 0, 'msg' => '基础套餐不存在'], 404);
}
return $this->savePlan($request, $response, $shop);
}
public function offerCreate($request, $response, $args)
{
$shop = Shop::find((int) ($args['id'] ?? 0));
if ($shop === null) {
return $response->withStatus(404);
}
return $this->view()->assign([
'shop' => $shop,
'offer' => null,
'offer_pools' => $this->poolOptions(),
])->display('admin/shop/offer_form.tpl');
}
public function offerAdd($request, $response, $args)
{
$shop = Shop::find((int) ($args['id'] ?? 0));
if ($shop === null) {
return $response->withJson(['ret' => 0, 'msg' => '基础套餐不存在'], 404);
}
return $this->saveOffer($request, $response, $shop, null);
}
public function offerEdit($request, $response, $args)
{
$shop = Shop::find((int) ($args['id'] ?? 0));
$offer = CloudOffer::where('plan_id', (int) ($args['id'] ?? 0))
->where('id', (int) ($args['offer_id'] ?? 0))->first();
if ($shop === null || $offer === null) {
return $response->withStatus(404);
}
return $this->view()->assign([
'shop' => $shop,
'offer' => $offer,
'offer_pools' => $this->poolOptions(),
])->display('admin/shop/offer_form.tpl');
}
public function offerUpdate($request, $response, $args)
{
$shop = Shop::find((int) ($args['id'] ?? 0));
$offer = CloudOffer::where('plan_id', (int) ($args['id'] ?? 0))
->where('id', (int) ($args['offer_id'] ?? 0))->first();
if ($shop === null || $offer === null) {
return $response->withJson(['ret' => 0, 'msg' => '销售方案不存在'], 404);
}
return $this->saveOffer($request, $response, $shop, $offer);
}
public function offerDelete($request, $response, $args)
{
if (!AdminPermission::isSuperAdmin()) {
return $response->withJson(['ret' => 0, 'msg' => '只有超级管理员可以删除销售方案'], 403);
}
$planId = (int) ($args['id'] ?? 0);
$offerId = (int) ($args['offer_id'] ?? 0);
$offer = CloudOffer::where('plan_id', $planId)->where('id', $offerId)->first();
if ($offer === null) {
return $response->withJson(['ret' => 0, 'msg' => '销售方案不存在'], 404);
}
try {
$message = $offer->getConnection()->transaction(function () use ($planId, $offerId) {
$locked = CloudOffer::where('plan_id', $planId)->where('id', $offerId)
->lockForUpdate()->first();
if ($locked === null) {
throw new \InvalidArgumentException('销售方案不存在');
}
$referenced = CloudOrder::where('offer_id', $offerId)->exists()
|| CloudInvoice::where('offer_id', $offerId)->exists()
|| CloudInstance::where('offer_id', $offerId)->exists()
|| CloudResourceReservation::where('offer_id', $offerId)->exists();
if ($referenced) {
$locked->status = 0;
$locked->updated_at = time();
if (!$locked->save()) {
throw new \RuntimeException('销售方案下架失败');
}
return '销售方案已被业务记录引用,已下架并保留历史数据';
}
if (!$locked->delete()) {
throw new \RuntimeException('销售方案删除失败');
}
return '未被引用的销售方案已删除';
});
} catch (\InvalidArgumentException $exception) {
return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 404);
} catch (\Throwable $exception) {
error_log('Offer delete failed: ' . get_class($exception));
return $response->withJson(['ret' => 0, 'msg' => '销售方案删除失败'], 500);
}
return $response->withJson(['ret' => 1, 'msg' => $message]);
}
private function savePlan($request, $response, Shop $shop)
{
if (!AdminPermission::isSuperAdmin()) {
return $response->withJson(['ret' => 0, 'msg' => '只有管理员可以修改套餐'], 403);
return $response->withJson(['ret' => 0, 'msg' => '只有超级管理员可以修改基础套餐'], 403);
}
try {
$input = [];
foreach (['name', 'host_id', 'price', 'cpu_cores', 'memory_gb', 'bandwidth_mbps', 'disk_gib',
'validity_days', 'traffic_tb', 'status', 'stock', 'sort'] as $field) {
foreach ([
'name', 'cpu_cores', 'memory_gb', 'bandwidth_mbps', 'disk_gib',
'validity_days', 'traffic_tb', 'status', 'sort',
] as $field) {
$default = $shop->exists
? match ($field) {
'memory_gb' => $shop->memoryGB(),
@ -71,52 +188,262 @@ class ShopController extends AdminController
$input[$field] = $request->getParam($field, $default);
}
$values = Shop::validatePlan($input);
if ($values['host_id'] !== null && !\App\Models\CloudHost::where('id', $values['host_id'])->where('enabled', 1)->exists()) {
throw new \InvalidArgumentException('宿主机不存在或已禁用');
}
$now = time();
foreach ($values as $field => $value) {
$shop->$field = $value;
}
if (!$shop->exists) {
$shop->created_at = $now;
}
$shop->updated_at = $now;
if (!$shop->save()) {
throw new \RuntimeException('套餐保存失败');
throw new \RuntimeException('基础套餐保存失败');
}
} catch (\InvalidArgumentException $exception) {
return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 422);
} catch (\Throwable $exception) {
error_log('Plan save failed: ' . get_class($exception));
return $response->withJson(['ret' => 0, 'msg' => '套餐保存失败'], 500);
return $response->withJson(['ret' => 0, 'msg' => '基础套餐保存失败'], 500);
}
return $response->withJson([
'ret' => 1,
'msg' => '基础套餐已保存',
'plan_id' => (int) $shop->id,
'redirect' => '/admin/shop/' . (int) $shop->id . '/edit',
]);
}
private function saveOffer($request, $response, Shop $shop, ?CloudOffer $offer)
{
if (!AdminPermission::isSuperAdmin()) {
return $response->withJson(['ret' => 0, 'msg' => '只有超级管理员可以修改销售方案'], 403);
}
try {
$input = [];
foreach (['resource_pool_id', 'code', 'name', 'price', 'stock', 'status', 'sort'] as $field) {
$input[$field] = $request->getParam($field, $offer === null ? null : $offer->$field);
}
$expectedRevision = $offer === null ? 0 : filter_var(
$request->getParam('revision'), FILTER_VALIDATE_INT
);
if ($offer !== null && ($expectedRevision === false || $expectedRevision < 1)) {
throw new \InvalidArgumentException('销售方案修订号无效,请刷新页面后重试');
}
$values = CloudOffer::validateOffer($input);
if ((int) $values['status'] === 1 && (int) $shop->status !== 1) {
throw new \InvalidArgumentException('基础套餐已停用,不能上架销售方案');
}
$currentPoolId = $offer === null ? null : (int) $offer->resource_pool_id;
$saved = (new CloudOffer())->getConnection()->transaction(function () use (
$shop, $offer, $values, $expectedRevision, $currentPoolId
) {
$locked = $offer === null ? new CloudOffer() : CloudOffer::where('plan_id', (int) $shop->id)
->where('id', (int) $offer->id)->lockForUpdate()->first();
if ($locked === null) {
throw new \InvalidArgumentException('销售方案不存在');
}
if ($locked->exists && (int) $locked->revision !== (int) $expectedRevision) {
throw new \DomainException('销售方案已被其他管理员修改,请刷新页面后重试');
}
$this->lockAndAssertPoolAvailable(
(int) $values['resource_pool_id'],
$currentPoolId,
(int) $values['status']
);
if ($locked->exists
&& (int) $locked->resource_pool_id !== (int) $values['resource_pool_id']
&& $this->offerReferenced((int) $locked->id)) {
throw new \DomainException(
'已被订单、账单、实例或资源预留引用的销售方案不能更换资源池,请新建方案'
);
}
$duplicatePool = CloudOffer::where('plan_id', (int) $shop->id)
->where('resource_pool_id', (int) $values['resource_pool_id']);
$duplicateCode = CloudOffer::where('code', (string) $values['code']);
if ($locked->exists) {
$duplicatePool->where('id', '<>', (int) $locked->id);
$duplicateCode->where('id', '<>', (int) $locked->id);
}
if ($duplicatePool->exists()) {
throw new \InvalidArgumentException('该基础套餐在所选资源池中已有销售方案');
}
if ($duplicateCode->exists()) {
throw new \InvalidArgumentException('销售方案代码已被使用');
}
$priceChanged = $locked->exists && (string) $locked->price !== (string) $values['price'];
foreach ($values as $field => $value) {
$locked->$field = $value;
}
$locked->plan_id = (int) $shop->id;
if (!$locked->exists) {
$locked->price_version = 1;
$locked->revision = 1;
$locked->created_at = time();
} elseif ($priceChanged) {
$locked->price_version = max(1, (int) $locked->price_version) + 1;
}
if ($locked->exists) {
$locked->revision = max(1, (int) $locked->revision) + 1;
}
$locked->updated_at = time();
if (!$locked->save()) {
throw new \RuntimeException('销售方案保存失败');
}
return $locked;
});
} catch (\InvalidArgumentException $exception) {
return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 422);
} catch (\DomainException $exception) {
return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 409);
} catch (\Throwable $exception) {
if ((string) $exception->getCode() === '23000') {
return $response->withJson([
'ret' => 0,
'msg' => '销售方案代码或基础套餐与资源池的组合已存在',
], 422);
}
error_log('Offer save failed: ' . get_class($exception));
return $response->withJson(['ret' => 0, 'msg' => '销售方案保存失败'], 500);
}
return $response->withJson(['ret' => 1, 'msg' => '套餐已保存']);
return $response->withJson([
'ret' => 1,
'msg' => '销售方案已保存',
'offer_id' => (int) $saved->id,
'price_version' => (int) $saved->price_version,
'revision' => (int) $saved->revision,
'redirect' => '/admin/shop/' . (int) $shop->id . '/edit',
]);
}
private function lockAndAssertPoolAvailable(int $poolId, ?int $currentPoolId,
int $offerStatus): void
{
$poolRef = CloudResourcePool::find($poolId);
$lineRef = $poolRef === null ? null : CloudNetworkLine::find((int) $poolRef->line_id);
$regionId = $lineRef === null ? 0 : (int) $lineRef->region_id;
$region = $regionId < 1 ? null
: CloudRegion::where('id', $regionId)->lockForUpdate()->first();
$line = $lineRef === null ? null
: CloudNetworkLine::where('id', (int) $lineRef->id)->lockForUpdate()->first();
$pool = $poolRef === null ? null
: CloudResourcePool::where('id', (int) $poolRef->id)->lockForUpdate()->first();
if ($pool === null || (int) $pool->id !== $poolId) {
throw new \InvalidArgumentException('资源池不存在');
}
$active = (string) $pool->status === 'active'
&& $line !== null && (int) $pool->line_id === (int) $line->id
&& (string) $line->status === 'active'
&& $region !== null && (int) $line->region_id === (int) $region->id
&& (string) $region->status === 'active';
if (!$active && !($currentPoolId !== null && $poolId === $currentPoolId && $offerStatus === 0)) {
throw new \InvalidArgumentException(
'只能在已启用的地区、线路和资源池中上架销售方案'
);
}
}
private function offerReferenced(int $offerId): bool
{
return CloudOrder::where('offer_id', $offerId)->exists()
|| CloudInvoice::where('offer_id', $offerId)->exists()
|| CloudInstance::where('offer_id', $offerId)->exists()
|| CloudResourceReservation::where('offer_id', $offerId)->exists();
}
private function poolOptions(): array
{
return CloudResourcePool::query()->from('cloud_resource_pools as pool')
->join('cloud_network_lines as line', 'line.id', '=', 'pool.line_id')
->join('cloud_regions as region', 'region.id', '=', 'line.region_id')
->orderByDesc('region.sort')->orderBy('region.id')
->orderByDesc('line.sort')->orderBy('line.id')
->orderByDesc('pool.sort')->orderBy('pool.id')
->get([
'pool.id', 'pool.code', 'pool.name', 'pool.status',
'line.name as line_name', 'line.status as line_status',
'region.name as region_name', 'region.status as region_status',
])->map(static function ($pool) {
return [
'id' => (int) $pool->id,
'code' => (string) $pool->code,
'label' => (string) $pool->region_name . ' / ' . (string) $pool->line_name
. ' / ' . (string) $pool->name,
'active' => (string) $pool->status === 'active'
&& (string) $pool->line_status === 'active'
&& (string) $pool->region_status === 'active',
];
})->all();
}
private function offerRows(int $planId): array
{
return CloudOffer::query()->from('cloud_offers as offer')
->leftJoin('cloud_resource_pools as pool', 'pool.id', '=', 'offer.resource_pool_id')
->leftJoin('cloud_network_lines as line', 'line.id', '=', 'pool.line_id')
->leftJoin('cloud_regions as region', 'region.id', '=', 'line.region_id')
->where('offer.plan_id', $planId)
->orderByDesc('offer.sort')->orderBy('offer.id')
->get([
'offer.*', 'pool.name as pool_name', 'line.name as line_name',
'region.name as region_name',
])->map(static function ($offer) {
return [
'id' => (int) $offer->id,
'code' => (string) $offer->code,
'name' => (string) $offer->name,
'pool' => trim(implode(' / ', array_filter([
(string) $offer->region_name,
(string) $offer->line_name,
(string) $offer->pool_name,
], static fn ($value) => $value !== ''))),
'price' => '$' . number_format((float) $offer->price, 2, '.', ''),
'price_version' => (int) $offer->price_version,
'stock' => (int) $offer->stock,
'status' => (bool) $offer->status,
'sort' => (int) $offer->sort,
];
})->all();
}
public function deleteGet($request, $response, $args)
{
if (!AdminPermission::isSuperAdmin()) {
return $response->withJson(['ret' => 0, 'msg' => '只有管理员可以下架套餐'], 403);
return $response->withJson(['ret' => 0, 'msg' => '只有超级管理员可以下架基础套餐'], 403);
}
$shop = Shop::find((int) $request->getParam('id', 0));
if ($shop === null) {
return $response->withJson(['ret' => 0, 'msg' => '套餐不存在'], 404);
return $response->withJson(['ret' => 0, 'msg' => '基础套餐不存在'], 404);
}
$shop->status = 0;
$shop->save();
$shop->updated_at = time();
if (!$shop->save()) {
return $response->withJson(['ret' => 0, 'msg' => '基础套餐下架失败'], 500);
}
return $response->withJson(['ret' => 1, 'msg' => '套餐已下架']);
return $response->withJson(['ret' => 1, 'msg' => '基础套餐已下架,所属销售方案将不再对用户展示']);
}
public function ajax_shop($request, $response, $args)
{
$table = new Datatables(new DatatablesHelper());
$table->query('SELECT id AS op,id,name,host_id,cpu_cores,ROUND(memory_mib/1024,1) AS memory_gb,bandwidth_mbps,disk_gib,'
. 'validity_days,CASE WHEN traffic_quota_bytes=0 THEN 0 ELSE ROUND(traffic_quota_bytes/1099511627776,10) END AS traffic_tb,'
. 'price,status,stock,sort FROM shop');
$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 '
. '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,'
. "CASE WHEN EXISTS(SELECT 1 FROM cloud_offers offer WHERE offer.plan_id=shop.id) "
. "THEN CONCAT('$',FORMAT((SELECT MIN(offer.price) FROM cloud_offers offer WHERE offer.plan_id=shop.id),2),"
. "' - $',FORMAT((SELECT MAX(offer.price) FROM cloud_offers offer WHERE offer.plan_id=shop.id),2)) "
. "ELSE '未设置' END AS price_range,shop.status,shop.sort FROM shop");
$table->edit('op', static function ($data) {
if (!AdminPermission::isSuperAdmin()) {
return '<span class="text-muted">只读</span>';
}
$id = (int) $data['id'];
return '<a class="btn btn-brand" href="/admin/shop/' . $id . '/edit">编辑</a>';
$label = AdminPermission::isSuperAdmin() ? '编辑' : '查看';
return '<a class="btn btn-brand" href="/admin/shop/' . $id . '/edit">' . $label . '</a>';
});
$table->edit('name', static function ($data) {
return htmlspecialchars((string) $data['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
@ -131,14 +458,10 @@ class ShopController extends AdminController
return rtrim(rtrim(number_format((float) $data['traffic_tb'], 10, '.', ''), '0'), '.');
});
$table->edit('status', static function ($data) {
return (int) $data['status'] === 1 ? '上架' : '下架';
});
$table->edit('price', static function ($data) {
return '$' . number_format((float) $data['price'], 2, '.', '');
return (int) $data['status'] === 1 ? '已启用' : '已停用';
});
$response->getBody()->write($table->generate());
return $response;
}
}

@ -13,10 +13,65 @@ final class CloudOffer extends Model
'resource_pool_id' => 'int',
'price' => 'decimal:2',
'price_version' => 'int',
'revision' => 'int',
'status' => 'boolean',
'stock' => 'int',
'sort' => 'int',
'created_at' => 'int',
'updated_at' => 'int',
];
public static function validateOffer(array $input): array
{
$poolId = filter_var($input['resource_pool_id'] ?? null, FILTER_VALIDATE_INT);
if ($poolId === false || $poolId < 1) {
throw new \InvalidArgumentException('请选择有效的资源池');
}
$code = isset($input['code']) && is_string($input['code'])
? trim($input['code']) : '';
if (preg_match('/^[a-z0-9][a-z0-9_-]{0,63}$/D', $code) !== 1) {
throw new \InvalidArgumentException('销售方案代码需为 1 至 64 位小写字母、数字、下划线或连字符');
}
$name = isset($input['name']) && is_string($input['name']) ? trim($input['name']) : '';
if ($name === '' || mb_strlen($name) > 128) {
throw new \InvalidArgumentException('销售方案名称需为 1 至 128 个字符');
}
$price = $input['price'] ?? '';
if ((!is_string($price) && !is_int($price))
|| preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $price) !== 1) {
throw new \InvalidArgumentException('价格需为非负美元金额,最多两位小数');
}
$parts = explode('.', (string) $price);
$whole = ltrim($parts[0], '0');
$normalizedPrice = ($whole === '' ? '0' : $whole) . '.'
. str_pad($parts[1] ?? '', 2, '0');
$data = [
'resource_pool_id' => (int) $poolId,
'code' => $code,
'name' => $name,
'price' => $normalizedPrice,
'currency' => 'USD',
];
foreach ([
'status' => [0, 1, 1, '销售状态'],
'stock' => [-1, 2147483647, -1, '库存'],
'sort' => [-1000000, 1000000, 0, '排序'],
] as $field => [$minimum, $maximum, $default, $label]) {
$raw = $input[$field] ?? $default;
$value = is_string($raw) || is_int($raw)
? filter_var($raw, FILTER_VALIDATE_INT) : false;
if ($value === false || $value < $minimum || $value > $maximum) {
throw new \InvalidArgumentException(
$label . ' 需为 ' . $minimum . ' 至 ' . $maximum . ' 的整数'
);
}
$data[$field] = (int) $value;
}
return $data;
}
}

@ -11,11 +11,9 @@ class Shop extends Model
protected $table = 'shop';
protected $casts = [
'host_id' => 'int',
'cpu_cores' => 'int', 'memory_mib' => 'int', 'bandwidth_mbps' => 'int',
'disk_gib' => 'int', 'validity_days' => 'int', 'traffic_quota_bytes' => 'int',
'status' => 'int', 'stock' => 'int', 'sort' => 'int',
'price' => 'decimal:2',
'status' => 'int', 'sort' => 'int',
'created_at' => 'int', 'updated_at' => 'int',
];
@ -53,23 +51,13 @@ class Shop extends Model
throw new \InvalidArgumentException('套餐名称需为 1 至 128 个字符');
}
$data = ['name' => $name];
$host = $input['host_id'] ?? null;
if ($host === null || $host === '') {
$data['host_id'] = null;
} else {
$host = filter_var($host, FILTER_VALIDATE_INT);
if ($host === false || $host < 1) {
throw new \InvalidArgumentException('请选择有效的宿主机');
}
$data['host_id'] = $host;
}
foreach ([
'cpu_cores' => [1, 64],
'bandwidth_mbps' => [1, 100000], 'disk_gib' => [1, 4096],
'validity_days' => [1, 3650],
'status' => [0, 1], 'stock' => [-1, 2147483647], 'sort' => [-1000000, 1000000],
'status' => [0, 1], 'sort' => [-1000000, 1000000],
] as $field => [$minimum, $maximum]) {
$raw = $input[$field] ?? (['status' => 1, 'stock' => -1, 'sort' => 0][$field] ?? null);
$raw = $input[$field] ?? (['status' => 1, 'sort' => 0][$field] ?? null);
$value = is_string($raw) || is_int($raw) ? filter_var($raw, FILTER_VALIDATE_INT) : false;
if ($value === false || $value < $minimum || $value > $maximum) {
throw new \InvalidArgumentException($field . ' 需为 ' . $minimum . ' 至 ' . $maximum . ' 的整数');
@ -89,16 +77,6 @@ class Shop extends Model
throw new \InvalidArgumentException('每期流量额度的最小步进为 1 GiB(1/1024 TB)');
}
$data['traffic_quota_bytes'] = (int) round($trafficGiB) * self::GIB;
$price = $input['price'] ?? '';
if ((!is_string($price) && !is_int($price)) || preg_match('/^\d{1,10}(?:\.\d{1,2})?$/D', (string) $price) !== 1) {
throw new \InvalidArgumentException('价格需为非负金额,最多两位小数');
}
$parts = explode('.', (string) $price);
$data['price'] = ltrim($parts[0], '0');
if ($data['price'] === '') {
$data['price'] = '0';
}
$data['price'] .= '.' . str_pad($parts[1] ?? '', 2, '0');
return $data;
}

@ -199,9 +199,14 @@ $app->group('/admin', function () {
$this->get('/shop/create', 'App\Controllers\Admin\ShopController:create')->add(new SuperAdmin());
$this->post('/shop', 'App\Controllers\Admin\ShopController:add')->add(new SuperAdmin());
$this->get('/shop/{id}/edit', 'App\Controllers\Admin\ShopController:edit')->add(new SuperAdmin());
$this->get('/shop/{id}/edit', 'App\Controllers\Admin\ShopController:edit');
$this->put('/shop/{id}', 'App\Controllers\Admin\ShopController:update')->add(new SuperAdmin());
$this->delete('/shop', 'App\Controllers\Admin\ShopController:deleteGet')->add(new SuperAdmin());
$this->get('/shop/{id}/offers/create', 'App\Controllers\Admin\ShopController:offerCreate')->add(new SuperAdmin());
$this->post('/shop/{id}/offers', 'App\Controllers\Admin\ShopController:offerAdd')->add(new SuperAdmin());
$this->get('/shop/{id}/offers/{offer_id}/edit', 'App\Controllers\Admin\ShopController:offerEdit');
$this->put('/shop/{id}/offers/{offer_id}', 'App\Controllers\Admin\ShopController:offerUpdate')->add(new SuperAdmin());
$this->delete('/shop/{id}/offers/{offer_id}', 'App\Controllers\Admin\ShopController:offerDelete')->add(new SuperAdmin());
// Ann Mange
$this->get('/announcement', 'App\Controllers\Admin\AnnController:index');

@ -255,10 +255,10 @@ window.__VENIX_ADMIN_TABLE__ = {
function cellValue(column, item) {
if (column.action === 'shopActions') {
var disabled = item.status === '下架';
var editAction = canManage
? '<a class="btn btn-sm btn-light" href="/admin/shop/' + escapeHtml(item.id) + '/edit"><i class="mdi mdi-pencil-outline me-1"></i>编辑</a>'
: '<button class="btn btn-sm btn-light" type="button" disabled aria-disabled="true">编辑</button>';
var disabled = item.status === '下架' || item.status === '已停用';
var editAction = '<a class="btn btn-sm btn-light" href="/admin/shop/' + escapeHtml(item.id) + '/edit"><i class="mdi ' +
(canManage ? 'mdi-pencil-outline' : 'mdi-eye-outline') + ' me-1"></i>' +
(canManage ? '编辑' : '查看') + '</a>';
return '<div class="admin-log-row-actions">' + editAction +
'<button class="btn btn-sm btn-danger" type="button" data-log-action="delete" data-log-id="' + escapeHtml(item.id) + '"' + (disabled || !canManage ? ' disabled' : '') + ' aria-disabled="' + (disabled || !canManage ? 'true' : 'false') + '"><i class="mdi mdi-tray-arrow-down me-1"></i>下架</button></div>';
}

@ -1,15 +1,34 @@
{assign var=admin_title value='新增商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'}
<div class="py-3"><h4>新增云服务器套餐</h4><p class="text-muted">绑定宿主机并设置账期、每期流量额度后,用户部署时会先生成支持余额或在线支付的开通账单;支付成功后才创建实例,到期前再自动生成续费账单。</p><a class="btn btn-light" href="/admin/shop">返回商品列表</a></div>
<form class="card" id="shopForm" data-method="POST" data-url="/admin/shop"><div class="card-body"><div class="row g-3"><div class="col-12"><label class="form-label" for="name">商品名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" value="" required></div>
<div class="col-md-6"><label class="form-label" for="cpu_cores">CPU 核数</label><input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="2" required></div>
<div class="col-md-6"><label class="form-label" for="host_id">开通宿主机</label><select class="form-select" id="host_id" name="host_id" data-selected=""><option value="">未绑定(禁止购买)</option></select></div>
<div class="col-md-6"><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"><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="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"><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="100000000" step="0.01" value="0" required></div></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">每个账期独立计算下载与上传合计额度;填 0 表示不限流量。</div></div>
<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="100" required></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></div><p id="shopFormStatus" class="admin-config-status">待保存</p><button class="btn btn-primary" id="shopFormSubmit" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>保存商品</button></div></form><div class="admin-toast" id="shopFormToast"></div>
{include file='admin/shop/form_js.tpl'}{include file='admin/static_footer.tpl'}
{assign var=admin_title value='新增基础套餐'}
{assign var=admin_active value='shop'}
{include file='admin/static_header.tpl'}
<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>
</div>
<div class="admin-config-actions flex-shrink-0">
<span id="shopFormStatus" class="admin-config-status" role="status" aria-live="polite">待保存</span>
<a class="btn btn-light" href="/admin/shop">返回套餐列表</a>
<button class="btn btn-primary" id="shopFormSubmit" type="submit" form="shopForm" {if !$admin_can_manage|default:false}disabled{/if}>保存并配置销售方案</button>
</div>
</div>
<form class="card" id="shopForm" data-method="POST" data-url="/admin/shop">
<div class="card-body">
<div class="row g-3">
<div class="col-12"><label class="form-label" for="name">套餐名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" required></div>
<div class="col-md-6 col-xl-3"><label class="form-label" for="cpu_cores">CPU 核数</label><input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="2" required></div>
<div class="col-md-6 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>
</div>
</div>
</form>
<div class="admin-toast" id="shopFormToast"></div>
{include file='admin/shop/form_js.tpl'}
{include file='admin/static_footer.tpl'}

@ -1,85 +1,68 @@
{assign var=admin_title value='编辑商品'}
{assign var=admin_title value='编辑基础套餐'}
{assign var=admin_active value='shop'}
{include file='admin/static_header.tpl'}
<div class="py-3 d-flex align-items-xl-center flex-xl-row flex-column gap-3">
<div class="flex-grow-1">
<h4 class="fs-20 fw-semibold mb-1">编辑云服务器套餐</h4>
<p class="text-muted mb-0">绑定宿主机后,用户可用余额购买开通。修改套餐不会改变已经开通的虚拟机。</p>
<h1 class="fs-20 fw-semibold mb-1">基础套餐与销售方案</h1>
<p class="text-muted mb-0">资源规格与销售位置解耦;同一套餐可在多个资源池中使用不同价格、库存和上下架状态。</p>
</div>
<div class="admin-config-actions flex-shrink-0">
<span id="shopFormStatus" class="admin-config-status" role="status" aria-live="polite">待保存</span>
<a class="btn btn-light" href="/admin/shop">返回商品列表</a>
<button class="btn btn-primary" id="shopFormSubmit" type="submit" form="shopForm" {if !$admin_can_manage|default:false}disabled{/if}>保存商品</button>
<span id="shopFormStatus" class="admin-config-status" role="status" aria-live="polite">{if $admin_can_manage|default:false}待保存{else}只读模式{/if}</span>
<a class="btn btn-light" href="/admin/shop">返回套餐列表</a>
<button class="btn btn-primary" id="shopFormSubmit" type="submit" form="shopForm" {if !$admin_can_manage|default:false}disabled{/if}>保存基础套餐</button>
</div>
</div>
<form class="card" id="shopForm" data-method="PUT" data-url="/admin/shop/{$shop->id}">
<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-body">
<div class="row g-3">
<div class="col-md-6">
<label class="form-label" for="name">商品名称</label>
<input class="form-control" id="name" name="name" type="text" maxlength="128" value="{$shop->name|escape:'html'}" required>
</div>
<div class="col-md-6">
<label class="form-label" for="host_id">开通宿主机</label>
<select class="form-select" id="host_id" name="host_id" data-selected="{$shop->host_id|default:''|escape:'html'}">
<option value="">未绑定(禁止购买)</option>
</select>
</div>
<div class="col-md-6 col-xl-3">
<label class="form-label" for="cpu_cores">CPU 核数</label>
<input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="{$shop->cpu_cores|escape:'html'}" required>
</div>
<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>
</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>
</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>
</div>
<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="100000000" step="0.01" value="{$shop->price|escape:'html'}" required>
</div>
</div>
<div class="col-md-6 col-xl-4">
<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>
<div class="form-text">购买或续费一次增加的服务天数;修改后不追溯已有服务周期。</div>
</div>
<div class="col-md-6 col-xl-4">
<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>
<div class="form-text">每个账期独立计算下载与上传合计额度;填 0 表示不限流量,修改后不追溯已有实例。</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="{$shop->stock|escape:'html'}" required>
</div>
<div class="col-md-6 col-xl-4">
<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>
</div>
<div class="col-md-6 col-xl-4">
<label class="form-label" for="status">状态</label>
<select class="form-select" id="status" name="status">
<option value="1" {if $shop->status == 1}selected{/if}>上架</option>
<option value="0" {if $shop->status == 0}selected{/if}>下架</option>
</select>
<form id="shopForm" data-method="PUT" data-url="/admin/shop/{$shop->id|escape:'html'}">
<div class="row g-3">
<div class="col-12"><label class="form-label" for="name">套餐名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" value="{$shop->name|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="cpu_cores">CPU 核数</label><input class="form-control" id="cpu_cores" name="cpu_cores" type="number" min="1" max="64" step="1" value="{$shop->cpu_cores|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="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>
</div>
</form>
</div>
</section>
<section class="card" aria-labelledby="offer-list-title">
<div class="card-header d-flex align-items-center justify-content-between gap-2 flex-wrap">
<div><h2 class="h5 card-title mb-1" id="offer-list-title">销售方案</h2><p class="text-muted fs-13 mb-0">价格固定为 USD;资源池决定地区、线路和可调度宿主机范围。</p></div>
{if $admin_can_manage|default:false}<a class="btn btn-primary" href="/admin/shop/{$shop->id|escape:'html'}/offers/create"><i class="mdi mdi-plus me-1" aria-hidden="true"></i>新增销售方案</a>{else}<button class="btn btn-primary" type="button" disabled>新增销售方案</button>{/if}
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover align-middle mb-0">
<caption class="visually-hidden">基础套餐的销售方案</caption>
<thead><tr><th>方案</th><th>地区 / 线路 / 资源池</th><th>价格</th><th>库存</th><th>价格版本</th><th>状态</th><th class="text-end">操作</th></tr></thead>
<tbody>
{foreach $offers as $item}
<tr>
<td><div class="fw-semibold">{$item.name|escape}</div><span class="text-muted fs-12">{$item.code|escape} · #{$item.id|escape}</span></td>
<td class="text-muted">{$item.pool|default:'资源池不可用'|escape}</td>
<td class="fw-semibold">{$item.price|escape}</td>
<td>{if $item.stock == -1}不限{else}{$item.stock|escape}{/if}</td>
<td>v{$item.price_version|escape}</td>
<td><span class="badge {if $item.status}text-bg-success{else}text-bg-light{/if}">{if $item.status}已上架{else}已下架{/if}</span></td>
<td class="text-end"><a class="btn btn-sm btn-light" href="/admin/shop/{$shop->id|escape:'html'}/offers/{$item.id|escape:'html'}/edit">{if $admin_can_manage|default:false}编辑{else}查看{/if}</a></td>
</tr>
{foreachelse}
<tr><td colspan="7" class="text-center text-muted py-4">尚未配置销售方案,该基础套餐不会出现在用户购买页。</td></tr>
{/foreach}
</tbody>
</table>
</div>
</div>
</form>
</section>
<div class="admin-toast" id="shopFormToast"></div>
{include file='admin/shop/form_js.tpl'}
{include file='admin/static_footer.tpl'}

@ -5,80 +5,66 @@
var submit = document.getElementById('shopFormSubmit');
var status = document.getElementById('shopFormStatus');
var toast = document.getElementById('shopFormToast');
var fields = ['name','host_id','price','validity_days','traffic_tb','cpu_cores','memory_gb','bandwidth_mbps','disk_gib','status','stock','sort'];
var hostSelect = document.getElementById('host_id');
var submitLocked = submit ? submit.disabled : false;
if (hostSelect) {
fetch('/api/v1/admin/hosts', {credentials: 'same-origin'})
.then(function (response) { if (!response.ok) throw new Error('宿主机列表读取失败'); return response.json(); })
.then(function (data) {
var hosts = Array.isArray(data.hosts) ? data.hosts : (Array.isArray(data.items) ? data.items : []);
hosts.forEach(function (host) {
if (!host.enabled) return;
var option = document.createElement('option');
option.value = String(host.id);
option.textContent = host.name + (host.region ? ' · ' + host.region : '');
hostSelect.appendChild(option);
});
var selected = hostSelect.getAttribute('data-selected') || '';
if (selected && !Array.from(hostSelect.options).some(function (option) { return option.value === selected; })) {
var unavailable = document.createElement('option');
unavailable.value = selected;
unavailable.textContent = '已绑定宿主机不可用(ID ' + selected + ')';
hostSelect.appendChild(unavailable);
}
hostSelect.value = selected;
}).catch(function (error) { setStatus(error.message + ',请先配置宿主机', 'is-error'); submit.disabled = true; });
}
var fields = ['name', 'cpu_cores', 'memory_gb', 'bandwidth_mbps', 'disk_gib',
'validity_days', 'traffic_tb', 'status', 'sort'];
var submitLocked = !submit || submit.disabled;
function get(id) {
var el = document.getElementById(id);
return el ? el.value : '';
function value(id) {
var control = document.getElementById(id);
return control ? control.value : '';
}
function showToast(text, type) {
if (!toast) return;
toast.textContent = text;
toast.className = 'admin-toast is-show ' + (type || '');
setTimeout(function () { toast.className = 'admin-toast'; }, 2400);
window.setTimeout(function () { toast.className = 'admin-toast'; }, 2400);
}
function setStatus(text, type) {
if (!status) return;
status.textContent = text;
status.className = 'admin-config-status ' + (type || '');
}
function buildParams() {
var params = new URLSearchParams();
fields.forEach(function (id) { params.set(id, get(id)); });
return params;
function buildBody() {
var body = new URLSearchParams();
fields.forEach(function (field) { body.set(field, value(field)); });
return body.toString();
}
function save(event) {
event.preventDefault();
if (submitLocked) return;
if (!get('name')) {
showToast('商品名称不能为空', 'is-error');
if (submitLocked || !form || !submit) return;
if (!value('name').trim()) {
showToast('套餐名称不能为空', 'is-error');
return;
}
submit.disabled = true;
var original = submit.innerHTML;
submit.innerHTML = '<i class="mdi mdi-loading mdi-spin me-1"></i>保存中';
setStatus('保存中', 'is-loading');
fetch(form.getAttribute('data-url'), {
method: form.getAttribute('data-method'),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
body: buildParams().toString(),
body: buildBody(),
credentials: 'same-origin'
}).then(function (response) { return response.json(); }).then(function (data) {
showToast(data.msg || '操作完成', data.ret ? 'is-success' : 'is-error');
setStatus(data.ret ? '已保存' : '保存失败', data.ret ? 'is-success' : 'is-error');
if (data.ret) {
setTimeout(function () { location.href = '/admin/shop'; }, 700);
}
}).catch(function () {
}).then(function (response) {
return response.json().then(function (data) {
return {ok: response.ok, data: data};
});
}).then(function (result) {
var data = result.data || {};
if (!result.ok || !data.ret) throw new Error(data.msg || '保存失败');
showToast(data.msg || '基础套餐已保存', 'is-success');
setStatus('已保存', 'is-success');
window.setTimeout(function () {
location.href = data.redirect || '/admin/shop';
}, 500);
}).catch(function (error) {
setStatus('保存失败', 'is-error');
showToast('保存请求失败', 'is-error');
showToast(error.message || '保存请求失败', 'is-error');
}).finally(function () {
submit.disabled = submitLocked;
submit.innerHTML = original;
@ -87,7 +73,9 @@
if (form) {
form.addEventListener('submit', save);
form.addEventListener('input', function () { setStatus('有未保存修改', 'is-loading'); });
form.addEventListener('input', function () {
if (!submitLocked) setStatus('有未保存修改', 'is-loading');
});
}
})();
</script>

@ -1,18 +1,18 @@
{assign var=admin_title value='商品管理'}
{assign var=admin_title value='套餐与销售方案'}
{assign var=admin_active value='shop'}
{assign var=page_title value='商品列表'}
{assign var=page_desc value='管理云服务器套餐资源规格、账期、每期流量额度、价格、库存和上下架状态。'}
{assign var=page_title value='基础套餐'}
{assign var=page_desc value='统一管理云服务器规格、账期和流量;每个基础套餐可按资源池配置多个独立销售方案。'}
{assign var=page_icon value='mdi-storefront-outline'}
{assign var=admin_table_storage_key value='venix-admin-shop-columns'}
{assign var=admin_table_storage_key value='venix-admin-base-plans-columns-v2'}
{assign var=admin_table_ajax_url value='/admin/shop/ajax'}
{assign var=admin_table_default_sort value='sort'}
{assign var=admin_table_default_dir value='desc'}
{assign var=admin_table_delete_url value='/admin/shop'}
{assign var=admin_table_delete_text value='下架后商品不会继续展示,不会删除历史订单。'}
{assign var=admin_table_delete_text value='下架基础套餐后,其所有销售方案都不再对用户展示,历史订单保留。'}
{assign var=admin_table_delete_button_text value='确认下架'}
{assign var=admin_table_create_url value='/admin/shop/create'}
{assign var=admin_table_create_text value='新增商品'}
{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":"120px"},{"key":"name","label":"商品名称","width":"120px"},{"key":"cpu_cores","label":"CPU","width":"120px"},{"key":"memory_gb","label":"内存 GB","width":"120px"},{"key":"bandwidth_mbps","label":"带宽 Mbps","width":"120px"},{"key":"disk_gib","label":"硬盘 GB","width":"120px"},{"key":"validity_days","label":"每期天数","width":"130px"},{"key":"traffic_tb","label":"每期流量 TB(0=不限)","width":"190px"},{"key":"price","label":"每期价格(USD)","width":"150px"},{"key":"status","label":"状态","width":"120px"},{"key":"stock","label":"库存","width":"120px"},{"key":"sort","label":"排序","width":"120px"}]'}
{assign var=admin_table_default_columns_json value='["op","id","name","cpu_cores","memory_gb","bandwidth_mbps","disk_gib","validity_days","traffic_tb","price","status","stock","sort"]'}
{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"]'}
{include file='admin/components/table_page.tpl'}

@ -0,0 +1,76 @@
{if $offer}
{assign var=admin_title value='编辑销售方案'}
{assign var=offer_pool_id value=$offer->resource_pool_id}
{assign var=offer_code value=$offer->code}
{assign var=offer_name value=$offer->name}
{assign var=offer_price value=$offer->price}
{assign var=offer_stock value=$offer->stock}
{assign var=offer_sort value=$offer->sort}
{else}
{assign var=admin_title value='新增销售方案'}
{assign var=offer_pool_id value=0}
{assign var=offer_code value=''}
{assign var=offer_name value=''}
{assign var=offer_price value='0.00'}
{assign var=offer_stock value=-1}
{assign var=offer_sort value=0}
{/if}
{assign var=admin_active value='shop'}
{include file='admin/static_header.tpl'}
<div class="py-3 d-flex align-items-xl-center flex-xl-row flex-column gap-3">
<div class="flex-grow-1">
<p class="text-primary fs-13 fw-semibold text-uppercase mb-1">{$shop->name|escape}</p>
<h1 class="fs-20 fw-semibold mb-1">{if $offer}编辑销售方案{else}新增销售方案{/if}</h1>
<p class="text-muted mb-0">一个基础套餐在每个资源池中最多建立一个销售方案,价格固定使用 USD。</p>
</div>
<div class="admin-config-actions flex-shrink-0">
<span id="offerFormStatus" class="admin-config-status" role="status" aria-live="polite">{if $admin_can_manage|default:false}待保存{else}只读模式{/if}</span>
<a class="btn btn-light" href="/admin/shop/{$shop->id|escape:'html'}/edit">返回套餐</a>
<button class="btn btn-primary" id="offerFormSubmit" type="submit" form="offerForm" {if !$admin_can_manage|default:false}disabled{/if}>保存销售方案</button>
</div>
</div>
<form class="card" id="offerForm" data-method="{if $offer}PUT{else}POST{/if}" data-url="/admin/shop/{$shop->id|escape:'html'}/offers{if $offer}/{$offer->id|escape:'html'}{/if}">
<input id="revision" name="revision" type="hidden" value="{if $offer}{$offer->revision|default:1|escape:'html'}{else}0{/if}">
<div class="card-body">
{if !$offer_pools}
<div class="alert alert-warning" role="alert">尚未建立地区、线路和资源池,请先在“资源调度”中完成配置。</div>
{/if}
<div class="row g-3">
<div class="col-12">
<label class="form-label" for="resource_pool_id">资源池</label>
<select class="form-select" id="resource_pool_id" name="resource_pool_id" required {if !$admin_can_manage|default:false}disabled{/if}>
<option value="">请选择资源池</option>
{foreach $offer_pools as $pool}
<option value="{$pool.id|escape:'html'}" {if $offer_pool_id == $pool.id}selected{/if} {if !$pool.active && $offer_pool_id != $pool.id}disabled{/if}>{$pool.label|escape}{if !$pool.active} · 已停用{/if}</option>
{/foreach}
</select>
<div class="form-text">新方案只能选择已启用的地区、线路和资源池;已有方案可保留原有停用资源池以供查看。</div>
</div>
<div class="col-md-6">
<label class="form-label" for="code">方案代码</label>
<input class="form-control" id="code" name="code" type="text" maxlength="64" pattern="[a-z0-9][a-z0-9_-]{ldelim}0,63{rdelim}" value="{$offer_code|escape:'html'}" placeholder="tokyo-standard" 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="name">方案名称</label><input class="form-control" id="name" name="name" type="text" maxlength="128" value="{$offer_name|escape:'html'}" placeholder="东京标准线路" required {if !$admin_can_manage|default:false}disabled{/if}></div>
<div class="col-md-6 col-xl-3"><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-3"><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-3"><label class="form-label" for="sort">排序</label><input class="form-control" id="sort" name="sort" type="number" min="-1000000" max="1000000" step="1" value="{$offer_sort|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="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>
</div>
</div>
</form>
{if $offer && $admin_can_manage|default:false}
<div class="card mt-3">
<div class="card-body d-flex align-items-center justify-content-between gap-3 flex-wrap">
<div><h2 class="h5 mb-1">删除销售方案</h2><p class="text-muted mb-0">未被业务记录引用时可物理删除;已被引用时系统仅会下架并保留历史数据。</p></div>
<button class="btn btn-danger" id="offerDeleteButton" type="button" data-url="/admin/shop/{$shop->id|escape:'html'}/offers/{$offer->id|escape:'html'}">删除销售方案</button>
</div>
</div>
{/if}
<div class="admin-toast" id="offerFormToast"></div>
{include file='admin/shop/offer_form_js.tpl'}
{include file='admin/static_footer.tpl'}

@ -0,0 +1,105 @@
{literal}
<script>
(function () {
var form = document.getElementById('offerForm');
var submit = document.getElementById('offerFormSubmit');
var status = document.getElementById('offerFormStatus');
var toast = document.getElementById('offerFormToast');
var deleteButton = document.getElementById('offerDeleteButton');
var fields = ['resource_pool_id', 'code', 'name', 'price', 'stock', 'status', 'sort', 'revision'];
var submitLocked = !submit || submit.disabled;
var deleteArmed = false;
var deleteArmTimer = null;
function value(id) {
var control = document.getElementById(id);
return control ? control.value : '';
}
function body() {
var params = new URLSearchParams();
fields.forEach(function (field) { params.set(field, value(field)); });
return params.toString();
}
function setStatus(text, type) {
if (!status) return;
status.textContent = text;
status.className = 'admin-config-status ' + (type || '');
}
function showToast(text, type) {
if (!toast) return;
toast.textContent = text;
toast.className = 'admin-toast is-show ' + (type || '');
window.setTimeout(function () { toast.className = 'admin-toast'; }, 2600);
}
function jsonRequest(url, options) {
return fetch(url, options).then(function (response) {
return response.json().then(function (data) {
if (!response.ok || !data.ret) throw new Error(data.msg || '请求失败');
return data;
});
});
}
function save(event) {
event.preventDefault();
if (submitLocked || !form || !submit) return;
submit.disabled = true;
var original = submit.innerHTML;
submit.innerHTML = '<i class="mdi mdi-loading mdi-spin me-1"></i>保存中';
setStatus('保存中', 'is-loading');
jsonRequest(form.getAttribute('data-url'), {
method: form.getAttribute('data-method'),
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
credentials: 'same-origin',
body: body()
}).then(function (data) {
showToast(data.msg || '销售方案已保存', 'is-success');
setStatus('已保存', 'is-success');
window.setTimeout(function () { location.href = data.redirect; }, 500);
}).catch(function (error) {
showToast(error.message, 'is-error');
setStatus('保存失败', 'is-error');
}).finally(function () {
submit.disabled = submitLocked;
submit.innerHTML = original;
});
}
if (form) {
form.addEventListener('submit', save);
form.addEventListener('input', function () {
if (!submitLocked) setStatus('有未保存修改', 'is-loading');
});
}
if (deleteButton) {
deleteButton.addEventListener('click', function () {
if (!deleteArmed) {
deleteArmed = true;
deleteButton.textContent = '再次点击确认删除';
showToast('已被引用的方案会改为下架;请在 5 秒内再次点击确认', 'is-error');
deleteArmTimer = window.setTimeout(function () {
deleteArmed = false;
deleteButton.textContent = '删除销售方案';
}, 5000);
return;
}
window.clearTimeout(deleteArmTimer);
deleteArmed = false;
deleteButton.disabled = true;
deleteButton.textContent = '处理中';
jsonRequest(deleteButton.getAttribute('data-url'), {
method: 'DELETE', credentials: 'same-origin'
}).then(function (data) {
showToast(data.msg || '销售方案已处理', 'is-success');
window.setTimeout(function () {
location.href = form.getAttribute('data-url').replace(/\/offers\/\d+$/, '/edit');
}, 600);
}).catch(function (error) {
showToast(error.message, 'is-error');
deleteButton.disabled = false;
deleteButton.textContent = '删除销售方案';
});
});
}
})();
</script>
{/literal}

@ -197,7 +197,7 @@
<li><a class="{if $admin_active|default:'' == 'yipay'}active{/if}" href="/admin/yipay"><i class="mdi mdi-credit-card-outline"></i><span>易支付</span></a></li>
<li><a class="{if $admin_active|default:'' == 'paytaro'}active{/if}" href="/admin/paytaro"><i class="mdi mdi-qrcode-scan"></i><span>Paytaro 支付</span></a></li>
<li><a class="{if $admin_active|default:'' == 'shop'}active{/if}" href="/admin/shop"><i class="mdi mdi-storefront-outline"></i><span>商品</span></a></li>
<li><a class="{if $admin_active|default:'' == 'shop'}active{/if}" href="/admin/shop"><i class="mdi mdi-storefront-outline"></i><span>套餐销售</span></a></li>
<li><a class="{if $admin_active|default:'' == 'coupon'}active{/if}" href="/admin/coupon"><i class="mdi mdi-gift-outline"></i><span>优惠码</span></a></li>
<li><a class="{if $admin_active|default:'' == 'billing'}active{/if}" href="/admin/billing"><i class="mdi mdi-receipt-text-outline"></i><span>账单系统</span></a></li>

@ -191,6 +191,7 @@ CREATE TABLE IF NOT EXISTS cloud_offers (
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,
status TINYINT(1) NOT NULL DEFAULT 1,
stock INT NOT NULL DEFAULT -1,
sort INT NOT NULL DEFAULT 0,

@ -0,0 +1,107 @@
<?php
namespace App\Models {
class Model
{
}
require dirname(__DIR__) . '/app/Models/CloudOffer.php';
}
namespace {
use App\Models\CloudOffer;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new \RuntimeException($message);
}
};
$valid = [
'resource_pool_id' => '8', 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '019.9', 'stock' => '-1', 'status' => '1', 'sort' => '-20',
];
$normalized = CloudOffer::validateOffer($valid);
$assert($normalized === [
'resource_pool_id' => 8, 'code' => 'tokyo-premium', 'name' => '东京高级线路',
'price' => '19.90', 'currency' => 'USD', 'status' => 1, 'stock' => -1, 'sort' => -20,
], 'Offer input was not normalized into the expected pool, USD price, inventory and status fields.');
foreach ([
['resource_pool_id' => 0], ['code' => 'Tokyo Premium'], ['code' => ''],
['name' => ''], ['price' => '-1'], ['price' => '1.999'], ['stock' => -2],
['status' => 2], ['sort' => 1000001],
] as $invalid) {
try {
CloudOffer::validateOffer(array_replace($valid, $invalid));
throw new \RuntimeException('Invalid offer input was accepted: ' . json_encode($invalid));
} catch (\InvalidArgumentException $exception) {
// Expected.
}
}
$root = dirname(__DIR__);
$controller = file_get_contents($root . '/app/Controllers/Admin/ShopController.php');
$shopModel = file_get_contents($root . '/app/Models/Shop.php');
$routes = file_get_contents($root . '/config/routes.php');
$planViews = file_get_contents($root . '/resources/views/venix/admin/shop/create.tpl')
. file_get_contents($root . '/resources/views/venix/admin/shop/edit.tpl');
$offerView = file_get_contents($root . '/resources/views/venix/admin/shop/offer_form.tpl');
$offerScript = file_get_contents($root . '/resources/views/venix/admin/shop/offer_form_js.tpl');
$assert(!str_contains($planViews, 'name="host_id"')
&& !str_contains($planViews, 'name="price"')
&& !str_contains($planViews, 'name="stock"')
&& !str_contains($controller, "foreach (['name', 'host_id'")
&& str_contains($controller, "'name', 'cpu_cores', 'memory_gb'")
&& str_contains($controller, 'CloudOffer::validateOffer($input)')
&& !str_contains($shopModel, "'host_id' => 'int'")
&& !str_contains($shopModel, "'price' => 'decimal:2'")
&& !str_contains($shopModel, "'stock' => 'int'"),
'Base-plan administration still owns host placement, price or stock.');
$assert(str_contains($routes,
"get('/shop/{id}/edit', 'App\\Controllers\\Admin\\ShopController:edit');")
&& str_contains($routes,
"get('/shop/{id}/offers/{offer_id}/edit', 'App\\Controllers\\Admin\\ShopController:offerEdit');")
&& str_contains($routes,
"get('/shop/{id}/offers/create', 'App\\Controllers\\Admin\\ShopController:offerCreate')->add(new SuperAdmin())")
&& str_contains($routes,
"post('/shop/{id}/offers', 'App\\Controllers\\Admin\\ShopController:offerAdd')->add(new SuperAdmin())")
&& str_contains($routes,
"put('/shop/{id}/offers/{offer_id}', 'App\\Controllers\\Admin\\ShopController:offerUpdate')->add(new SuperAdmin())")
&& str_contains($routes,
"delete('/shop/{id}/offers/{offer_id}', 'App\\Controllers\\Admin\\ShopController:offerDelete')->add(new SuperAdmin())"),
'Offer read routes must remain admin-readable while every mutation stays behind SuperAdmin middleware.');
$assert(str_contains($controller, 'if (!AdminPermission::isSuperAdmin())')
&& str_contains($controller, "(int) \$values['status'] === 1 && (int) \$shop->status !== 1")
&& str_contains($controller, 'CloudResourcePool::find($poolId)')
&& str_contains($controller, "(string) \$pool->status === 'active'")
&& str_contains($controller, "CloudOrder::where('offer_id', \$offerId)->exists()")
&& str_contains($controller, "CloudInvoice::where('offer_id', \$offerId)->exists()")
&& str_contains($controller, "CloudInstance::where('offer_id', \$offerId)->exists()")
&& str_contains($controller, "CloudResourceReservation::where('offer_id', \$offerId)->exists()")
&& str_contains($controller, '(int) $locked->revision !== (int) $expectedRevision')
&& str_contains($controller, 'lockAndAssertPoolAvailable(')
&& str_contains($controller, '$this->offerReferenced((int) $locked->id)')
&& str_contains($controller, '$priceChanged = $locked->exists')
&& str_contains($controller, '} elseif ($priceChanged) {')
&& str_contains($controller, '$locked->price_version = max(1, (int) $locked->price_version) + 1;')
&& str_contains($controller, '$locked->delete()')
&& str_contains($controller, '$locked->status = 0;'),
'Offer mutation lacks server authorization, price versioning, or reference-aware deletion.');
foreach (['resource_pool_id', 'code', 'name', '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, '当前价格版本')
&& str_contains($offerView, '{if !$admin_can_manage|default:false}disabled{/if}')
&& str_contains($offerScript, "method: form.getAttribute('data-method')")
&& str_contains($offerScript, "method: 'DELETE'")
&& !str_contains($offerView, '|nofilter'),
'Offer UI lost USD/version/read-only controls, mutation wiring, or output escaping.');
echo "Administrator base-plan and offer catalog contracts passed.\n";
}

@ -11,12 +11,12 @@ set_error_handler(static function (int $severity, string $message, string $file,
return false;
});
// The real model supplies price casts and GB/TB conversions without a database.
// The real model supplies GB/TB conversions without a database.
$attributes = [
'id' => 71, 'name' => '香港标准云服务器 · 月付', 'host_id' => 7,
'id' => 71, 'name' => '香港标准云服务器 · 月付',
'cpu_cores' => 4, 'memory_mib' => 2560, 'disk_gib' => 80,
'bandwidth_mbps' => 200, 'price' => '12.34', 'validity_days' => 45,
'traffic_quota_bytes' => 3 * Shop::TIB / 2, 'stock' => 25, 'sort' => -2, 'status' => 1,
'bandwidth_mbps' => 200, 'validity_days' => 45,
'traffic_quota_bytes' => 3 * Shop::TIB / 2, 'sort' => -2, 'status' => 1,
];
$makeShop = static function (array $overrides = []) use ($attributes): Shop {
$shop = new Shop();
@ -34,6 +34,11 @@ $smarty->assign('user', (object) ['isLogin' => false]);
$smarty->assign('admin_csrf_token', 'fixture-not-a-real-token');
$render = static function (Shop $shop, ?bool $canManage = true) use ($smarty): string {
$smarty->assign('shop', $shop);
$smarty->assign('offers', [[
'id' => 11, 'code' => 'hk-standard', 'name' => '香港标准线路',
'pool' => '香港 / 默认线路 / 通用资源池', 'price' => '$12.34',
'price_version' => 2, 'stock' => 25, 'status' => true, 'sort' => 0,
]]);
if ($canManage === null) {
$smarty->clearAssign('admin_can_manage');
} else {
@ -47,10 +52,7 @@ if (in_array('--fixture', $argv ?? [], true)) {
echo json_encode([
'html' => $html,
'readonly_html' => $readOnlyHtml,
'hosts' => [
['id' => 7, 'name' => '香港宿主机 A', 'region' => 'HongKong', 'enabled' => true],
['id' => 8, 'name' => '东京宿主机 B', 'region' => 'Tokyo', 'enabled' => true],
],
'offers' => [['id' => 11, 'code' => 'hk-standard']],
], JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR);
exit;
}
@ -75,8 +77,8 @@ $form = $one($xpath, '//form[@id="shopForm"]');
$assert($form->getAttribute('data-method') === 'PUT'
&& $form->getAttribute('data-url') === '/admin/shop/71',
'Restyling changed the existing update method or resource URL.');
$expectedNames = ['name', 'host_id', 'cpu_cores', 'memory_gb', 'disk_gib', 'bandwidth_mbps',
'price', 'validity_days', 'traffic_tb', 'stock', 'sort', 'status'];
$expectedNames = ['name', 'cpu_cores', 'memory_gb', 'disk_gib', 'bandwidth_mbps',
'validity_days', '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');
@ -101,10 +103,8 @@ $numbers = [
'memory_gb' => ['0.5', '256', '0.5', '2.5'],
'disk_gib' => ['1', '4096', '1', '80'],
'bandwidth_mbps' => ['1', '100000', '1', '200'],
'price' => ['0', '100000000', '0.01', '12.34'],
'validity_days' => ['1', '3650', '1', '45'],
'traffic_tb' => ['0', '1024', '0.0009765625', '1.5'],
'stock' => ['-1', '2147483647', '1', '25'],
'sort' => ['-1000000', '1000000', '1', '-2'],
];
foreach ($numbers as $id => [$minimum, $maximum, $step, $value]) {
@ -116,10 +116,8 @@ foreach ($numbers as $id => [$minimum, $maximum, $step, $value]) {
&& $control->getAttribute('value') === $value,
'Existing numeric field semantics changed: ' . $id);
}
$host = $one($xpath, '//select[@id="host_id"]');
$assert($host->getAttribute('data-selected') === '7'
&& $xpath->query('//select[@id="host_id"]/option[@value=""]')->length === 1,
'Host selection lost its current binding or unbound option before asynchronous loading.');
$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.');
$one($xpath, '//select[@id="status"]');
$statusOptions = [];
foreach ($xpath->query('//select[@id="status"]/option') as $option) {
@ -142,6 +140,9 @@ foreach ([$readOnlyHtml, $render($makeShop(), null)] as $restrictedHtml) {
$assert($restrictedSubmit->hasAttribute('disabled')
&& $restrictedSubmit->getAttribute('form') === 'shopForm',
'Read-only or missing management permission must keep the save button disabled.');
foreach ($restricted->query('//form[@id="shopForm"]//*[@name]') as $control) {
$assert($control->hasAttribute('disabled'), 'Read-only plan fields must be disabled.');
}
}
$assert(str_contains($html, 'window.ADMIN_CSRF_TOKEN ='),
'The shared administrator CSRF token bootstrap was removed.');
@ -149,17 +150,14 @@ $assert(!str_contains($html, 'window.ADMIN_CAN_MANAGE'),
'A duplicate client-side administrator permission flag survived.');
$off = $parse($render($makeShop([
'status' => 0, 'host_id' => null, 'stock' => -1, 'price' => '0.00',
'status' => 0,
'memory_mib' => 512, 'traffic_quota_bytes' => 0, 'validity_days' => null,
])));
$assert($one($off, '//select[@id="status"]/option[@selected]')->getAttribute('value') === '0'
&& $one($off, '//select[@id="host_id"]')->getAttribute('data-selected') === ''
&& $one($off, '//input[@id="stock"]')->getAttribute('value') === '-1'
&& $one($off, '//input[@id="price"]')->getAttribute('value') === '0.00'
&& $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',
'Unbound, off-sale, unlimited-stock/traffic, zero-price, or default-period values were lost.');
'Disabled, unlimited-traffic, or default-period 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.');
@ -171,6 +169,10 @@ $assert($one($unsafe, '//input[@id="name"]')->getAttribute('value') === $unsafeN
&& $unsafe->query('//*[@onerror]')->length === 0
&& !str_contains($unsafeHtml, '<script>window.__shopUnsafe=1</script>'),
'An existing product name escaped its attribute or became executable markup.');
$assert($xpath->query('//a[@href="/admin/shop/71/offers/11/edit"]')->length === 1
&& str_contains($html, '香港标准线路')
&& str_contains($html, '$12.34'),
'The base-plan editor did not render its independently priced offer list.');
// Assert the actual shared script still renders, preserving its one submit
// handler and its existing form-driven URL/method contract after moving save.

@ -81,6 +81,8 @@ $assert(str_contains($schema, 'offer_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema, 'reservation_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($schema,
"currency CHAR(3) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'USD'")
&& str_contains($schema, 'price_version INT UNSIGNED NOT NULL DEFAULT 1')
&& str_contains($schema, 'revision INT UNSIGNED NOT NULL DEFAULT 1')
&& str_contains($schema, 'ALTER TABLE cloud_orders MODIFY host_id BIGINT UNSIGNED NULL'),
'Orders, invoices or instances cannot retain offer and placement results.');

@ -18,11 +18,11 @@ namespace {
throw new \RuntimeException($message);
}
};
$input = ['name' => 'Cloud starter', 'price' => '19.90', 'cpu_cores' => '2', 'memory_gb' => '2',
$input = ['name' => 'Cloud starter', 'cpu_cores' => '2', 'memory_gb' => '2',
'bandwidth_mbps' => '100', 'disk_gib' => '20', 'validity_days' => '30', 'traffic_tb' => '1',
'status' => '1', 'stock' => '-1', 'sort' => '0'];
'status' => '1', 'sort' => '0'];
$data = Shop::validatePlan($input);
$assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20 && $data['price'] === '19.90'
$assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20
&& $data['memory_mib'] === 2048 && $data['validity_days'] === 30
&& $data['traffic_quota_bytes'] === Shop::TIB,
'GB/TB plan values were not normalized to the existing MiB/byte storage schema.');
@ -30,8 +30,10 @@ namespace {
$assert($oneUnitPlan['memory_mib'] === 1024 && $oneUnitPlan['traffic_quota_bytes'] === Shop::TIB,
'Entering 1 in the administrator editor must mean 1 GB of memory and 1 TB of traffic.');
$assert(!array_key_exists('class', $data) && !array_key_exists('expire', $data)
&& !array_key_exists('host_id', $data) && !array_key_exists('price', $data)
&& !array_key_exists('stock', $data)
&& !array_key_exists('memory_gb', $data) && !array_key_exists('traffic_tb', $data),
'A cloud plan contains presentation units instead of canonical stored entitlements.');
'A base plan contains placement, pricing, stock, or presentation-only fields.');
$halfGB = Shop::validatePlan(array_replace($input, ['memory_gb' => '0.5', 'traffic_tb' => '0.0009765625']));
$assert($halfGB['memory_mib'] === 512 && $halfGB['traffic_quota_bytes'] === Shop::GIB,
'Existing half-GB memory or one-GiB traffic values cannot round-trip through the GB/TB editor.');
@ -43,8 +45,8 @@ namespace {
&& str_contains($displayPlan->content(), '2 TB 流量'),
'Plan content does not present stored resources in GB/TB.');
foreach (['cpu_cores' => 0, 'memory_gb' => '0.75', 'disk_gib' => 4097, 'bandwidth_mbps' => 0,
'validity_days' => 0, 'traffic_tb' => '0.001', 'price' => '1.999', 'status' => 2,
'stock' => -2, 'name' => ''] as $key => $invalid) {
'validity_days' => 0, 'traffic_tb' => '0.001', 'status' => 2,
'name' => ''] as $key => $invalid) {
try {
Shop::validatePlan(array_replace($input, [$key => $invalid]));
throw new \RuntimeException('Invalid plan value accepted: ' . $key);
@ -66,7 +68,8 @@ namespace {
$shopController = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/ShopController.php');
$shopViews = file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/create.tpl')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/edit.tpl')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/index.tpl');
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/index.tpl')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/offer_form.tpl');
$invoiceView = file_get_contents(dirname(__DIR__) . '/resources/views/venix/cloud/pages/invoices.tpl');
$invoiceService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceService.php');
$invoicePaymentService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePaymentService.php');
@ -126,8 +129,9 @@ namespace {
&& !str_contains($shopViews, '每期流量额度(GiB)')
&& str_contains($shopController, "'memory_gb' => \$shop->memoryGB()")
&& str_contains($shopController, "'traffic_tb' => \$shop->trafficTB()")
&& str_contains($shopController, "return '$' . number_format"),
'The administrator plan editor/list must use GB, TB and USD while preserving canonical storage.');
&& str_contains($shopController, 'CloudOffer::validateOffer($input)')
&& !str_contains($shopController, "'host_id' => \$shop->host_id"),
'The administrator catalog must keep canonical plan units and move placement/pricing to offers.');
$assert(str_contains($client, 'function formatUsd(value)')
&& str_contains($client, 'formatUsd(plan.price)')
&& str_contains($client, 'formatUsd(invoice.amount)')

@ -503,7 +503,11 @@ $assert(str_contains($baseStyles, '.deployment-step')
&& str_contains($baseStyles, '.user-iso-row'),
'Region-first deployment and personal ISO pages must retain VM-panel styling.');
$assert(!str_contains($cloudTemplate, '购买并开通') && !str_contains($sharedSidebar, '我的虚拟机'), 'Retired VM sales labels remain');
$assert(str_contains($shopFormScript, 'Array.isArray(data.hosts)'), 'Plan editor must read the hosts collection returned by the admin API');
$assert(!str_contains($shopFormScript, 'data.hosts')
&& !str_contains($shopFormScript, "'host_id'")
&& !str_contains($shopFormScript, "'price'")
&& !str_contains($shopFormScript, "'stock'"),
'Base-plan editor must not load hosts or submit offer-owned placement, price, or stock fields.');
$assert(preg_match('/<input id="template-sha256"([^>]*)>/', $templateAdmin, $shaInput) === 1
&& !str_contains($shaInput[1], 'required'), 'Cloud image SHA-256 must be optional');
$assert(str_contains($templateAdmin, 'AlmaLinux 8/9/10')

Loading…
Cancel
Save