第一版

This commit is contained in:
2026-09-11 07:15:51 +08:00
parent e73c13657c
commit 14528eba64
226 changed files with 7942 additions and 0 deletions
@@ -0,0 +1,90 @@
# 前端布局修复与全量渲染审查 实施计划
## 调研结论(已用浏览器实测确认)
### 问题 1:顶部菜单重复(已证实)
- 管理员端与玩家端页面 `document.querySelectorAll('header').length === 2`,两个 header 中的桌面导航均 `display:flex` 可见。
- 根因:[app.js](file:///d:/GameParlor/src/main/resources/static/app.js) 的 `initLayout()` 先异步请求 `/api/user/me`,返回后才把 header 插入 DOM、并把 body 全部子节点移动进新建的 `<main>`。此时 Alpine.js 已启动,DOM 重排触发其 MutationObserver 对组件重新求值,`x-init="init()"` 二次执行 → `initLayout()` 二次注入 header;旧 header 在第二次包裹时被移入 `<main>`,最终两个 header 都渲染在页面上。
- 连带影响:init 中的数据加载、轮询(dashboard 的 setInterval)也会执行两次。
### 问题 2:弹窗部分超出浏览器视口(已证实)
- 实测:管理员设备弹窗底部越界 48.46px、玩家选时长弹窗底部越界 93.05px;`.modal-mask` 的 `offsetParent` 是 `<main>` 而非视口,虽然计算样式 `position:fixed`。
- 根因:`.page-fade` 的 `fadeIn` 动画 `animation-fill-mode: both` 结束后仍保留关键帧 `transform: translateY(0)`;非 none 的 transform 使 `<main>` 成为 fixed 后代的包含块。`.modal-mask{inset:0}` 因此相对 main(top=56.8px 起、高度超过视口)定位并居中,而不是相对视口。
### 问题 3:全量审查发现的其它渲染缺陷
1. [player/dashboard.html](file:///d:/GameParlor/src/main/resources/static/player/dashboard.html):`x-text="active.gameName || ..."` 在 `active=null` 时仍求值(x-show 不阻止求值),控制台报 `Cannot read properties of null (reading 'gameName')`。
2. [player/combos.html](file:///d:/GameParlor/src/main/resources/static/player/combos.html):`x-for="it in detail.items"` 初始 `detail=null` 直接报错;`detail.combo.*` 多处无空值保护。
3. [player/custom-combo.html](file:///d:/GameParlor/src/main/resources/static/player/custom-combo.html#L80) 与 [player/points.html](file:///d:/GameParlor/src/main/resources/static/player/points.html#L37):玩家越权调用 `GET /api/admin/config`,拦截器返回 403 并弹出错误 toast(目前靠 catch 兜底值工作,但每次进页面弹错)。
4. `[x-cloak]{display:none!important}` 靠 9 个页面各自内联 `<style>` 提供,[app.css](file:///d:/GameParlor/src/main/resources/static/app.css) 未全局定义,漏写即闪现弹窗。
5. [admin/users.html](file:///d:/GameParlor/src/main/resources/static/admin/users.html) 表格无空数据行。
6. 页面结构对 Tailwind Play CDN 动态注入类有隐性依赖(导航响应式显隐),健壮性不足。
## 修改方案
核心思路:**把 DOM 结构搭建提前到 Alpine 启动之前同步完成,`initLayout` 只负责取数填充,从根上消除二次初始化**;同时移除会形成 fixed 包含块的 transform。
## 涉及文件
- `src/main/resources/static/app.js`:重构布局逻辑(同步包裹 + 异步填充、幂等保护)。
- `src/main/resources/static/app.css`:header/nav 纯 CSS 组件类、动画去 transform、全局 x-cloak、弹窗安全边距。
- `src/main/java/com/gameparlor/controller/ConfigController.java`:**新增** 登录可读的 `GET /api/config`。
- `src/main/resources/static/index.html`:body 加 `gp-auth` 标记(登录页不套布局)。
- `src/main/resources/static/player/dashboard.html`:空值保护。
- `src/main/resources/static/player/combos.html`:x-for 与空值保护。
- `src/main/resources/static/player/custom-combo.html`、`src/main/resources/static/player/points.html`:改用 `/api/config`。
- `src/main/resources/static/admin/users.html`:补空数据行。
- 9 个含 `<style>[x-cloak]…</style>` 的页面:删除内联样式(已全局化)。
## 实施步骤
1. **app.css**
- `fadeIn` 关键帧改为仅 `opacity`(0→1),彻底不产生 transform 包含块;保留 0.35s 淡入。
- 新增全局 `[x-cloak]{display:none!important}`。
- 新增 header 组件类:`.gp-header`(sticky、z-50、毛玻璃、底边线)、`.gp-nav` 链接样式与 active 态、`.gp-nav-desktop`(默认隐藏,≥768px 显示为 flex)、`.gp-nav-mobile`(横向滚动,≥768px 隐藏)、`.gp-userbar`。
- `.gp-page`:`max-width:80rem;width:100%;margin-inline:auto;padding:1rem 1rem 2rem`。
- `.modal-mask` 增加 `padding:1rem`;`.modal` 增加 `margin:auto`,保证小屏下弹窗四周留白且内部可滚动。
2. **app.js(关键重构)**
- IIFE 加载时(app.js 位于 body 末尾、Alpine defer 启动之前执行,此刻不存在 MutationObserver)若 body 无 `gp-auth` 标记,则**同步**:
- 创建 `<header class="gp-header">`(含 logo、空的桌面 nav 容器、空的移动 nav 容器、空的用户信息容器);
- 创建 `<main class="gp-page page-fade">`,把 body 现有子节点(除 header 外;script/style 标签保留原位不动)移入;
- header 插在 body 最前、main 紧随其后。
- `initLayout(active)` 改为:幂等保护(`window.__gpLayoutFilled`)→ 请求 `/api/user/me`(401 仍跳登录)→ 仅用 innerHTML 填充两个 nav 容器和用户信息容器,**不再做任何 DOM 移动/包裹**。
- nav 的显隐完全由 app.css 媒体查询控制,不依赖 Tailwind 运行时生成。
3. **index.html**:body class 增加 `gp-auth`,布局脚本对其跳过。
4. **页面空值/数据修复**
- player/dashboard.html:`active && active.gameName`、续费按钮在无 active 时禁用;轮询逻辑不变。
- player/combos.html:`x-for="it in (detail && detail.items) || []"`;标题/价格文本全部加 `detail &&` 保护。
- admin/users.html:tbody 增加 colspan=7 的"暂无数据"行。
5. **后端配置接口**
- 新增 `ConfigController`:`GET /api/config` 返回 `configService.getAll()`(仅 3 个业务键,无敏感信息);拦截器要求登录但不限制角色。
- custom-combo.html、points.html 两处 `/api/admin/config` 改为 `/api/config`。
6. **清理**:删除 9 个页面末尾的 `<style>[x-cloak]{display:none!important}</style>`(browse、history、combos 玩家端、admin 端 combos/games/devices/snacks/users/timeslots/recharge)。
## 依赖与注意事项
- app.js 依赖"body 末尾经典脚本先于 defer 的 Alpine 执行"这一时序:经典脚本在解析阶段执行,defer 脚本在 DOMContentLoaded 前按序执行,时序天然成立,无需调整各页面 script 标签位置。
- 同步包裹时 app.js 之后的内联 `<script>`(定义 Alpine 组件函数)与 `<style>` 尚未解析,会自然留在 body 中作为 main 的后续兄弟节点,不影响功能。
- `GET /api/config` 仅暴露业务参数(积分汇率/会员折扣/积分比例),管理员写接口仍在 `/api/admin/config`,权限不放宽。
- 不改任何后端业务逻辑与 API 路径(除新增只读接口)。
## 验证
1. `mvn clean package -DskipTests` 重新打包,H2 模式启动。
2. 浏览器全量走查(管理员 + 玩家 + 会员),全部 17 个页面:
- 每页 `document.querySelectorAll('header').length === 1`;
- 桌面宽度(≥768px)仅桌面导航可见,模拟 375px 移动宽度仅移动导航可见且可横向滚动;
- 逐一打开全部弹窗(设备/游戏/时长/零食/套餐/组成项/用户/充值审批/玩家选时长/套餐详情):`.modal-mask` 的 offsetParent 为 viewport(null 或 html),modal 的 top≥0、bottom≤innerHeight、left≥0、right≤innerWidth,375px 宽度下同样不越界且可滚动;
- player/dashboard 无 active 时控制台无 null 报错;player/combos 打开页面前后控制台无错误;
- 会员访问拼套餐、积分兑换页不再出现 403 错误 toast,折扣率/汇率正确显示;
- 登录页(gp-auth)不出现导航;正常登录跳转、退出、各页数据渲染正常。
3. 控制台无 Alpine Expression Error(Tailwind 生产环境提示性警告可忽略)。
## 风险与应对
- 风险:同步包裹改变了页面初始 DOM 层级,可能影响个别依赖 body 直接子元素的样式。应对:页面样式均基于 class/后代选择器,审查未发现依赖;浏览器全量逐页验证兜底。
- 风险:内联 x-cloak 样式删除后若有页面未引 app.css 会闪现——所有 16 个业务页 head 均已引 app.css,已逐页确认。
+134
View File
@@ -0,0 +1,134 @@
# GameParlor 实现计划
## 环境与决策
- **运行时**:Java 21(已装),Maven 3.9.15。`pom.xml` 编译目标设为 Java 17(满足需求),Spring Boot 3.x。
- **数据库**:按需求使用 **MySQL 5.x**。`application.properties` 配置 MySQL 数据源;不实际连接,提供 `src/main/resources/schema.sql`(建表+索引)与 `data.sql`(初始管理员/示例数据)作为初始脚本。本机验证时通过命令行 `--spring.datasource.*` 临时覆盖为 H2(MySQL 模式)做冒烟,不污染默认配置。
- **积分 = 累计消费额**:`User.points` 即玩家累计消费额。**所有玩家**(含普通 PLAYER)消费时按比例累计积分(默认 1 元 = 1 积分,`SystemConfig.points_earn_rate` 可配),并在玩家仪表盘可见。仅 MEMBER 可使用积分兑换。
- **前端依赖**:禁止 CDN → 将 Alpine.js 3 与 Tailwind CSS 3 Play CDN 脚本下载到 `static/js/vendor/` 本地引用。图标使用**内联 SVG**(禁止大图标库)。
- **鉴权**:轻量 Token(UUID),内存 `ConcurrentHashMap<token,userId>`;前端存 `localStorage`,请求带 `Authorization: Bearer`。拦截器校验角色。
- **余额并发**:`User` 加 `@Version`;扣余额用「读后校验 + save」,捕获 `OptimisticLockingFailureException` 自动重试最多 3 次。
## 目录结构
```
src/main/java/com/gameparlor/
GameParlorApplication.java
common/ Result, ResultCode, GlobalExceptionHandler, AuthInterceptor, UserContext, WebMvcConfig
entity/ 11 个实体 + SystemConfig(积分汇率/会员折扣)
repository/ JPA Repository
service/ 业务服务
controller/ auth / admin / player
scheduler/ CountdownScheduler
src/main/resources/
application.properties
schema.sql (MySQL 建表+索引)
data.sql (初始管理员/示例数据)
static/
index.html (登录/注册)
app.css, app.js
js/vendor/alpine.min.js, tailwind.min.js
admin/{dashboard,devices,games,timeslots,combos,users,recharge}.html
player/{dashboard,browse,combos,custom-combo,snacks,recharge,points,history}.html
```
## 实体(11 + SystemConfig)
全部用 Lombok `@Data`、JPA 注解、`@EntityListeners(AuditingEntityListener)` 自动填充 `createdAt`,高频字段加 `@Index`。
1. **Device** — id, name, description, remark, createdAt
2. **Game** — id, name, description, remark, isUniversal, device(@ManyToOne Device), memberPrice
3. **Snack** — id, name, price, type(SNACK/DRINK), remark, memberPrice
4. **TimeSlot** — id, durationMinutes, basePrice, createdAt, memberPrice
5. **Combo** — id, name, type(VIP/DEVICE_GAME/SNACK_DRINK), discountRate, isActive, createdAt
6. **ComboItem** — id, combo(@ManyToOne), itemType, itemId, quantity, unitPriceAtCreation
7. **User** — id, username(unique), password(明文), role(PLAYER/MEMBER/ADMIN), balance, memberExpireDate, points, createdAt, **@Version**
8. **Order** — id, user(@ManyToOne), totalAmount, status(PAID/CANCELLED), createdAt
9. **OrderItem** — id, order(@ManyToOne), itemType, itemId, startTime, endTime, quantity
10. **TransactionLog** — id, user, type(RECHARGE/CONSUME/REFUND), amount, remark, createdAt
11. **RechargeApproval** — id, user, amount, authCode, status(PENDING/APPROVED/REJECTED), createdAt
12. **SystemConfig** — id, configKey(unique), value(存 `points_exchange_rate` 积分兑换汇率、`member_discount_rate` 会员折扣率、`points_earn_rate` 积分累计比例,默认 1 元=1 积分)
> 说明:`memberPrice` 字段用于会员自定义拼套餐的「会员单价」;`SystemConfig` 用于管理员可配的积分汇率、会员折扣率、积分累计比例。**积分 `points` 即累计消费额**,所有玩家消费时按 `points_earn_rate` 累计,对所有玩家可见,仅会员可兑换。
## 后端实现阶段
### 阶段 1:脚手架与公共层
- `pom.xml`:spring-boot-starter-web、data-jpa、validation、h2、mysql-connector-j(scope runtime)、lombok
- `application.properties`:H2 数据源(MySQL 模式)、JPA ddl-auto=update、show-sql=false、端口 8080
- `GameParlorApplication`(`@EnableJpaAuditing`、`@EnableScheduling`)
- `Result<T>` / `ResultCode` 统一返回 `{code,message,data}`;余额不足 code=4001
- `GlobalExceptionHandler`:参数校验、业务异常、乐观锁异常统一转 Result
- `AuthInterceptor` + `WebMvcConfig`:校验 Bearer token,按角色放行(`/api/auth/**` 放行;`/api/admin/**` 需 ADMIN;其余需登录)
- `UserContext`(ThreadLocal)、`TokenStore`(内存 token 映射)
### 阶段 2:实体 + Repository
- 全部实体类 + 枚举(Role / OrderStatus / ItemType / SnackType / ComboType / TxType / RechargeStatus)
- 对应 JpaRepository,按需加派生查询(`findByUsername`、`findByUserIdAndStatus` 等)
### 阶段 3:认证与用户/钱包服务
- `AuthService`:注册(默认 PLAYER,余额 0)、登录(生成 token)、登出
- `UserService`:CRUD、改余额/密码/角色/会员到期日
- `WalletService`:`deduct(userId, amount)` 带乐观锁重试;`recharge(userId, amount)`;写 `TransactionLog`
- 控制器:`AuthController`、`UserController`(me)
### 阶段 4:管理员 CRUD
- `AdminDeviceController` / `AdminGameController` / `AdminTimeSlotController`:增删改查 + 分页
- `AdminComboController`:Combo CRUD、添加/删除 ComboItem
- `AdminUserController`:用户列表、编辑、删除
- `AdminRechargeController`:待审批列表、批准(校验授权码 → 加余额 → 写日志)、拒绝
- `AdminConfigController`:读取/更新积分汇率、会员折扣率、积分累计比例
### 阶段 5:玩家端服务
- 浏览:`DeviceController`、`GameController`(支持 deviceId / universal 过滤)、`TimeSlotController`、`SnackController`、`ComboController`(列表/详情)
- `OrderService`:
- `startGame(gameId, timeSlotId)`:扣余额 → 建 Order(PAID) + OrderItem(startTime=now, endTime=now+分钟) → 写消费日志 → **按 `points_earn_rate` 累计积分**
- `renew(orderId, additionalMinutes)`:按原 TimeSlot 单价比例扣费 → 延长 endTime → **累计积分**
- `getActiveOrder(userId)`:返回进行中订单 + 剩余秒数
- `buyCombo(comboId)`:VIP = Σ(unitPriceAtCreation×quantity) × discountRate;DEVICE_GAME 同理 → **累计积分**
- `buySnacks(items)`:按 snack.price×quantity 扣余额 → **累计积分**
- 抽取 `awardPoints(userId, amount)` 供所有消费路径调用
- `MemberService`:
- `customComboPrice(items)`:Σ 各 item.memberPrice × 会员折扣率
- `purchaseCustomCombo(items)`:扣费 → 建订单
- `exchangePoints(itemType, itemId)`:按积分汇率扣积分,发放对应 TimeSlot/Snack/Combo
- `RechargeController`:玩家提交充值申请(生成 authCode)、查自己的申请
- `HistoryController`:订单历史、交易明细、充值记录
### 阶段 6:倒计时引擎
- `CountdownScheduler`(`@Scheduled(fixedRate=60000)`):扫描 `OrderItem` 中 `endTime <= now` 且对应订单仍视为进行中的记录;本系统订单状态保持 PAID(按需求枚举),会话「完成」由 `endTime` 判定,调度器用于一致性兜底(可记录日志)。
## 前端实现阶段
### 阶段 7:前端基础
- 下载 `alpine.min.js`、`tailwind.min.js` 到 `static/js/vendor/`
- `app.css`:深色主题变量(`#0f0f11` 背景、`#00d4ff` 霓虹蓝)、卡片玻璃拟态、悬停上浮阴影、按钮 `active:scale-95`、页面 `fade-in` 动画、等宽倒计时字体、移动端 375px 适配
- `app.js`:`api()` 封装(带 token、统一错误处理)、`toast()`(绿/红)、`auth`(登录态/登出/跳转)、分页组件、格式化工具
- 所有页面共享顶栏(角色、余额、会员到期)+ 侧边导航
### 阶段 8:登录/注册页 (`index.html`)
- 单页切换登录/注册表单,提交后按角色跳转 admin 或 player 仪表盘
### 阶段 9:管理员页面
- dashboard:统计卡片(用户数、订单数、待审批充值)
- devices / games / timeslots:表格 CRUD,备注直接灰色小字显示
- combos:套餐列表 + 弹窗编辑组成项与打折率
- users:用户列表 + 编辑余额/密码/角色/会员到期日
- recharge:待审批列表 + 输入授权码批准/拒绝
### 阶段 10:玩家页面
- dashboard:进行中游戏倒计时(等宽字体,<5 分钟渐变红)、最近订单、余额、会员到期、**积分(累计消费额,所有玩家可见)**
- browse:按设备/按游戏切换 → 选游戏 → 弹窗选时长 → 开始游玩;倒计时中可续费
- combos:套餐列表 → 详情 → 购买
- custom-combo(仅 MEMBER):勾选 Device/Game/Snack/TimeSlot → 实时价格 → 下单
- snacks:列表 → 加入购物车 → 结算
- recharge:提交金额 → 显示 authCode → 管理员审批后到账
- points(仅 MEMBER):积分兑换 TimeSlot/Snack/Combo
- history:订单、消费、充值记录
## 验证
- `mvn clean package` 编译通过
- 提供 `schema.sql` / `data.sql`(MySQL 方言)作为初始脚本;`application.properties` 默认指向 MySQL
- 冒烟运行(不污染配置):`java -jar target/*.jar --spring.datasource.url=jdbc:h2:file:./data/gp;MODE=MySQL;DB_CLOSE_DELAY=-1 --spring.datasource.driver-class-name=org.h2.Driver --spring.jpa.database-platform=org.hibernate.dialect.H2Dialect`
- 预置一个 ADMIN 账号(admin/admin123)通过 `data.sql` 初始化
- 冒烟:注册玩家 → 登录 → 浏览 → 开局 → 倒计时 → 续费;管理员审批充值、CRUD 设备/游戏;玩家仪表盘可见积分(累计消费额)
## 范围说明
- 严格按需求文档实现 11 个实体 + 必要扩展(memberPrice、SystemConfig)。
- 不引入需求外的框架;UI 遵循深色+霓虹蓝、微动效、轻拟物,拒绝 Bootstrap/纯色块布局。
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+134
View File
@@ -0,0 +1,134 @@
2026-09-10 23:52:34.908963+08:00 database: wrong user or password; user: "ROOT"
org.h2.message.DbException: Wrong user name or password [28000-224]
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.message.DbException.get(DbException.java:188)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:343)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:125)
at org.h2.Driver.connect(Driver.java:59)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:137)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:360)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:461)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:550)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:98)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:111)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:439)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:61)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.getJdbcEnvironmentUsingJdbcMetadata(JdbcEnvironmentInitiator.java:292)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:124)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:78)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:130)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:238)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:215)
at org.hibernate.boot.model.relational.Database.<init>(Database.java:45)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.getDatabase(InFlightMetadataCollectorImpl.java:221)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:189)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:171)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1431)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1502)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1802)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:954)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1352)
at com.gameparlor.GameParlorApplication.main(GameParlorApplication.java:13)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at org.springframework.boot.loader.launch.Launcher.launch(Launcher.java:102)
at org.springframework.boot.loader.launch.Launcher.launch(Launcher.java:64)
at org.springframework.boot.loader.launch.JarLauncher.main(JarLauncher.java:40)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:522)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 59 more
2026-09-10 23:52:39.000914+08:00 database: wrong user or password; user: "ROOT"
org.h2.message.DbException: Wrong user name or password [28000-224]
at org.h2.message.DbException.get(DbException.java:223)
at org.h2.message.DbException.get(DbException.java:199)
at org.h2.message.DbException.get(DbException.java:188)
at org.h2.engine.Engine.openSession(Engine.java:154)
at org.h2.engine.Engine.openSession(Engine.java:222)
at org.h2.engine.Engine.createSession(Engine.java:201)
at org.h2.engine.SessionRemote.connectEmbeddedOrServer(SessionRemote.java:343)
at org.h2.jdbc.JdbcConnection.<init>(JdbcConnection.java:125)
at org.h2.Driver.connect(Driver.java:59)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:137)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:360)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:202)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:461)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:550)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:98)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:111)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:439)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:46)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.java:39)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:63)
at org.hibernate.tool.schema.extract.spi.ExtractionContext.getQueryResults(ExtractionContext.java:43)
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:39)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.initializeSequences(DatabaseInformationImpl.java:66)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.<init>(DatabaseInformationImpl.java:60)
at org.hibernate.tool.schema.internal.Helper.buildDatabaseInformation(Helper.java:185)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:100)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:280)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:144)
at java.base/java.util.HashMap.forEach(HashMap.java:1429)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:141)
at org.hibernate.boot.internal.SessionFactoryObserverForSchemaExport.sessionFactoryCreated(SessionFactoryObserverForSchemaExport.java:37)
at org.hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:322)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:457)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1506)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1802)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:954)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1352)
at com.gameparlor.GameParlorApplication.main(GameParlorApplication.java:13)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at org.springframework.boot.loader.launch.Launcher.launch(Launcher.java:102)
at org.springframework.boot.loader.launch.Launcher.launch(Launcher.java:64)
at org.springframework.boot.loader.launch.JarLauncher.main(JarLauncher.java:40)
Caused by: org.h2.jdbc.JdbcSQLInvalidAuthorizationSpecException: Wrong user name or password [28000-224]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:522)
at org.h2.message.DbException.getJdbcSQLException(DbException.java:489)
... 63 more
+83
View File
@@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.5</version>
<relativePath/>
</parent>
<groupId>com.gameparlor</groupId>
<artifactId>gameparlor</artifactId>
<version>1.0.0</version>
<name>GameParlor</name>
<description>GameParlor 电玩店自助管理与消费系统</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate6</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,15 @@
package com.gameparlor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
public class GameParlorApplication {
public static void main(String[] args) {
SpringApplication.run(GameParlorApplication.class, args);
}
}
@@ -0,0 +1,57 @@
package com.gameparlor.common;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@RequiredArgsConstructor
public class AuthInterceptor implements HandlerInterceptor {
private final TokenStore tokenStore;
private final ObjectMapper objectMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
return true;
}
String authHeader = request.getHeader("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
writeError(response, ResultCode.UNAUTHORIZED);
return false;
}
String token = authHeader.substring(7);
TokenStore.TokenInfo info = tokenStore.get(token);
if (info == null) {
writeError(response, ResultCode.UNAUTHORIZED);
return false;
}
// 管理员接口校验
String uri = request.getRequestURI();
if (uri.startsWith("/api/admin/") && !"ADMIN".equals(info.role())) {
writeError(response, ResultCode.FORBIDDEN);
return false;
}
UserContext.set(info.userId(), info.role());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
UserContext.clear();
}
private void writeError(HttpServletResponse response, ResultCode rc) throws Exception {
response.setStatus(200);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(Result.fail(rc)));
}
}
@@ -0,0 +1,18 @@
package com.gameparlor.common;
import lombok.Getter;
@Getter
public class BusinessException extends RuntimeException {
private final ResultCode resultCode;
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.resultCode = resultCode;
}
public BusinessException(ResultCode resultCode, String message) {
super(message);
this.resultCode = resultCode;
}
}
@@ -0,0 +1,49 @@
package com.gameparlor.common;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result<Void> handleBusiness(BusinessException e) {
return Result.fail(e.getResultCode(), e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleValidation(MethodArgumentNotValidException e) {
FieldError fe = e.getBindingResult().getFieldError();
String msg = fe != null ? fe.getField() + ": " + fe.getDefaultMessage() : "参数校验失败";
return Result.fail(ResultCode.BAD_REQUEST, msg);
}
@ExceptionHandler(ConstraintViolationException.class)
public Result<Void> handleConstraint(ConstraintViolationException e) {
return Result.fail(ResultCode.BAD_REQUEST, e.getMessage());
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<Void> handleNotReadable(HttpMessageNotReadableException e) {
return Result.fail(ResultCode.BAD_REQUEST, "请求体格式错误");
}
@ExceptionHandler(OptimisticLockingFailureException.class)
public Result<Void> handleOptimisticLock(OptimisticLockingFailureException e) {
log.warn("乐观锁冲突: {}", e.getMessage());
return Result.fail(ResultCode.OPTIMISTIC_LOCK);
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e) {
log.error("未处理异常", e);
return Result.fail(ResultCode.INTERNAL_ERROR, e.getMessage());
}
}
@@ -0,0 +1,38 @@
package com.gameparlor.common;
import lombok.Data;
@Data
public class Result<T> {
private int code;
private String message;
private T data;
public Result() {}
public Result(int code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> Result<T> ok(T data) {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
public static <T> Result<T> ok() {
return new Result<>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
}
public static <T> Result<T> fail(ResultCode rc) {
return new Result<>(rc.getCode(), rc.getMessage(), null);
}
public static <T> Result<T> fail(int code, String message) {
return new Result<>(code, message, null);
}
public static <T> Result<T> fail(ResultCode rc, String message) {
return new Result<>(rc.getCode(), message, null);
}
}
@@ -0,0 +1,33 @@
package com.gameparlor.common;
import lombok.Getter;
@Getter
public enum ResultCode {
SUCCESS(200, "成功"),
BAD_REQUEST(400, "请求参数错误"),
UNAUTHORIZED(401, "未登录或登录已过期"),
FORBIDDEN(403, "没有权限"),
NOT_FOUND(404, "资源不存在"),
INTERNAL_ERROR(500, "服务器内部错误"),
// 业务错误
BALANCE_NOT_ENOUGH(4001, "余额不足"),
POINTS_NOT_ENOUGH(4002, "积分不足"),
USERNAME_EXISTS(4003, "用户名已存在"),
USERNAME_OR_PASSWORD_ERROR(4004, "用户名或密码错误"),
AUTH_CODE_ERROR(4005, "授权码错误"),
ORDER_NOT_FOUND(4006, "订单不存在"),
ITEM_NOT_FOUND(4007, "项目不存在"),
MEMBER_ONLY(4008, "仅会员可操作"),
OPTIMISTIC_LOCK(4009, "操作过于频繁,请重试"),
;
private final int code;
private final String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
}
@@ -0,0 +1,24 @@
package com.gameparlor.common;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class TokenStore {
private final ConcurrentHashMap<String, TokenInfo> store = new ConcurrentHashMap<>();
public void put(String token, Long userId, String role) {
store.put(token, new TokenInfo(userId, role));
}
public TokenInfo get(String token) {
return store.get(token);
}
public void remove(String token) {
store.remove(token);
}
public record TokenInfo(Long userId, String role) {}
}
@@ -0,0 +1,24 @@
package com.gameparlor.common;
public class UserContext {
private static final ThreadLocal<Long> CURRENT_USER_ID = new ThreadLocal<>();
private static final ThreadLocal<String> CURRENT_ROLE = new ThreadLocal<>();
public static void set(Long userId, String role) {
CURRENT_USER_ID.set(userId);
CURRENT_ROLE.set(role);
}
public static Long getUserId() {
return CURRENT_USER_ID.get();
}
public static String getRole() {
return CURRENT_ROLE.get();
}
public static void clear() {
CURRENT_USER_ID.remove();
CURRENT_ROLE.remove();
}
}
@@ -0,0 +1,33 @@
package com.gameparlor.common;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {
private final AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor)
.addPathPatterns("/api/**")
.excludePathPatterns(
"/api/auth/login",
"/api/auth/register"
);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true);
}
}
@@ -0,0 +1,156 @@
package com.gameparlor.config;
import com.gameparlor.entity.*;
import com.gameparlor.entity.enums.*;
import com.gameparlor.repository.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.time.LocalDate;
@Slf4j
@Component
@RequiredArgsConstructor
public class DataInitializer implements CommandLineRunner {
private final UserRepository userRepository;
private final DeviceRepository deviceRepository;
private final GameRepository gameRepository;
private final TimeSlotRepository timeSlotRepository;
private final SnackRepository snackRepository;
private final SystemConfigRepository systemConfigRepository;
@Override
public void run(String... args) {
initAdmin();
initDevicesAndGames();
initTimeSlots();
initSnacks();
initConfigs();
log.info("数据初始化完成");
}
private void initAdmin() {
if (!userRepository.existsByUsername("admin")) {
User admin = new User();
admin.setUsername("admin");
admin.setPassword("admin123");
admin.setRole(Role.ADMIN);
admin.setBalance(new BigDecimal("9999"));
admin.setPoints(0);
admin.setMemberExpireDate(LocalDate.now().plusYears(10));
userRepository.save(admin);
log.info("已创建管理员账号: admin / admin123");
}
}
private void initDevicesAndGames() {
if (deviceRepository.count() == 0) {
Device ps5 = new Device();
ps5.setName("PS5");
ps5.setDescription("PlayStation 5 主机");
ps5.setRemark("4K 120Hz,支持次世代游戏");
deviceRepository.save(ps5);
Device switchDevice = new Device();
switchDevice.setName("Switch");
switchDevice.setDescription("任天堂 Switch");
switchDevice.setRemark("多人派对游戏首选");
deviceRepository.save(switchDevice);
Game g1 = new Game();
g1.setName("艾尔登法环");
g1.setDescription("开放世界动作 RPG");
g1.setRemark("运行设备:PS5");
g1.setIsUniversal(false);
g1.setDevice(ps5);
g1.setMemberPrice(new BigDecimal("30"));
gameRepository.save(g1);
Game g2 = new Game();
g2.setName("马里奥赛车");
g2.setDescription("竞速派对游戏");
g2.setRemark("运行设备:Switch");
g2.setIsUniversal(false);
g2.setDevice(switchDevice);
g2.setMemberPrice(new BigDecimal("20"));
gameRepository.save(g2);
Game g3 = new Game();
g3.setName("街机合集");
g3.setDescription("经典街机游戏合集");
g3.setRemark("通用游戏,全设备可玩");
g3.setIsUniversal(true);
g3.setMemberPrice(new BigDecimal("15"));
gameRepository.save(g3);
}
}
private void initTimeSlots() {
if (timeSlotRepository.count() == 0) {
TimeSlot t1 = new TimeSlot();
t1.setDurationMinutes(30);
t1.setBasePrice(new BigDecimal("15"));
t1.setMemberPrice(new BigDecimal("12"));
timeSlotRepository.save(t1);
TimeSlot t2 = new TimeSlot();
t2.setDurationMinutes(60);
t2.setBasePrice(new BigDecimal("25"));
t2.setMemberPrice(new BigDecimal("20"));
timeSlotRepository.save(t2);
TimeSlot t3 = new TimeSlot();
t3.setDurationMinutes(120);
t3.setBasePrice(new BigDecimal("45"));
t3.setMemberPrice(new BigDecimal("38"));
timeSlotRepository.save(t3);
}
}
private void initSnacks() {
if (snackRepository.count() == 0) {
Snack s1 = new Snack();
s1.setName("可乐");
s1.setPrice(new BigDecimal("8"));
s1.setType(SnackType.DRINK);
s1.setRemark("冰镇 330ml");
s1.setMemberPrice(new BigDecimal("6"));
snackRepository.save(s1);
Snack s2 = new Snack();
s2.setName("薯片");
s2.setPrice(new BigDecimal("10"));
s2.setType(SnackType.SNACK);
s2.setRemark("原味");
s2.setMemberPrice(new BigDecimal("8"));
snackRepository.save(s2);
Snack s3 = new Snack();
s3.setName("绿茶");
s3.setPrice(new BigDecimal("6"));
s3.setType(SnackType.DRINK);
s3.setRemark("无糖");
s3.setMemberPrice(new BigDecimal("5"));
snackRepository.save(s3);
}
}
private void initConfigs() {
saveConfig("points_exchange_rate", "100");
saveConfig("member_discount_rate", "0.85");
saveConfig("points_earn_rate", "1");
}
private void saveConfig(String key, String value) {
if (systemConfigRepository.findByConfigKey(key).isEmpty()) {
SystemConfig c = new SystemConfig();
c.setConfigKey(key);
c.setValue(value);
systemConfigRepository.save(c);
}
}
}
@@ -0,0 +1,17 @@
package com.gameparlor.config;
import com.fasterxml.jackson.datatype.hibernate6.Hibernate6Module;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfig {
@Bean
public Hibernate6Module hibernate6Module() {
Hibernate6Module module = new Hibernate6Module();
// 不强制加载懒加载属性,未初始化的序列化为 null,避免 ByteBuddyInterceptor 序列化异常
module.disable(Hibernate6Module.Feature.FORCE_LAZY_LOADING);
return module;
}
}
@@ -0,0 +1,48 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {
private final AuthService authService;
@PostMapping("/register")
public Result<Map<String, Object>> register(@RequestBody @Validated AuthRequest req) {
return Result.ok(authService.register(req.getUsername(), req.getPassword()));
}
@PostMapping("/login")
public Result<Map<String, Object>> login(@RequestBody @Validated AuthRequest req) {
return Result.ok(authService.login(req.getUsername(), req.getPassword()));
}
@PostMapping("/logout")
public Result<Void> logout(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header != null && header.startsWith("Bearer ")) {
authService.logout(header.substring(7));
}
return Result.ok();
}
@Data
public static class AuthRequest {
@NotBlank(message = "用户名不能为空")
private String username;
@NotBlank(message = "密码不能为空")
private String password;
}
}
@@ -0,0 +1,33 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Combo;
import com.gameparlor.entity.ComboItem;
import com.gameparlor.service.ComboService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/combos")
@RequiredArgsConstructor
public class ComboController {
private final ComboService comboService;
@GetMapping
public Result<List<Combo>> list() {
return Result.ok(comboService.listActive());
}
@GetMapping("/{id}")
public Result<Map<String, Object>> detail(@PathVariable Long id) {
Combo combo = comboService.getById(id);
List<ComboItem> items = comboService.getItems(id);
return Result.ok(Map.of("combo", combo, "items", items, "price", comboService.calcPrice(id)));
}
}
@@ -0,0 +1,27 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.service.ConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* 登录用户可读的业务配置(积分汇率、会员折扣率、积分累计比例)。
* 仅读不写;修改配置仍走 /api/admin/config(ADMIN 权限)。
*/
@RestController
@RequestMapping("/api/config")
@RequiredArgsConstructor
public class ConfigController {
private final ConfigService configService;
@GetMapping
public Result<Map<String, String>> list() {
return Result.ok(configService.getAll());
}
}
@@ -0,0 +1,23 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Device;
import com.gameparlor.repository.DeviceRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/devices")
@RequiredArgsConstructor
public class DeviceController {
private final DeviceRepository deviceRepository;
@GetMapping
public Result<List<Device>> list() {
return Result.ok(deviceRepository.findAll());
}
}
@@ -0,0 +1,31 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Game;
import com.gameparlor.repository.GameRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/games")
@RequiredArgsConstructor
public class GameController {
private final GameRepository gameRepository;
@GetMapping
public Result<List<Game>> list(@RequestParam(required = false) Long deviceId,
@RequestParam(required = false) Boolean universal) {
if (Boolean.TRUE.equals(universal)) {
return Result.ok(gameRepository.findByIsUniversalTrue());
}
if (deviceId != null) {
return Result.ok(gameRepository.findByDeviceId(deviceId));
}
return Result.ok(gameRepository.findAll());
}
}
@@ -0,0 +1,42 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.common.UserContext;
import com.gameparlor.entity.Order;
import com.gameparlor.entity.TransactionLog;
import com.gameparlor.entity.enums.TxType;
import com.gameparlor.repository.OrderRepository;
import com.gameparlor.repository.TransactionLogRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/history")
@RequiredArgsConstructor
public class HistoryController {
private final OrderRepository orderRepository;
private final TransactionLogRepository txLogRepository;
@GetMapping("/orders")
public Result<Page<Order>> orders(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(orderRepository.findByUserIdOrderByCreatedAtDesc(UserContext.getUserId(), pageable));
}
@GetMapping("/transactions")
public Result<Page<TransactionLog>> transactions(@RequestParam(required = false) String type,
@PageableDefault(size = 10) Pageable pageable) {
Long userId = UserContext.getUserId();
if (type != null && !type.isBlank()) {
return Result.ok(txLogRepository.findByUserIdAndTypeOrderByCreatedAtDesc(
userId, TxType.valueOf(type), pageable));
}
return Result.ok(txLogRepository.findByUserIdOrderByCreatedAtDesc(userId, pageable));
}
}
@@ -0,0 +1,47 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Order;
import com.gameparlor.entity.enums.ItemType;
import com.gameparlor.service.MemberService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/member")
@RequiredArgsConstructor
public class MemberController {
private final MemberService memberService;
@PostMapping("/custom-combo/price")
public Result<BigDecimal> customComboPrice(@RequestBody CustomComboForm form) {
return Result.ok(memberService.calcCustomComboPrice(form.getItems()));
}
@PostMapping("/custom-combo/purchase")
public Result<Order> purchaseCustomCombo(@RequestBody CustomComboForm form) {
return Result.ok(memberService.purchaseCustomCombo(form.getItems()));
}
@PostMapping("/points/exchange")
public Result<Order> exchangePoints(@RequestBody ExchangeForm form) {
return Result.ok(memberService.exchangePoints(ItemType.valueOf(form.getItemType()), form.getItemId()));
}
@Data
public static class CustomComboForm {
private List<MemberService.CustomItem> items;
}
@Data
public static class ExchangeForm {
private String itemType;
private Long itemId;
}
}
@@ -0,0 +1,61 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Order;
import com.gameparlor.service.OrderService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/orders")
@RequiredArgsConstructor
public class OrderController {
private final OrderService orderService;
@PostMapping
public Result<Order> startGame(@RequestBody StartGameForm form) {
return Result.ok(orderService.startGame(form.getGameId(), form.getTimeSlotId()));
}
@PostMapping("/renew")
public Result<Order> renew(@RequestBody RenewForm form) {
return Result.ok(orderService.renew(form.getOrderId(), form.getAdditionalMinutes()));
}
@GetMapping("/active")
public Result<Map<String, Object>> active() {
return Result.ok(orderService.getActiveOrder());
}
@PostMapping("/combos/{comboId}")
public Result<Order> buyCombo(@PathVariable Long comboId) {
return Result.ok(orderService.buyCombo(comboId));
}
@PostMapping("/snacks")
public Result<Order> buySnacks(@RequestBody SnackListForm form) {
return Result.ok(orderService.buySnacks(form.getItems()));
}
@Data
public static class StartGameForm {
private Long gameId;
private Long timeSlotId;
}
@Data
public static class RenewForm {
private Long orderId;
private Integer additionalMinutes;
}
@Data
public static class SnackListForm {
private List<OrderService.SnackItem> items;
}
}
@@ -0,0 +1,50 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.common.UserContext;
import com.gameparlor.entity.RechargeApproval;
import com.gameparlor.entity.User;
import com.gameparlor.entity.enums.RechargeStatus;
import com.gameparlor.repository.RechargeApprovalRepository;
import com.gameparlor.repository.UserRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.UUID;
@RestController
@RequestMapping("/api/recharge")
@RequiredArgsConstructor
public class RechargeController {
private final RechargeApprovalRepository rechargeApprovalRepository;
private final UserRepository userRepository;
@PostMapping("/request")
public Result<RechargeApproval> request(@RequestBody RechargeForm form) {
Long userId = UserContext.getUserId();
User user = userRepository.getReferenceById(userId);
RechargeApproval ra = new RechargeApproval();
ra.setUser(user);
ra.setAmount(form.getAmount());
ra.setAuthCode(UUID.randomUUID().toString().substring(0, 6).toUpperCase());
ra.setStatus(RechargeStatus.PENDING);
return Result.ok(rechargeApprovalRepository.save(ra));
}
@GetMapping("/my")
public Result<Page<RechargeApproval>> myRequests(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(rechargeApprovalRepository.findByUser_IdOrderByCreatedAtDesc(
UserContext.getUserId(), pageable));
}
@Data
public static class RechargeForm {
private BigDecimal amount;
}
}
@@ -0,0 +1,28 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Snack;
import com.gameparlor.entity.enums.SnackType;
import com.gameparlor.repository.SnackRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/snacks")
@RequiredArgsConstructor
public class SnackController {
private final SnackRepository snackRepository;
@GetMapping
public Result<List<Snack>> list(@RequestParam(required = false) String type) {
if (type != null && !type.isBlank()) {
return Result.ok(snackRepository.findByType(SnackType.valueOf(type)));
}
return Result.ok(snackRepository.findAll());
}
}
@@ -0,0 +1,23 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.entity.TimeSlot;
import com.gameparlor.repository.TimeSlotRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/timeslots")
@RequiredArgsConstructor
public class TimeSlotController {
private final TimeSlotRepository timeSlotRepository;
@GetMapping
public Result<List<TimeSlot>> list() {
return Result.ok(timeSlotRepository.findAll());
}
}
@@ -0,0 +1,35 @@
package com.gameparlor.controller;
import com.gameparlor.common.Result;
import com.gameparlor.common.UserContext;
import com.gameparlor.entity.User;
import com.gameparlor.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("/me")
public Result<Map<String, Object>> me() {
Long userId = UserContext.getUserId();
User user = userService.getById(userId);
Map<String, Object> map = new HashMap<>();
map.put("id", user.getId());
map.put("username", user.getUsername());
map.put("role", user.getRole().name());
map.put("balance", user.getBalance());
map.put("memberExpireDate", user.getMemberExpireDate());
map.put("points", user.getPoints());
return Result.ok(map);
}
}
@@ -0,0 +1,81 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.Result;
import com.gameparlor.entity.Combo;
import com.gameparlor.entity.ComboItem;
import com.gameparlor.entity.enums.ComboType;
import com.gameparlor.entity.enums.ItemType;
import com.gameparlor.service.ComboService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/admin/combos")
@RequiredArgsConstructor
public class AdminComboController {
private final ComboService comboService;
@GetMapping
public Result<List<Combo>> list() {
return Result.ok(comboService.listActive());
}
@GetMapping("/{id}")
public Result<Map<String, Object>> detail(@PathVariable Long id) {
Combo combo = comboService.getById(id);
List<ComboItem> items = comboService.getItems(id);
return Result.ok(Map.of("combo", combo, "items", items, "price", comboService.calcPrice(id)));
}
@PostMapping
public Result<Combo> create(@RequestBody ComboForm form) {
return Result.ok(comboService.create(form.getName(),
ComboType.valueOf(form.getType()), form.getDiscountRate(), form.getIsActive()));
}
@PutMapping("/{id}")
public Result<Combo> update(@PathVariable Long id, @RequestBody ComboForm form) {
return Result.ok(comboService.update(id, form.getName(),
form.getType() == null ? null : ComboType.valueOf(form.getType()),
form.getDiscountRate(), form.getIsActive()));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
comboService.delete(id);
return Result.ok();
}
@PostMapping("/{id}/items")
public Result<ComboItem> addItem(@PathVariable Long id, @RequestBody ItemForm form) {
return Result.ok(comboService.addItem(id, ItemType.valueOf(form.getItemType()),
form.getItemId(), form.getQuantity()));
}
@DeleteMapping("/items/{itemId}")
public Result<Void> removeItem(@PathVariable Long itemId) {
comboService.removeItem(itemId);
return Result.ok();
}
@Data
public static class ComboForm {
private String name;
private String type;
private BigDecimal discountRate;
private Boolean isActive;
}
@Data
public static class ItemForm {
private String itemType;
private Long itemId;
private Integer quantity;
}
}
@@ -0,0 +1,29 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.Result;
import com.gameparlor.service.ConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/admin/config")
@RequiredArgsConstructor
public class AdminConfigController {
private final ConfigService configService;
@GetMapping
public Result<Map<String, String>> list() {
return Result.ok(configService.getAll());
}
@PutMapping
public Result<Void> update(@RequestBody Map<String, String> configs) {
for (Map.Entry<String, String> e : configs.entrySet()) {
configService.set(e.getKey(), e.getValue());
}
return Result.ok();
}
}
@@ -0,0 +1,65 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.Result;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.Device;
import com.gameparlor.repository.DeviceRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/admin/devices")
@RequiredArgsConstructor
public class AdminDeviceController {
private final DeviceRepository deviceRepository;
@GetMapping
public Result<Page<Device>> list(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(deviceRepository.findAll(pageable));
}
@GetMapping("/{id}")
public Result<Device> get(@PathVariable Long id) {
return Result.ok(deviceRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND)));
}
@PostMapping
public Result<Device> create(@RequestBody @Validated DeviceForm form) {
Device d = new Device();
d.setName(form.getName());
d.setDescription(form.getDescription());
d.setRemark(form.getRemark());
return Result.ok(deviceRepository.save(d));
}
@PutMapping("/{id}")
public Result<Device> update(@PathVariable Long id, @RequestBody @Validated DeviceForm form) {
Device d = deviceRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND));
d.setName(form.getName());
d.setDescription(form.getDescription());
d.setRemark(form.getRemark());
return Result.ok(deviceRepository.save(d));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
deviceRepository.deleteById(id);
return Result.ok();
}
@Data
public static class DeviceForm {
private String name;
private String description;
private String remark;
}
}
@@ -0,0 +1,76 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.Result;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.Device;
import com.gameparlor.entity.Game;
import com.gameparlor.repository.DeviceRepository;
import com.gameparlor.repository.GameRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/admin/games")
@RequiredArgsConstructor
public class AdminGameController {
private final GameRepository gameRepository;
private final DeviceRepository deviceRepository;
@GetMapping
public Result<Page<Game>> list(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(gameRepository.findAll(pageable));
}
@PostMapping
public Result<Game> create(@RequestBody @Validated GameForm form) {
return Result.ok(gameRepository.save(toEntity(new Game(), form)));
}
@PutMapping("/{id}")
public Result<Game> update(@PathVariable Long id, @RequestBody @Validated GameForm form) {
Game g = gameRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND));
return Result.ok(gameRepository.save(toEntity(g, form)));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
gameRepository.deleteById(id);
return Result.ok();
}
private Game toEntity(Game g, GameForm form) {
g.setName(form.getName());
g.setDescription(form.getDescription());
g.setRemark(form.getRemark());
g.setIsUniversal(form.getIsUniversal() != null && form.getIsUniversal());
g.setMemberPrice(form.getMemberPrice() == null ? BigDecimal.ZERO : form.getMemberPrice());
if (Boolean.TRUE.equals(form.getIsUniversal())) {
g.setDevice(null);
} else if (form.getDeviceId() != null) {
Device device = deviceRepository.findById(form.getDeviceId())
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "设备不存在"));
g.setDevice(device);
}
return g;
}
@Data
public static class GameForm {
private String name;
private String description;
private String remark;
private Boolean isUniversal;
private Long deviceId;
private BigDecimal memberPrice;
}
}
@@ -0,0 +1,38 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.Result;
import com.gameparlor.entity.RechargeApproval;
import com.gameparlor.service.RechargeService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/admin/recharge")
@RequiredArgsConstructor
public class AdminRechargeController {
private final RechargeService rechargeService;
@GetMapping("/pending")
public Result<List<RechargeApproval>> pending() {
return Result.ok(rechargeService.listPending());
}
@PostMapping("/{id}/approve")
public Result<RechargeApproval> approve(@PathVariable Long id, @RequestBody ApproveForm form) {
return Result.ok(rechargeService.approve(id, form.getAuthCode()));
}
@PostMapping("/{id}/reject")
public Result<RechargeApproval> reject(@PathVariable Long id) {
return Result.ok(rechargeService.reject(id));
}
@Data
public static class ApproveForm {
private String authCode;
}
}
@@ -0,0 +1,66 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.Result;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.Snack;
import com.gameparlor.entity.enums.SnackType;
import com.gameparlor.repository.SnackRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/admin/snacks")
@RequiredArgsConstructor
public class AdminSnackController {
private final SnackRepository snackRepository;
@GetMapping
public Result<Page<Snack>> list(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(snackRepository.findAll(pageable));
}
@PostMapping
public Result<Snack> create(@RequestBody @Validated SnackForm form) {
return Result.ok(snackRepository.save(toEntity(new Snack(), form)));
}
@PutMapping("/{id}")
public Result<Snack> update(@PathVariable Long id, @RequestBody @Validated SnackForm form) {
Snack s = snackRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND));
return Result.ok(snackRepository.save(toEntity(s, form)));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
snackRepository.deleteById(id);
return Result.ok();
}
private Snack toEntity(Snack s, SnackForm form) {
s.setName(form.getName());
s.setPrice(form.getPrice());
s.setType(SnackType.valueOf(form.getType()));
s.setRemark(form.getRemark());
s.setMemberPrice(form.getMemberPrice() == null ? BigDecimal.ZERO : form.getMemberPrice());
return s;
}
@Data
public static class SnackForm {
private String name;
private BigDecimal price;
private String type;
private String remark;
private BigDecimal memberPrice;
}
}
@@ -0,0 +1,33 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.Result;
import com.gameparlor.entity.enums.RechargeStatus;
import com.gameparlor.repository.OrderRepository;
import com.gameparlor.repository.RechargeApprovalRepository;
import com.gameparlor.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/admin/stats")
@RequiredArgsConstructor
public class AdminStatsController {
private final UserRepository userRepository;
private final OrderRepository orderRepository;
private final RechargeApprovalRepository rechargeApprovalRepository;
@GetMapping
public Result<Map<String, Object>> stats() {
Map<String, Object> map = new HashMap<>();
map.put("userCount", userRepository.count());
map.put("orderCount", orderRepository.count());
map.put("pendingRechargeCount", rechargeApprovalRepository.findByStatus(RechargeStatus.PENDING).size());
return Result.ok(map);
}
}
@@ -0,0 +1,61 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.Result;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.TimeSlot;
import com.gameparlor.repository.TimeSlotRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
@RestController
@RequestMapping("/api/admin/timeslots")
@RequiredArgsConstructor
public class AdminTimeSlotController {
private final TimeSlotRepository timeSlotRepository;
@GetMapping
public Result<Page<TimeSlot>> list(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(timeSlotRepository.findAll(pageable));
}
@PostMapping
public Result<TimeSlot> create(@RequestBody @Validated SlotForm form) {
return Result.ok(timeSlotRepository.save(toEntity(new TimeSlot(), form)));
}
@PutMapping("/{id}")
public Result<TimeSlot> update(@PathVariable Long id, @RequestBody @Validated SlotForm form) {
TimeSlot t = timeSlotRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND));
return Result.ok(timeSlotRepository.save(toEntity(t, form)));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
timeSlotRepository.deleteById(id);
return Result.ok();
}
private TimeSlot toEntity(TimeSlot t, SlotForm form) {
t.setDurationMinutes(form.getDurationMinutes());
t.setBasePrice(form.getBasePrice());
t.setMemberPrice(form.getMemberPrice() == null ? BigDecimal.ZERO : form.getMemberPrice());
return t;
}
@Data
public static class SlotForm {
private Integer durationMinutes;
private BigDecimal basePrice;
private BigDecimal memberPrice;
}
}
@@ -0,0 +1,53 @@
package com.gameparlor.controller.admin;
import com.gameparlor.common.Result;
import com.gameparlor.entity.User;
import com.gameparlor.entity.enums.Role;
import com.gameparlor.service.UserService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.time.LocalDate;
@RestController
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
public class AdminUserController {
private final UserService userService;
@GetMapping
public Result<Page<User>> list(@PageableDefault(size = 10) Pageable pageable) {
return Result.ok(userService.list(pageable));
}
@PutMapping("/{id}")
public Result<User> update(@PathVariable Long id, @RequestBody UserForm form) {
Role role = form.getRole() == null ? null : Role.valueOf(form.getRole());
LocalDate expire = form.getMemberExpireDate() == null || form.getMemberExpireDate().isBlank()
? null : LocalDate.parse(form.getMemberExpireDate());
return Result.ok(userService.update(id, form.getUsername(), form.getPassword(), role,
form.getBalance(), expire, form.getPoints()));
}
@DeleteMapping("/{id}")
public Result<Void> delete(@PathVariable Long id) {
userService.delete(id);
return Result.ok();
}
@Data
public static class UserForm {
private String username;
private String password;
private String role;
private BigDecimal balance;
private String memberExpireDate;
private Integer points;
}
}
@@ -0,0 +1,37 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.ComboType;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "combo")
@EntityListeners(AuditingEntityListener.class)
public class Combo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private ComboType type;
@Column(nullable = false, precision = 5, scale = 2)
private BigDecimal discountRate = BigDecimal.ONE;
@Column(nullable = false)
private Boolean isActive = true;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,33 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.ItemType;
import jakarta.persistence.*;
import lombok.Data;
import java.math.BigDecimal;
@Data
@Entity
@Table(name = "combo_item")
public class ComboItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "combo_id", nullable = false)
private Combo combo;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private ItemType itemType;
@Column(nullable = false)
private Long itemId;
@Column(nullable = false)
private Integer quantity = 1;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal unitPriceAtCreation;
}
@@ -0,0 +1,33 @@
package com.gameparlor.entity;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "device", indexes = {
@Index(name = "idx_device_name", columnList = "name")
})
@EntityListeners(AuditingEntityListener.class)
public class Device {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(length = 500)
private String description;
@Column(length = 255)
private String remark;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,46 @@
package com.gameparlor.entity;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "game", indexes = {
@Index(name = "idx_game_device_id", columnList = "device_id"),
@Index(name = "idx_game_name", columnList = "name")
})
@EntityListeners(AuditingEntityListener.class)
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(length = 500)
private String description;
@Column(length = 255)
private String remark;
@Column(nullable = false)
private Boolean isUniversal = false;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "device_id")
private Device device;
/** 会员自定义拼套餐时的会员单价 */
@Column(precision = 10, scale = 2)
private BigDecimal memberPrice = BigDecimal.ZERO;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,38 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.OrderStatus;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "orders", indexes = {
@Index(name = "idx_order_user_id", columnList = "user_id"),
@Index(name = "idx_order_status", columnList = "status")
})
@EntityListeners(AuditingEntityListener.class)
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal totalAmount;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private OrderStatus status = OrderStatus.PAID;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,37 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.ItemType;
import jakarta.persistence.*;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "order_item", indexes = {
@Index(name = "idx_order_item_order_id", columnList = "order_id"),
@Index(name = "idx_order_item_end_time", columnList = "end_time")
})
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id", nullable = false)
private Order order;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private ItemType itemType;
@Column(nullable = false)
private Long itemId;
private LocalDateTime startTime;
private LocalDateTime endTime;
@Column(nullable = false)
private Integer quantity = 1;
}
@@ -0,0 +1,47 @@
package com.gameparlor.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.gameparlor.entity.enums.RechargeStatus;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "recharge_approval", indexes = {
@Index(name = "idx_recharge_user_id", columnList = "user_id"),
@Index(name = "idx_recharge_status", columnList = "status")
})
@EntityListeners(AuditingEntityListener.class)
public class RechargeApproval {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal amount;
@Column(length = 50)
private String authCode;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private RechargeStatus status = RechargeStatus.PENDING;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
@JsonProperty("userId")
public Long getUserIdJson() {
return user != null ? user.getId() : null;
}
}
@@ -0,0 +1,43 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.SnackType;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "snack", indexes = {
@Index(name = "idx_snack_type", columnList = "type")
})
@EntityListeners(AuditingEntityListener.class)
public class Snack {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 100)
private String name;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal price;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private SnackType type;
@Column(length = 255)
private String remark;
/** 会员自定义拼套餐时的会员单价 */
@Column(precision = 10, scale = 2)
private BigDecimal memberPrice = BigDecimal.ZERO;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,19 @@
package com.gameparlor.entity;
import jakarta.persistence.*;
import lombok.Data;
@Data
@Entity
@Table(name = "system_config")
public class SystemConfig {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String configKey;
@Column(length = 100)
private String value;
}
@@ -0,0 +1,33 @@
package com.gameparlor.entity;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "time_slot")
@EntityListeners(AuditingEntityListener.class)
public class TimeSlot {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private Integer durationMinutes;
@Column(nullable = false, precision = 10, scale = 2)
private BigDecimal basePrice;
/** 会员自定义拼套餐时的会员单价 */
@Column(precision = 10, scale = 2)
private BigDecimal memberPrice = BigDecimal.ZERO;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,41 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.TxType;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "transaction_log", indexes = {
@Index(name = "idx_tx_user_id", columnList = "user_id"),
@Index(name = "idx_tx_type", columnList = "type")
})
@EntityListeners(AuditingEntityListener.class)
public class TransactionLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private TxType type;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal amount;
@Column(length = 255)
private String remark;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
}
@@ -0,0 +1,49 @@
package com.gameparlor.entity;
import com.gameparlor.entity.enums.Role;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Entity
@Table(name = "user", indexes = {
@Index(name = "idx_user_username", columnList = "username", unique = true),
@Index(name = "idx_user_role", columnList = "role")
})
@EntityListeners(AuditingEntityListener.class)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 50)
private String username;
@Column(nullable = false, length = 100)
private String password;
@Enumerated(EnumType.STRING)
@Column(nullable = false, length = 20)
private Role role = Role.PLAYER;
@Column(nullable = false, precision = 12, scale = 2)
private BigDecimal balance = BigDecimal.ZERO;
private LocalDate memberExpireDate;
@Column(nullable = false)
private Integer points = 0;
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdAt;
@Version
private Long version;
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum ComboType {
VIP, DEVICE_GAME, SNACK_DRINK
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum ItemType {
GAME, DEVICE, SNACK, TIMESLOT, COMBO
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum OrderStatus {
PAID, CANCELLED
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum RechargeStatus {
PENDING, APPROVED, REJECTED
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum Role {
PLAYER, MEMBER, ADMIN
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum SnackType {
SNACK, DRINK
}
@@ -0,0 +1,5 @@
package com.gameparlor.entity.enums;
public enum TxType {
RECHARGE, CONSUME, REFUND
}
@@ -0,0 +1,11 @@
package com.gameparlor.repository;
import com.gameparlor.entity.ComboItem;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ComboItemRepository extends JpaRepository<ComboItem, Long> {
List<ComboItem> findByComboId(Long comboId);
void deleteByComboId(Long comboId);
}
@@ -0,0 +1,12 @@
package com.gameparlor.repository;
import com.gameparlor.entity.Combo;
import com.gameparlor.entity.enums.ComboType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ComboRepository extends JpaRepository<Combo, Long> {
List<Combo> findByIsActiveTrue();
List<Combo> findByType(ComboType type);
}
@@ -0,0 +1,7 @@
package com.gameparlor.repository;
import com.gameparlor.entity.Device;
import org.springframework.data.jpa.repository.JpaRepository;
public interface DeviceRepository extends JpaRepository<Device, Long> {
}
@@ -0,0 +1,11 @@
package com.gameparlor.repository;
import com.gameparlor.entity.Game;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface GameRepository extends JpaRepository<Game, Long> {
List<Game> findByDeviceId(Long deviceId);
List<Game> findByIsUniversalTrue();
}
@@ -0,0 +1,13 @@
package com.gameparlor.repository;
import com.gameparlor.entity.OrderItem;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.LocalDateTime;
import java.util.List;
public interface OrderItemRepository extends JpaRepository<OrderItem, Long> {
List<OrderItem> findByOrderId(Long orderId);
List<OrderItem> findByEndTimeAfter(LocalDateTime time);
List<OrderItem> findByEndTimeLessThanEqual(LocalDateTime time);
}
@@ -0,0 +1,14 @@
package com.gameparlor.repository;
import com.gameparlor.entity.Order;
import com.gameparlor.entity.enums.OrderStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface OrderRepository extends JpaRepository<Order, Long> {
Page<Order> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
List<Order> findByUserIdAndStatus(Long userId, OrderStatus status);
}
@@ -0,0 +1,15 @@
package com.gameparlor.repository;
import com.gameparlor.entity.RechargeApproval;
import com.gameparlor.entity.enums.RechargeStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface RechargeApprovalRepository extends JpaRepository<RechargeApproval, Long> {
List<RechargeApproval> findByStatus(RechargeStatus status);
Page<RechargeApproval> findByUser_IdOrderByCreatedAtDesc(Long userId, Pageable pageable);
Page<RechargeApproval> findAllByOrderByCreatedAtDesc(Pageable pageable);
}
@@ -0,0 +1,11 @@
package com.gameparlor.repository;
import com.gameparlor.entity.Snack;
import com.gameparlor.entity.enums.SnackType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface SnackRepository extends JpaRepository<Snack, Long> {
List<Snack> findByType(SnackType type);
}
@@ -0,0 +1,10 @@
package com.gameparlor.repository;
import com.gameparlor.entity.SystemConfig;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface SystemConfigRepository extends JpaRepository<SystemConfig, Long> {
Optional<SystemConfig> findByConfigKey(String key);
}
@@ -0,0 +1,7 @@
package com.gameparlor.repository;
import com.gameparlor.entity.TimeSlot;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TimeSlotRepository extends JpaRepository<TimeSlot, Long> {
}
@@ -0,0 +1,12 @@
package com.gameparlor.repository;
import com.gameparlor.entity.TransactionLog;
import com.gameparlor.entity.enums.TxType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TransactionLogRepository extends JpaRepository<TransactionLog, Long> {
Page<TransactionLog> findByUserIdOrderByCreatedAtDesc(Long userId, Pageable pageable);
Page<TransactionLog> findByUserIdAndTypeOrderByCreatedAtDesc(Long userId, TxType type, Pageable pageable);
}
@@ -0,0 +1,11 @@
package com.gameparlor.repository;
import com.gameparlor.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
boolean existsByUsername(String username);
}
@@ -0,0 +1,33 @@
package com.gameparlor.scheduler;
import com.gameparlor.entity.OrderItem;
import com.gameparlor.repository.OrderItemRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Component
@RequiredArgsConstructor
public class CountdownScheduler {
private final OrderItemRepository orderItemRepository;
/**
* 每分钟检查已结束的游玩会话。
* 订单状态保持 PAID(按需求枚举),会话「完成」由 endTime 判定,
* 此处用于一致性兜底与日志记录。
*/
@Scheduled(fixedRate = 60000)
public void checkExpiredSessions() {
LocalDateTime now = LocalDateTime.now();
List<OrderItem> expired = orderItemRepository.findByEndTimeLessThanEqual(now);
if (!expired.isEmpty()) {
log.info("检测到 {} 个已结束的游玩会话", expired.size());
}
}
}
@@ -0,0 +1,72 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.common.TokenStore;
import com.gameparlor.entity.User;
import com.gameparlor.entity.enums.Role;
import com.gameparlor.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class AuthService {
private final UserRepository userRepository;
private final TokenStore tokenStore;
@Transactional
public Map<String, Object> register(String username, String password) {
if (userRepository.existsByUsername(username)) {
throw new BusinessException(ResultCode.USERNAME_EXISTS);
}
User user = new User();
user.setUsername(username);
user.setPassword(password); // 明文密码
user.setRole(Role.PLAYER);
user.setBalance(BigDecimal.ZERO);
user.setPoints(0);
userRepository.save(user);
String token = issueToken(user);
return buildAuthResult(user, token);
}
public Map<String, Object> login(String username, String password) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new BusinessException(ResultCode.USERNAME_OR_PASSWORD_ERROR));
if (!user.getPassword().equals(password)) {
throw new BusinessException(ResultCode.USERNAME_OR_PASSWORD_ERROR);
}
String token = issueToken(user);
return buildAuthResult(user, token);
}
public void logout(String token) {
if (token != null) {
tokenStore.remove(token);
}
}
private String issueToken(User user) {
String token = UUID.randomUUID().toString().replace("-", "");
tokenStore.put(token, user.getId(), user.getRole().name());
return token;
}
private Map<String, Object> buildAuthResult(User user, String token) {
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("userId", user.getId());
map.put("username", user.getUsername());
map.put("role", user.getRole().name());
return map;
}
}
@@ -0,0 +1,113 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.*;
import com.gameparlor.entity.enums.ComboType;
import com.gameparlor.entity.enums.ItemType;
import com.gameparlor.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ComboService {
private final ComboRepository comboRepository;
private final ComboItemRepository comboItemRepository;
private final GameRepository gameRepository;
private final DeviceRepository deviceRepository;
private final SnackRepository snackRepository;
private final TimeSlotRepository timeSlotRepository;
public List<Combo> listActive() {
return comboRepository.findByIsActiveTrue();
}
public Combo getById(Long id) {
return comboRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "套餐不存在"));
}
public List<ComboItem> getItems(Long comboId) {
return comboItemRepository.findByComboId(comboId);
}
@Transactional
public Combo create(String name, ComboType type, BigDecimal discountRate, Boolean isActive) {
Combo c = new Combo();
c.setName(name);
c.setType(type);
c.setDiscountRate(discountRate == null ? BigDecimal.ONE : discountRate);
c.setIsActive(isActive == null || isActive);
return comboRepository.save(c);
}
@Transactional
public Combo update(Long id, String name, ComboType type, BigDecimal discountRate, Boolean isActive) {
Combo c = getById(id);
if (name != null) c.setName(name);
if (type != null) c.setType(type);
if (discountRate != null) c.setDiscountRate(discountRate);
if (isActive != null) c.setIsActive(isActive);
return comboRepository.save(c);
}
@Transactional
public void delete(Long id) {
comboItemRepository.deleteByComboId(id);
comboRepository.deleteById(id);
}
/**
* 计算套餐总价:Σ(unitPriceAtCreation * quantity) * discountRate
*/
public BigDecimal calcPrice(Long comboId) {
List<ComboItem> items = comboItemRepository.findByComboId(comboId);
Combo combo = getById(comboId);
BigDecimal sum = BigDecimal.ZERO;
for (ComboItem item : items) {
sum = sum.add(item.getUnitPriceAtCreation().multiply(BigDecimal.valueOf(item.getQuantity())));
}
return sum.multiply(combo.getDiscountRate()).setScale(2, java.math.RoundingMode.HALF_UP);
}
@Transactional
public ComboItem addItem(Long comboId, ItemType itemType, Long itemId, Integer quantity) {
Combo combo = getById(comboId);
BigDecimal unitPrice = resolveUnitPrice(itemType, itemId);
ComboItem ci = new ComboItem();
ci.setCombo(combo);
ci.setItemType(itemType);
ci.setItemId(itemId);
ci.setQuantity(quantity == null ? 1 : quantity);
ci.setUnitPriceAtCreation(unitPrice);
return comboItemRepository.save(ci);
}
@Transactional
public void removeItem(Long itemId) {
comboItemRepository.deleteById(itemId);
}
private BigDecimal resolveUnitPrice(ItemType type, Long itemId) {
if (type == null) type = ItemType.COMBO;
return switch (type) {
case GAME -> {
Game g = gameRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "游戏不存在"));
yield g.getMemberPrice() != null ? g.getMemberPrice() : BigDecimal.ZERO;
}
case DEVICE -> BigDecimal.ZERO; // 设备本身无单价
case SNACK -> snackRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "零食不存在")).getPrice();
case TIMESLOT -> timeSlotRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "时长不存在")).getBasePrice();
case COMBO -> BigDecimal.ZERO; // 套餐本身不直接作为套餐组成项
};
}
}
@@ -0,0 +1,84 @@
package com.gameparlor.service;
import com.gameparlor.entity.SystemConfig;
import com.gameparlor.repository.SystemConfigRepository;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
@Service
@RequiredArgsConstructor
public class ConfigService {
public static final String KEY_POINTS_EXCHANGE_RATE = "points_exchange_rate";
public static final String KEY_MEMBER_DISCOUNT_RATE = "member_discount_rate";
public static final String KEY_POINTS_EARN_RATE = "points_earn_rate";
private final SystemConfigRepository configRepository;
@PostConstruct
public void initDefaults() {
setDefault(KEY_POINTS_EXCHANGE_RATE, "100");
setDefault(KEY_MEMBER_DISCOUNT_RATE, "0.85");
setDefault(KEY_POINTS_EARN_RATE, "1");
}
private void setDefault(String key, String defaultValue) {
if (configRepository.findByConfigKey(key).isEmpty()) {
SystemConfig c = new SystemConfig();
c.setConfigKey(key);
c.setValue(defaultValue);
configRepository.save(c);
}
}
public String get(String key) {
return configRepository.findByConfigKey(key).map(SystemConfig::getValue).orElse("0");
}
@Transactional
public void set(String key, String value) {
SystemConfig c = configRepository.findByConfigKey(key).orElseGet(() -> {
SystemConfig nc = new SystemConfig();
nc.setConfigKey(key);
return nc;
});
c.setValue(value);
configRepository.save(c);
}
public Map<String, String> getAll() {
Map<String, String> map = new HashMap<>();
for (SystemConfig c : configRepository.findAll()) {
map.put(c.getConfigKey(), c.getValue());
}
return map;
}
/** 积分兑换汇率:多少积分 = 1 元 */
public static BigDecimal getPointsExchangeRate() {
return new BigDecimal(getStatic(KEY_POINTS_EXCHANGE_RATE, "100"));
}
/** 会员折扣率 */
public static BigDecimal getMemberDiscountRate() {
return new BigDecimal(getStatic(KEY_MEMBER_DISCOUNT_RATE, "0.85"));
}
/** 积分累计比例:1 元 = 多少积分 */
public static BigDecimal getPointsEarnRate() {
return new BigDecimal(getStatic(KEY_POINTS_EARN_RATE, "1"));
}
private static String getStatic(String key, String def) {
// 通过 Spring 上下文获取 bean
ConfigService bean = SpringContext.getBean(ConfigService.class);
if (bean == null) return def;
return bean.get(key);
}
}
@@ -0,0 +1,191 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.common.UserContext;
import com.gameparlor.entity.*;
import com.gameparlor.entity.enums.ItemType;
import com.gameparlor.entity.enums.OrderStatus;
import com.gameparlor.entity.enums.Role;
import com.gameparlor.repository.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class MemberService {
private final UserRepository userRepository;
private final GameRepository gameRepository;
private final DeviceRepository deviceRepository;
private final SnackRepository snackRepository;
private final TimeSlotRepository timeSlotRepository;
private final OrderRepository orderRepository;
private final OrderItemRepository orderItemRepository;
private final WalletService walletService;
private final ComboService comboService;
private void checkMember() {
Long userId = UserContext.getUserId();
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
if (user.getRole() != Role.MEMBER && user.getRole() != Role.ADMIN) {
throw new BusinessException(ResultCode.MEMBER_ONLY);
}
}
/**
* 计算自定义拼套餐价格:Σ 各项 memberPrice × 会员折扣率
*/
public BigDecimal calcCustomComboPrice(List<CustomItem> items) {
BigDecimal sum = BigDecimal.ZERO;
for (CustomItem ci : items) {
sum = sum.add(resolveMemberPrice(ci.getItemType(), ci.getItemId())
.multiply(BigDecimal.valueOf(ci.getQuantity())));
}
return sum.multiply(ConfigService.getMemberDiscountRate()).setScale(2, RoundingMode.HALF_UP);
}
@Transactional
public Order purchaseCustomCombo(List<CustomItem> items) {
checkMember();
Long userId = UserContext.getUserId();
BigDecimal price = calcCustomComboPrice(items);
walletService.deduct(userId, price, "会员自定义拼套餐");
Order order = new Order();
order.setUser(userRepository.getReferenceById(userId));
order.setTotalAmount(price);
order.setStatus(OrderStatus.PAID);
order = orderRepository.save(order);
LocalDateTime now = LocalDateTime.now();
for (CustomItem ci : items) {
OrderItem oi = new OrderItem();
oi.setOrder(order);
oi.setItemType(ci.getItemType());
oi.setItemId(ci.getItemId());
oi.setQuantity(ci.getQuantity());
if (ci.getItemType() == ItemType.TIMESLOT) {
TimeSlot slot = timeSlotRepository.findById(ci.getItemId()).orElse(null);
if (slot != null) {
oi.setStartTime(now);
oi.setEndTime(now.plusMinutes(slot.getDurationMinutes()));
}
}
orderItemRepository.save(oi);
}
walletService.awardPoints(userId, price);
return order;
}
/**
* 积分兑换:按积分汇率扣积分,发放对应项目
*/
@Transactional
public Order exchangePoints(ItemType itemType, Long itemId) {
checkMember();
Long userId = UserContext.getUserId();
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
BigDecimal unitPrice = resolveExchangePrice(itemType, itemId);
BigDecimal rate = ConfigService.getPointsExchangeRate();
int pointsNeeded = unitPrice.multiply(rate).setScale(0, RoundingMode.UP).intValue();
if (user.getPoints() < pointsNeeded) {
throw new BusinessException(ResultCode.POINTS_NOT_ENOUGH);
}
user.setPoints(user.getPoints() - pointsNeeded);
userRepository.save(user);
Order order = new Order();
order.setUser(user);
order.setTotalAmount(BigDecimal.ZERO);
order.setStatus(OrderStatus.PAID);
order = orderRepository.save(order);
LocalDateTime now = LocalDateTime.now();
if (itemType == ItemType.COMBO) {
// 兑换套餐:展开为多个订单项
List<ComboItem> comboItems = comboService.getItems(itemId);
for (ComboItem ci : comboItems) {
OrderItem oi = new OrderItem();
oi.setOrder(order);
oi.setItemType(ci.getItemType());
oi.setItemId(ci.getItemId());
oi.setQuantity(ci.getQuantity());
if (ci.getItemType() == ItemType.TIMESLOT) {
TimeSlot slot = timeSlotRepository.findById(ci.getItemId()).orElse(null);
if (slot != null) {
oi.setStartTime(now);
oi.setEndTime(now.plusMinutes(slot.getDurationMinutes()));
}
}
orderItemRepository.save(oi);
}
} else {
OrderItem oi = new OrderItem();
oi.setOrder(order);
oi.setItemType(itemType);
oi.setItemId(itemId);
oi.setQuantity(1);
if (itemType == ItemType.TIMESLOT) {
TimeSlot slot = timeSlotRepository.findById(itemId).orElse(null);
if (slot != null) {
oi.setStartTime(now);
oi.setEndTime(now.plusMinutes(slot.getDurationMinutes()));
}
}
orderItemRepository.save(oi);
}
return order;
}
private BigDecimal resolveMemberPrice(ItemType type, Long itemId) {
if (type == null) type = ItemType.COMBO;
return switch (type) {
case GAME -> gameRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "游戏不存在"))
.getMemberPrice();
case DEVICE -> BigDecimal.ZERO;
case SNACK -> snackRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "零食不存在"))
.getMemberPrice();
case TIMESLOT -> timeSlotRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "时长不存在"))
.getMemberPrice();
case COMBO -> comboService.calcPrice(itemId);
};
}
private BigDecimal resolveExchangePrice(ItemType type, Long itemId) {
if (type == null) type = ItemType.COMBO;
return switch (type) {
case GAME -> gameRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "游戏不存在"))
.getMemberPrice();
case DEVICE -> BigDecimal.ZERO;
case SNACK -> snackRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "零食不存在")).getPrice();
case TIMESLOT -> timeSlotRepository.findById(itemId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "时长不存在")).getBasePrice();
case COMBO -> comboService.calcPrice(itemId);
};
}
@Data
public static class CustomItem {
private ItemType itemType;
private Long itemId;
private Integer quantity = 1;
}
}
@@ -0,0 +1,218 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.common.UserContext;
import com.gameparlor.entity.*;
import com.gameparlor.entity.enums.ItemType;
import com.gameparlor.entity.enums.OrderStatus;
import com.gameparlor.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final OrderItemRepository orderItemRepository;
private final GameRepository gameRepository;
private final TimeSlotRepository timeSlotRepository;
private final SnackRepository snackRepository;
private final UserRepository userRepository;
private final WalletService walletService;
private final ComboService comboService;
/**
* 开始游玩:选择游戏 + 时长
*/
@Transactional
public Order startGame(Long gameId, Long timeSlotId) {
Long userId = UserContext.getUserId();
Game game = gameRepository.findById(gameId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "游戏不存在"));
TimeSlot slot = timeSlotRepository.findById(timeSlotId)
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "时长不存在"));
BigDecimal price = slot.getBasePrice();
walletService.deduct(userId, price, "游戏消费: " + game.getName());
Order order = new Order();
order.setUser(userRepository.getReferenceById(userId));
order.setTotalAmount(price);
order.setStatus(OrderStatus.PAID);
order = orderRepository.save(order);
LocalDateTime now = LocalDateTime.now();
// 游戏项
OrderItem gameItem = new OrderItem();
gameItem.setOrder(order);
gameItem.setItemType(ItemType.GAME);
gameItem.setItemId(gameId);
gameItem.setQuantity(1);
orderItemRepository.save(gameItem);
// 时长项(携带起止时间,用于倒计时与续费)
OrderItem slotItem = new OrderItem();
slotItem.setOrder(order);
slotItem.setItemType(ItemType.TIMESLOT);
slotItem.setItemId(timeSlotId);
slotItem.setStartTime(now);
slotItem.setEndTime(now.plusMinutes(slot.getDurationMinutes()));
slotItem.setQuantity(1);
orderItemRepository.save(slotItem);
walletService.awardPoints(userId, price);
return order;
}
/**
* 续费:按原时长单价比例扣费,延长 endTime
*/
@Transactional
public Order renew(Long orderId, Integer additionalMinutes) {
Long userId = UserContext.getUserId();
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new BusinessException(ResultCode.ORDER_NOT_FOUND));
if (!order.getUser().getId().equals(userId)) {
throw new BusinessException(ResultCode.FORBIDDEN);
}
List<OrderItem> items = orderItemRepository.findByOrderId(orderId);
OrderItem slotItem = items.stream()
.filter(i -> i.getItemType() == ItemType.TIMESLOT)
.findFirst()
.orElseThrow(() -> new BusinessException(ResultCode.ORDER_NOT_FOUND));
TimeSlot slot = timeSlotRepository.findById(slotItem.getItemId())
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "时长不存在"));
BigDecimal pricePerMinute = slot.getBasePrice()
.divide(BigDecimal.valueOf(slot.getDurationMinutes()), 4, RoundingMode.HALF_UP);
BigDecimal cost = pricePerMinute.multiply(BigDecimal.valueOf(additionalMinutes))
.setScale(2, RoundingMode.HALF_UP);
walletService.deduct(userId, cost, "续费: " + additionalMinutes + "分钟");
slotItem.setEndTime(slotItem.getEndTime().plusMinutes(additionalMinutes));
orderItemRepository.save(slotItem);
order.setTotalAmount(order.getTotalAmount().add(cost));
orderRepository.save(order);
walletService.awardPoints(userId, cost);
return order;
}
/**
* 获取当前进行中的订单及剩余秒数
*/
public Map<String, Object> getActiveOrder() {
Long userId = UserContext.getUserId();
LocalDateTime now = LocalDateTime.now();
List<Order> orders = orderRepository.findByUserIdAndStatus(userId, OrderStatus.PAID);
for (Order order : orders) {
List<OrderItem> items = orderItemRepository.findByOrderId(order.getId());
OrderItem slotItem = items.stream()
.filter(i -> i.getItemType() == ItemType.TIMESLOT && i.getEndTime() != null
&& i.getEndTime().isAfter(now))
.findFirst().orElse(null);
if (slotItem != null) {
long seconds = java.time.Duration.between(now, slotItem.getEndTime()).getSeconds();
// 找到对应的游戏名
String gameName = items.stream()
.filter(i -> i.getItemType() == ItemType.GAME)
.findFirst()
.flatMap(i -> gameRepository.findById(i.getItemId()))
.map(Game::getName).orElse("");
Map<String, Object> map = new HashMap<>();
map.put("orderId", order.getId());
map.put("gameId", items.stream().filter(i -> i.getItemType() == ItemType.GAME)
.map(OrderItem::getItemId).findFirst().orElse(null));
map.put("gameName", gameName);
map.put("startTime", slotItem.getStartTime());
map.put("endTime", slotItem.getEndTime());
map.put("remainingSeconds", seconds);
map.put("totalAmount", order.getTotalAmount());
return map;
}
}
return null;
}
/**
* 购买套餐
*/
@Transactional
public Order buyCombo(Long comboId) {
Long userId = UserContext.getUserId();
BigDecimal price = comboService.calcPrice(comboId);
walletService.deduct(userId, price, "购买套餐");
Order order = new Order();
order.setUser(userRepository.getReferenceById(userId));
order.setTotalAmount(price);
order.setStatus(OrderStatus.PAID);
order = orderRepository.save(order);
List<ComboItem> comboItems = comboService.getItems(comboId);
LocalDateTime now = LocalDateTime.now();
for (ComboItem ci : comboItems) {
OrderItem oi = new OrderItem();
oi.setOrder(order);
oi.setItemType(ci.getItemType());
oi.setItemId(ci.getItemId());
oi.setQuantity(ci.getQuantity());
if (ci.getItemType() == ItemType.TIMESLOT) {
TimeSlot slot = timeSlotRepository.findById(ci.getItemId()).orElse(null);
if (slot != null) {
oi.setStartTime(now);
oi.setEndTime(now.plusMinutes(slot.getDurationMinutes()));
}
}
orderItemRepository.save(oi);
}
walletService.awardPoints(userId, price);
return order;
}
/**
* 购买零食饮料
*/
@Transactional
public Order buySnacks(List<SnackItem> snackItems) {
Long userId = UserContext.getUserId();
BigDecimal total = BigDecimal.ZERO;
for (SnackItem si : snackItems) {
Snack snack = snackRepository.findById(si.snackId())
.orElseThrow(() -> new BusinessException(ResultCode.ITEM_NOT_FOUND, "零食不存在"));
total = total.add(snack.getPrice().multiply(BigDecimal.valueOf(si.quantity())));
}
walletService.deduct(userId, total, "购买零食饮料");
Order order = new Order();
order.setUser(userRepository.getReferenceById(userId));
order.setTotalAmount(total);
order.setStatus(OrderStatus.PAID);
order = orderRepository.save(order);
for (SnackItem si : snackItems) {
OrderItem oi = new OrderItem();
oi.setOrder(order);
oi.setItemType(ItemType.SNACK);
oi.setItemId(si.snackId());
oi.setQuantity(si.quantity());
orderItemRepository.save(oi);
}
walletService.awardPoints(userId, total);
return order;
}
public record SnackItem(Long snackId, Integer quantity) {}
}
@@ -0,0 +1,57 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.RechargeApproval;
import com.gameparlor.entity.enums.RechargeStatus;
import com.gameparlor.repository.RechargeApprovalRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@RequiredArgsConstructor
public class RechargeService {
private final RechargeApprovalRepository rechargeApprovalRepository;
private final WalletService walletService;
public List<RechargeApproval> listPending() {
return rechargeApprovalRepository.findByStatus(RechargeStatus.PENDING);
}
public Page<RechargeApproval> listAll(Pageable pageable) {
return rechargeApprovalRepository.findAllByOrderByCreatedAtDesc(pageable);
}
@Transactional
public RechargeApproval approve(Long id, String authCode) {
RechargeApproval ra = rechargeApprovalRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "充值申请不存在"));
if (ra.getStatus() != RechargeStatus.PENDING) {
throw new BusinessException(ResultCode.BAD_REQUEST, "该申请已处理");
}
if (authCode == null || !authCode.equals(ra.getAuthCode())) {
throw new BusinessException(ResultCode.AUTH_CODE_ERROR);
}
ra.setStatus(RechargeStatus.APPROVED);
rechargeApprovalRepository.save(ra);
walletService.recharge(ra.getUser().getId(), ra.getAmount(), "充值审批通过");
return ra;
}
@Transactional
public RechargeApproval reject(Long id) {
RechargeApproval ra = rechargeApprovalRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "充值申请不存在"));
if (ra.getStatus() != RechargeStatus.PENDING) {
throw new BusinessException(ResultCode.BAD_REQUEST, "该申请已处理");
}
ra.setStatus(RechargeStatus.REJECTED);
return rechargeApprovalRepository.save(ra);
}
}
@@ -0,0 +1,21 @@
package com.gameparlor.service;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContext implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
if (context == null) return null;
return context.getBean(clazz);
}
}
@@ -0,0 +1,56 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.User;
import com.gameparlor.entity.enums.Role;
import com.gameparlor.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDate;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
public User getById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
}
public Page<User> list(Pageable pageable) {
return userRepository.findAll(pageable);
}
@Transactional
public User update(Long id, String username, String password, Role role, BigDecimal balance,
LocalDate memberExpireDate, Integer points) {
User user = getById(id);
if (username != null && !username.equals(user.getUsername())) {
if (userRepository.existsByUsername(username)) {
throw new BusinessException(ResultCode.USERNAME_EXISTS);
}
user.setUsername(username);
}
if (password != null && !password.isBlank()) {
user.setPassword(password);
}
if (role != null) user.setRole(role);
if (balance != null) user.setBalance(balance);
if (memberExpireDate != null) user.setMemberExpireDate(memberExpireDate);
if (points != null) user.setPoints(points);
return userRepository.save(user);
}
@Transactional
public void delete(Long id) {
userRepository.deleteById(id);
}
}
@@ -0,0 +1,88 @@
package com.gameparlor.service;
import com.gameparlor.common.BusinessException;
import com.gameparlor.common.ResultCode;
import com.gameparlor.entity.TransactionLog;
import com.gameparlor.entity.User;
import com.gameparlor.entity.enums.TxType;
import com.gameparlor.repository.TransactionLogRepository;
import com.gameparlor.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Slf4j
@Service
@RequiredArgsConstructor
public class WalletService {
private final UserRepository userRepository;
private final TransactionLogRepository txLogRepository;
/**
* 扣减余额,带乐观锁重试
*/
@Transactional
public void deduct(Long userId, BigDecimal amount, String remark) {
int maxRetry = 3;
for (int i = 0; i < maxRetry; i++) {
try {
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
if (user.getBalance().compareTo(amount) < 0) {
throw new BusinessException(ResultCode.BALANCE_NOT_ENOUGH);
}
user.setBalance(user.getBalance().subtract(amount));
userRepository.save(user);
TransactionLog log = new TransactionLog();
log.setUser(user);
log.setType(TxType.CONSUME);
log.setAmount(amount.negate());
log.setRemark(remark);
txLogRepository.save(log);
return;
} catch (OptimisticLockingFailureException e) {
log.warn("扣余额乐观锁冲突,重试 {}/{}", i + 1, maxRetry);
if (i == maxRetry - 1) {
throw new BusinessException(ResultCode.OPTIMISTIC_LOCK);
}
}
}
}
@Transactional
public void recharge(Long userId, BigDecimal amount, String remark) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
user.setBalance(user.getBalance().add(amount));
userRepository.save(user);
TransactionLog log = new TransactionLog();
log.setUser(user);
log.setType(TxType.RECHARGE);
log.setAmount(amount);
log.setRemark(remark);
txLogRepository.save(log);
}
/**
* 累计积分(消费时调用)
*/
@Transactional(propagation = Propagation.REQUIRED)
public void awardPoints(Long userId, BigDecimal amount) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new BusinessException(ResultCode.NOT_FOUND, "用户不存在"));
BigDecimal rate = ConfigService.getPointsEarnRate();
int earned = amount.multiply(rate).setScale(0, java.math.RoundingMode.HALF_UP).intValue();
if (earned > 0) {
user.setPoints(user.getPoints() + earned);
userRepository.save(user);
}
}
}
+22
View File
@@ -0,0 +1,22 @@
# 服务端口
server.port=8080
# MySQL 数据源(按需求使用 MySQL 5.x)
spring.datasource.url=jdbc:mysql://192.168.8.3:3306/gameparlor?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=xiaoyu
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=false
spring.jpa.open-in-view=true
# 全局引号标识符,兼容 MySQL 保留字(user、value 等)
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
# 不自动执行 schema.sql / data.sql(由用户手动在 MySQL 中执行;H2 验证时同样跳过)
spring.sql.init.mode=never
# 静态资源
spring.web.resources.static-locations=classpath:/static/
+39
View File
@@ -0,0 +1,39 @@
-- =====================================================
-- GameParlor 初始数据脚本(MySQL 5.x)
-- 在执行完 schema.sql 后执行本脚本
-- =====================================================
USE gameparlor;
-- 管理员账号(明文密码)
INSERT INTO `user` (`username`, `password`, `role`, `balance`, `member_expire_date`, `points`, `version`)
VALUES ('admin', 'admin123', 'ADMIN', 9999.00, DATE_ADD(CURDATE(), INTERVAL 10 YEAR), 0, 0);
-- 设备
INSERT INTO `device` (`name`, `description`, `remark`, `created_at`) VALUES
('PS5', 'PlayStation 5 主机', '4K 120Hz,支持次世代游戏', NOW()),
('Switch', '任天堂 Switch', '多人派对游戏首选', NOW());
-- 游戏
INSERT INTO `game` (`name`, `description`, `remark`, `is_universal`, `device_id`, `member_price`, `created_at`) VALUES
('艾尔登法环', '开放世界动作 RPG', '运行设备:PS5', b'0', 1, 30.00, NOW()),
('马里奥赛车', '竞速派对游戏', '运行设备:Switch', b'0', 2, 20.00, NOW()),
('街机合集', '经典街机游戏合集', '通用游戏,全设备可玩', b'1', NULL, 15.00, NOW());
-- 时长
INSERT INTO `time_slot` (`duration_minutes`, `base_price`, `member_price`, `created_at`) VALUES
(30, 15.00, 12.00, NOW()),
(60, 25.00, 20.00, NOW()),
(120, 45.00, 38.00, NOW());
-- 零食饮料
INSERT INTO `snack` (`name`, `price`, `type`, `remark`, `member_price`, `created_at`) VALUES
('可乐', 8.00, 'DRINK', '冰镇 330ml', 6.00, NOW()),
('薯片', 10.00, 'SNACK', '原味', 8.00, NOW()),
('绿茶', 6.00, 'DRINK', '无糖', 5.00, NOW());
-- 系统配置
INSERT INTO `system_config` (`config_key`, `value`) VALUES
('points_exchange_rate', '100'),
('member_discount_rate', '0.85'),
('points_earn_rate', '1');
+155
View File
@@ -0,0 +1,155 @@
-- =====================================================
-- GameParlor 初始建表脚本(MySQL 5.x)
-- 使用方法:在 MySQL 中创建 gameparlor 库后执行本脚本
-- =====================================================
CREATE DATABASE IF NOT EXISTS gameparlor DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE gameparlor;
-- 设备
CREATE TABLE IF NOT EXISTS `device` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`description` VARCHAR(500),
`remark` VARCHAR(255),
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_device_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 游戏
CREATE TABLE IF NOT EXISTS `game` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`description` VARCHAR(500),
`remark` VARCHAR(255),
`is_universal` BIT(1) NOT NULL DEFAULT b'0',
`device_id` BIGINT,
`member_price` DECIMAL(10,2),
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_game_device_id` (`device_id`),
INDEX `idx_game_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 零食/饮料
CREATE TABLE IF NOT EXISTS `snack` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`price` DECIMAL(10,2) NOT NULL,
`type` VARCHAR(20) NOT NULL,
`remark` VARCHAR(255),
`member_price` DECIMAL(10,2),
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_snack_type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 游玩时长选项
CREATE TABLE IF NOT EXISTS `time_slot` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`duration_minutes` INT NOT NULL,
`base_price` DECIMAL(10,2) NOT NULL,
`member_price` DECIMAL(10,2),
`created_at` DATETIME,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 套餐
CREATE TABLE IF NOT EXISTS `combo` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`type` VARCHAR(20) NOT NULL,
`discount_rate` DECIMAL(5,2) NOT NULL DEFAULT 1.00,
`is_active` BIT(1) NOT NULL DEFAULT b'1',
`created_at` DATETIME,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 套餐组成项
CREATE TABLE IF NOT EXISTS `combo_item` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`combo_id` BIGINT NOT NULL,
`item_type` VARCHAR(20) NOT NULL,
`item_id` BIGINT NOT NULL,
`quantity` INT NOT NULL DEFAULT 1,
`unit_price_at_creation` DECIMAL(10,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 用户
CREATE TABLE IF NOT EXISTS `user` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(50) NOT NULL,
`password` VARCHAR(100) NOT NULL,
`role` VARCHAR(20) NOT NULL,
`balance` DECIMAL(12,2) NOT NULL DEFAULT 0.00,
`member_expire_date` DATE,
`points` INT NOT NULL DEFAULT 0,
`created_at` DATETIME,
`version` BIGINT,
PRIMARY KEY (`id`),
UNIQUE INDEX `idx_user_username` (`username`),
INDEX `idx_user_role` (`role`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单
CREATE TABLE IF NOT EXISTS `orders` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`user_id` BIGINT NOT NULL,
`total_amount` DECIMAL(12,2) NOT NULL,
`status` VARCHAR(20) NOT NULL,
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_order_user_id` (`user_id`),
INDEX `idx_order_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单项
CREATE TABLE IF NOT EXISTS `order_item` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`order_id` BIGINT NOT NULL,
`item_type` VARCHAR(20) NOT NULL,
`item_id` BIGINT NOT NULL,
`start_time` DATETIME,
`end_time` DATETIME,
`quantity` INT NOT NULL DEFAULT 1,
PRIMARY KEY (`id`),
INDEX `idx_order_item_order_id` (`order_id`),
INDEX `idx_order_item_end_time` (`end_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 交易日志
CREATE TABLE IF NOT EXISTS `transaction_log` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`user_id` BIGINT NOT NULL,
`type` VARCHAR(20) NOT NULL,
`amount` DECIMAL(12,2) NOT NULL,
`remark` VARCHAR(255),
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_tx_user_id` (`user_id`),
INDEX `idx_tx_type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 充值审批
CREATE TABLE IF NOT EXISTS `recharge_approval` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`user_id` BIGINT NOT NULL,
`amount` DECIMAL(12,2) NOT NULL,
`auth_code` VARCHAR(50),
`status` VARCHAR(20) NOT NULL,
`created_at` DATETIME,
PRIMARY KEY (`id`),
INDEX `idx_recharge_user_id` (`user_id`),
INDEX `idx_recharge_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 系统配置
CREATE TABLE IF NOT EXISTS `system_config` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`config_key` VARCHAR(50) NOT NULL,
`value` VARCHAR(100),
PRIMARY KEY (`id`),
UNIQUE INDEX `uk_config_key` (`config_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+121
View File
@@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>套餐管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="combosApp()" x-init="init()">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold">套餐管理</h2>
<button class="btn btn-primary" @click="openCreate()">+ 新增套餐</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<template x-for="c in list" :key="c.id">
<div class="card card-hover p-4">
<div class="flex items-start justify-between">
<div>
<div class="font-bold" x-text="c.name"></div>
<span class="badge badge-accent mt-1" x-text="c.type"></span>
</div>
<span class="badge" :class="c.isActive ? 'badge-success' : 'badge-danger'" x-text="c.isActive ? '启用' : '停用'"></span>
</div>
<div class="text-sm text-[#9a9aa5] mt-2">折扣率:<span x-text="c.discountRate"></span></div>
<div class="flex gap-2 mt-3">
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openItems(c)">组成项</button>
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(c)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(c.id)">删除</button>
</div>
</div>
</template>
</div>
<!-- 套餐编辑 -->
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4" x-text="editing ? '编辑套餐' : '新增套餐'"></h3>
<div class="space-y-3">
<div><label class="label">名称</label><input x-model="form.name" class="input"></div>
<div><label class="label">类型</label>
<select x-model="form.type" class="select">
<option value="VIP">VIP</option><option value="DEVICE_GAME">设备游戏</option><option value="SNACK_DRINK">零食饮料</option>
</select>
</div>
<div><label class="label">折扣率(如 0.85)</label><input type="number" step="0.01" x-model="form.discountRate" class="input"></div>
<div class="flex items-center gap-2"><input type="checkbox" x-model="form.isActive" id="act"><label for="act">启用</label></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<!-- 组成项 -->
<div x-show="itemsModal" x-cloak class="modal-mask" @click.self="itemsModal=false">
<div class="modal" style="max-width:600px">
<h3 class="text-lg font-bold mb-2" x-text="'组成项:' + (curCombo ? curCombo.name : '')"></h3>
<div class="text-sm text-[#9a9aa5] mb-3">总价 = Σ(单价×数量) × 折扣率 = <span class="text-[#00d4ff]" x-text="'¥'+fmtMoney(curPrice)"></span></div>
<div class="space-y-2 mb-3">
<template x-for="it in items" :key="it.id">
<div class="flex items-center justify-between p-2 rounded-lg bg-[#16161a]">
<span class="text-sm" x-text="`${it.itemType} #${it.itemId} × ${it.quantity} (¥${fmtMoney(it.unitPriceAtCreation)})`"></span>
<button class="btn btn-danger !py-0.5 !px-2 text-xs" @click="removeItem(it.id)">移除</button>
</div>
</template>
<div x-show="items.length===0" class="text-center text-[#6b6b78] py-4 text-sm">暂无组成项</div>
</div>
<div class="border-t border-[#2a2a33] pt-3">
<div class="text-sm font-medium mb-2">添加组成项</div>
<div class="grid grid-cols-2 gap-2">
<select x-model="newItem.itemType" class="select">
<option value="GAME">游戏</option><option value="DEVICE">设备</option><option value="SNACK">零食</option><option value="TIMESLOT">时长</option>
</select>
<input type="number" placeholder="项目ID" x-model="newItem.itemId" class="input">
<input type="number" placeholder="数量" x-model="newItem.quantity" class="input">
<button class="btn btn-primary" @click="addItem()">添加</button>
</div>
</div>
<div class="flex justify-end mt-4"><button class="btn btn-ghost" @click="itemsModal=false">关闭</button></div>
</div>
</div>
<script src="/app.js"></script>
<script>
function combosApp() {
return {
list: [], modal: false, editing: null, itemsModal: false, curCombo: null, items: [], curPrice: 0,
form: { name: '', type: 'VIP', discountRate: 1, isActive: true },
newItem: { itemType: 'GAME', itemId: '', quantity: 1 },
async init() { await initLayout('combos'); this.load(); },
async load() { this.list = await api('/api/combos').catch(() => []); },
openCreate() { this.editing = null; this.form = { name: '', type: 'VIP', discountRate: 1, isActive: true }; this.modal = true; },
openEdit(c) { this.editing = c; this.form = { name: c.name, type: c.type, discountRate: c.discountRate, isActive: c.isActive }; this.modal = true; },
async save() {
const method = this.editing ? 'PUT' : 'POST';
const url = this.editing ? `/api/admin/combos/${this.editing.id}` : '/api/admin/combos';
await api(url, { method, body: JSON.stringify(this.form) });
toast(this.editing ? '已更新' : '已创建', 'success');
this.modal = false; this.load();
},
async remove(id) { if (!confirm('确认删除套餐?')) return; await api(`/api/admin/combos/${id}`, { method: 'DELETE' }); toast('已删除', 'success'); this.load(); },
async openItems(c) {
this.curCombo = c; this.itemsModal = true;
const d = await api(`/api/combos/${c.id}`).catch(() => ({ items: [], price: 0 }));
this.items = d.items || []; this.curPrice = d.price || 0;
},
async addItem() {
if (!this.newItem.itemId) { toast('请输入项目ID', 'error'); return; }
await api(`/api/admin/combos/${this.curCombo.id}/items`, { method: 'POST', body: JSON.stringify({ itemType: this.newItem.itemType, itemId: Number(this.newItem.itemId), quantity: Number(this.newItem.quantity) || 1 }) });
toast('已添加', 'success');
this.openItems(this.curCombo);
},
async removeItem(id) { await api(`/api/admin/combos/items/${id}`, { method: 'DELETE' }); toast('已移除', 'success'); this.openItems(this.curCombo); }
};
}
</script>
</body>
</html>
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>概览 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="dashApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">管理概览</h2>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div class="card card-hover p-5">
<div class="text-sm text-[#9a9aa5]">用户总数</div>
<div class="text-3xl font-bold mt-2 text-[#00d4ff]" x-text="stats.userCount ?? 0"></div>
</div>
<div class="card card-hover p-5">
<div class="text-sm text-[#9a9aa5]">订单总数</div>
<div class="text-3xl font-bold mt-2 text-[#00d4ff]" x-text="stats.orderCount ?? 0"></div>
</div>
<div class="card card-hover p-5">
<div class="text-sm text-[#9a9aa5]">待审批充值</div>
<div class="text-3xl font-bold mt-2" :class="(stats.pendingRechargeCount||0)>0 ? 'text-[#fbbf24]' : 'text-[#34d399]'" x-text="stats.pendingRechargeCount ?? 0"></div>
</div>
</div>
<div class="card p-5 mt-6">
<h3 class="font-semibold mb-3">系统配置</h3>
<template x-for="(v,k) in config" :key="k">
<div class="flex items-center justify-between py-2 border-b border-[#2a2a33] last:border-0">
<span class="text-sm text-[#9a9aa5]" x-text="k"></span>
<input :value="v" class="input !w-40 text-right" @change="saveConfig(k, $event.target.value)">
</div>
</template>
</div>
<script src="/app.js"></script>
<script>
function dashApp() {
return {
stats: {}, config: {},
async init() { await initLayout('dashboard'); this.stats = await api('/api/admin/stats').catch(() => ({})); this.config = await api('/api/admin/config').catch(() => ({})); },
async saveConfig(k, v) { await api('/api/admin/config', { method: 'PUT', body: JSON.stringify({ [k]: v }) }); toast('配置已更新', 'success'); }
};
}
</script>
</body>
</html>
@@ -0,0 +1,97 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>设备管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="devicesApp()" x-init="init()">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold">设备管理</h2>
<button class="btn btn-primary" @click="openCreate()">+ 新增设备</button>
</div>
<div class="card overflow-x-auto">
<table class="table">
<thead>
<tr><th>ID</th><th>名称</th><th>描述</th><th>备注</th><th>创建时间</th><th>操作</th></tr>
</thead>
<tbody>
<template x-for="d in list" :key="d.id">
<tr>
<td x-text="d.id"></td>
<td x-text="d.name"></td>
<td class="text-[#9a9aa5]" x-text="d.description"></td>
<td class="remark" x-text="d.remark"></td>
<td class="text-[#9a9aa5]" x-text="fmtDateTime(d.createdAt)"></td>
<td>
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(d)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(d.id)">删除</button>
</td>
</tr>
</template>
<tr x-show="list.length === 0"><td colspan="6" class="text-center text-[#6b6b78] py-8">暂无数据</td></tr>
</tbody>
</table>
</div>
<div class="flex justify-center gap-2 mt-4">
<button class="btn btn-ghost !py-1 text-xs" :disabled="page===0" @click="page--;load()">上一页</button>
<span class="text-sm text-[#9a9aa5] self-center" x-text="`${page+1} / ${totalPages}`"></span>
<button class="btn btn-ghost !py-1 text-xs" :disabled="page>=totalPages-1" @click="page++;load()">下一页</button>
</div>
<!-- 模态框 -->
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4" x-text="editing ? '编辑设备' : '新增设备'"></h3>
<div class="space-y-3">
<div><label class="label">名称</label><input x-model="form.name" class="input"></div>
<div><label class="label">描述</label><input x-model="form.description" class="input"></div>
<div><label class="label">备注</label><input x-model="form.remark" class="input"></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function devicesApp() {
return {
list: [], page: 0, totalPages: 1, modal: false, editing: null,
form: { name: '', description: '', remark: '' },
async init() {
await initLayout('devices');
this.load();
},
async load() {
const data = await api(`/api/admin/devices?page=${this.page}&size=10`).catch(() => ({ content: [], totalPages: 1 }));
this.list = data.content || [];
this.totalPages = data.totalPages || 1;
},
openCreate() { this.editing = null; this.form = { name: '', description: '', remark: '' }; this.modal = true; },
openEdit(d) { this.editing = d; this.form = { name: d.name, description: d.description || '', remark: d.remark || '' }; this.modal = true; },
async save() {
if (!this.form.name) { toast('请输入名称', 'error'); return; }
const method = this.editing ? 'PUT' : 'POST';
const url = this.editing ? `/api/admin/devices/${this.editing.id}` : '/api/admin/devices';
await api(url, { method, body: JSON.stringify(this.form) });
toast(this.editing ? '已更新' : '已创建', 'success');
this.modal = false; this.load();
},
async remove(id) {
if (!confirm('确认删除该设备?')) return;
await api(`/api/admin/devices/${id}`, { method: 'DELETE' });
toast('已删除', 'success'); this.load();
}
};
}
</script>
</body>
</html>
+113
View File
@@ -0,0 +1,113 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>游戏管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="gamesApp()" x-init="init()">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold">游戏管理</h2>
<button class="btn btn-primary" @click="openCreate()">+ 新增游戏</button>
</div>
<div class="card overflow-x-auto">
<table class="table">
<thead>
<tr><th>ID</th><th>名称</th><th>通用</th><th>设备</th><th>会员单价</th><th>备注</th><th>操作</th></tr>
</thead>
<tbody>
<template x-for="g in list" :key="g.id">
<tr>
<td x-text="g.id"></td>
<td x-text="g.name"></td>
<td><span class="badge" :class="g.isUniversal ? 'badge-accent' : 'badge-success'" x-text="g.isUniversal ? '通用' : '绑定'"></span></td>
<td x-text="g.device ? g.device.name : '-'"></td>
<td x-text="'¥'+fmtMoney(g.memberPrice)"></td>
<td class="remark" x-text="g.remark"></td>
<td>
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(g)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(g.id)">删除</button>
</td>
</tr>
</template>
<tr x-show="list.length === 0"><td colspan="7" class="text-center text-[#6b6b78] py-8">暂无数据</td></tr>
</tbody>
</table>
</div>
<div class="flex justify-center gap-2 mt-4">
<button class="btn btn-ghost !py-1 text-xs" :disabled="page===0" @click="page--;load()">上一页</button>
<span class="text-sm text-[#9a9aa5] self-center" x-text="`${page+1} / ${totalPages}`"></span>
<button class="btn btn-ghost !py-1 text-xs" :disabled="page>=totalPages-1" @click="page++;load()">下一页</button>
</div>
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4" x-text="editing ? '编辑游戏' : '新增游戏'"></h3>
<div class="space-y-3">
<div><label class="label">名称</label><input x-model="form.name" class="input"></div>
<div><label class="label">描述</label><input x-model="form.description" class="input"></div>
<div><label class="label">备注(小字灰色显示)</label><input x-model="form.remark" class="input"></div>
<div class="flex items-center gap-2">
<input type="checkbox" x-model="form.isUniversal" id="univ">
<label for="univ" class="text-sm">通用游戏(不绑定设备)</label>
</div>
<div x-show="!form.isUniversal">
<label class="label">绑定设备</label>
<select x-model="form.deviceId" class="select">
<option value="">请选择</option>
<template x-for="d in devices" :key="d.id">
<option :value="d.id" x-text="d.name"></option>
</template>
</select>
</div>
<div><label class="label">会员单价(用于拼套餐)</label><input type="number" step="0.01" x-model="form.memberPrice" class="input"></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function gamesApp() {
return {
list: [], devices: [], page: 0, totalPages: 1, modal: false, editing: null,
form: { name: '', description: '', remark: '', isUniversal: false, deviceId: '', memberPrice: 0 },
async init() { await initLayout('games'); this.devices = await api('/api/devices').catch(() => []); this.load(); },
async load() {
const data = await api(`/api/admin/games?page=${this.page}&size=10`).catch(() => ({ content: [], totalPages: 1 }));
this.list = data.content || []; this.totalPages = data.totalPages || 1;
},
openCreate() { this.editing = null; this.form = { name: '', description: '', remark: '', isUniversal: false, deviceId: '', memberPrice: 0 }; this.modal = true; },
openEdit(g) {
this.editing = g;
this.form = { name: g.name, description: g.description || '', remark: g.remark || '', isUniversal: !!g.isUniversal, deviceId: g.device ? g.device.id : '', memberPrice: g.memberPrice || 0 };
this.modal = true;
},
async save() {
if (!this.form.name) { toast('请输入名称', 'error'); return; }
const payload = { ...this.form, memberPrice: Number(this.form.memberPrice) || 0 };
if (!payload.isUniversal) payload.deviceId = Number(payload.deviceId) || null;
const method = this.editing ? 'PUT' : 'POST';
const url = this.editing ? `/api/admin/games/${this.editing.id}` : '/api/admin/games';
await api(url, { method, body: JSON.stringify(payload) });
toast(this.editing ? '已更新' : '已创建', 'success');
this.modal = false; this.load();
},
async remove(id) {
if (!confirm('确认删除?')) return;
await api(`/api/admin/games/${id}`, { method: 'DELETE' });
toast('已删除', 'success'); this.load();
}
};
}
</script>
</body>
</html>
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>充值审批 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="rechargeApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">充值审批</h2>
<div class="card overflow-x-auto">
<table class="table">
<thead><tr><th>ID</th><th>用户ID</th><th>金额</th><th>授权码</th><th>状态</th><th>时间</th><th>操作</th></tr></thead>
<tbody>
<template x-for="r in list" :key="r.id">
<tr>
<td x-text="r.id"></td>
<td x-text="r.user ? r.user.id : r.userId"></td>
<td class="text-[#00d4ff]" x-text="'¥'+fmtMoney(r.amount)"></td>
<td class="mono" x-text="r.authCode"></td>
<td><span class="badge" :class="r.status==='PENDING'?'badge-warning':r.status==='APPROVED'?'badge-success':'badge-danger'" x-text="r.status"></span></td>
<td class="text-[#9a9aa5]" x-text="fmtDateTime(r.createdAt)"></td>
<td x-show="r.status==='PENDING'">
<button class="btn btn-primary !py-1 !px-2 text-xs" @click="approve(r)">批准</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="reject(r.id)">拒绝</button>
</td>
</tr>
</template>
<tr x-show="list.length === 0"><td colspan="7" class="text-center text-[#6b6b78] py-8">暂无待审批</td></tr>
</tbody>
</table>
</div>
<div x-show="approveModal" x-cloak class="modal-mask" @click.self="approveModal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4">批准充值</h3>
<p class="text-sm text-[#9a9aa5] mb-3">金额:<span class="text-[#00d4ff]" x-text="'¥'+fmtMoney(cur && cur.amount)"></span></p>
<div><label class="label">请输入授权码</label><input x-model="authCode" class="input mono" placeholder="6位授权码"></div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="approveModal=false">取消</button>
<button class="btn btn-primary" @click="doApprove()">确认批准</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function rechargeApp() {
return {
list: [], approveModal: false, cur: null, authCode: '',
async init() { await initLayout('recharge'); this.load(); },
async load() { this.list = await api('/api/admin/recharge/pending').catch(() => []); },
approve(r) { this.cur = r; this.authCode = ''; this.approveModal = true; },
async doApprove() {
await api(`/api/admin/recharge/${this.cur.id}/approve`, { method: 'POST', body: JSON.stringify({ authCode: this.authCode }) });
toast('已批准,余额已到账', 'success'); this.approveModal = false; this.load();
},
async reject(id) { if (!confirm('确认拒绝?')) return; await api(`/api/admin/recharge/${id}/reject`, { method: 'POST' }); toast('已拒绝', 'success'); this.load(); }
};
}
</script>
</body>
</html>
@@ -0,0 +1,89 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>零食管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="snacksApp()" x-init="init()">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold">零食/饮料管理</h2>
<button class="btn btn-primary" @click="openCreate()">+ 新增</button>
</div>
<div class="card overflow-x-auto">
<table class="table">
<thead><tr><th>ID</th><th>名称</th><th>类型</th><th>价格</th><th>会员单价</th><th>备注</th><th>操作</th></tr></thead>
<tbody>
<template x-for="s in list" :key="s.id">
<tr>
<td x-text="s.id"></td>
<td x-text="s.name"></td>
<td><span class="badge" :class="s.type==='DRINK' ? 'badge-accent' : 'badge-success'" x-text="s.type==='DRINK' ? '饮料' : '零食'"></span></td>
<td x-text="'¥'+fmtMoney(s.price)"></td>
<td x-text="'¥'+fmtMoney(s.memberPrice)"></td>
<td class="remark" x-text="s.remark"></td>
<td>
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(s)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(s.id)">删除</button>
</td>
</tr>
</template>
<tr x-show="list.length === 0"><td colspan="7" class="text-center text-[#6b6b78] py-8">暂无数据</td></tr>
</tbody>
</table>
</div>
<div class="flex justify-center gap-2 mt-4">
<button class="btn btn-ghost !py-1 text-xs" :disabled="page===0" @click="page--;load()">上一页</button>
<span class="text-sm text-[#9a9aa5] self-center" x-text="`${page+1} / ${totalPages}`"></span>
<button class="btn btn-ghost !py-1 text-xs" :disabled="page>=totalPages-1" @click="page++;load()">下一页</button>
</div>
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4" x-text="editing ? '编辑' : '新增'"></h3>
<div class="space-y-3">
<div><label class="label">名称</label><input x-model="form.name" class="input"></div>
<div><label class="label">类型</label>
<select x-model="form.type" class="select">
<option value="SNACK">零食</option><option value="DRINK">饮料</option>
</select>
</div>
<div><label class="label">价格</label><input type="number" step="0.01" x-model="form.price" class="input"></div>
<div><label class="label">会员单价</label><input type="number" step="0.01" x-model="form.memberPrice" class="input"></div>
<div><label class="label">备注</label><input x-model="form.remark" class="input"></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function snacksApp() {
return {
list: [], page: 0, totalPages: 1, modal: false, editing: null,
form: { name: '', type: 'SNACK', price: 0, memberPrice: 0, remark: '' },
async init() { await initLayout('snacks'); this.load(); },
async load() {
const data = await api(`/api/admin/snacks?page=${this.page}&size=10`).catch(() => ({ content: [], totalPages: 1 }));
this.list = data.content || []; this.totalPages = data.totalPages || 1;
},
openCreate() { this.editing = null; this.form = { name: '', type: 'SNACK', price: 0, memberPrice: 0, remark: '' }; this.modal = true; },
openEdit(s) { this.editing = s; this.form = { name: s.name, type: s.type, price: s.price, memberPrice: s.memberPrice || 0, remark: s.remark || '' }; this.modal = true; },
async save() {
const payload = { ...this.form, price: Number(this.form.price), memberPrice: Number(this.form.memberPrice) || 0 };
const method = this.editing ? 'PUT' : 'POST';
const url = this.editing ? `/api/admin/snacks/${this.editing.id}` : '/api/admin/snacks';
await api(url, { method, body: JSON.stringify(payload) });
toast(this.editing ? '已更新' : '已创建', 'success');
this.modal = false; this.load();
},
async remove(id) { if (!confirm('确认删除?')) return; await api(`/api/admin/snacks/${id}`, { method: 'DELETE' }); toast('已删除', 'success'); this.load(); }
};
}
</script>
</body>
</html>
@@ -0,0 +1,81 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时长管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="slotsApp()" x-init="init()">
<div class="flex items-center justify-between mb-6">
<h2 class="text-xl font-bold">时长管理</h2>
<button class="btn btn-primary" @click="openCreate()">+ 新增时长</button>
</div>
<div class="card overflow-x-auto">
<table class="table">
<thead><tr><th>ID</th><th>时长(分钟)</th><th>基础单价</th><th>会员单价</th><th>操作</th></tr></thead>
<tbody>
<template x-for="s in list" :key="s.id">
<tr>
<td x-text="s.id"></td>
<td><span class="badge badge-accent" x-text="s.durationMinutes + ' 分钟'"></span></td>
<td x-text="'¥'+fmtMoney(s.basePrice)"></td>
<td x-text="'¥'+fmtMoney(s.memberPrice)"></td>
<td>
<button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(s)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(s.id)">删除</button>
</td>
</tr>
</template>
<tr x-show="list.length === 0"><td colspan="5" class="text-center text-[#6b6b78] py-8">暂无数据</td></tr>
</tbody>
</table>
</div>
<div class="flex justify-center gap-2 mt-4">
<button class="btn btn-ghost !py-1 text-xs" :disabled="page===0" @click="page--;load()">上一页</button>
<span class="text-sm text-[#9a9aa5] self-center" x-text="`${page+1} / ${totalPages}`"></span>
<button class="btn btn-ghost !py-1 text-xs" :disabled="page>=totalPages-1" @click="page++;load()">下一页</button>
</div>
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4" x-text="editing ? '编辑时长' : '新增时长'"></h3>
<div class="space-y-3">
<div><label class="label">时长(分钟)</label><input type="number" x-model="form.durationMinutes" class="input"></div>
<div><label class="label">基础单价</label><input type="number" step="0.01" x-model="form.basePrice" class="input"></div>
<div><label class="label">会员单价(拼套餐用)</label><input type="number" step="0.01" x-model="form.memberPrice" class="input"></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function slotsApp() {
return {
list: [], page: 0, totalPages: 1, modal: false, editing: null,
form: { durationMinutes: 30, basePrice: 0, memberPrice: 0 },
async init() { await initLayout('timeslots'); this.load(); },
async load() {
const data = await api(`/api/admin/timeslots?page=${this.page}&size=10`).catch(() => ({ content: [], totalPages: 1 }));
this.list = data.content || []; this.totalPages = data.totalPages || 1;
},
openCreate() { this.editing = null; this.form = { durationMinutes: 30, basePrice: 0, memberPrice: 0 }; this.modal = true; },
openEdit(s) { this.editing = s; this.form = { durationMinutes: s.durationMinutes, basePrice: s.basePrice, memberPrice: s.memberPrice || 0 }; this.modal = true; },
async save() {
const payload = { durationMinutes: Number(this.form.durationMinutes), basePrice: Number(this.form.basePrice), memberPrice: Number(this.form.memberPrice) || 0 };
const method = this.editing ? 'PUT' : 'POST';
const url = this.editing ? `/api/admin/timeslots/${this.editing.id}` : '/api/admin/timeslots';
await api(url, { method, body: JSON.stringify(payload) });
toast(this.editing ? '已更新' : '已创建', 'success');
this.modal = false; this.load();
},
async remove(id) { if (!confirm('确认删除?')) return; await api(`/api/admin/timeslots/${id}`, { method: 'DELETE' }); toast('已删除', 'success'); this.load(); }
};
}
</script>
</body>
</html>
@@ -0,0 +1,83 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户管理 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="usersApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">用户管理</h2>
<div class="card overflow-x-auto">
<table class="table">
<thead><tr><th>ID</th><th>用户名</th><th>角色</th><th>余额</th><th>积分</th><th>会员到期</th><th>操作</th></tr></thead>
<tbody>
<template x-for="u in list" :key="u.id">
<tr>
<td x-text="u.id"></td>
<td x-text="u.username"></td>
<td><span class="badge" :class="u.role==='ADMIN'?'badge-accent':u.role==='MEMBER'?'badge-success':'badge-warning'" x-text="u.role"></span></td>
<td x-text="'¥'+fmtMoney(u.balance)"></td>
<td x-text="u.points"></td>
<td class="text-[#9a9aa5]" x-text="fmtDate(u.memberExpireDate)"></td>
<td><button class="btn btn-ghost !py-1 !px-2 text-xs" @click="openEdit(u)">编辑</button>
<button class="btn btn-danger !py-1 !px-2 text-xs" @click="remove(u.id)">删除</button></td>
</tr>
</template>
<tr x-show="list.length===0"><td colspan="7" class="text-center text-[#6b6b78] py-8">暂无数据</td></tr>
</tbody>
</table>
</div>
<div class="flex justify-center gap-2 mt-4">
<button class="btn btn-ghost !py-1 text-xs" :disabled="page===0" @click="page--;load()">上一页</button>
<span class="text-sm text-[#9a9aa5] self-center" x-text="`${page+1} / ${totalPages}`"></span>
<button class="btn btn-ghost !py-1 text-xs" :disabled="page>=totalPages-1" @click="page++;load()">下一页</button>
</div>
<div x-show="modal" x-cloak class="modal-mask" @click.self="modal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-4">编辑用户</h3>
<div class="space-y-3">
<div><label class="label">用户名</label><input x-model="form.username" class="input"></div>
<div><label class="label">密码(留空不修改)</label><input x-model="form.password" class="input"></div>
<div><label class="label">角色</label>
<select x-model="form.role" class="select"><option value="PLAYER">PLAYER</option><option value="MEMBER">MEMBER</option><option value="ADMIN">ADMIN</option></select>
</div>
<div><label class="label">余额</label><input type="number" step="0.01" x-model="form.balance" class="input"></div>
<div><label class="label">积分(累计消费额)</label><input type="number" x-model="form.points" class="input"></div>
<div><label class="label">会员到期日</label><input type="date" x-model="form.memberExpireDate" class="input"></div>
</div>
<div class="flex justify-end gap-2 mt-5">
<button class="btn btn-ghost" @click="modal=false">取消</button>
<button class="btn btn-primary" @click="save()">保存</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function usersApp() {
return {
list: [], page: 0, totalPages: 1, modal: false, editing: null,
form: { username: '', password: '', role: 'PLAYER', balance: 0, points: 0, memberExpireDate: '' },
async init() { await initLayout('users'); this.load(); },
async load() {
const data = await api(`/api/admin/users?page=${this.page}&size=10`).catch(() => ({ content: [], totalPages: 1 }));
this.list = data.content || []; this.totalPages = data.totalPages || 1;
},
openEdit(u) {
this.editing = u;
this.form = { username: u.username, password: '', role: u.role, balance: u.balance, points: u.points, memberExpireDate: u.memberExpireDate ? String(u.memberExpireDate).slice(0,10) : '' };
this.modal = true;
},
async save() {
const payload = { ...this.form, balance: Number(this.form.balance), points: Number(this.form.points) };
await api(`/api/admin/users/${this.editing.id}`, { method: 'PUT', body: JSON.stringify(payload) });
toast('已更新', 'success'); this.modal = false; this.load();
},
async remove(id) { if (!confirm('确认删除该用户?')) return; await api(`/api/admin/users/${id}`, { method: 'DELETE' }); toast('已删除', 'success'); this.load(); }
};
}
</script>
</body>
</html>
+216
View File
@@ -0,0 +1,216 @@
/* GameParlor 全局样式 — 深色主题 + 霓虹蓝 */
/* 注:Tailwind 工具类由 tailwind.min.js (Play CDN) 运行时注入;本文件仅定义组件类与基础样式 */
:root {
--bg: #0f0f11;
--bg-soft: #16161a;
--bg-card: #1c1c22;
--border: #2a2a33;
--accent: #00d4ff;
--accent-dim: rgba(0, 212, 255, 0.15);
--text: #e8e8ed;
--text-dim: #9a9aa5;
--text-faint: #6b6b78;
--success: #34d399;
--danger: #f87171;
--warning: #fbbf24;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
padding: 0;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
min-height: 100vh;
}
a { color: var(--accent); text-decoration: none; }
/* 滚动条 */
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #2a2a33; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #3a3a45; }
.card {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 14px;
transition: transform .25s ease, box-shadow .25s ease, border-color .25s ease;
}
.card-hover:hover {
transform: translateY(-3px);
box-shadow: 0 10px 30px rgba(0, 0, 0, .4), 0 0 0 1px rgba(0, 212, 255, .15);
border-color: rgba(0, 212, 255, .3);
}
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: .4rem;
padding: .55rem 1.1rem;
border-radius: 10px;
font-size: .875rem; font-weight: 500;
border: 1px solid transparent;
cursor: pointer;
transition: transform .1s ease, background .2s ease, border-color .2s ease, opacity .2s ease;
user-select: none;
}
.btn:active { transform: scale(0.95); }
.btn:disabled { opacity: .5; cursor: not-allowed; }
.btn-primary { background: var(--accent); color: #06242b; }
.btn-primary:hover:not(:disabled) { background: #33ddff; }
.btn-ghost { background: transparent; color: var(--text); border-color: var(--border); }
.btn-ghost:hover:not(:disabled) { border-color: var(--accent); color: var(--accent); }
.btn-danger { background: rgba(248, 113, 113, .12); color: var(--danger); border-color: rgba(248, 113, 113, .3); }
.btn-danger:hover:not(:disabled) { background: rgba(248, 113, 113, .22); }
.input, .select, .textarea {
width: 100%;
background: var(--bg-soft);
border: 1px solid var(--border);
border-radius: 10px;
padding: .55rem .8rem;
color: var(--text);
font-size: .875rem;
transition: border-color .2s ease, box-shadow .2s ease;
}
.input:focus, .select:focus, .textarea:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 3px var(--accent-dim);
}
.label { font-size: .8rem; color: var(--text-dim); margin-bottom: .35rem; display: block; }
.badge {
display: inline-flex; align-items: center;
padding: .15rem .55rem;
border-radius: 999px;
font-size: .72rem; font-weight: 600;
}
.badge-accent { background: var(--accent-dim); color: var(--accent); }
.badge-success { background: rgba(52, 211, 153, .12); color: var(--success); }
.badge-danger { background: rgba(248, 113, 113, .12); color: var(--danger); }
.badge-warning { background: rgba(251, 191, 36, .12); color: var(--warning); }
.remark { font-size: .75rem; color: var(--text-faint); }
.mono { font-family: "JetBrains Mono", "Fira Code", "Cascadia Code", Consolas, monospace; }
/* 页面淡入(仅用 opacity:transform 会成为 position:fixed 后代的包含块,导致弹窗越界) */
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.page-fade { animation: fadeIn .35s ease both; }
/* Alpine 初始化前隐藏 x-cloak 元素(避免弹窗闪现) */
[x-cloak] { display: none !important; }
/* 顶部导航布局(纯 CSS,不依赖 Tailwind 运行时) */
.gp-header {
position: sticky; top: 0; z-index: 50;
background: rgba(15, 15, 17, .85);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
border-bottom: 1px solid var(--border);
}
.gp-header-inner {
max-width: 80rem; margin: 0 auto; padding: 0 1rem;
min-height: 3.5rem;
display: flex; align-items: center; gap: 1.5rem;
}
.gp-brand { display: flex; align-items: center; gap: .5rem; font-weight: 700; font-size: 1rem; flex: none; }
.gp-logo {
width: 1.75rem; height: 1.75rem; border-radius: .5rem;
background: var(--accent); color: #06242b;
display: flex; align-items: center; justify-content: center; font-size: .875rem;
}
.gp-nav { display: flex; align-items: center; gap: .15rem; margin: 0; padding: 0; list-style: none; }
.gp-nav a {
display: inline-block; padding: .375rem .75rem; border-radius: .5rem;
font-size: .875rem; color: var(--text-dim);
white-space: nowrap; cursor: pointer;
transition: color .2s ease, background .2s ease;
}
.gp-nav a:hover { color: #fff; background: rgba(255, 255, 255, .04); }
.gp-nav a.is-active { background: var(--accent-dim); color: var(--accent); }
.gp-nav-desktop { display: none; }
.gp-nav-mobile {
gap: .25rem; padding: .35rem .75rem .5rem;
max-width: 80rem; margin: 0 auto;
overflow-x: auto; flex-wrap: nowrap;
}
.gp-nav-mobile a { font-size: .75rem; padding: .3rem .6rem; flex: none; }
@media (min-width: 768px) {
.gp-nav-desktop { display: flex; }
.gp-nav-mobile { display: none; }
}
.gp-userbar { margin-left: auto; display: flex; align-items: center; gap: .75rem; font-size: .875rem; flex: none; }
.gp-user-meta { display: none; align-items: center; gap: .75rem; color: var(--text-dim); }
.gp-username { color: var(--accent); }
.gp-logout { padding: .25rem .6rem; font-size: .75rem; }
@media (min-width: 640px) {
.gp-user-meta { display: flex; }
}
/* 页面内容容器 */
.gp-page {
max-width: 80rem;
width: 100%;
margin: 0 auto;
padding: 1.5rem 1rem 2rem;
}
/* Toast */
@keyframes toastIn {
from { opacity: 0; transform: translateY(-10px) scale(.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.toast {
position: fixed; top: 1.2rem; left: 50%; transform: translateX(-50%);
z-index: 9999;
padding: .7rem 1.2rem;
border-radius: 10px;
font-size: .875rem;
box-shadow: 0 8px 30px rgba(0,0,0,.5);
animation: toastIn .25s ease both;
}
.toast-success { background: rgba(52, 211, 153, .15); color: var(--success); border: 1px solid rgba(52, 211, 153, .35); }
.toast-error { background: rgba(248, 113, 113, .15); color: var(--danger); border: 1px solid rgba(248, 113, 113, .35); }
/* 倒计时颜色渐变 */
.countdown { font-variant-numeric: tabular-nums; letter-spacing: .02em; }
/* 表格 */
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: .7rem .8rem; text-align: left; border-bottom: 1px solid var(--border); font-size: .85rem; }
.table th { color: var(--text-dim); font-weight: 500; font-size: .75rem; text-transform: uppercase; letter-spacing: .04em; }
.table tr:hover td { background: rgba(255,255,255,.02); }
/* 模态遮罩(fixed 相对视口:祖先不得残留非 none 的 transform) */
.modal-mask {
position: fixed; inset: 0; background: rgba(0,0,0,.6);
backdrop-filter: blur(4px);
z-index: 1000;
display: flex; align-items: center; justify-content: center;
padding: 1rem;
overflow-y: auto;
animation: fadeIn .2s ease both;
}
.modal {
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 16px;
padding: 1.4rem;
width: 100%; max-width: 480px;
max-height: calc(100vh - 2rem); overflow-y: auto;
margin: auto;
}
/* 移动端适配 */
@media (max-width: 640px) {
.btn { padding: .5rem .85rem; font-size: .8rem; }
}
+171
View File
@@ -0,0 +1,171 @@
// GameParlor 前端公共脚本
(function () {
const API_BASE = '';
// ---------- 存储 ----------
const TOKEN_KEY = 'gp_token';
const USER_KEY = 'gp_user';
window.GP = {
getToken() { return localStorage.getItem(TOKEN_KEY); },
setToken(t) { localStorage.setItem(TOKEN_KEY, t); },
clearAuth() { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY); },
getUser() {
try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); }
catch { return null; }
},
setUser(u) { localStorage.setItem(USER_KEY, JSON.stringify(u)); },
isAdmin() { const u = this.getUser(); return u && u.role === 'ADMIN'; },
isMember() { const u = this.getUser(); return u && (u.role === 'MEMBER' || u.role === 'ADMIN'); },
redirectLogin() { window.location.href = '/index.html'; },
};
// ---------- API ----------
async function api(path, options = {}) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, options.headers || {});
const token = GP.getToken();
if (token) headers['Authorization'] = 'Bearer ' + token;
const res = await fetch(API_BASE + path, Object.assign({ headers }, options));
let body;
try { body = await res.json(); } catch { body = { code: 500, message: '网络错误' }; }
if (body.code === 401) {
GP.clearAuth();
GP.redirectLogin();
throw new Error(body.message || '未登录');
}
if (body.code !== 200) {
toast(body.message || '操作失败', 'error');
throw new Error(body.message);
}
return body.data;
}
window.api = api;
// ---------- Toast ----------
let toastTimer = null;
function toast(message, type = 'success') {
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const el = document.createElement('div');
el.className = 'toast toast-' + type;
el.textContent = message;
document.body.appendChild(el);
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.remove(), 2200);
}
window.toast = toast;
// ---------- 登出 ----------
window.logout = async function () {
try { await api('/api/auth/logout', { method: 'POST' }); } catch {}
GP.clearAuth();
GP.redirectLogin();
};
// ---------- 工具 ----------
window.fmtMoney = function (n) {
if (n == null) return '0.00';
return Number(n).toFixed(2);
};
window.fmtDateTime = function (s) {
if (!s) return '-';
return s.replace('T', ' ').slice(0, 16);
};
window.fmtDate = function (s) {
if (!s) return '-';
return String(s).slice(0, 10);
};
window.fmtDuration = function (seconds) {
if (seconds == null) return '00:00';
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
};
// ---------- 布局骨架 ----------
// 本脚本在 body 末尾以经典脚本方式加载,执行时 Alpine(defer) 尚未启动。
// 在此同步完成 header/main 的 DOM 搭建,可避免 Alpine 启动后再移动节点
// 触发 MutationObserver 而导致 x-init / initLayout 二次执行(顶部菜单重复的根因)。
if (!document.body.classList.contains('gp-auth')) {
const header = document.createElement('header');
header.className = 'gp-header';
header.innerHTML =
'<div class="gp-header-inner">' +
'<div class="gp-brand"><span class="gp-logo">G</span><span>GameParlor</span></div>' +
'<nav class="gp-nav gp-nav-desktop" data-gp-nav="desktop"></nav>' +
'<div class="gp-userbar" data-gp-userbar></div>' +
'</div>' +
'<nav class="gp-nav gp-nav-mobile" data-gp-nav="mobile"></nav>';
const main = document.createElement('main');
main.className = 'gp-page page-fade';
Array.from(document.body.children).forEach(c => main.appendChild(c));
document.body.appendChild(header);
document.body.appendChild(main);
}
// ---------- 顶部导航数据填充(Alpine 启动后调用,仅填充,不再移动 DOM) ----------
window.initLayout = async function (active) {
if (window.__gpLayoutMe) return window.__gpLayoutMe; // 幂等,防止重复注入
const me = await api('/api/user/me').catch(() => null);
if (!me) { GP.clearAuth(); GP.redirectLogin(); throw new Error('未登录'); }
GP.setUser(me);
window.__gpLayoutMe = me;
const isAdmin = me.role === 'ADMIN';
const isMember = me.role === 'MEMBER' || isAdmin;
const navItems = isAdmin ? [
{ key: 'dashboard', label: '概览', href: '/admin/dashboard.html' },
{ key: 'devices', label: '设备', href: '/admin/devices.html' },
{ key: 'games', label: '游戏', href: '/admin/games.html' },
{ key: 'timeslots', label: '时长', href: '/admin/timeslots.html' },
{ key: 'snacks', label: '零食', href: '/admin/snacks.html' },
{ key: 'combos', label: '套餐', href: '/admin/combos.html' },
{ key: 'users', label: '用户', href: '/admin/users.html' },
{ key: 'recharge', label: '充值审批', href: '/admin/recharge.html' },
] : [
{ key: 'dashboard', label: '首页', href: '/player/dashboard.html' },
{ key: 'browse', label: '玩游戏', href: '/player/browse.html' },
{ key: 'combos', label: '套餐', href: '/player/combos.html' },
...(isMember ? [{ key: 'custom', label: '拼套餐', href: '/player/custom-combo.html' }] : []),
{ key: 'snacks', label: '零食', href: '/player/snacks.html' },
{ key: 'recharge', label: '充值', href: '/player/recharge.html' },
...(isMember ? [{ key: 'points', label: '积分兑换', href: '/player/points.html' }] : []),
{ key: 'history', label: '记录', href: '/player/history.html' },
];
const navHtml = navItems.map(n =>
`<a href="${n.href}"${active === n.key ? ' class="is-active"' : ''}>${n.label}</a>`).join('');
document.querySelectorAll('[data-gp-nav]').forEach(el => { el.innerHTML = navHtml; });
const userbar = document.querySelector('[data-gp-userbar]');
if (userbar) {
userbar.innerHTML =
'<span class="gp-user-meta">' +
'<span>余额 ¥' + fmtMoney(me.balance) + '</span>' +
(isMember ? '<span class="badge badge-accent">会员</span>' : '') +
'<span title="累计消费额(积分)">★ ' + (me.points || 0) + '</span>' +
'</span>' +
'<span class="gp-username"></span>' +
'<button type="button" onclick="logout()" class="btn btn-ghost gp-logout">退出</button>';
userbar.querySelector('.gp-username').textContent = me.username;
}
return me;
};
// ---------- 内联 SVG 图标 ----------
const iconHome = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
const iconDevice = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="inline"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 12h.01M10 12h.01"/></svg>';
const iconGame = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><line x1="6" y1="11" x2="10" y2="11"/><line x1="8" y1="9" x2="8" y2="13"/><line x1="15" y1="12" x2="15.01" y2="12"/><line x1="18" y1="10" x2="18.01" y2="10"/><rect x="2" y="6" width="20" height="12" rx="6"/></svg>';
const iconClock = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';
const iconSnack = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M5 3h14l-2 18H7z"/><line x1="9" y1="8" x2="9" y2="13"/><line x1="15" y1="8" x2="15" y2="13"/></svg>';
const iconCombo = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>';
const iconUser = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>';
const iconWallet = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4z"/></svg>';
const iconStar = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>';
const iconList = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>';
})();
+79
View File
@@ -0,0 +1,79 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
<title>GameParlor · 登录</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body class="gp-auth min-h-screen flex items-center justify-center p-4"
style="background: radial-gradient(1200px 600px at 50% -10%, rgba(0,212,255,.12), transparent 60%), #0f0f11;">
<div x-data="authApp()" class="w-full max-w-md">
<div class="card p-8 page-fade">
<div class="flex items-center gap-3 mb-8">
<div class="w-11 h-11 rounded-xl bg-[#00d4ff] text-[#06242b] flex items-center justify-center text-xl font-bold">G</div>
<div>
<h1 class="text-xl font-bold">GameParlor</h1>
<p class="text-xs text-[#6b6b78]">电玩店自助管理与消费系统</p>
</div>
</div>
<div class="flex gap-1 p-1 rounded-xl bg-[#16161a] mb-6">
<button @click="mode='login'" :class="mode==='login' ? 'bg-[#00d4ff] text-[#06242b]' : 'text-[#9a9aa5]'"
class="flex-1 py-2 rounded-lg text-sm font-medium transition-colors">登录</button>
<button @click="mode='register'" :class="mode==='register' ? 'bg-[#00d4ff] text-[#06242b]' : 'text-[#9a9aa5]'"
class="flex-1 py-2 rounded-lg text-sm font-medium transition-colors">注册</button>
</div>
<form @submit.prevent="submit" class="space-y-4">
<div>
<label class="label">用户名</label>
<input x-model="form.username" class="input" placeholder="请输入用户名" autocomplete="username" required>
</div>
<div>
<label class="label">密码</label>
<input x-model="form.password" type="password" class="input" placeholder="请输入密码"
autocomplete="current-password" required>
</div>
<button type="submit" class="btn btn-primary w-full" :disabled="loading">
<span x-show="!loading" x-text="mode==='login' ? '登 录' : '注 册'"></span>
<span x-show="loading">处理中...</span>
</button>
</form>
<p class="remark mt-6 text-center">默认管理员:admin / admin123</p>
</div>
</div>
<script src="/app.js"></script>
<script>
function authApp() {
return {
mode: 'login',
loading: false,
form: { username: '', password: '' },
async submit() {
this.loading = true;
try {
const path = this.mode === 'login' ? '/api/auth/login' : '/api/auth/register';
const data = await api(path, { method: 'POST', body: JSON.stringify(this.form) });
GP.setToken(data.token);
GP.setUser({ userId: data.userId, username: data.username, role: data.role });
toast(this.mode === 'login' ? '登录成功' : '注册成功', 'success');
const isAdmin = data.role === 'ADMIN';
setTimeout(() => {
window.location.href = isAdmin ? '/admin/dashboard.html' : '/player/dashboard.html';
}, 400);
} catch (e) {
// toast already shown
} finally {
this.loading = false;
}
}
};
}
</script>
</body>
</html>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>玩游戏 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="browseApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">玩游戏</h2>
<div class="flex gap-2 mb-5">
<button class="btn" :class="mode==='device' ? 'btn-primary' : 'btn-ghost'" @click="mode='device';loadGames()">按设备浏览</button>
<button class="btn" :class="mode==='game' ? 'btn-primary' : 'btn-ghost'" @click="mode='game';loadGames()">按游戏浏览</button>
<button class="btn" :class="mode==='universal' ? 'btn-primary' : 'btn-ghost'" @click="mode='universal';loadGames()">通用游戏</button>
</div>
<!-- 按设备 -->
<div x-show="mode==='device'" class="mb-4">
<select x-model="selectedDevice" @change="loadGames()" class="select max-w-xs">
<option value="">选择设备</option>
<template x-for="d in devices" :key="d.id"><option :value="d.id" x-text="d.name"></option></template>
</select>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<template x-for="g in games" :key="g.id">
<div class="card card-hover p-4 cursor-pointer" @click="pickGame(g)">
<div class="font-bold" x-text="g.name"></div>
<div class="text-xs text-[#9a9aa5] mt-1" x-text="g.description"></div>
<div class="remark mt-2" x-text="g.remark"></div>
</div>
</template>
<div x-show="games.length===0" class="text-center text-[#6b6b78] py-12 col-span-full">暂无游戏</div>
</div>
<!-- 选时长弹窗 -->
<div x-show="pickModal" x-cloak class="modal-mask" @click.self="pickModal=false">
<div class="modal">
<h3 class="text-lg font-bold mb-1" x-text="curGame && curGame.name"></h3>
<div class="remark mb-4" x-text="curGame && curGame.remark"></div>
<div class="space-y-2 mb-4">
<template x-for="s in slots" :key="s.id">
<div class="flex items-center justify-between p-3 rounded-lg bg-[#16161a] cursor-pointer hover:bg-[#1c1c22]"
@click="curSlot = s" :class="curSlot && curSlot.id===s.id ? 'ring-1 ring-[#00d4ff]' : ''">
<div>
<div class="font-medium" x-text="s.durationMinutes + ' 分钟'"></div>
<div class="text-xs text-[#9a9aa5]">基础价 ¥<span x-text="fmtMoney(s.basePrice)"></span></div>
</div>
<div class="text-[#00d4ff] font-bold" x-text="'¥'+fmtMoney(s.basePrice)"></div>
</div>
</template>
</div>
<div class="flex justify-between items-center">
<div class="text-sm text-[#9a9aa5]">余额 ¥<span x-text="fmtMoney(me.balance)"></span></div>
<div class="flex gap-2">
<button class="btn btn-ghost" @click="pickModal=false">取消</button>
<button class="btn btn-primary" :disabled="!curSlot" @click="startGame()">开始游玩</button>
</div>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function browseApp() {
return {
me: {}, mode: 'device', devices: [], games: [], slots: [], selectedDevice: '',
pickModal: false, curGame: null, curSlot: null,
async init() {
await initLayout('browse');
this.me = await api('/api/user/me').catch(() => ({}));
this.devices = await api('/api/devices').catch(() => []);
this.slots = await api('/api/timeslots').catch(() => []);
this.loadGames();
},
async loadGames() {
let url = '/api/games';
if (this.mode === 'device' && this.selectedDevice) url = '/api/games?deviceId=' + this.selectedDevice;
else if (this.mode === 'universal') url = '/api/games?universal=true';
this.games = await api(url).catch(() => []);
},
pickGame(g) { this.curGame = g; this.curSlot = null; this.pickModal = true; },
async startGame() {
await api('/api/orders', { method: 'POST', body: JSON.stringify({ gameId: this.curGame.id, timeSlotId: this.curSlot.id }) });
toast('开始游玩,祝玩得开心!', 'success');
this.pickModal = false;
setTimeout(() => window.location.href = '/player/dashboard.html', 500);
}
};
}
</script>
</body>
</html>
@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>套餐 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="combosApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">套餐</h2>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<template x-for="c in list" :key="c.id">
<div class="card card-hover p-5">
<div class="flex items-start justify-between">
<div class="font-bold text-lg" x-text="c.name"></div>
<span class="badge badge-accent" x-text="c.type"></span>
</div>
<div class="text-sm text-[#9a9aa5] mt-2">折扣率 <span x-text="c.discountRate"></span></div>
<button class="btn btn-ghost !py-1 text-xs mt-3" @click="showDetail(c)">查看详情</button>
</div>
</template>
</div>
<div x-show="detailModal" x-cloak class="modal-mask" @click.self="detailModal=false">
<div class="modal" style="max-width:560px">
<h3 class="text-lg font-bold mb-2" x-text="detail && detail.combo && detail.combo.name"></h3>
<div class="text-sm text-[#9a9aa5] mb-3">
类型 <span x-text="detail && detail.combo && detail.combo.type"></span> · 折扣率 <span x-text="detail && detail.combo && detail.combo.discountRate"></span>
</div>
<div class="text-sm mb-2 text-[#9a9aa5]">包含项目:</div>
<div class="space-y-2 mb-4">
<template x-for="it in ((detail && detail.items) || [])" :key="it.id">
<div class="flex justify-between text-sm p-2 rounded bg-[#16161a]">
<span x-text="`${it.itemType} #${it.itemId} × ${it.quantity}`"></span>
<span class="text-[#9a9aa5]" x-text="'¥'+fmtMoney(it.unitPriceAtCreation)"></span>
</div>
</template>
</div>
<div class="flex justify-between items-center">
<div class="text-xl font-bold text-[#00d4ff]" x-text="'¥'+fmtMoney(detail && detail.price)"></div>
<button class="btn btn-primary" :disabled="!detail" @click="buy()">立即购买</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function combosApp() {
return {
list: [], detailModal: false, detail: null,
async init() { await initLayout('combos'); this.list = await api('/api/combos').catch(() => []); },
async showDetail(c) { this.detail = await api('/api/combos/' + c.id).catch(() => null); this.detailModal = true; },
async buy() {
await api('/api/orders/combos/' + this.detail.combo.id, { method: 'POST' });
toast('购买成功', 'success'); this.detailModal = false;
}
};
}
</script>
</body>
</html>
@@ -0,0 +1,105 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定义拼套餐 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="customApp()" x-init="init()">
<h2 class="text-xl font-bold mb-2">自定义拼套餐</h2>
<p class="text-sm text-[#9a9aa5] mb-6">仅会员可用。自由勾选项目,享会员专属折扣。</p>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="lg:col-span-2 space-y-6">
<!-- 游戏 -->
<div class="card p-4">
<h3 class="font-semibold mb-3">游戏</h3>
<div class="grid grid-cols-2 gap-2">
<template x-for="g in games" :key="'g'+g.id">
<label class="flex items-center gap-2 p-2 rounded-lg bg-[#16161a] cursor-pointer">
<input type="checkbox" :value="g.id" @change="toggle('GAME', g.id, g.memberPrice, $event.target.checked)">
<span class="text-sm" x-text="g.name"></span>
<span class="text-xs text-[#9a9aa5] ml-auto">¥<span x-text="fmtMoney(g.memberPrice)"></span></span>
</label>
</template>
</div>
</div>
<!-- 时长 -->
<div class="card p-4">
<h3 class="font-semibold mb-3">时长</h3>
<div class="grid grid-cols-2 gap-2">
<template x-for="s in slots" :key="'s'+s.id">
<label class="flex items-center gap-2 p-2 rounded-lg bg-[#16161a] cursor-pointer">
<input type="checkbox" :value="s.id" @change="toggle('TIMESLOT', s.id, s.memberPrice, $event.target.checked)">
<span class="text-sm" x-text="s.durationMinutes + ' 分钟'"></span>
<span class="text-xs text-[#9a9aa5] ml-auto">¥<span x-text="fmtMoney(s.memberPrice)"></span></span>
</label>
</template>
</div>
</div>
<!-- 零食 -->
<div class="card p-4">
<h3 class="font-semibold mb-3">零食饮料</h3>
<div class="grid grid-cols-2 gap-2">
<template x-for="sn in snacks" :key="'sn'+sn.id">
<label class="flex items-center gap-2 p-2 rounded-lg bg-[#16161a] cursor-pointer">
<input type="checkbox" :value="sn.id" @change="toggle('SNACK', sn.id, sn.memberPrice, $event.target.checked)">
<span class="text-sm" x-text="sn.name"></span>
<span class="text-xs text-[#9a9aa5] ml-auto">¥<span x-text="fmtMoney(sn.memberPrice)"></span></span>
</label>
</template>
</div>
</div>
</div>
<!-- 结算栏 -->
<div class="lg:col-span-1">
<div class="card p-5 sticky top-20">
<h3 class="font-semibold mb-3">结算</h3>
<div class="text-sm text-[#9a9aa5] mb-2">已选 <span x-text="selected.length"></span> 项</div>
<div class="text-sm text-[#9a9aa5] mb-1">会员折扣率:<span x-text="discountRate"></span></div>
<div class="text-3xl font-bold text-[#00d4ff] my-3" x-text="'¥'+fmtMoney(total)"></div>
<button class="btn btn-primary w-full" :disabled="selected.length===0" @click="purchase()">确认下单</button>
</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function customApp() {
return {
games: [], slots: [], snacks: [], selected: [], total: 0, discountRate: '0.85',
async init() {
await initLayout('custom');
this.games = await api('/api/games').catch(() => []);
this.slots = await api('/api/timeslots').catch(() => []);
this.snacks = await api('/api/snacks').catch(() => []);
const cfg = await api('/api/config').catch(() => ({}));
this.discountRate = cfg.member_discount_rate || '0.85';
},
toggle(type, id, price, checked) {
const key = type + '-' + id;
if (checked) this.selected.push({ itemType: type, itemId: id, quantity: 1, unitPrice: Number(price) || 0 });
else this.selected = this.selected.filter(i => !(i.itemType === type && i.itemId === id));
this.calc();
},
async calc() {
if (this.selected.length === 0) { this.total = 0; return; }
const items = this.selected.map(i => ({ itemType: i.itemType, itemId: i.itemId, quantity: i.quantity }));
this.total = await api('/api/member/custom-combo/price', { method: 'POST', body: JSON.stringify({ items }) }).catch(() => 0);
},
async purchase() {
const items = this.selected.map(i => ({ itemType: i.itemType, itemId: i.itemId, quantity: i.quantity }));
await api('/api/member/custom-combo/purchase', { method: 'POST', body: JSON.stringify({ items }) });
toast('下单成功', 'success');
this.selected = []; this.total = 0;
document.querySelectorAll('input[type=checkbox]').forEach(c => c.checked = false);
}
};
}
</script>
</body>
</html>
@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="dashApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">欢迎回来</h2>
<!-- 进行中倒计时 -->
<div class="card p-6 mb-6" x-show="active">
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<div class="text-sm text-[#9a9aa5]">正在游玩</div>
<div class="text-2xl font-bold mt-1" x-text="(active && active.gameName) || '游戏中'"></div>
</div>
<div class="text-right">
<div class="text-xs text-[#9a9aa5] mb-1">剩余时间</div>
<div class="countdown mono text-5xl font-bold tabular-nums"
:style="remaining < 300 ? 'color:#f87171' : 'color:#34d399'"
x-text="fmtDuration(remaining)"></div>
</div>
</div>
<div class="mt-4 flex gap-2">
<button class="btn btn-primary" :disabled="!active" @click="renew(30)">续费 30 分钟</button>
<button class="btn btn-ghost" :disabled="!active" @click="renew(60)">续费 60 分钟</button>
</div>
</div>
<!-- 信息卡片 -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
<div class="card p-4">
<div class="text-xs text-[#9a9aa5]">钱包余额</div>
<div class="text-2xl font-bold mt-1 text-[#00d4ff]" x-text="'¥'+fmtMoney(me.balance)"></div>
</div>
<div class="card p-4">
<div class="text-xs text-[#9a9aa5]">积分(累计消费)</div>
<div class="text-2xl font-bold mt-1 text-[#fbbf24]" x-text="me.points || 0"></div>
</div>
<div class="card p-4">
<div class="text-xs text-[#9a9aa5]">会员到期</div>
<div class="text-lg font-bold mt-1" x-text="fmtDate(me.memberExpireDate)"></div>
</div>
<div class="card p-4">
<div class="text-xs text-[#9a9aa5]">角色</div>
<div class="text-lg font-bold mt-1" x-text="me.role"></div>
</div>
</div>
<!-- 最近订单 -->
<div class="card p-5">
<h3 class="font-semibold mb-3">最近订单</h3>
<div class="space-y-2">
<template x-for="o in recent" :key="o.id">
<div class="flex items-center justify-between py-2 border-b border-[#2a2a33] last:border-0">
<div>
<div class="text-sm" x-text="'订单 #' + o.id"></div>
<div class="text-xs text-[#6b6b78]" x-text="fmtDateTime(o.createdAt)"></div>
</div>
<div class="flex items-center gap-3">
<span class="badge" :class="o.status==='PAID'?'badge-success':'badge-danger'" x-text="o.status"></span>
<span class="text-[#00d4ff]" x-text="'¥'+fmtMoney(o.totalAmount)"></span>
</div>
</div>
</template>
<div x-show="recent.length===0" class="text-center text-[#6b6b78] py-4 text-sm">暂无订单</div>
</div>
</div>
<script src="/app.js"></script>
<script>
function dashApp() {
return {
me: {}, active: null, remaining: 0, recent: [], timer: null,
async init() {
await initLayout('dashboard');
this.me = await api('/api/user/me').catch(() => ({}));
const orders = await api('/api/history/orders?page=0&size=5').catch(() => ({ content: [] }));
this.recent = orders.content || [];
await this.poll();
setInterval(() => { if (this.remaining > 0) this.remaining--; }, 1000);
this.timer = setInterval(() => this.poll(), 10000);
},
async poll() {
this.active = await api('/api/orders/active').catch(() => null);
if (this.active) this.remaining = this.active.remainingSeconds;
else this.remaining = 0;
},
async renew(min) {
await api('/api/orders/renew', { method: 'POST', body: JSON.stringify({ orderId: this.active.orderId, additionalMinutes: min }) });
toast('续费成功', 'success'); this.poll();
}
};
}
</script>
</body>
</html>
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>历史记录 · GameParlor</title>
<link rel="stylesheet" href="/app.css">
<script src="/js/vendor/tailwind.min.js"></script>
<script defer src="/js/vendor/alpine.min.js"></script>
</head>
<body x-data="historyApp()" x-init="init()">
<h2 class="text-xl font-bold mb-6">历史记录</h2>
<div class="flex gap-2 mb-4">
<button class="btn" :class="tab==='orders'?'btn-primary':'btn-ghost'" @click="tab='orders';load()">订单</button>
<button class="btn" :class="tab==='tx'?'btn-primary':'btn-ghost'" @click="tab='tx';load()">消费明细</button>
<button class="btn" :class="tab==='recharge'?'btn-primary':'btn-ghost'" @click="tab='recharge';load()">充值记录</button>
</div>
<div class="card overflow-x-auto" x-show="tab==='orders'">
<table class="table">
<thead><tr><th>订单号</th><th>金额</th><th>状态</th><th>时间</th></tr></thead>
<tbody>
<template x-for="o in orders" :key="o.id">
<tr>
<td x-text="'#'+o.id"></td>
<td class="text-[#00d4ff]" x-text="'¥'+fmtMoney(o.totalAmount)"></td>
<td><span class="badge" :class="o.status==='PAID'?'badge-success':'badge-danger'" x-text="o.status"></span></td>
<td class="text-[#9a9aa5]" x-text="fmtDateTime(o.createdAt)"></td>
</tr>
</template>
<tr x-show="orders.length===0"><td colspan="4" class="text-center text-[#6b6b78] py-8">暂无订单</td></tr>
</tbody>
</table>
</div>
<div class="card overflow-x-auto" x-show="tab==='tx'">
<table class="table">
<thead><tr><th>类型</th><th>金额</th><th>备注</th><th>时间</th></tr></thead>
<tbody>
<template x-for="t in txs" :key="t.id">
<tr>
<td><span class="badge" :class="t.type==='RECHARGE'?'badge-success':t.type==='CONSUME'?'badge-danger':'badge-warning'" x-text="t.type"></span></td>
<td :class="t.amount > 0 ? 'text-[#34d399]' : 'text-[#f87171]'" x-text="(t.amount>0?'+':'') + fmtMoney(t.amount)"></td>
<td class="text-[#9a9aa5]" x-text="t.remark"></td>
<td class="text-[#9a9aa5]" x-text="fmtDateTime(t.createdAt)"></td>
</tr>
</template>
<tr x-show="txs.length===0"><td colspan="4" class="text-center text-[#6b6b78] py-8">暂无记录</td></tr>
</tbody>
</table>
</div>
<div class="card overflow-x-auto" x-show="tab==='recharge'">
<table class="table">
<thead><tr><th>金额</th><th>授权码</th><th>状态</th><th>时间</th></tr></thead>
<tbody>
<template x-for="r in recharges" :key="r.id">
<tr>
<td class="text-[#00d4ff]" x-text="'¥'+fmtMoney(r.amount)"></td>
<td class="mono" x-text="r.authCode"></td>
<td><span class="badge" :class="r.status==='APPROVED'?'badge-success':r.status==='REJECTED'?'badge-danger':'badge-warning'" x-text="r.status"></span></td>
<td class="text-[#9a9aa5]" x-text="fmtDateTime(r.createdAt)"></td>
</tr>
</template>
<tr x-show="recharges.length===0"><td colspan="4" class="text-center text-[#6b6b78] py-8">暂无记录</td></tr>
</tbody>
</table>
</div>
<script src="/app.js"></script>
<script>
function historyApp() {
return {
tab: 'orders', orders: [], txs: [], recharges: [],
async init() { await initLayout('history'); this.load(); },
async load() {
if (this.tab === 'orders') {
const d = await api('/api/history/orders?page=0&size=20').catch(() => ({ content: [] }));
this.orders = d.content || [];
} else if (this.tab === 'tx') {
const d = await api('/api/history/transactions?page=0&size=20').catch(() => ({ content: [] }));
this.txs = d.content || [];
} else {
const d = await api('/api/recharge/my?page=0&size=20').catch(() => ({ content: [] }));
this.recharges = d.content || [];
}
}
};
}
</script>
</body>
</html>

Some files were not shown because too many files have changed in this diff Show More