You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Controllers/Admin/ShopController.php

575 lines
26 KiB
PHTML

<?php
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\Services\Cloud\CloudJobService;
use App\Services\Cloud\CloudNetworkLineFeature;
use App\Utils\DatatablesHelper;
use App\Utils\SafeDatatables as Datatables;
class ShopController extends AdminController
{
public function index($request, $response, $args)
{
$columns = [
'op' => '操作', 'id' => 'ID', 'name' => '基础套餐',
'cpu_cores' => 'CPU 核数', 'memory_gb' => '内存 GB',
'bandwidth_mbps' => '带宽 Mbps', 'disk_gib' => '磁盘 GB',
'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);
}
$lineFeatureEnabled = CloudNetworkLineFeature::enabled();
return $this->view()->assign([
'shop' => $shop,
'offers' => $this->offerRows((int) $shop->id, $lineFeatureEnabled),
'line_feature_enabled' => $lineFeatureEnabled,
])->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);
}
$lineFeatureEnabled = CloudNetworkLineFeature::enabled();
return $this->view()->assign([
'shop' => $shop,
'offer' => null,
'offer_pools' => $this->poolOptions($lineFeatureEnabled),
'line_feature_enabled' => $lineFeatureEnabled,
])->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);
}
$lineFeatureEnabled = CloudNetworkLineFeature::enabled();
return $this->view()->assign([
'shop' => $shop,
'offer' => $offer,
'offer_pools' => $this->poolOptions(
$lineFeatureEnabled,
(int) $offer->resource_pool_id
),
'line_feature_enabled' => $lineFeatureEnabled,
])->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',
'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);
}
// Service length is selected from the offer's fixed 30/90/365-day
// cycles. Keep the legacy base-plan column canonical and hidden;
// it is no longer an administrator-controlled billing term.
$input['validity_days'] =
CloudOffer::BILLING_CYCLES['monthly']['days'];
$values = Shop::validatePlan($input);
$now = time();
foreach ($values as $field => $value) {
$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 {
$submittedCode = $request->getParam('code');
if ($submittedCode !== null) {
if ($offer !== null) {
throw new \DomainException(
'销售方案系统标识由系统管理,不接受修改'
);
}
throw new \InvalidArgumentException(
'新销售方案的系统标识由系统自动生成'
);
}
$input = [];
foreach ([
'resource_pool_id', 'name',
'price', 'quarterly_price', 'annual_price',
'backup_price', 'backup_quarterly_price',
'backup_annual_price', 'stock', 'status', 'sort',
] as $field) {
$input[$field] = $request->getParam($field, $offer === null ? null : $offer->$field);
}
$input['code'] = $offer === null
? $this->availableOfferSystemCode()
: (string) $offer->code;
$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('销售方案已被其他管理员修改,请刷新页面后重试');
}
if ($locked->exists && (string) $locked->code !== (string) $values['code']) {
throw new \DomainException('销售方案系统标识创建后不可修改,请新建方案');
}
$stockModeChanged = $locked->exists
&& ((int) $locked->stock === -1)
!== ((int) $values['stock'] === -1);
if ($stockModeChanged
&& CloudJobService::blockingUpgradeQueryForOffer(
(int) $locked->id
)->exists()) {
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 = false;
if ($locked->exists) {
foreach ([
'price', 'quarterly_price', 'annual_price',
'backup_price', 'backup_quarterly_price',
'backup_annual_price',
] as $priceField) {
$priceChanged = $priceChanged
|| (string) $locked->$priceField
!== (string) $values[$priceField];
}
}
foreach ($values as $field => $value) {
if ($locked->exists && $field === 'code') {
continue;
}
$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'
&& CloudNetworkLineFeature::allowsLine((bool) $line->is_default)
&& $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(bool $lineFeatureEnabled,
?int $currentPoolId = null): 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.name', 'pool.status',
'line.name as line_name', 'line.status as line_status',
'line.is_default',
'region.name as region_name', 'region.status as region_status',
])->filter(static function ($pool) use (
$lineFeatureEnabled, $currentPoolId
): bool {
return $lineFeatureEnabled || (bool) $pool->is_default
|| (int) $pool->id === $currentPoolId;
})->map(static function ($pool) use ($lineFeatureEnabled) {
$lineAllowed = $lineFeatureEnabled || (bool) $pool->is_default;
$active = (string) $pool->status === 'active'
&& (string) $pool->line_status === 'active'
&& $lineAllowed
&& (string) $pool->region_status === 'active';
return [
'id' => (int) $pool->id,
'label' => (string) $pool->region_name
. ($lineFeatureEnabled ? ' → ' . (string) $pool->line_name : '')
. ' → ' . (string) $pool->name,
'active' => $active,
'availability_reason' => $active ? '' : ($lineAllowed
? '位置已停用' : '线路选择已关闭'),
];
})->all();
}
private function offerRows(int $planId, bool $lineFeatureEnabled): 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', 'pool.status as pool_status',
'line.name as line_name', 'line.status as line_status',
'line.is_default', 'region.name as region_name',
'region.status as region_status',
])->map(static function ($offer) use ($lineFeatureEnabled) {
$lineAllowed = $lineFeatureEnabled || (bool) $offer->is_default;
$locationActive = (string) $offer->pool_status === 'active'
&& (string) $offer->line_status === 'active'
&& $lineAllowed
&& (string) $offer->region_status === 'active';
return [
'id' => (int) $offer->id,
'code' => (string) $offer->code,
'name' => (string) $offer->name,
'pool' => trim(implode(' → ', array_filter([
(string) $offer->region_name,
$lineFeatureEnabled ? (string) $offer->line_name : '',
(string) $offer->pool_name,
], static fn ($value) => $value !== ''))),
'prices' => [
'30 天' => '$' . number_format(
(float) $offer->price, 2, '.', ''
),
'90 天' => '$' . number_format(
(float) $offer->quarterly_price, 2, '.', ''
),
'365 天' => '$' . number_format(
(float) $offer->annual_price, 2, '.', ''
),
],
'price_version' => (int) $offer->price_version,
'stock' => (int) $offer->stock,
'status' => (bool) $offer->status,
'location_active' => $locationActive,
'availability_reason' => $locationActive ? '' : ($lineAllowed
? '销售位置已停用' : '线路选择已关闭'),
'sort' => (int) $offer->sort,
];
})->all();
}
private function availableOfferSystemCode(): string
{
for ($attempt = 0; $attempt < 5; $attempt++) {
$code = CloudOffer::generateSystemCode();
if (!CloudOffer::where('code', $code)->exists()) {
return $code;
}
}
throw new \RuntimeException('无法生成唯一的销售方案系统标识');
}
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,'
. '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 '<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');
});
$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;
}
}