Feat: 商店功能完整实现(单次特效卡888/周卡8888/改名卡5000,含购买、周卡覆盖、改名黑名单)

This commit is contained in:
2026-02-27 15:57:12 +08:00
parent c52998671b
commit 7fb86bfe21
15 changed files with 999 additions and 4 deletions

View File

@@ -36,6 +36,7 @@ class ChatController extends Controller
private readonly ChatStateService $chatState,
private readonly MessageFilterService $filter,
private readonly VipService $vipService,
private readonly \App\Services\ShopService $shopService,
) {}
/**
@@ -97,8 +98,9 @@ class ChatController extends Controller
// 渲染主聊天框架视图
return view('chat.frame', [
'room' => $room,
'user' => $user,
'room' => $room,
'user' => $user,
'weekEffect' => $this->shopService->getActiveWeekEffect($user), // 周卡特效(登录自动播放)
]);
}

View File

@@ -0,0 +1,105 @@
<?php
/**
* 文件功能:商店控制器
* 提供商品列表查询、商品购买、改名卡使用 三个接口
*/
namespace App\Http\Controllers;
use App\Models\ShopItem;
use App\Services\ShopService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ShopController extends Controller
{
/**
* 注入商店服务
*/
public function __construct(
private readonly ShopService $shopService,
) {}
/**
* 获取商店商品列表及当前用户状态
*
* 返回字段items商品列表、user_jjb当前金币
* active_week_effect当前周卡、has_rename_card是否持有改名卡
*/
public function items(): JsonResponse
{
$user = Auth::user();
$items = ShopItem::active()->map(fn ($item) => [
'id' => $item->id,
'name' => $item->name,
'slug' => $item->slug,
'description' => $item->description,
'icon' => $item->icon,
'price' => $item->price,
'type' => $item->type,
'duration_days' => $item->duration_days,
]);
return response()->json([
'items' => $items,
'user_jjb' => $user->jjb ?? 0,
'active_week_effect' => $this->shopService->getActiveWeekEffect($user),
'has_rename_card' => $this->shopService->hasRenameCard($user),
]);
}
/**
* 购买商品
*
* @param Request $request item_id
*/
public function buy(Request $request): JsonResponse
{
$request->validate(['item_id' => 'required|integer|exists:shop_items,id']);
$item = ShopItem::find($request->item_id);
if (! $item->is_active) {
return response()->json(['status' => 'error', 'message' => '该商品已下架。'], 400);
}
$result = $this->shopService->buyItem(Auth::user(), $item);
if (! $result['ok']) {
return response()->json(['status' => 'error', 'message' => $result['message']], 400);
}
$response = ['status' => 'success', 'message' => $result['message']];
// 单次特效卡:告诉前端立即播放哪个特效
if (isset($result['play_effect'])) {
$response['play_effect'] = $result['play_effect'];
}
// 返回最新金币余额
$response['jjb'] = Auth::user()->fresh()->jjb;
return response()->json($response);
}
/**
* 使用改名卡修改昵称
*
* @param Request $request new_name
*/
public function rename(Request $request): JsonResponse
{
$request->validate([
'new_name' => 'required|string|min:1|max:10',
]);
$result = $this->shopService->useRenameCard(Auth::user(), $request->new_name);
if (! $result['ok']) {
return response()->json(['status' => 'error', 'message' => $result['message']], 400);
}
return response()->json(['status' => 'success', 'message' => $result['message']]);
}
}

81
app/Models/ShopItem.php Normal file
View File

@@ -0,0 +1,81 @@
<?php
/**
* 文件功能:商店商品模型
* 对应 shop_items 表,存储商品定义信息
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class ShopItem extends Model
{
protected $table = 'shop_items';
protected $fillable = [
'name', 'slug', 'description', 'icon', 'price',
'type', 'duration_days', 'sort_order', 'is_active',
];
protected $casts = [
'is_active' => 'boolean',
];
/**
* 获取该商品的所有购买记录
*/
public function purchases(): HasMany
{
return $this->hasMany(UserPurchase::class);
}
/**
* 是否为特效类商品instant durationslug once_ week_ 开头)
*/
public function isEffect(): bool
{
return str_starts_with($this->slug, 'once_') || str_starts_with($this->slug, 'week_');
}
/**
* 是否为周卡duration 类型)
*/
public function isWeekCard(): bool
{
return $this->type === 'duration';
}
/**
* 是否为单次卡instant 类型)
*/
public function isInstant(): bool
{
return $this->type === 'instant';
}
/**
* 获取特效 key去掉 once_ / week_ 前缀,返回 fireworks/rain/lightning/snow
*/
public function effectKey(): ?string
{
if (str_starts_with($this->slug, 'once_')) {
return substr($this->slug, 5);
}
if (str_starts_with($this->slug, 'week_')) {
return substr($this->slug, 5);
}
return null;
}
/**
* 获取所有上架商品(按排序)
*/
public static function active(): Collection
{
return static::where('is_active', true)->orderBy('sort_order')->get();
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* 文件功能:用户购买记录模型
* 对应 user_purchases 表,追踪每次商品购买的状态与有效期
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class UserPurchase extends Model
{
protected $table = 'user_purchases';
protected $fillable = [
'user_id', 'shop_item_id', 'status', 'price_paid',
'expires_at', 'used_at',
];
protected $casts = [
'expires_at' => 'datetime',
'used_at' => 'datetime',
];
/**
* 购买记录所属用户
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
/**
* 购买记录对应的商品
*/
public function shopItem(): BelongsTo
{
return $this->belongsTo(ShopItem::class, 'shop_item_id');
}
/**
* 判断周卡是否仍在有效期内
*/
public function isAlive(): bool
{
if ($this->status !== 'active') {
return false;
}
if ($this->expires_at && $this->expires_at->isPast()) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 文件功能:用户名黑名单模型
* 用户改名后旧名称写入此表,保留期间其他人无法注册该名称
*/
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UsernameBlacklist extends Model
{
protected $table = 'username_blacklist';
public $timestamps = false; // 只有 created_at 无 updated_at
protected $fillable = ['username', 'reserved_until', 'created_at'];
protected $casts = [
'reserved_until' => 'datetime',
'created_at' => 'datetime',
];
/**
* 判断给定名称是否在黑名单有效期内
*/
public static function isReserved(string $username): bool
{
return static::where('username', $username)
->where('reserved_until', '>', now())
->exists();
}
}

View File

@@ -0,0 +1,222 @@
<?php
/**
* 文件功能:商店业务逻辑服务层
* 处理商品购买、周卡激活/覆盖、改名卡使用等全部核心业务
*/
namespace App\Services;
use App\Models\ShopItem;
use App\Models\User;
use App\Models\UsernameBlacklist;
use App\Models\UserPurchase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
class ShopService
{
/**
* 购买商品入口:扣金币、按类型分发处理
*
* @return array{ok:bool, message:string, play_effect?:string}
*/
public function buyItem(User $user, ShopItem $item): array
{
// 校验金币是否足够
if ($user->jjb < $item->price) {
return ['ok' => false, 'message' => "金币不足,购买 [{$item->name}] 需要 {$item->price} 金币,当前仅有 {$user->jjb} 金币。"];
}
return match ($item->type) {
'instant' => $this->buyInstant($user, $item),
'duration' => $this->buyWeekCard($user, $item),
'one_time' => $this->buyRenameCard($user, $item),
default => ['ok' => false, 'message' => '未知商品类型'],
};
}
/**
* 购买单次特效卡:立即扣金币,记录已用,返回需要播放的特效 key
*
* @return array{ok:bool, message:string, play_effect?:string}
*/
public function buyInstant(User $user, ShopItem $item): array
{
DB::transaction(function () use ($user, $item) {
// 扣除金币
$user->decrement('jjb', $item->price);
// 写入已使用记录(用于统计)
UserPurchase::create([
'user_id' => $user->id,
'shop_item_id' => $item->id,
'status' => 'used',
'price_paid' => $item->price,
'used_at' => Carbon::now(),
]);
});
return [
'ok' => true,
'message' => "购买成功!{$item->icon} {$item->name} 正在为您播放...",
'play_effect' => $item->effectKey(), // 返回特效 key 让前端立即播放
];
}
/**
* 购买周卡取消旧周卡金币不退激活新周卡有效期7天
*
* @return array{ok:bool, message:string}
*/
public function buyWeekCard(User $user, ShopItem $item): array
{
DB::transaction(function () use ($user, $item) {
// 将所有已激活的周卡标记为 cancelled金币不退
UserPurchase::where('user_id', $user->id)
->where('status', 'active')
->whereHas('shopItem', fn ($q) => $q->where('type', 'duration'))
->update(['status' => 'cancelled']);
// 扣除金币
$user->decrement('jjb', $item->price);
// 写入新的激活记录
UserPurchase::create([
'user_id' => $user->id,
'shop_item_id' => $item->id,
'status' => 'active',
'price_paid' => $item->price,
'expires_at' => Carbon::now()->addDays($item->duration_days ?? 7),
]);
});
return ['ok' => true, 'message' => "购买成功!{$item->icon} {$item->name} 已激活下次登录自动生效连续7天"];
}
/**
* 购买改名卡:扣金币、写 active 记录备用
*
* @return array{ok:bool, message:string}
*/
public function buyRenameCard(User $user, ShopItem $item): array
{
// 检查是否已有未使用的改名卡
$existing = UserPurchase::where('user_id', $user->id)
->where('status', 'active')
->whereHas('shopItem', fn ($q) => $q->where('slug', 'rename_card'))
->exists();
if ($existing) {
return ['ok' => false, 'message' => '您已有一张未使用的改名卡,使用后再购买。'];
}
DB::transaction(function () use ($user, $item) {
$user->decrement('jjb', $item->price);
UserPurchase::create([
'user_id' => $user->id,
'shop_item_id' => $item->id,
'status' => 'active',
'price_paid' => $item->price,
]);
});
return ['ok' => true, 'message' => '改名卡购买成功!请在商店中使用改名卡修改昵称。'];
}
/**
* 使用改名卡:校验新名、加黑名单、更新用户名
*
* @param string $newName 新昵称
* @return array{ok:bool, message:string}
*/
public function useRenameCard(User $user, string $newName): array
{
$newName = trim($newName);
// 格式校验1-10字符中英文数字下划线
if (! preg_match('/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_]{1,10}$/u', $newName)) {
return ['ok' => false, 'message' => '新昵称格式不合法1-10字中英文/数字/下划线)。'];
}
// 不能与自己现有名相同
if ($newName === $user->username) {
return ['ok' => false, 'message' => '新昵称与当前昵称相同,请重新输入。'];
}
// 不能与其他用户重名
if (User::where('username', $newName)->exists()) {
return ['ok' => false, 'message' => '该昵称已被他人注册,请换一个。'];
}
// 不能在黑名单保留期内
if (UsernameBlacklist::isReserved($newName)) {
return ['ok' => false, 'message' => '该昵称处于保护期,暂时无法使用。'];
}
// 查找有效的改名卡记录
$purchase = UserPurchase::where('user_id', $user->id)
->where('status', 'active')
->whereHas('shopItem', fn ($q) => $q->where('slug', 'rename_card'))
->first();
if (! $purchase) {
return ['ok' => false, 'message' => '您没有可用的改名卡,请先购买。'];
}
DB::transaction(function () use ($user, $purchase, $newName) {
$oldName = $user->username;
// 修改用户名
$user->username = $newName;
$user->save();
// 旧名入黑名单保留30天
UsernameBlacklist::updateOrCreate(
['username' => $oldName],
['reserved_until' => Carbon::now()->addDays(30), 'created_at' => Carbon::now()]
);
// 标记改名卡为已使用
$purchase->update(['status' => 'used', 'used_at' => Carbon::now()]);
});
return ['ok' => true, 'message' => "改名成功!您的新昵称为【{$newName}旧昵称将保留30天黑名单。注意历史消息中的旧名不会同步修改。"];
}
/**
* 获取用户当前激活的周卡特效 key fireworks/rain/lightning/snow
* 过期的周卡会自动标记为 expired
*/
public function getActiveWeekEffect(User $user): ?string
{
$purchase = UserPurchase::with('shopItem')
->where('user_id', $user->id)
->where('status', 'active')
->whereHas('shopItem', fn ($q) => $q->where('type', 'duration'))
->first();
if (! $purchase) {
return null;
}
// 检查是否过期
if ($purchase->expires_at && $purchase->expires_at->isPast()) {
$purchase->update(['status' => 'expired']);
return null;
}
return $purchase->shopItem->effectKey();
}
/**
* 获取用户当前激活的改名卡(是否持有未用改名卡)
*/
public function hasRenameCard(User $user): bool
{
return UserPurchase::where('user_id', $user->id)
->where('status', 'active')
->whereHas('shopItem', fn ($q) => $q->where('slug', 'rename_card'))
->exists();
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* 文件功能创建商店商品表shop_items
* 存储商店内所有可购买的商品定义
*
* @package Database\Migrations
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* 执行迁移:创建商品表
*/
public function up(): void
{
Schema::create('shop_items', function (Blueprint $table) {
$table->id();
$table->string('name', 50)->comment('商品名称');
$table->string('slug', 50)->unique()->comment('商品唯一标识');
$table->string('description', 255)->nullable()->comment('商品描述');
$table->string('icon', 20)->default('🛍')->comment('商品图标 emoji');
$table->unsignedInteger('price')->comment('价格(金币)');
// type: instant=单次立即执行, duration=有时效, one_time=一次性道具
$table->enum('type', ['instant', 'duration', 'one_time'])->comment('商品类型');
$table->unsignedTinyInteger('duration_days')->nullable()->comment('有效天数duration 类型用)');
$table->unsignedTinyInteger('sort_order')->default(0)->comment('排序');
$table->boolean('is_active')->default(true)->comment('是否上架');
$table->timestamps();
});
}
/**
* 回滚迁移:删除商品表
*/
public function down(): void
{
Schema::dropIfExists('shop_items');
}
};

View File

@@ -0,0 +1,49 @@
<?php
/**
* 文件功能创建用户购买记录表user_purchases
* 记录每个用户购买商店商品的流水与状态
*
* @package Database\Migrations
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* 执行迁移:创建购买记录表
*/
public function up(): void
{
Schema::create('user_purchases', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->comment('购买用户 ID');
$table->unsignedBigInteger('shop_item_id')->comment('商品 ID');
// status:
// active = 有效中(周卡 / 改名卡未使用)
// expired = 已过期(周卡到期)
// used = 已使用(单次卡已播 / 改名卡已用)
// cancelled = 被新购买的周卡覆盖作废(金币不退)
$table->enum('status', ['active', 'expired', 'used', 'cancelled'])->default('active');
$table->unsignedInteger('price_paid')->comment('购买时实际扣除金币');
$table->timestamp('expires_at')->nullable()->comment('到期时间duration 类型使用)');
$table->timestamp('used_at')->nullable()->comment('使用时间one_time/instant 使用)');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('shop_item_id')->references('id')->on('shop_items')->onDelete('cascade');
$table->index(['user_id', 'status']);
});
}
/**
* 回滚迁移:删除购买记录表
*/
public function down(): void
{
Schema::dropIfExists('user_purchases');
}
};

View File

@@ -0,0 +1,36 @@
<?php
/**
* 文件功能创建用户名黑名单表username_blacklist
* 用户使用改名卡后旧名称写入此表保留30天防止他人立即抢注
*
* @package Database\Migrations
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* 执行迁移:创建用户名黑名单表
*/
public function up(): void
{
Schema::create('username_blacklist', function (Blueprint $table) {
$table->id();
$table->string('username', 20)->unique()->comment('被保留的旧用户名');
$table->timestamp('reserved_until')->comment('保留到期时间默认30天');
$table->timestamp('created_at')->nullable();
});
}
/**
* 回滚迁移:删除黑名单表
*/
public function down(): void
{
Schema::dropIfExists('username_blacklist');
}
};

View File

@@ -0,0 +1,61 @@
<?php
/**
* 文件功能:商店初始商品数据填充器
* 初始化9种商品4种单次特效卡 + 4种周卡 + 改名卡
*
* @package Database\Seeders
*/
namespace Database\Seeders;
use App\Models\ShopItem;
use Illuminate\Database\Seeder;
class ShopItemSeeder extends Seeder
{
/**
* 填充商店商品初始数据
*/
public function run(): void
{
$items = [
// ── 单次特效卡立即播放一次888金币────────────────
['name' => '烟花单次卡', 'slug' => 'once_fireworks', 'icon' => '🎆',
'description' => '购买即刻在聊天室绽放一场烟花(仅自己可见),喜庆氛围拉满!',
'price' => 888, 'type' => 'instant', 'duration_days' => null, 'sort_order' => 1],
['name' => '下雨单次卡', 'slug' => 'once_rain', 'icon' => '🌧',
'description' => '立刻召唤一场滂沱大雨,感受诗意雨天(仅自己可见)。',
'price' => 888, 'type' => 'instant', 'duration_days' => null, 'sort_order' => 2],
['name' => '雷电单次卡', 'slug' => 'once_lightning', 'icon' => '⚡',
'description' => '电闪雷鸣,瞬间震撼全场!立即触发雷电特效(仅自己可见)。',
'price' => 888, 'type' => 'instant', 'duration_days' => null, 'sort_order' => 3],
['name' => '下雪单次卡', 'slug' => 'once_snow', 'icon' => '❄️',
'description' => '银装素裹,漫天飞雪!立即触发下雪特效(仅自己可见)。',
'price' => 888, 'type' => 'instant', 'duration_days' => null, 'sort_order' => 4],
// ── 周卡登录自动播放7天8888金币──────────────────
['name' => '烟花周卡', 'slug' => 'week_fireworks', 'icon' => '🎆',
'description' => '连续7天每次进入聊天室自动绽放烟花同时只能激活一种周卡。',
'price' => 8888, 'type' => 'duration', 'duration_days' => 7, 'sort_order' => 11],
['name' => '下雨周卡', 'slug' => 'week_rain', 'icon' => '🌧',
'description' => '连续7天每次进入聊天室自动下雨。同时只能激活一种周卡。',
'price' => 8888, 'type' => 'duration', 'duration_days' => 7, 'sort_order' => 12],
['name' => '雷电周卡', 'slug' => 'week_lightning', 'icon' => '⚡',
'description' => '连续7天每次进入聊天室自动触发雷电特效。同时只能激活一种周卡。',
'price' => 8888, 'type' => 'duration', 'duration_days' => 7, 'sort_order' => 13],
['name' => '下雪周卡', 'slug' => 'week_snow', 'icon' => '❄️',
'description' => '连续7天每次进入聊天室自动下雪。同时只能激活一种周卡。',
'price' => 8888, 'type' => 'duration', 'duration_days' => 7, 'sort_order' => 14],
// ── 改名卡一次性5000金币────────────────────────
['name' => '改名卡', 'slug' => 'rename_card', 'icon' => '🎭',
'description' => '使用后可修改一次昵称旧名保留30天黑名单不可被他人注册。注意历史聊天记录中的旧名不会更改。',
'price' => 5000, 'type' => 'one_time', 'duration_days' => null, 'sort_order' => 20],
];
foreach ($items as $item) {
ShopItem::firstOrCreate(['slug' => $item['slug']], $item + ['is_active' => true]);
}
}
}

View File

@@ -103,6 +103,17 @@
@include('chat.partials.scripts')
{{-- 周卡特效:登录时自动播放(仅持卡用户可见) --}}
@if (!empty($weekEffect))
<script>
/** 周卡特效延迟1秒待页面完成加载后自动播放 */
setTimeout(() => {
if (window.EffectManager) {
window.EffectManager.play('{{ $weekEffect }}');
}
}, 1000);
</script>
@endif
</body>

View File

@@ -5,13 +5,15 @@
依赖变量:$room当前房间模型
--}}
<div class="chat-right">
{{-- Tab 标题栏(原版:名单/房间/贴图/酷库) --}}
<div class="chat-right" style="position:relative;">
{{-- Tab 标题栏 --}}
<div class="right-tabs">
<button class="tab-btn active" id="tab-users" onclick="switchTab('users')">名单</button>
<button class="tab-btn" id="tab-rooms" onclick="switchTab('rooms')">房间</button>
<button class="tab-btn" id="tab-emoji" onclick="switchTab('emoji')">贴图</button>
<button class="tab-btn" id="tab-action" onclick="switchTab('action')">酷库</button>
<button class="tab-btn" id="tab-shop" onclick="switchTab('shop'); loadShop();"
style="color:#fbbf24;">🛍商店</button>
</div>
{{-- 用户列表面板 --}}
@@ -88,4 +90,7 @@
<div class="online-stats">
在线: <strong id="online-count-footer">0</strong>
</div>
{{-- 商店面板(位于最后,默认隐藏) --}}
@include('chat.partials.shop-panel')
</div>

View File

@@ -27,10 +27,20 @@
// ── Tab 切换 ──────────────────────────────────────
function switchTab(tab) {
// 所有内容面板(名单/房间/贴图/酷库 用 block商店用 flex
['users', 'rooms', 'emoji', 'action'].forEach(t => {
document.getElementById('panel-' + t).style.display = t === tab ? 'block' : 'none';
document.getElementById('tab-' + t).classList.toggle('active', t === tab);
});
// 商店面板单独处理flex 布局以支持内部滚动)
const shopPanel = document.getElementById('shop-panel');
const shopTab = document.getElementById('tab-shop');
if (shopPanel && shopTab) {
shopPanel.style.display = tab === 'shop' ? 'flex' : 'none';
shopPanel.style.flexDirection = 'column';
shopPanel.style.height = '100%';
shopTab.classList.toggle('active', tab === 'shop');
}
// 贴图 Tab 懒加载:首次切换时将 data-src 赋值到 src
if (tab === 'emoji') {
document.querySelectorAll('#panel-emoji img[data-src]').forEach(img => {

View File

@@ -0,0 +1,273 @@
{{--
文件功能:商店面板视图(嵌入聊天室右侧)
展示单次卡、周卡、改名卡,支持购买和改名操作
--}}
<div id="shop-panel" style="display:none;" class="flex flex-col h-full">
{{-- 顶部余额显示 --}}
<div id="shop-balance-bar"
style="padding:8px 10px; background:#1e1b4b; border-bottom:1px solid #3730a3; font-size:12px; color:#a5b4fc; display:flex; align-items:center; gap:6px;">
🪙 我的金币:<span id="shop-jjb" style="color:#fbbf24; font-weight:bold;">--</span>
<span id="shop-week-badge"
style="margin-left:auto; display:none; font-size:11px; background:#312e81; padding:2px 6px; border-radius:4px; color:#c7d2fe;"></span>
</div>
{{-- Toast 提示 --}}
<div id="shop-toast"
style="display:none; margin:6px 8px; padding:6px 10px; border-radius:4px; font-size:12px; font-weight:bold;">
</div>
{{-- 商品列表(滚动区) --}}
<div id="shop-items-list" style="flex:1; overflow-y:auto; padding:8px;">
<div style="text-align:center; color:#6366f1; padding:20px; font-size:13px;">加载中...</div>
</div>
{{-- 改名弹框 --}}
<div id="rename-modal"
style="display:none; position:absolute; inset:0; background:rgba(0,0,0,.7); z-index:200; display:none; align-items:center; justify-content:center;">
<div style="background:#1e1b4b; border:1px solid #4f46e5; border-radius:8px; padding:16px; width:220px;">
<div style="font-weight:bold; color:#c7d2fe; margin-bottom:10px;">🎭 使用改名卡</div>
<input id="rename-input" type="text" maxlength="10" placeholder="输入新昵称1-10字"
style="width:100%; background:#312e81; border:1px solid #4f46e5; border-radius:4px; padding:6px 8px; color:#e0e7ff; font-size:13px; box-sizing:border-box; margin-bottom:8px;">
<div style="display:flex; gap:6px;">
<button onclick="submitRename()"
style="flex:1; background:#4f46e5; color:#fff; border:none; border-radius:4px; padding:6px; cursor:pointer; font-size:12px; font-weight:bold;">确认改名</button>
<button onclick="closeRenameModal()"
style="flex:1; background:#374151; color:#d1d5db; border:none; border-radius:4px; padding:6px; cursor:pointer; font-size:12px;">取消</button>
</div>
<div id="rename-err" style="color:#f87171; font-size:11px; margin-top:6px;"></div>
</div>
</div>
</div>
<script>
/**
* 商店面板前端逻辑
* 负责拉取商品、购买确认、改名卡交互
*/
(function() {
let shopLoaded = false;
/**
* 打开商店面板时加载数据
*/
window.loadShop = function() {
if (shopLoaded) return;
shopLoaded = true;
fetchShopData();
};
/**
* 拉取商品列表与当前用户状态
*/
function fetchShopData() {
fetch('{{ route('shop.items') }}', {
headers: {
'Accept': 'application/json',
'X-CSRF-TOKEN': _csrf()
}
})
.then(r => r.json())
.then(data => renderShop(data))
.catch(() => showShopToast('加载失败,请刷新重试', false));
}
/**
* 渲染商品列表
*/
function renderShop(data) {
// 更新金币余额
document.getElementById('shop-jjb').textContent = Number(data.user_jjb).toLocaleString();
// 显示当前周卡
const badge = document.getElementById('shop-week-badge');
if (data.active_week_effect) {
const icons = {
fireworks: '🎆',
rain: '🌧',
lightning: '⚡',
snow: '❄️'
};
badge.textContent = '周卡生效中:' + (icons[data.active_week_effect] ?? '') + data.active_week_effect;
badge.style.display = 'block';
}
// 分组
const groups = [{
label: '⚡ 单次特效卡',
desc: '立即播放一次,仅自己可见',
type: 'instant'
},
{
label: '📅 周卡7天登录自动播放',
desc: '同时只能激活一种,购买新的旧的作废不退款',
type: 'duration'
},
{
label: '🎭 道具卡',
desc: '',
type: 'one_time'
},
];
const itemsEl = document.getElementById('shop-items-list');
itemsEl.innerHTML = '';
const hasCard = data.has_rename_card;
groups.forEach(g => {
const items = data.items.filter(i => i.type === g.type);
if (!items.length) return;
const section = document.createElement('div');
section.style.cssText = 'margin-bottom:10px;';
section.innerHTML = `
<div style="font-size:11px; font-weight:bold; color:#818cf8; padding:4px 0 4px; border-bottom:1px solid #312e81; margin-bottom:6px;">${g.label}</div>
${g.desc ? `<div style="font-size:10px;color:#6b7280;margin-bottom:6px;">${g.desc}</div>` : ''}
`;
items.forEach(item => {
const isRename = item.slug === 'rename_card';
const card = document.createElement('div');
card.style.cssText =
'background:#1e1b4b;border:1px solid #3730a3;border-radius:6px;padding:8px 10px;margin-bottom:6px;';
card.innerHTML = `
<div style="display:flex;justify-content:space-between;align-items:center;gap:6px;">
<div>
<span style="font-size:16px;">${item.icon}</span>
<span style="font-size:13px;font-weight:bold;color:#e0e7ff;margin-left:4px;">${item.name}</span>
</div>
<div style="white-space:nowrap;">
${isRename && hasCard
? `<button onclick="openRenameModal()" style="background:#7c3aed;color:#fff;border:none;border-radius:4px;padding:3px 8px;cursor:pointer;font-size:11px;font-weight:bold;">使用改名卡</button>`
: `<button onclick="buyItem(${item.id}, '${item.name}', ${item.price})"
style="background:#4f46e5;color:#fff;border:none;border-radius:4px;padding:3px 8px;cursor:pointer;font-size:11px;font-weight:bold;">
🪙 ${Number(item.price).toLocaleString()}
</button>`
}
</div>
</div>
<div style="font-size:10px;color:#6b7280;margin-top:3px;">${item.description ?? ''}</div>
`;
section.appendChild(card);
});
itemsEl.appendChild(section);
});
}
/**
* 购买商品
*/
window.buyItem = function(itemId, name, price) {
if (!confirm(`确定花费 ${Number(price).toLocaleString()} 金币购买【${name}】吗?`)) return;
fetch('{{ route('shop.buy') }}', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': _csrf()
},
body: JSON.stringify({
item_id: itemId
}),
})
.then(r => r.json())
.then(data => {
showShopToast(data.message, data.status === 'success');
if (data.status === 'success') {
// 更新金币显示
if (data.jjb !== undefined) document.getElementById('shop-jjb').textContent =
Number(data.jjb).toLocaleString();
// 单次卡立即触发特效
if (data.play_effect && window.EffectManager) {
window.EffectManager.play(data.play_effect);
}
// 延迟重新加载商店数据(刷新周卡状态等)
shopLoaded = false;
setTimeout(() => {
fetchShopData();
shopLoaded = true;
}, 800);
}
})
.catch(() => showShopToast('网络异常,请重试', false));
};
/**
* 显示/隐藏 商店 Toast 通知
*/
window.showShopToast = function(msg, ok) {
const el = document.getElementById('shop-toast');
el.textContent = msg;
el.style.display = 'block';
el.style.background = ok ? '#064e3b' : '#7f1d1d';
el.style.color = ok ? '#6ee7b7' : '#fca5a5';
clearTimeout(el._t);
el._t = setTimeout(() => {
el.style.display = 'none';
}, 4000);
};
/**
* 打开改名弹框
*/
window.openRenameModal = function() {
const m = document.getElementById('rename-modal');
m.style.display = 'flex';
document.getElementById('rename-input').focus();
document.getElementById('rename-err').textContent = '';
};
/**
* 关闭改名弹框
*/
window.closeRenameModal = function() {
document.getElementById('rename-modal').style.display = 'none';
};
/**
* 提交改名请求
*/
window.submitRename = function() {
const newName = document.getElementById('rename-input').value.trim();
if (!newName) {
document.getElementById('rename-err').textContent = '请输入新昵称';
return;
}
fetch('{{ route('shop.rename') }}', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': _csrf()
},
body: JSON.stringify({
new_name: newName
}),
})
.then(r => r.json())
.then(data => {
if (data.status === 'success') {
closeRenameModal();
showShopToast(data.message, true);
shopLoaded = false;
setTimeout(() => window.location.reload(), 2000); // 改名后刷新页面
} else {
document.getElementById('rename-err').textContent = data.message;
}
})
.catch(() => {
document.getElementById('rename-err').textContent = '网络异常,请重试';
});
};
/**
* 获取 CSRF Token
*/
function _csrf() {
return document.querySelector('meta[name="csrf-token"]')?.content ?? '';
}
})();
</script>

View File

@@ -100,6 +100,11 @@ Route::middleware(['chat.auth'])->group(function () {
Route::post('/command/announce', [AdminCommandController::class, 'announce'])->name('command.announce');
Route::post('/command/clear-screen', [AdminCommandController::class, 'clearScreen'])->name('command.clear_screen');
Route::post('/command/effect', [AdminCommandController::class, 'effect'])->name('command.effect');
// ---- 商店(购买特效卡/改名卡)----
Route::get('/shop/items', [\App\Http\Controllers\ShopController::class, 'items'])->name('shop.items');
Route::post('/shop/buy', [\App\Http\Controllers\ShopController::class, 'buy'])->name('shop.buy');
Route::post('/shop/rename', [\App\Http\Controllers\ShopController::class, 'rename'])->name('shop.rename');
});
// 强力特权层中间件:同时验证 chat.auth 登录态 和 chat.level:super 特权superlevel 由 sysparam 配置)