'操作', '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', ])->display('admin/shop/index.tpl'); } public function create($request, $response, $args) { return $this->view()->display('admin/shop/create.tpl'); } public function add($request, $response, $args) { return $this->savePlan($request, $response, new Shop()); } public function edit($request, $response, $args) { $shop = Shop::find((int) ($args['id'] ?? 0)); if ($shop === null) { return $response->withStatus(404); } 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'] ?? 0)); if ($shop === null) { 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); } try { $input = []; 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(), 'traffic_tb' => $shop->trafficTB(), default => $shop->$field, } : null; $input[$field] = $request->getParam($field, $default); } $values = Shop::validatePlan($input); $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('基础套餐保存失败'); } } 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' => 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' => '销售方案已保存', '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); } $shop = Shop::find((int) $request->getParam('id', 0)); if ($shop === null) { return $response->withJson(['ret' => 0, 'msg' => '基础套餐不存在'], 404); } $shop->status = 0; $shop->updated_at = time(); if (!$shop->save()) { return $response->withJson(['ret' => 0, 'msg' => '基础套餐下架失败'], 500); } return $response->withJson(['ret' => 1, 'msg' => '基础套餐已下架,所属销售方案将不再对用户展示']); } public function ajax_shop($request, $response, $args) { $table = new Datatables(new DatatablesHelper()); $table->query('SELECT shop.id AS op,shop.id,shop.name,shop.cpu_cores,' . 'ROUND(shop.memory_mib/1024,1) AS memory_gb,shop.bandwidth_mbps,shop.disk_gib,' . 'shop.validity_days,CASE WHEN shop.traffic_quota_bytes=0 THEN 0 ' . '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) { $id = (int) $data['id']; $label = AdminPermission::isSuperAdmin() ? '编辑' : '查看'; return '' . $label . ''; }); $table->edit('name', static function ($data) { return htmlspecialchars((string) $data['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }); $table->edit('memory_gb', static function ($data) { return rtrim(rtrim(number_format((float) $data['memory_gb'], 1, '.', ''), '0'), '.'); }); $table->edit('traffic_tb', static function ($data) { if ((float) $data['traffic_tb'] === 0.0) { return '不限'; } return rtrim(rtrim(number_format((float) $data['traffic_tb'], 10, '.', ''), '0'), '.'); }); $table->edit('status', static function ($data) { return (int) $data['status'] === 1 ? '已启用' : '已停用'; }); $response->getBody()->write($table->generate()); return $response; } }