diff --git a/web/app/Controllers/Admin/ShopController.php b/web/app/Controllers/Admin/ShopController.php index 11141d01..8023d0da 100644 --- a/web/app/Controllers/Admin/ShopController.php +++ b/web/app/Controllers/Admin/ShopController.php @@ -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 '只读'; - } $id = (int) $data['id']; - return '编辑'; + $label = AdminPermission::isSuperAdmin() ? '编辑' : '查看'; + return '' . $label . ''; }); $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; } - } diff --git a/web/app/Models/CloudOffer.php b/web/app/Models/CloudOffer.php index 515369c1..33098225 100644 --- a/web/app/Models/CloudOffer.php +++ b/web/app/Models/CloudOffer.php @@ -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; + } } diff --git a/web/app/Models/Shop.php b/web/app/Models/Shop.php index e3433460..d10272e6 100644 --- a/web/app/Models/Shop.php +++ b/web/app/Models/Shop.php @@ -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; } diff --git a/web/config/routes.php b/web/config/routes.php index 2b0f3fdc..854acb0d 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -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'); diff --git a/web/resources/views/venix/admin/components/table_page.tpl b/web/resources/views/venix/admin/components/table_page.tpl index be14e173..f9261a21 100644 --- a/web/resources/views/venix/admin/components/table_page.tpl +++ b/web/resources/views/venix/admin/components/table_page.tpl @@ -255,10 +255,10 @@ window.__VENIX_ADMIN_TABLE__ = { function cellValue(column, item) { if (column.action === 'shopActions') { - var disabled = item.status === '下架'; - var editAction = canManage - ? '编辑' - : ''; + var disabled = item.status === '下架' || item.status === '已停用'; + var editAction = '' + + (canManage ? '编辑' : '查看') + ''; return '
' + editAction + '
'; } diff --git a/web/resources/views/venix/admin/shop/create.tpl b/web/resources/views/venix/admin/shop/create.tpl index ff88bf29..ab44ffed 100755 --- a/web/resources/views/venix/admin/shop/create.tpl +++ b/web/resources/views/venix/admin/shop/create.tpl @@ -1,15 +1,34 @@ -{assign var=admin_title value='新增商品'}{assign var=admin_active value='shop'}{include file='admin/static_header.tpl'} -

新增云服务器套餐

绑定宿主机并设置账期、每期流量额度后,用户部署时会先生成支持余额或在线支付的开通账单;支付成功后才创建实例,到期前再自动生成续费账单。

返回商品列表
-
-
-
-
-
-
-
$
-
购买或续费一次增加的服务天数。
-
每个账期独立计算下载与上传合计额度;填 0 表示不限流量。
-
-
-

待保存

-{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'} + +
+
+

新增基础套餐

+

基础套餐只定义 CPU、内存、磁盘、带宽、账期和流量;保存后再为不同资源池添加独立的美元价格与库存。

+
+
+ 待保存 + 返回套餐列表 + +
+
+ +
+
+
+
+
+
+
+
+
购买或续费一次增加的服务天数。
+
最小步进 1 GiB;填 0 表示不限流量。
+
+
用户只能购买已启用套餐下已上架的销售方案。
+
+
+
+
+{include file='admin/shop/form_js.tpl'} +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/shop/edit.tpl b/web/resources/views/venix/admin/shop/edit.tpl index 2b6b8f66..4944482c 100755 --- a/web/resources/views/venix/admin/shop/edit.tpl +++ b/web/resources/views/venix/admin/shop/edit.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'}
-

编辑云服务器套餐

-

绑定宿主机后,用户可用余额购买开通。修改套餐不会改变已经开通的虚拟机。

+

基础套餐与销售方案

+

资源规格与销售位置解耦;同一套餐可在多个资源池中使用不同价格、库存和上下架状态。

- 待保存 - 返回商品列表 - + {if $admin_can_manage|default:false}待保存{else}只读模式{/if} + 返回套餐列表 +
-
+
+

资源规格与账期

-
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
- -
- $ - -
-
-
- - -
购买或续费一次增加的服务天数;修改后不追溯已有服务周期。
-
-
- - -
每个账期独立计算下载与上传合计额度;填 0 表示不限流量,修改后不追溯已有实例。
-
-
- - -
-
- - -
-
- - + +
+
+
+
+
+
+
修改不追溯已开通的服务周期。
+
最小步进 1 GiB;填 0 表示不限流量。
+
+
+ +
+
+ +
+
+

销售方案

价格固定为 USD;资源池决定地区、线路和可调度宿主机范围。

+ {if $admin_can_manage|default:false}新增销售方案{else}{/if} +
+
+
+ + + + + {foreach $offers as $item} + + + + + + + + + + {foreachelse} + + {/foreach} + +
基础套餐的销售方案
方案地区 / 线路 / 资源池价格库存价格版本状态操作
{$item.name|escape}
{$item.code|escape} · #{$item.id|escape}
{$item.pool|default:'资源池不可用'|escape}{$item.price|escape}{if $item.stock == -1}不限{else}{$item.stock|escape}{/if}v{$item.price_version|escape}{if $item.status}已上架{else}已下架{/if}{if $admin_can_manage|default:false}编辑{else}查看{/if}
尚未配置销售方案,该基础套餐不会出现在用户购买页。
- +
- {include file='admin/shop/form_js.tpl'} {include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/shop/form_js.tpl b/web/resources/views/venix/admin/shop/form_js.tpl index 23e534dd..8a0d7eed 100755 --- a/web/resources/views/venix/admin/shop/form_js.tpl +++ b/web/resources/views/venix/admin/shop/form_js.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 = '保存中'; 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'); + }); } })(); diff --git a/web/resources/views/venix/admin/shop/index.tpl b/web/resources/views/venix/admin/shop/index.tpl index 8b5c57fb..d9e1f0d2 100755 --- a/web/resources/views/venix/admin/shop/index.tpl +++ b/web/resources/views/venix/admin/shop/index.tpl @@ -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'} diff --git a/web/resources/views/venix/admin/shop/offer_form.tpl b/web/resources/views/venix/admin/shop/offer_form.tpl new file mode 100644 index 00000000..190263bd --- /dev/null +++ b/web/resources/views/venix/admin/shop/offer_form.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'} + +
+
+

{$shop->name|escape}

+

{if $offer}编辑销售方案{else}新增销售方案{/if}

+

一个基础套餐在每个资源池中最多建立一个销售方案,价格固定使用 USD。

+
+
+ {if $admin_can_manage|default:false}待保存{else}只读模式{/if} + 返回套餐 + +
+
+ +
+ +
+ {if !$offer_pools} + + {/if} +
+
+ + +
新方案只能选择已启用的地区、线路和资源池;已有方案可保留原有停用资源池以供查看。
+
+
+ + +
全局唯一,仅允许小写字母、数字、下划线和连字符。
+
+
+
$
{if $offer}
当前价格版本 v{$offer->price_version|escape},价格变更后自动递增。
{/if}
+
-1 表示不限,0 表示暂停新购。
+
+
+
+
+
+ +{if $offer && $admin_can_manage|default:false} +
+
+

删除销售方案

未被业务记录引用时可物理删除;已被引用时系统仅会下架并保留历史数据。

+ +
+
+{/if} + +
+{include file='admin/shop/offer_form_js.tpl'} +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/shop/offer_form_js.tpl b/web/resources/views/venix/admin/shop/offer_form_js.tpl new file mode 100644 index 00000000..2f5fdcc6 --- /dev/null +++ b/web/resources/views/venix/admin/shop/offer_form_js.tpl @@ -0,0 +1,105 @@ +{literal} + +{/literal} diff --git a/web/resources/views/venix/admin/static_header.tpl b/web/resources/views/venix/admin/static_header.tpl index 1ffd1743..271b5adb 100644 --- a/web/resources/views/venix/admin/static_header.tpl +++ b/web/resources/views/venix/admin/static_header.tpl @@ -197,7 +197,7 @@
  • 易支付
  • Paytaro 支付
  • -
  • 商品
  • +
  • 套餐销售
  • 优惠码
  • 账单系统
  • diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 358efe3e..f29df3dc 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -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, diff --git a/web/tests/AdminOfferCatalogContractTest.php b/web/tests/AdminOfferCatalogContractTest.php new file mode 100644 index 00000000..8da809e4 --- /dev/null +++ b/web/tests/AdminOfferCatalogContractTest.php @@ -0,0 +1,107 @@ + '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"; +} diff --git a/web/tests/AdminShopEditViewTest.php b/web/tests/AdminShopEditViewTest.php index e3a50c4b..3f52a287 100644 --- a/web/tests/AdminShopEditViewTest.php +++ b/web/tests/AdminShopEditViewTest.php @@ -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, ''), '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. diff --git a/web/tests/CloudMultiHostSchemaDefinitionTest.php b/web/tests/CloudMultiHostSchemaDefinitionTest.php index a0bfd08c..b13e29c4 100644 --- a/web/tests/CloudMultiHostSchemaDefinitionTest.php +++ b/web/tests/CloudMultiHostSchemaDefinitionTest.php @@ -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.'); diff --git a/web/tests/CloudPlanDefinitionTest.php b/web/tests/CloudPlanDefinitionTest.php index 6d09cbce..aa087520 100644 --- a/web/tests/CloudPlanDefinitionTest.php +++ b/web/tests/CloudPlanDefinitionTest.php @@ -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)') diff --git a/web/tests/VirtualizationAssetsTest.php b/web/tests/VirtualizationAssetsTest.php index c6c84b5f..313116be 100644 --- a/web/tests/VirtualizationAssetsTest.php +++ b/web/tests/VirtualizationAssetsTest.php @@ -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('/]*)>/', $templateAdmin, $shaInput) === 1 && !str_contains($shaInput[1], 'required'), 'Cloud image SHA-256 must be optional'); $assert(str_contains($templateAdmin, 'AlmaLinux 8/9/10')