From c1aef986928f9d0eb048a39f6065b75e2215b079 Mon Sep 17 00:00:00 2001 From: hellcat Date: Fri, 30 Oct 2026 15:25:58 +0800 Subject: [PATCH] feat(hn): restrict administrator plan and fix payment modal --- .../Controllers/V1/User/PlanController.php | 2 +- app/Services/PlanService.php | 49 +++++++++-- docs/maintenance/HN_ADMIN_PLAN.md | 17 ++++ docs/maintenance/SITE_PROFILES.md | 11 +++ frontends/hn/payment-modal.mjs | 18 +++++ frontends/hn/vite.config.mjs | 7 ++ tests/Feature/Plans/HnAdminPlanTest.php | 81 +++++++++++++++++++ 7 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 docs/maintenance/HN_ADMIN_PLAN.md create mode 100644 frontends/hn/payment-modal.mjs create mode 100644 tests/Feature/Plans/HnAdminPlanTest.php diff --git a/app/Http/Controllers/V1/User/PlanController.php b/app/Http/Controllers/V1/User/PlanController.php index 7db7aad4..32bf3953 100755 --- a/app/Http/Controllers/V1/User/PlanController.php +++ b/app/Http/Controllers/V1/User/PlanController.php @@ -32,7 +32,7 @@ class PlanController extends Controller return $this->success(PlanResource::make($plan)); } - $plans = $this->planService->getAvailablePlans(); + $plans = $this->planService->getAvailablePlans($user); return $this->success(PlanResource::collection($plans)); } } diff --git a/app/Services/PlanService.php b/app/Services/PlanService.php index e67363d2..e755a9f4 100644 --- a/app/Services/PlanService.php +++ b/app/Services/PlanService.php @@ -3,6 +3,7 @@ namespace App\Services; use App\Models\Plan; +use App\Support\SiteProfile; use App\Models\User; use App\Exceptions\ApiException; use Illuminate\Database\Eloquent\Collection; @@ -22,15 +23,30 @@ class PlanService * * @return Collection */ - public function getAvailablePlans(): Collection + public function getAvailablePlans(?User $user = null): Collection { - return Plan::where('show', true) - ->where('sell', true) - ->orderBy('sort') - ->get() - ->filter(function ($plan) { - return $this->hasCapacity($plan); - }); + $privateIds = $this->adminOnlyPlanIds(); + $administrator = $user && $user->is_admin; + return Plan::where(function ($query) use ($privateIds, $administrator) { + $query->where('show', true); + if ($administrator && $privateIds) $query->orWhereIn('id', $privateIds); + }) + ->when(!$administrator && $privateIds, fn ($query) => $query->whereNotIn('id', $privateIds)) + ->where('sell', true)->orderBy('sort')->get() + ->filter(fn ($plan) => $this->hasCapacity($plan)); + } + + private function adminOnlyPlanIds(): array + { + if (!SiteProfile::isHn()) return []; + $ids = admin_setting('hn_admin_only_plan_ids', []); + if (!is_array($ids)) return []; + return array_values(array_unique(array_filter(array_map('intval', $ids), fn ($id) => $id > 0))); + } + + private function isAdminOnlyPlan(Plan $plan): bool + { + return in_array((int) $plan->id, $this->adminOnlyPlanIds(), true); } /** @@ -57,6 +73,11 @@ class PlanService */ public function isPlanAvailableForUser(Plan $plan, User $user): bool { + if ($this->isAdminOnlyPlan($plan)) { + return (bool) $user->is_admin && $plan->sell + && ($user->plan_id === $plan->id ? $plan->renew : $this->hasCapacity($plan)); + } + // 如果是续费 if ($user->plan_id === $plan->id) { return $plan->renew; @@ -72,6 +93,11 @@ class PlanService throw new ApiException(__('Subscription plan does not exist')); } + // Check before every period, including reset traffic and existing-plan renewals. + if ($this->isAdminOnlyPlan($this->plan) && (!$user->is_admin || !$this->plan->sell)) { + throw new ApiException(__('Subscription plan does not exist')); + } + // 转换周期格式为新版格式 $periodKey = self::getPeriodKey($period); $price = $this->plan->prices[$periodKey] ?? null; @@ -149,6 +175,13 @@ class PlanService protected function validatePlanAvailability(User $user): void { + if ($this->isAdminOnlyPlan($this->plan)) { + if (!$user->is_admin || !$this->plan->sell || (!$this->plan->renew && $user->plan_id === $this->plan->id)) { + throw new ApiException(__('This subscription cannot be purchased')); + } + return; + } + if ((!$this->plan->show && !$this->plan->renew) || (!$this->plan->show && $user->plan_id !== $this->plan->id)) { throw new ApiException(__('This subscription has been sold out, please choose another subscription')); } diff --git a/docs/maintenance/HN_ADMIN_PLAN.md b/docs/maintenance/HN_ADMIN_PLAN.md new file mode 100644 index 00000000..f529e3c5 --- /dev/null +++ b/docs/maintenance/HN_ADMIN_PLAN.md @@ -0,0 +1,17 @@ +# HN管理员专属套餐 + +2026-10-30用户明确批准本次核心方案:在HN工作树修改PlanService与用户套餐接口,仅HN按管理员套餐ID配置控制列表、单项访问和购买权限;不改数据库结构或DPL默认行为,先本地实现测试,不自动发布。 + +## 当前配置(仅本地) + +本地套餐ID4,名称管理员套餐,16元/月,110GB/月,仅月付。复制标准套餐的介绍、流量重置方式和其他限制,show=false/sell=true/renew=true;标准及其它套餐不改。私有设置hn_admin_only_plan_ids=[4],仅SITE_PROFILE=hn时生效。生产尚未配置,未来创建时按实际生产ID登记,不能盲用本地ID。 + +PlanService.getAvailablePlans增加可选User参数;访客不传用户且不返回专属套餐,用户套餐接口用数据库中的当前用户角色。管理员可见并新购隐藏套餐;普通用户即便猜中ID、被误设show=true、曾持有该套餐或提交流量重置周期,均不能绕过。仍遵守停售、库存和续费开关。订单接口在调用现有PlanService.validatePurchase时执行同一权限校验,未改OrderController或支付逻辑。DPL忽略该HN设置,维持旧行为。 + +## 验收与恢复 + +6项隔离内存数据库权限测试覆盖列表/访客、单项访问、降权用户、实际订单控制器三种周期拒绝且订单0、管理员可购、停售/库存/续费限制及DPL默认回归。原站点隔离14项/31断言及HN现有配置测试通过。未创建订单、调用支付商或实际付款;未改当前账号套餐、管理员账号或权限。尚未发布线上,也未以管理员浏览器登录验收。 + +本地备份位于共享仓库codex/output/hn-admin-plan-20261030/local-before*.sqlite。首次CLI缺少Redis扩展导致事务回滚,使用现有扩展后成功创建;没有安装或更改PHP服务。先停售并保留管理员ID配置,使非管理员继续被拒绝;若最终移除设置/回退代码,必须确认没有后续用户/订单依赖,只隐藏本次套餐,不整库覆盖。当前代码与配置需成套发布,数据库增量必须以HN实例与实际ID守卫执行。既有content/hn/release-data.json仅维护此前3个公开套餐,不包含本专属计划,不要用旧3套餐脚本覆盖新增计划。 + +2026-10-30用户在指定支付提示最终文案后明确要求发布,本次授权包含已完成的管理员专属套餐核心方案。发布仅HN,生产套餐按实际新ID登记,备份、事务、权限正负验证及DPL保护按HN_PRODUCTION本轮记录执行。 diff --git a/docs/maintenance/SITE_PROFILES.md b/docs/maintenance/SITE_PROFILES.md index 52b1c181..a072eb39 100644 --- a/docs/maintenance/SITE_PROFILES.md +++ b/docs/maintenance/SITE_PROFILES.md @@ -239,3 +239,14 @@ HN语言入口图标(2026-10-29本地):按用户截图将LanguageSelector 用户反馈订单处理中Toast默认蓝色与主题不一致。HN专用适配器仅为Toast.vue追加scoped规则,在.toast.toast-info内将--info-color映射到--theme-color(回退#8bcf36),普通提示的侧边线、信息图标描边、进度条共同使用主题色,背景/文字沿用现有明暗变量。错误、警告、成功提示语义及定时器不变;未修改共享EZ或DPL。未提交/发布线上。 本地实际Toast组件隔离预览通过:侧边线、图标stroke、进度条backgroundColor计算值均rgb(139,207,54),截图共享仓库codex/output/hn-toast-theme-20261030/preview.png。临时预览页已移除,无订单提交或付款;主题模块与附加样式Vite编译通过。关闭确认弹窗后的正常结算页已实际打开,未点击提交订单。 + + +### 支付弹窗修复(2026-10-30,仅本地) + +HN专用payment-modal.mjs按paymentQRCode区分扫码与跳转提示,跳转型显示前往收银台;中英文/繁中新增文案,其他语言回退en-US。外层modal-container透明且无边框,内层保留20px圆角及单一边框,解决全局card-surfaces同时装饰两层造成的方框。正常Safari提示、支付接口和结算逻辑不改。用真实模板/样式和空操作按钮隔离预览:跳转提示与按钮正确;二维码分支仍有SVG二维码和扫码说明;外框computed border0、透明,内层border1px/radius20px。截图共享仓库codex/output/hn-payment-modal-20261030/redirect.png及qr.png。无订单或支付商请求,临时预览已移除。未提交/发布。 + +### 管理员专属套餐(2026-10-30,仅本地) + +用户已明确批准具体XB核心变更,管理员专属16元110GB/月套餐及权限实施、隔离测试与回退唯一正文见[HN_ADMIN_PLAN](HN_ADMIN_PLAN.md);普通用户不得仅靠隐藏前端保护。未发布线上。 + +支付跳转提示最终按用户2026-10-30指定改为“请在收银台扫描二维码完成支付”,删除后半段;扫码型原提示保留。用户同轮明确授权发布本次支付弹窗修复及此前已批准的管理员专属套餐,实际发布状态以HN_PRODUCTION收据为准。 diff --git a/frontends/hn/payment-modal.mjs b/frontends/hn/payment-modal.mjs new file mode 100644 index 00000000..a1fac1a2 --- /dev/null +++ b/frontends/hn/payment-modal.mjs @@ -0,0 +1,18 @@ +export const paymentModalMessages = { + 'zh-CN': ['请在收银台扫描二维码完成支付', '前往收银台'], + 'zh-TW': ['請在收銀台掃描二維碼完成付款', '前往收銀台'], + 'en-US': ['Scan the QR code at checkout to complete payment.', 'Open checkout'], +}; + +export function adaptPaymentModal(code) { + const prompt = "{{ $t('payment.scan_qrcode') }}"; + if (!code.includes(prompt)) throw new Error('HN payment modal prompt changed upstream'); + code = code.replace(prompt, "{{ paymentQRCode ? $t('payment.scan_qrcode') : $t('payment.open_cashier_notice') }}") + .replace("{{ $t('payment.open_in_new_tab') }}", "{{ $t('payment.open_cashier_button') }}"); + return code + ` + +`; +} diff --git a/frontends/hn/vite.config.mjs b/frontends/hn/vite.config.mjs index 5448f815..1f9b88f5 100644 --- a/frontends/hn/vite.config.mjs +++ b/frontends/hn/vite.config.mjs @@ -1,6 +1,7 @@ import {defineConfig} from 'vite'; import vue from '@vitejs/plugin-vue'; import fs from 'node:fs'; +import {adaptPaymentModal, paymentModalMessages} from './payment-modal.mjs'; import path from 'node:path'; import {fileURLToPath} from 'node:url'; const root = path.dirname(fileURLToPath(import.meta.url)); @@ -17,6 +18,12 @@ export default defineConfig(({mode}) => ({ transform(code, id) { if (!id.startsWith(upstream + '/src/')) return; code = code.replaceAll('src="/images/logo.png"', ':src="hnLogo"').replaceAll('/images/logo.png', '/brand/hn/logo.svg'); + if (id === path.join(upstream,'src/views/shop/Payment.vue')) code = adaptPaymentModal(code); + const paymentLocale = Object.keys(paymentModalMessages).find(locale => id === path.join(upstream, 'src/i18n/locales', locale + '.js')); + if (paymentLocale) { + const [notice, button] = paymentModalMessages[paymentLocale]; + code = code.replace(/(\s+scan_qrcode:)/, `\n open_cashier_notice: ${JSON.stringify(notice)},\n open_cashier_button: ${JSON.stringify(button)},$1`); + } if (id === path.join(upstream,'src/views/shop/Shop.vue')) { code = code.replace('v-for="(price, type) in getPlanPrices(plan)"', 'v-for="(price, type) in Object.fromEntries(Object.entries(getPlanPrices(plan)).filter(([, price]) => price !== null))"'); } diff --git a/tests/Feature/Plans/HnAdminPlanTest.php b/tests/Feature/Plans/HnAdminPlanTest.php new file mode 100644 index 00000000..ae4b62a8 --- /dev/null +++ b/tests/Feature/Plans/HnAdminPlanTest.php @@ -0,0 +1,81 @@ +beforeBootstrapping(RegisterProviders::class, function ($app) { + $app['config']->set(['database.default'=>'sqlite', 'database.connections.sqlite.database'=>':memory:', + 'cache.default'=>'array', 'cache.stores.redis'=>['driver'=>'array'], 'queue.default'=>'sync', + 'app.key'=>'base64:'.base64_encode(str_repeat('t',32)), 'site.profile'=>'dpl']); + }); + $app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); + return $app; + } + + + protected function setUp(): void { + parent::setUp(); + Schema::create('v2_plugins',fn(Blueprint $t)=>[$t->id(),$t->boolean('is_enabled')->default(false)]); + Schema::create('v2_settings',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->text('value')->nullable(),$t->timestamps()]); + Schema::create('v2_plan',function(Blueprint $t){$t->id();$t->string('name');$t->text('prices');foreach(['show','sell','renew'] as $f)$t->boolean($f)->default(true);$t->integer('capacity_limit')->nullable();$t->integer('transfer_enable')->default(110);$t->integer('sort')->default(1);$t->timestamps();}); + Schema::create('v2_user',function(Blueprint $t){$t->id();$t->boolean('is_admin')->default(false);$t->integer('plan_id')->nullable();$t->timestamps();}); + Schema::create('v2_order',fn(Blueprint $t)=>[$t->id(),$t->integer('user_id'),$t->integer('status')]); + Cache::store('redis')->flush();$this->app->forgetInstance(Setting::class);Http::preventStrayRequests(); + config(['site.profile'=>'hn']);admin_setting(['hn_admin_only_plan_ids'=>[2]]); + Plan::create(['id'=>1,'name'=>'Standard','prices'=>['monthly'=>32]]); + Plan::create(['id'=>2,'name'=>'Administrator','show'=>false,'prices'=>['monthly'=>16]]); + \Illuminate\Support\Facades\DB::table('v2_user')->insert([['id'=>1,'is_admin'=>true],['id'=>2,'is_admin'=>false]]); + } + private function service():PlanService {return new PlanService(Plan::findOrFail(2));} + public function test_listing_is_admin_only_including_guest_and_accidentally_visible_plan():void { + $s=$this->service();$this->assertSame([1],$s->getAvailablePlans()->pluck('id')->values()->all()); + $this->assertSame([1],$s->getAvailablePlans(User::find(2))->pluck('id')->values()->all()); + $this->assertSame([1,2],$s->getAvailablePlans(User::find(1))->pluck('id')->values()->all()); + Plan::where('id',2)->update(['show'=>true]); + $this->assertSame([1],$s->getAvailablePlans(User::find(2))->pluck('id')->values()->all()); + } + public function test_direct_lookup_and_demoted_owner_are_denied():void { + $s=$this->service();$this->assertTrue((bool)$s->isPlanAvailableForUser($s->plan,User::find(1))); + $u=User::find(2);$u->plan_id=2;$this->assertFalse($s->isPlanAvailableForUser($s->plan,$u)); + $request=Request::create('/api/v1/user/plan/fetch','GET',['id'=>2]);$request->setUserResolver(fn()=>$u); + $controller=$this->app->make(\App\Http\Controllers\V1\User\PlanController::class); + $json=json_decode($controller->fetch($request)->getContent(),true);$this->assertNotEquals(2,$json['data']['id']??null); + } + public function test_direct_order_controller_rejects_all_periods_without_writing_orders():void { + \Illuminate\Support\Facades\DB::table('v2_user')->where('id',2)->update(['plan_id'=>2]); + foreach(['month_price','reset_price','onetime_price']as$period){ + $request=\App\Http\Requests\User\OrderSave::create('/api/v1/user/order/save','POST',['plan_id'=>2,'period'=>$period]); + $request->setContainer($this->app);$request->setRedirector($this->app->make('redirect'));$request->setUserResolver(fn()=>User::find(2)); + try{$this->app->make(\App\Http\Controllers\V1\User\OrderController::class)->save($request);$this->fail('Ordinary user bypassed purchase guard');}catch(ApiException $e){$this->assertNotEmpty($e->getMessage());} + } + $this->assertSame(0,Order::count()); + } + public function test_administrator_can_buy_hidden_monthly_plan_but_sale_and_capacity_still_apply():void { + $s=$this->service();$s->validatePurchase(User::find(1),'month_price');$this->assertTrue(true); + $s->plan->sell=false; + $this->expectException(ApiException::class);$s->validatePurchase(User::find(1),'month_price'); + } + public function test_admin_cannot_bypass_capacity_or_disabled_renewal():void { + $s=$this->service();$s->plan->capacity_limit=0; + try{$s->validatePurchase(User::find(1),'month_price');$this->fail('Capacity bypassed');}catch(ApiException $e){$this->assertNotEmpty($e->getMessage());} + $s->plan->capacity_limit=null;$s->plan->renew=false;$u=User::find(1);$u->plan_id=2; + $this->expectException(ApiException::class);$s->validatePurchase($u,'month_price'); + } + public function test_dpl_ignores_hn_private_configuration_and_retains_hidden_plan_rules():void { + config(['site.profile'=>'dpl']);$s=$this->service(); + $this->assertSame([1],$s->getAvailablePlans(User::find(1))->pluck('id')->values()->all()); + Plan::where('id',2)->update(['show'=>true]);$this->assertSame([1,2],$s->getAvailablePlans(User::find(2))->pluck('id')->values()->all()); + $s->plan->show=false;$this->expectException(ApiException::class);$s->validatePurchase(User::find(1),'month_price'); + } +}