8 Commits

37 changed files with 476 additions and 579 deletions

4
.gitignore vendored
View File

@@ -1,8 +1,8 @@
# 通过 Git 部署项目至线上时建议删除的忽略规则 # 通过 Git 部署项目至线上时建议删除的忽略规则
/vendor /vendor
/modules /modules
/public/*.lock #/public/*.lock
/public/index.html #/public/index.html
/public/assets /public/assets
# 通过 Git 部署项目至线上时可以考虑删除的忽略规则 # 通过 Git 部署项目至线上时可以考虑删除的忽略规则

View File

@@ -180,9 +180,9 @@ php webman migrate
``` ```
3. **访问地址:** 3. **访问地址:**
- 安装向导http://localhost:1818/install/ - 安装向导http://localhost:1818/install/
- 前台地址http://localhost:1818/index.html/#/ - 前台地址http://localhost:1818/index.html/#/
- 后台地址http://localhost:1818/index.html/#/admin - 后台地址http://localhost:1818/index.html/#/admin
> 注意:前端通过 Vite 代理将 `/api`、`/admin`、`/install` 转发到后端 8787 端口,请勿直接访问 8787 端口的前端页面,否则可能出现 404。 > 注意:前端通过 Vite 代理将 `/api`、`/admin`、`/install` 转发到后端 8787 端口,请勿直接访问 8787 端口的前端页面,否则可能出现 404。
@@ -215,7 +215,7 @@ location ^~ / {
## 六、路由说明 ## 六、路由说明
- **后台 API**`/admin/{module}.{Controller}/{action}` - **后台 API**`/admin/{module}.{Controller}/{action}`
- 示例:`/admin/mall.Player/index` → `app\admin\controller\mall\Player::index` - 示例:`/admin/mall.Player/index` → `app\admin\controller\mall\Player::index`
- **前台 API**`/api/...` - **前台 API**`/api/...`
- **安装**`/api/Install/...` - **安装**`/api/Install/...`

View File

@@ -581,13 +581,6 @@ class Crud extends Backend
private function parseModelMethods($field, &$modelData): void private function parseModelMethods($field, &$modelData): void
{ {
// MySQL bigint/int 时间戳字段:显式声明为 integer避免 ThinkORM 自动时间戳写入 'now' 字符串
if (in_array($field['name'] ?? '', ['create_time', 'update_time', 'createtime', 'updatetime'], true)
&& in_array($field['type'] ?? '', ['int', 'bigint'], true)
) {
$modelData['fieldType'][$field['name']] = 'integer';
}
if (($field['designType'] ?? '') == 'array') { if (($field['designType'] ?? '') == 'array') {
$modelData['fieldType'][$field['name']] = 'json'; $modelData['fieldType'][$field['name']] = 'json';
} elseif (!in_array($field['name'], ['create_time', 'update_time', 'updatetime', 'createtime']) } elseif (!in_array($field['name'], ['create_time', 'update_time', 'updatetime', 'createtime'])

View File

@@ -0,0 +1,149 @@
<?php
namespace app\admin\controller\mall;
use app\common\controller\Backend;
use support\Response;
use Throwable;
use Webman\Http\Request;
/**
* 积分商城用户
*/
class Player extends Backend
{
/**
* Player模型对象
* @var object|null
* @phpstan-var \app\admin\model\mall\Player|null
*/
protected ?object $model = null;
protected array|string $preExcludeFields = ['id', 'create_time', 'update_time', 'password'];
protected string|array $quickSearchField = ['id'];
/** 列表不返回密码字段 */
protected string|array $indexField = ['id', 'username', 'create_time', 'update_time', 'score'];
public function initialize(): void
{
parent::initialize();
$this->model = new \app\admin\model\mall\Player();
}
/**
* 添加(重写以支持密码加密)
*/
public function add(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response instanceof Response) {
return $response;
}
if ($request->method() !== 'POST') {
$this->error(__('Parameter error'));
}
$data = $request->post();
if (!$data) {
$this->error(__('Parameter %s can not be empty', ['']));
}
$passwd = $data['password'] ?? '';
if (empty($passwd)) {
$this->error(__('Parameter %s can not be empty', [__('Password')]));
}
$data = $this->applyInputFilter($data);
$data = $this->excludeFields($data);
$result = false;
$this->model->startTrans();
try {
if ($this->modelValidate) {
$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
if (class_exists($validate)) {
$validate = new $validate();
if ($this->modelSceneValidate) {
$validate->scene('add');
}
$validate->check($data);
}
}
$result = $this->model->save($data);
if ($result !== false && $passwd) {
$this->model->resetPassword((int) $this->model->id, $passwd);
}
$this->model->commit();
} catch (Throwable $e) {
$this->model->rollback();
$this->error($e->getMessage());
}
$result !== false ? $this->success(__('Added successfully')) : $this->error(__('No rows were added'));
}
/**
* 编辑(重写以支持编辑时密码可选)
*/
public function edit(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response instanceof Response) {
return $response;
}
$pk = $this->model->getPk();
$id = $request->post($pk) ?? $request->get($pk);
$row = $this->model->find($id);
if (!$row) {
$this->error(__('Record not found'));
}
if ($request->method() === 'POST') {
$data = $request->post();
if (!$data) {
$this->error(__('Parameter %s can not be empty', ['']));
}
if (!empty($data['password'])) {
$this->model->resetPassword((int) $row->id, $data['password']);
}
$data = $this->applyInputFilter($data);
$data = $this->excludeFields($data);
$result = false;
$this->model->startTrans();
try {
if ($this->modelValidate) {
$validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
if (class_exists($validate)) {
$validate = new $validate();
if ($this->modelSceneValidate) {
$validate->scene('edit');
}
$validate->check(array_merge($data, [$pk => $row[$pk]]));
}
}
$result = $row->save($data);
$this->model->commit();
} catch (Throwable $e) {
$this->model->rollback();
$this->error($e->getMessage());
}
return $result !== false ? $this->success(__('Update successful')) : $this->error(__('No rows updated'));
}
unset($row['password']);
$row['password'] = '';
$this->success('', ['row' => $row]);
}
/**
* 若需重写查看、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
*/
}

View File

@@ -802,8 +802,8 @@ class Helper
$indexVueData['defaultItems'] = self::getJsonFromArray($indexVueData['defaultItems'] ?? []); $indexVueData['defaultItems'] = self::getJsonFromArray($indexVueData['defaultItems'] ?? []);
$indexVueData['tableColumn'] = self::buildTableColumn($indexVueData['tableColumn'] ?? []); $indexVueData['tableColumn'] = self::buildTableColumn($indexVueData['tableColumn'] ?? []);
$indexVueData['dblClickNotEditColumn'] = self::buildSimpleArray($indexVueData['dblClickNotEditColumn'] ?? ['undefined']); $indexVueData['dblClickNotEditColumn'] = self::buildSimpleArray($indexVueData['dblClickNotEditColumn'] ?? ['undefined']);
$urlSegments = array_merge($controllerFile['path'], [$controllerFile['originalLastName']]); $controllerFile['path'][] = $controllerFile['originalLastName'];
$indexVueData['controllerUrl'] = '\'/admin/' . ($urlSegments ? implode('.', array_map('strtolower', $urlSegments)) : '') . '/\''; $indexVueData['controllerUrl'] = '\'/admin/' . ($controllerFile['path'] ? implode('.', $controllerFile['path']) : '') . '/\'';
$indexVueData['componentName'] = ($webViewsDir['path'] ? implode('/', $webViewsDir['path']) . '/' : '') . $webViewsDir['originalLastName']; $indexVueData['componentName'] = ($webViewsDir['path'] ? implode('/', $webViewsDir['path']) . '/' : '') . $webViewsDir['originalLastName'];
$indexVueContent = self::assembleStub('html/index', $indexVueData); $indexVueContent = self::assembleStub('html/index', $indexVueData);
self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'index.vue', $indexVueContent); self::writeFile(root_path() . $webViewsDir['views'] . '/' . 'index.vue', $indexVueContent);

View File

@@ -3,8 +3,6 @@
namespace {%namespace%}; namespace {%namespace%};
{%use%} {%use%}
use app\common\controller\Backend; use app\common\controller\Backend;
use support\Response;
use Webman\Http\Request as WebmanRequest;
/** /**
* {%tableComment%} * {%tableComment%}

View File

@@ -3,11 +3,11 @@
* 查看 * 查看
* @throws Throwable * @throws Throwable
*/ */
protected function _index(): Response public function index(): void
{ {
// 如果是 select 则转发到 select 方法,若未重写该方法,其实还是继续执行 index // 如果是 select 则转发到 select 方法,若未重写该方法,其实还是继续执行 index
if ($this->request && $this->request->get('select')) { if ($this->request->param('select')) {
return $this->select($this->request); $this->select();
} }
/** /**
@@ -18,14 +18,13 @@
list($where, $alias, $limit, $order) = $this->queryBuilder(); list($where, $alias, $limit, $order) = $this->queryBuilder();
$res = $this->model $res = $this->model
->withJoin($this->withJoinTable, $this->withJoinType) ->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
{%relationVisibleFields%} {%relationVisibleFields%}
->alias($alias) ->alias($alias)
->where($where) ->where($where)
->order($order) ->order($order)
->paginate($limit); ->paginate($limit);
return $this->success('', [ $this->success('', [
'list' => $res->items(), 'list' => $res->items(),
'total' => $res->total(), 'total' => $res->total(),
'remark' => get_route_remark(), 'remark' => get_route_remark(),

View File

@@ -1,6 +1,6 @@
protected function initController(WebmanRequest $request): ?Response public function initialize(): void
{ {
parent::initialize();
$this->model = new \{%modelNamespace%}\{%modelName%}();{%filterRule%} $this->model = new \{%modelNamespace%}\{%modelName%}();{%filterRule%}
return null;
} }

View File

@@ -50,7 +50,6 @@ trait Backend
$res = $this->model $res = $this->model
->field($this->indexField) ->field($this->indexField)
->withJoin($this->withJoinTable, $this->withJoinType) ->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->alias($alias) ->alias($alias)
->where($where) ->where($where)
->order($order) ->order($order)
@@ -302,40 +301,7 @@ trait Backend
/** /**
* 加载为 select(远程下拉选择框)数据,子类可覆盖 * 加载为 select(远程下拉选择框)数据,子类可覆盖
*/ */
protected function _select(): Response protected function _select(): void
{ {
if (empty($this->model)) {
return $this->success('', [
'list' => [],
'total' => 0,
]);
}
$pk = $this->model->getPk();
// 远程下拉只要求包含主键与可显示字段;这里尽量返回主键 + quickSearch 字段,避免全量字段带来性能问题
$fields = [$pk];
$quickSearchArr = is_array($this->quickSearchField) ? $this->quickSearchField : explode(',', (string) $this->quickSearchField);
foreach ($quickSearchArr as $f) {
$f = trim((string) $f);
if ($f === '') continue;
$f = str_contains($f, '.') ? substr($f, strrpos($f, '.') + 1) : $f;
if ($f !== '' && !in_array($f, $fields, true)) {
$fields[] = $f;
}
}
list($where, $alias, $limit, $order) = $this->queryBuilder();
$res = $this->model
->field($fields)
->alias($alias)
->where($where)
->order($order)
->paginate($limit);
return $this->success('', [
'list' => $res->items(),
'total' => $res->total(),
]);
} }
} }

View File

@@ -0,0 +1,28 @@
<?php
namespace app\admin\model\mall;
use app\common\model\traits\TimestampInteger;
use support\think\Model;
/**
* Player
*/
class Player extends Model
{
use TimestampInteger;
// 表名
protected $name = 'mall_player';
// 自动写入时间戳字段
protected $autoWriteTimestamp = true;
/**
* 重置密码
*/
public function resetPassword(int $id, string $newPassword): bool
{
return $this->where(['id' => $id])->update(['password' => hash_password($newPassword)]) !== false;
}
}

View File

@@ -12,7 +12,6 @@ use ba\Filesystem;
use app\common\controller\Api; use app\common\controller\Api;
use app\admin\model\Admin as AdminModel; use app\admin\model\Admin as AdminModel;
use app\admin\model\User as UserModel; use app\admin\model\User as UserModel;
use app\process\Monitor;
use support\Response; use support\Response;
use Webman\Http\Request; use Webman\Http\Request;
use Phinx\Config\Config as PhinxConfig; use Phinx\Config\Config as PhinxConfig;
@@ -429,20 +428,6 @@ class Install extends Api
]); ]);
} }
// Windows 下 php windows.php 会每秒检测监控目录;写入 config/.env 等会触发 taskkill 整进程,导致 POST 被中断ERR_CONNECTION_RESET
Monitor::pause();
try {
return $this->baseConfigPost($request, $envOk, $rootPath, $migrateCommand);
} finally {
Monitor::resume();
}
}
/**
* 系统基础配置 POST写入配置并执行迁移
*/
private function baseConfigPost(Request $request, bool $envOk, string $rootPath, string $migrateCommand): Response
{
$connectData = $databaseParam = $request->only(['hostname', 'username', 'password', 'hostport', 'database', 'prefix']); $connectData = $databaseParam = $request->only(['hostname', 'username', 'password', 'hostport', 'database', 'prefix']);
// 数据库配置测试 // 数据库配置测试
@@ -470,9 +455,6 @@ class Install extends Api
return "\$env('database.{$key}', '" . addslashes($value) . "')"; return "\$env('database.{$key}', '" . addslashes($value) . "')";
}; };
$dbConfigText = preg_replace_callback("/\\\$env\('database\.(hostname|database|username|password|hostport|prefix)',\s*'[^']*'\)/", $callback, $dbConfigContent); $dbConfigText = preg_replace_callback("/\\\$env\('database\.(hostname|database|username|password|hostport|prefix)',\s*'[^']*'\)/", $callback, $dbConfigContent);
if ($dbConfigText === null) {
return $this->error(__('Failed to update database config file:%s', ['config/' . self::$dbConfigFileName]));
}
$result = @file_put_contents($dbConfigFile, $dbConfigText); $result = @file_put_contents($dbConfigFile, $dbConfigText);
if (!$result) { if (!$result) {
return $this->error(__('File has no write permission:%s', ['config/' . self::$dbConfigFileName])); return $this->error(__('File has no write permission:%s', ['config/' . self::$dbConfigFileName]));
@@ -668,7 +650,7 @@ class Install extends Api
/** /**
* 获取安装完成后的访问地址(根据请求来源区分 API 与前端开发模式) * 获取安装完成后的访问地址(根据请求来源区分 API 与前端开发模式)
* - 通过 API 访问8787index#/admin、index#/(无 index 与 # 之间的斜杠) * - 通过 API 访问8787index.html#/admin、index.html#/
* - 通过前端开发服务访问1818/#/admin、/#/ * - 通过前端开发服务访问1818/#/admin、/#/
*/ */
public function accessUrls(Request $request): Response public function accessUrls(Request $request): Response
@@ -680,8 +662,7 @@ class Install extends Api
$port = substr($host, strrpos($host, ':') + 1); $port = substr($host, strrpos($host, ':') + 1);
} }
$scheme = $request->header('x-forwarded-proto', 'http'); $scheme = $request->header('x-forwarded-proto', 'http');
$basePath = $request instanceof \support\Request ? $request->publicBasePath() : ''; $base = rtrim($scheme . '://' . $host, '/');
$base = rtrim($scheme . '://' . $host, '/') . $basePath;
if ($port === '1818') { if ($port === '1818') {
$adminUrl = $base . '/#/admin'; $adminUrl = $base . '/#/admin';

View File

@@ -142,14 +142,9 @@ class Backend extends Api
if ($needLogin) { if ($needLogin) {
if (!$this->auth->isLogin()) { if (!$this->auth->isLogin()) {
if ($request->method() === 'GET' && !$this->expectsApiJsonResponse($request)) {
$location = $this->adminSpaLoginUrl($request);
return redirect($location);
}
// 必须使用 HTTP 200 返回 JSON若用 HTTP 303axios 会跟随重定向,拿不到 JSON前端无法跳转登录
return $this->error(__('Please login first'), [ return $this->error(__('Please login first'), [
'type' => Auth::NEED_LOGIN, 'type' => Auth::NEED_LOGIN,
], 0); ], 0, ['statusCode' => Auth::LOGIN_RESPONSE_CODE]);
} }
if ($needPermission) { if ($needPermission) {
$controllerPath = $this->getControllerPath($request); $controllerPath = $this->getControllerPath($request);
@@ -172,37 +167,6 @@ class Backend extends Api
return null; return null;
} }
/**
* 是否应按 API 返回 JSON前端 axios 会带 server: true纯浏览器地址栏访问多为 HTML Accept
*/
protected function expectsApiJsonResponse(WebmanRequest $request): bool
{
$server = $request->header('server', '');
if ($server === 'true' || $server === '1') {
return true;
}
if (strtolower($request->header('x-requested-with', '')) === 'xmlhttprequest') {
return true;
}
$accept = strtolower($request->header('accept', ''));
if (str_contains($accept, 'application/json')) {
return true;
}
// 浏览器地址栏/点击链接触发的主文档请求,优先 302 到前端登录(避免误判为 API
if (strtolower((string) $request->header('sec-fetch-mode', '')) === 'navigate') {
return false;
}
return false;
}
/**
* 后台 Vue 为 hash 路由时的登录页(相对路径,与 web/src/router 一致)
*/
protected function adminSpaLoginUrl(WebmanRequest $request): string
{
return '/#/admin/login';
}
/** /**
* 子类可覆盖,用于初始化 model 等(替代原 initialize * 子类可覆盖,用于初始化 model 等(替代原 initialize
* @return Response|null 需直接返回时返回 Response否则 null * @return Response|null 需直接返回时返回 Response否则 null
@@ -250,8 +214,9 @@ class Backend extends Api
public function select(WebmanRequest $request): Response public function select(WebmanRequest $request): Response
{ {
$response = $this->initializeBackend($request); $response = $this->initializeBackend($request);
if ($response instanceof Response) return $response; if ($response !== null) return $response;
return $this->_select(); $this->_select();
return $this->success();
} }
/** /**

View File

@@ -11,15 +11,12 @@ use Exception;
*/ */
class TokenExpirationException extends Exception class TokenExpirationException extends Exception
{ {
protected array $data = [];
public function __construct( public function __construct(
string $message = '', protected string $message = '',
int $code = 409, protected int $code = 409,
array $data = [], protected array $data = [],
?\Throwable $previous = null ?\Throwable $previous = null
) { ) {
$this->data = $data;
parent::__construct($message, $code, $previous); parent::__construct($message, $code, $previous);
} }

View File

@@ -1,31 +0,0 @@
<?php
namespace app\common\validate;
use think\Validate;
class MallItem extends Validate
{
protected $failException = true;
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}

View File

@@ -1,31 +0,0 @@
<?php
namespace app\common\validate;
use think\Validate;
class MallWalletRecord extends Validate
{
protected $failException = true;
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}

View File

@@ -204,24 +204,7 @@ if (!function_exists('get_controller_path')) {
if (count($parts) < 2) { if (count($parts) < 2) {
return $parts[0] ?? null; return $parts[0] ?? null;
} }
$segments = array_slice($parts, 1, -1); return implode('/', array_slice($parts, 1, -1)) ?: $parts[1];
if ($segments === []) {
return $parts[1] ?? null;
}
// ThinkPHP 风格段 game.Config -> game/config与 $request->controller 解析结果一致(否则权限节点对不上)
$normalized = [];
foreach ($segments as $seg) {
if (str_contains($seg, '.')) {
$dotPos = strpos($seg, '.');
$mod = substr($seg, 0, $dotPos);
$ctrl = substr($seg, $dotPos + 1);
$normalized[] = strtolower($mod);
$normalized[] = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $ctrl));
} else {
$normalized[] = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $seg));
}
}
return implode('/', $normalized);
} }
} }

View File

@@ -5,7 +5,7 @@
return [ return [
// 允许跨域访问的域名(* 表示任意;开发可用 *,生产建议填具体域名) // 允许跨域访问的域名(* 表示任意;开发可用 *,生产建议填具体域名)
'cors_request_domain' => '*', 'cors_request_domain' => '*,test.zhenhui666.top',
// 是否开启会员登录验证码 // 是否开启会员登录验证码
'user_login_captcha' => true, 'user_login_captcha' => true,
// 是否开启管理员登录验证码 // 是否开启管理员登录验证码

View File

@@ -245,34 +245,6 @@ Route::get('/admin/security/dataRecycleLog/index', [\app\admin\controller\securi
Route::post('/admin/security/dataRecycleLog/restore', [\app\admin\controller\security\DataRecycleLog::class, 'restore']); Route::post('/admin/security/dataRecycleLog/restore', [\app\admin\controller\security\DataRecycleLog::class, 'restore']);
Route::get('/admin/security/dataRecycleLog/info', [\app\admin\controller\security\DataRecycleLog::class, 'info']); Route::get('/admin/security/dataRecycleLog/info', [\app\admin\controller\security\DataRecycleLog::class, 'info']);
// ==================== CRUD 生成的根级控制器(/admin/item/index 或 /admin/Item/index无子目录、无点号 ====================
// 显式路由在上,此处作为兜底;与 /admin/module.controller/action 互补
Route::add(
['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'],
'/admin/{controller:[a-zA-Z][a-zA-Z0-9]*}/{action}',
function (\Webman\Http\Request $request, string $controller, string $action) {
$class = '\\app\\admin\\controller\\' . ucfirst(strtolower($controller));
if (!class_exists($class)) {
return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
}
if (!method_exists($class, $action)) {
return new Response(404, ['Content-Type' => 'application/json'], json_encode(['code' => 404, 'msg' => '404 Not Found', 'data' => []], JSON_UNESCAPED_UNICODE));
}
$request->controller = $class;
try {
$instance = new $class();
return $instance->$action($request);
} catch (\Throwable $e) {
return new Response(500, ['Content-Type' => 'application/json'], json_encode([
'code' => 0,
'msg' => $e->getMessage(),
'time' => time(),
'data' => null,
], JSON_UNESCAPED_UNICODE));
}
}
);
// ==================== 兼容 ThinkPHP 风格 URLmodule.Controller/action ==================== // ==================== 兼容 ThinkPHP 风格 URLmodule.Controller/action ====================
// 前端使用 /admin/user.Rule/index 格式,需转换为控制器调用 // 前端使用 /admin/user.Rule/index 格式,需转换为控制器调用
Route::add( Route::add(

View File

@@ -227,8 +227,6 @@ class Install extends AbstractMigration
->addColumn('extend', 'string', ['limit' => 255, 'default' => '', 'comment' => '扩展属性', 'null' => false]) ->addColumn('extend', 'string', ['limit' => 255, 'default' => '', 'comment' => '扩展属性', 'null' => false])
->addColumn('allow_del', 'integer', ['signed' => false, 'limit' => MysqlAdapter::INT_TINY, 'default' => 0, 'comment' => '允许删除:0=否,1=是', 'null' => false]) ->addColumn('allow_del', 'integer', ['signed' => false, 'limit' => MysqlAdapter::INT_TINY, 'default' => 0, 'comment' => '允许删除:0=否,1=是', 'null' => false])
->addColumn('weigh', 'integer', ['comment' => '权重', 'default' => 0, 'null' => false]) ->addColumn('weigh', 'integer', ['comment' => '权重', 'default' => 0, 'null' => false])
->addColumn('update_time', 'biginteger', ['limit' => 16, 'signed' => false, 'null' => true, 'default' => null, 'comment' => '更新时间'])
->addColumn('create_time', 'biginteger', ['limit' => 16, 'signed' => false, 'null' => true, 'default' => null, 'comment' => '创建时间'])
->addIndex(['name'], [ ->addIndex(['name'], [
'unique' => true, 'unique' => true,
]) ])

View File

@@ -231,17 +231,8 @@ class InstallData extends AbstractMigration
public function menuRule(): void public function menuRule(): void
{ {
// Install 迁移在已存在 admin_rule旧版表名时会跳过创建 menu_rule此处需与之一致 if (!$this->hasTable('menu_rule')) return;
$ruleTable = null; $table = $this->table('menu_rule');
if ($this->hasTable('menu_rule')) {
$ruleTable = 'menu_rule';
} elseif ($this->hasTable('admin_rule')) {
$ruleTable = 'admin_rule';
}
if ($ruleTable === null) {
return;
}
$table = $this->table($ruleTable);
$rows = [ $rows = [
[ [
'id' => '1', 'id' => '1',
@@ -1164,7 +1155,7 @@ class InstallData extends AbstractMigration
'createtime' => $this->nowTime, 'createtime' => $this->nowTime,
], ],
]; ];
$exist = Db::name($ruleTable)->where('id', 1)->value('id'); $exist = Db::name('menu_rule')->where('id', 1)->value('id');
if (!$exist) { if (!$exist) {
$table->insert($rows)->saveData(); $table->insert($rows)->saveData();
} }

View File

@@ -1,55 +0,0 @@
<?php
/**
* config 表在初始 install 中未含 create_time/update_time而 Config 模型开启自动时间戳,
* Version205 等迁移使用 Model::save() 会生成对 update_time 的 UPDATE导致 1054 错误。
* 本迁移在 Version205 之前执行,补齐字段。
*/
use Phinx\Migration\AbstractMigration;
class AddConfigTimestamps extends AbstractMigration
{
public function up(): void
{
if (!$this->hasTable('config')) {
return;
}
$config = $this->table('config');
if (!$config->hasColumn('update_time')) {
$config->addColumn('update_time', 'biginteger', [
'limit' => 16,
'signed' => false,
'null' => true,
'default' => null,
'comment' => '更新时间',
'after' => 'weigh',
])->save();
}
$config = $this->table('config');
if (!$config->hasColumn('create_time')) {
$config->addColumn('create_time', 'biginteger', [
'limit' => 16,
'signed' => false,
'null' => true,
'default' => null,
'comment' => '创建时间',
'after' => 'update_time',
])->save();
}
}
public function down(): void
{
if (!$this->hasTable('config')) {
return;
}
$config = $this->table('config');
if ($config->hasColumn('create_time')) {
$config->removeColumn('create_time')->save();
}
$config = $this->table('config');
if ($config->hasColumn('update_time')) {
$config->removeColumn('update_time')->save();
}
}
}

View File

@@ -1,39 +0,0 @@
<?php
use Phinx\Migration\AbstractMigration;
/**
* game_user档位权重、中大奖权重、抽奖券数量JSON 文本)
*/
class GameUserTierBigwinTicket extends AbstractMigration
{
public function change(): void
{
if (!$this->hasTable('game_user')) {
return;
}
$table = $this->table('game_user');
if (!$table->hasColumn('tier_weight')) {
$table->addColumn('tier_weight', 'text', [
'null' => true,
'default' => null,
'comment' => '档位权重 JSON如 [{"T1":"5"},{"T2":"20"}]',
]);
}
if (!$table->hasColumn('bigwin_weight')) {
$table->addColumn('bigwin_weight', 'text', [
'null' => true,
'default' => null,
'comment' => '中大奖权重 JSON',
]);
}
if (!$table->hasColumn('ticket_count')) {
$table->addColumn('ticket_count', 'text', [
'null' => true,
'default' => null,
'comment' => '抽奖券 JSON如 [{"ante":1,"count":1}]',
]);
}
$table->update();
}
}

View File

@@ -1,40 +0,0 @@
# BuildAdmin Webman - Nginx 反向代理示例
# 将 server_name 和 root 改为实际值后,放入 nginx 的 conf.d 或 sites-available
upstream webman {
server 127.0.0.1:8787;
keepalive 10240;
}
server {
server_name 你的域名;
listen 80;
access_log off;
root /path/to/dafuweng-webman/public;
location / {
try_files $uri $uri/ @proxy;
}
location @proxy {
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_pass http://webman;
}
location ~ \.php$ {
return 404;
}
location ~ ^/\.well-known/ {
allow all;
}
location ~ /\. {
return 404;
}
}

View File

@@ -13,7 +13,11 @@ if (!defined('BASE_PATH')) {
require $baseDir . '/vendor/autoload.php'; require $baseDir . '/vendor/autoload.php';
if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) { if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) {
Dotenv\Dotenv::createMutable($baseDir)->load(); if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
Dotenv\Dotenv::createUnsafeImmutable($baseDir)->load();
} else {
Dotenv\Dotenv::createMutable($baseDir)->load();
}
} }
if (!function_exists('env')) { if (!function_exists('env')) {
@@ -38,27 +42,8 @@ if (!function_exists('env')) {
require $baseDir . '/vendor/workerman/webman-framework/src/support/helpers.php'; require $baseDir . '/vendor/workerman/webman-framework/src/support/helpers.php';
require $baseDir . '/app/functions.php'; require $baseDir . '/app/functions.php';
use Webman\Config; Webman\Config::load($baseDir . '/config', ['route', 'middleware', 'process', 'server', 'static']);
$thinkorm = config('thinkorm', []);
Config::clear();
Config::load($baseDir . '/config', ['route', 'middleware', 'process', 'server', 'static']);
// 与 Webman\ThinkOrm\ThinkOrm::start() 一致,并与 phinx.php 中 $thinkorm 来源一致
$thinkorm = array_replace_recursive(config('thinkorm', []), config('think-orm', []));
if (!empty($thinkorm)) { if (!empty($thinkorm)) {
support\think\Db::setConfig($thinkorm); support\think\Db::setConfig($thinkorm);
// Webman DbManager 使用连接池且忽略 force安装向导在同进程内迁移时若不清理会沿用旧前缀连接
// 导致 Phinx 已建带前缀表而 Db::name() 仍查无前缀表(如 menu_rule 不存在)。
if (class_exists(\Webman\ThinkOrm\DbManager::class)) {
$ref = new \ReflectionClass(\Webman\ThinkOrm\DbManager::class);
if ($ref->hasProperty('pools')) {
$poolsProp = $ref->getProperty('pools');
$poolsProp->setAccessible(true);
$poolsProp->setValue(null, []);
}
}
if (class_exists(\Webman\Context::class)) {
foreach (array_keys($thinkorm['connections'] ?? []) as $connName) {
\Webman\Context::set('think-orm.connections.' . $connName, null);
}
}
} }

View File

@@ -1,7 +1,7 @@
<?php <?php
/** /**
* Phinx 数据库迁移配置 * Phinx 数据库迁移配置
* 与 Webman ThinkOrm 引导一致Config 加载后合并 thinkorm + think-ormphinx migrate 使用 * 从 config/thinkorm.php 读取数据库连接,用于 php vendor/bin/phinx migrate
*/ */
declare(strict_types=1); declare(strict_types=1);
@@ -10,8 +10,11 @@ $baseDir = __DIR__;
require $baseDir . '/vendor/autoload.php'; require $baseDir . '/vendor/autoload.php';
if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) { if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) {
// 必须用 MutableWebman Worker 已加载过时Immutable 不会覆盖 $_ENV会导致 Phinx 与 Db::name() 前缀/库名不一致 if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
Dotenv\Dotenv::createMutable($baseDir)->load(); Dotenv\Dotenv::createUnsafeImmutable($baseDir)->load();
} else {
Dotenv\Dotenv::createMutable($baseDir)->load();
}
} }
if (!function_exists('env')) { if (!function_exists('env')) {
@@ -33,18 +36,7 @@ if (!function_exists('env')) {
} }
} }
if (!defined('BASE_PATH')) { $thinkorm = require $baseDir . '/config/thinkorm.php';
define('BASE_PATH', $baseDir);
}
require $baseDir . '/vendor/workerman/webman-framework/src/support/helpers.php';
require $baseDir . '/app/functions.php';
use Webman\Config;
Config::clear();
Config::load($baseDir . '/config', ['route', 'middleware', 'process', 'server', 'static']);
$thinkorm = array_replace_recursive(config('thinkorm', []), config('think-orm', []));
$conn = $thinkorm['connections'][$thinkorm['default'] ?? 'mysql'] ?? []; $conn = $thinkorm['connections'][$thinkorm['default'] ?? 'mysql'] ?? [];
$prefix = $conn['prefix'] ?? ''; $prefix = $conn['prefix'] ?? '';

23
public/index.html Normal file

File diff suppressed because one or more lines are too long

1
public/install.lock Normal file
View File

@@ -0,0 +1 @@
2026-03-18 11:17:18

File diff suppressed because one or more lines are too long

View File

@@ -11,103 +11,11 @@
fetch('/api/install/accessUrls').then(function(r){return r.json();}).then(function(res){ fetch('/api/install/accessUrls').then(function(r){return r.json();}).then(function(res){
if (res && res.data) { urls.adminUrl = res.data.adminUrl || ''; urls.frontUrl = res.data.frontUrl || ''; } if (res && res.data) { urls.adminUrl = res.data.adminUrl || ''; urls.frontUrl = res.data.frontUrl || ''; }
}).catch(function(){}); }).catch(function(){});
function ensureQuickPanel() {
if (!urls.adminUrl && !urls.frontUrl) return;
if (document.getElementById('__ba_install_quick_urls__')) return;
var wrap = document.createElement('div');
wrap.id = '__ba_install_quick_urls__';
wrap.style.position = 'fixed';
wrap.style.right = '16px';
wrap.style.bottom = '16px';
wrap.style.zIndex = '99999';
wrap.style.maxWidth = '560px';
wrap.style.fontFamily = 'ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji"';
wrap.innerHTML =
'<div style="background:rgba(255,255,255,.96);border:1px solid rgba(0,0,0,.08);box-shadow:0 8px 24px rgba(0,0,0,.12);border-radius:12px;overflow:hidden">' +
'<div style="padding:10px 12px;border-bottom:1px solid rgba(0,0,0,.06);display:flex;gap:8px;align-items:center;justify-content:space-between">' +
'<div style="font-weight:600;color:#111">安装完成快捷入口</div>' +
'<button type="button" aria-label="close" style="border:0;background:transparent;cursor:pointer;font-size:16px;line-height:16px;color:#666;padding:4px 6px">×</button>' +
'</div>' +
'<div style="padding:12px;display:flex;flex-direction:column;gap:10px">' +
'<div>' +
'<div style="font-size:12px;color:#666;margin-bottom:6px">后台地址</div>' +
'<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">' +
'<a data-k="admin" target="_blank" rel="noreferrer" style="color:#1677ff;text-decoration:none;word-break:break-all"></a>' +
'<button data-copy="admin" type="button" style="border:1px solid rgba(0,0,0,.12);background:#fff;border-radius:8px;padding:6px 10px;cursor:pointer">复制</button>' +
'</div>' +
'</div>' +
'<div>' +
'<div style="font-size:12px;color:#666;margin-bottom:6px">前台地址</div>' +
'<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">' +
'<a data-k="front" target="_blank" rel="noreferrer" style="color:#1677ff;text-decoration:none;word-break:break-all"></a>' +
'<button data-copy="front" type="button" style="border:1px solid rgba(0,0,0,.12);background:#fff;border-radius:8px;padding:6px 10px;cursor:pointer">复制</button>' +
'</div>' +
'</div>' +
'<div data-msg style="font-size:12px;color:#52c41a;min-height:16px"></div>' +
'</div>' +
'</div>';
document.body.appendChild(wrap);
var closeBtn = wrap.querySelector('button[aria-label="close"]');
if (closeBtn) closeBtn.addEventListener('click', function(){ wrap.remove(); });
function setLink(which, val) {
var a = wrap.querySelector('a[data-k="' + which + '"]');
if (!a) return;
a.textContent = val || '';
a.href = val || 'javascript:void(0)';
}
setLink('admin', urls.adminUrl);
setLink('front', urls.frontUrl);
function showMsg(text, ok) {
var el = wrap.querySelector('[data-msg]');
if (!el) return;
el.style.color = ok ? '#52c41a' : '#ff4d4f';
el.textContent = text;
window.clearTimeout(el.__t);
el.__t = window.setTimeout(function(){ el.textContent = ''; }, 1800);
}
function copyText(text) {
if (!text) return Promise.reject(new Error('empty'));
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(text);
}
return new Promise(function(resolve, reject){
try {
var ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', 'readonly');
ta.style.position = 'fixed';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
var ok = document.execCommand('copy');
document.body.removeChild(ta);
ok ? resolve() : reject(new Error('copy failed'));
} catch (e) {
reject(e);
}
});
}
wrap.addEventListener('click', function(e){
var t = e.target;
if (!t || !t.getAttribute) return;
var which = t.getAttribute('data-copy');
if (!which) return;
var text = which === 'admin' ? urls.adminUrl : urls.frontUrl;
copyText(text).then(function(){
showMsg('已复制:' + text, true);
}).catch(function(){
showMsg('复制失败,请手动复制', false);
});
});
}
function applyUrls() { function applyUrls() {
if (!urls.adminUrl && !urls.frontUrl) return; if (!urls.adminUrl && !urls.frontUrl) return;
document.querySelectorAll('input[type="text"], input:not([type])').forEach(function(inp){ document.querySelectorAll('input[type="text"], input:not([type])').forEach(function(inp){
var v = (inp.value || '').trim(); var v = (inp.value || '').trim();
if (v && (v.indexOf('#/admin') >= 0 || v.indexOf('index.html') >= 0 || v.indexOf('/index#') >= 0) && v.indexOf('#/') >= 0) { if (v && (v.indexOf('#/admin') >= 0 || v.indexOf('index.html') >= 0) && v.indexOf('#/') >= 0) {
inp.value = urls.adminUrl; inp.value = urls.adminUrl;
inp.dispatchEvent(new Event('input', { bubbles: true })); inp.dispatchEvent(new Event('input', { bubbles: true }));
} }
@@ -116,23 +24,6 @@
document.querySelectorAll('a[href*="#/"]').forEach(function(a){ document.querySelectorAll('a[href*="#/"]').forEach(function(a){
if (urls.frontUrl && a.href.indexOf('#/admin') < 0) a.href = urls.frontUrl; if (urls.frontUrl && a.href.indexOf('#/admin') < 0) a.href = urls.frontUrl;
}); });
// index.html/#/ 会被当成路径 /index.html/ 导致 webman 404统一为 index.html#/
document.querySelectorAll('a[href*="index.html/#"]').forEach(function(a){
a.href = a.href.replace(/index\.html\/#\//g, 'index.html#/');
});
// 打包的 index.js 完成页用 protocol+host 拼 adminUrl会漏掉 /index.php 等前缀;用接口结果覆盖展示与点击
if (urls.adminUrl) {
document.querySelectorAll('.admin-url').forEach(function(el){
el.textContent = urls.adminUrl;
el.style.cursor = 'pointer';
el.onclick = function(ev){
ev.preventDefault();
ev.stopPropagation();
window.open(urls.adminUrl, '_blank', 'noreferrer');
};
});
}
ensureQuickPanel();
} }
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function(){ setInterval(applyUrls, 800); }); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function(){ setInterval(applyUrls, 800); });
else setInterval(applyUrls, 800); else setInterval(applyUrls, 800);

View File

@@ -35,18 +35,6 @@ class Request extends \Webman\Http\Request
return $path; return $path;
} }
/**
* 入口为 /index.php/... 时返回 /index.php用于拼接后台/前台完整 URL与路由 path() 剥离规则对应)
*/
public function publicBasePath(): string
{
$path = parent::path();
if (str_starts_with($path, '/index.php')) {
return '/index.php';
}
return '';
}
/** /**
* 获取请求参数(兼容 ThinkPHP param合并 get/postpost 优先) * 获取请求参数(兼容 ThinkPHP param合并 get/postpost 优先)
* @param string|null $name 参数名null 返回全部 * @param string|null $name 参数名null 返回全部

View File

@@ -8,4 +8,4 @@ VITE_BASE_PATH = '/'
VITE_OUT_DIR = 'dist' VITE_OUT_DIR = 'dist'
# 线上环境接口地址 - 'getCurrentDomain:表示获取当前域名' # 线上环境接口地址 - 'getCurrentDomain:表示获取当前域名'
VITE_AXIOS_BASE_URL = 'getCurrentDomain' VITE_AXIOS_BASE_URL = 'https://test-api.zhenhui666.top'

View File

@@ -0,0 +1,9 @@
export default {
id: 'id',
username: 'username',
password: 'password',
create_time: 'create_time',
update_time: 'update_time',
score: 'score',
quickSearchFields: 'id',
}

View File

@@ -0,0 +1,9 @@
export default {
id: 'ID',
username: '用户名',
password: '密码',
create_time: '创建时间',
update_time: '修改时间',
score: '积分',
quickSearchFields: 'ID',
}

View File

@@ -100,16 +100,6 @@ export const useTerminal = defineStore(
} }
function addTask(command: string, blockOnFailure = true, extend = '', callback: Function = () => {}) { function addTask(command: string, blockOnFailure = true, extend = '', callback: Function = () => {}) {
const duplicatePending = state.taskList.some(
(item) =>
item.command === command &&
(item.status === taskStatus.Waiting ||
item.status === taskStatus.Connecting ||
item.status === taskStatus.Executing)
)
if (duplicatePending) {
return
}
if (!state.show) toggleDot(true) if (!state.show) toggleDot(true)
state.taskList = state.taskList.concat({ state.taskList = state.taskList.concat({
uuid: uuid(), uuid: uuid(),

View File

@@ -1,7 +1,6 @@
import type { AxiosRequestConfig, Method } from 'axios' import type { AxiosRequestConfig, Method } from 'axios'
import axios from 'axios' import axios from 'axios'
import { ElLoading, ElNotification, type LoadingOptions } from 'element-plus' import { ElLoading, ElNotification, type LoadingOptions } from 'element-plus'
import { nextTick } from 'vue'
import { refreshToken } from '/@/api/common' import { refreshToken } from '/@/api/common'
import { i18n } from '/@/lang/index' import { i18n } from '/@/lang/index'
import router from '/@/router/index' import router from '/@/router/index'
@@ -21,12 +20,6 @@ const loadingInstance: LoadingInstance = {
count: 0, count: 0,
} }
/** 请求是否后台 /admin/ 接口(不依赖当前路由,避免 loading 等场景误判为前台) */
function isAdminBackendRequest(config: AxiosRequestConfig): boolean {
const u = `${config.baseURL ?? ''}${config.url ?? ''}`
return /\/admin\//i.test(u)
}
/** /**
* 根据运行环境获取基础请求URL * 根据运行环境获取基础请求URL
*/ */
@@ -119,25 +112,6 @@ function createAxios<Data = any, T = ApiPromise<Data>>(axiosConfig: AxiosRequest
if (response.config.responseType == 'json') { if (response.config.responseType == 'json') {
if (response.data && response.data.code !== 1) { if (response.data && response.data.code !== 1) {
const needLogin =
response.data.data &&
typeof response.data.data === 'object' &&
response.data.data.type === 'need login'
if (needLogin) {
const isAdminAppFlag = isAdminApp() || isAdminBackendRequest(response.config)
if (isAdminAppFlag) {
adminInfo.removeToken()
} else {
userInfo.removeToken()
}
const loginRouteName = isAdminAppFlag ? 'adminLogin' : 'userLogin'
if (router.currentRoute.value.name !== loginRouteName) {
nextTick(() => {
void router.replace({ name: loginRouteName })
})
}
return Promise.reject(response.data)
}
if (response.data.code == 409) { if (response.data.code == 409) {
if (!window.tokenRefreshing) { if (!window.tokenRefreshing) {
window.tokenRefreshing = true window.tokenRefreshing = true

View File

@@ -0,0 +1,102 @@
<template>
<div class="default-main ba-table-box">
<el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<!-- 表格顶部菜单 -->
<!-- 自定义按钮请使用插槽甚至公共搜索也可以使用具名插槽渲染参见文档 -->
<TableHeader
:buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('mall.player.quickSearchFields') })"
></TableHeader>
<!-- 表格 -->
<!-- 表格列有多种自定义渲染方式比如自定义组件具名插槽等参见文档 -->
<!-- 要使用 el-table 组件原有的属性直接加在 Table 标签上即可 -->
<Table ref="tableRef"></Table>
<!-- 表单 -->
<PopupForm />
</div>
</template>
<script setup lang="ts">
import { onMounted, provide, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import PopupForm from './popupForm.vue'
import { baTableApi } from '/@/api/common'
import { defaultOptButtons } from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
defineOptions({
name: 'mall/player',
})
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
/**
* baTable 内包含了表格的所有数据且数据具备响应性,然后通过 provide 注入给了后代组件
*/
const baTable = new baTableClass(
new baTableApi('/admin/mall.Player/'),
{
pk: 'id',
column: [
{ type: 'selection', align: 'center', operator: false },
{ label: t('mall.player.id'), prop: 'id', align: 'center', width: 70, operator: 'RANGE', sortable: 'custom' },
{
label: t('mall.player.username'),
prop: 'username',
align: 'center',
operatorPlaceholder: t('Fuzzy query'),
sortable: false,
operator: 'LIKE',
},
{
label: t('mall.player.create_time'),
prop: 'create_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 160,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('mall.player.update_time'),
prop: 'update_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 160,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{ label: t('mall.player.score'), prop: 'score', align: 'center', sortable: false, operator: 'RANGE' },
{ label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false },
],
dblClickNotEditColumn: [undefined],
},
{
defaultItems: {},
}
)
provide('baTable', baTable)
onMounted(() => {
baTable.table.ref = tableRef.value
baTable.mount()
baTable.getData()?.then(() => {
baTable.initSort()
baTable.dragSort()
})
})
</script>
<style scoped lang="scss"></style>

View File

@@ -0,0 +1,109 @@
<template>
<!-- 对话框表单 -->
<!-- 建议使用 Prettier 格式化代码 -->
<!-- el-form 内可以混用 el-form-itemFormItemba-input 等输入组件 -->
<el-dialog
class="ba-operate-dialog"
:close-on-click-modal="false"
:model-value="['Add', 'Edit'].includes(baTable.form.operate!)"
@close="baTable.toggleForm"
>
<template #header>
<div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
{{ baTable.form.operate ? t(baTable.form.operate) : '' }}
</div>
</template>
<el-scrollbar v-loading="baTable.form.loading" class="ba-table-form-scrollbar">
<div
class="ba-operate-form"
:class="'ba-' + baTable.form.operate + '-form'"
:style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
>
<el-form
v-if="!baTable.form.loading"
ref="formRef"
@submit.prevent=""
@keyup.enter="baTable.onSubmit(formRef)"
:model="baTable.form.items"
:label-position="config.layout.shrink ? 'top' : 'right'"
:label-width="baTable.form.labelWidth + 'px'"
:rules="rules"
>
<FormItem
:label="t('mall.player.username')"
type="string"
v-model="baTable.form.items!.username"
prop="username"
:placeholder="t('Please input field', { field: t('mall.player.username') })"
/>
<FormItem
:label="t('mall.player.password')"
type="password"
v-model="baTable.form.items!.password"
prop="password"
:placeholder="t('Please input field', { field: t('mall.player.password') })"
/>
<FormItem
:label="t('mall.player.score')"
type="number"
v-model="baTable.form.items!.score"
prop="score"
:input-attr="{ step: 1 }"
:placeholder="t('Please input field', { field: t('mall.player.score') })"
/>
</el-form>
</div>
</el-scrollbar>
<template #footer>
<div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
<el-button @click="baTable.toggleForm()">{{ t('Cancel') }}</el-button>
<el-button v-blur :loading="baTable.form.submitLoading" @click="baTable.onSubmit(formRef)" type="primary">
{{ baTable.form.operateIds && baTable.form.operateIds.length > 1 ? t('Save and edit next item') : t('Save') }}
</el-button>
</div>
</template>
</el-dialog>
</template>
<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { inject, reactive, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData, regularPassword } from '/@/utils/validate'
const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
username: [buildValidatorData({ name: 'required', title: t('mall.player.username') })],
password: [
{
validator: (_rule: unknown, val: string, callback: (error?: Error) => void) => {
if (baTable.form.operate === 'Add') {
if (!val) {
return callback(new Error(t('Please input field', { field: t('mall.player.password') })))
}
} else {
if (!val) {
return callback()
}
}
if (!regularPassword(val)) {
return callback(new Error(t('validate.Please enter the correct password')))
}
return callback()
},
trigger: 'blur',
},
],
score: [buildValidatorData({ name: 'number', title: t('mall.player.score') })],
})
</script>
<style scoped lang="scss"></style>