1.优化开奖逻辑

2.优化后台开奖派彩
3.优化接口规范
This commit is contained in:
2026-04-17 13:56:13 +08:00
parent 3cf386756b
commit bf3d50a309
50 changed files with 1036 additions and 770 deletions

View File

@@ -25,9 +25,9 @@ class Channel extends Backend
*/ */
protected ?object $model = null; protected ?object $model = null;
protected array|string $preExcludeFields = ['id', 'user_count', 'profit_amount', 'create_time', 'update_time']; protected array|string $preExcludeFields = ['id', 'user_count', 'profit_amount', 'create_time', 'update_time', 'admin_id'];
protected array $withJoinTable = ['adminGroup', 'admin']; protected array $withJoinTable = [];
protected string|array $quickSearchField = ['id', 'code', 'name']; protected string|array $quickSearchField = ['id', 'code', 'name'];
@@ -51,7 +51,7 @@ class Channel extends Backend
if ($response !== null) return $response; if ($response !== null) return $response;
$query = Db::name('channel') $query = Db::name('channel')
->field(['id', 'name', 'admin_group_id']) ->field(['id', 'name'])
->order('id', 'asc'); ->order('id', 'asc');
if (!$this->auth->isSuperAdmin()) { if (!$this->auth->isSuperAdmin()) {
$query = $query->where('id', 'in', $this->currentChannelIds ?: [0]); $query = $query->where('id', 'in', $this->currentChannelIds ?: [0]);
@@ -79,11 +79,16 @@ class Channel extends Backend
$tree = []; $tree = [];
foreach ($channels as $ch) { foreach ($channels as $ch) {
$groupId = $ch['admin_group_id'] ?? null; $channelId = (int) ($ch['id'] ?? 0);
$rootGroupIds = Db::name('admin_group')
->where('channel_id', $channelId)
->where('pid', 0)
->where('status', 1)
->column('id');
$groupIds = []; $groupIds = [];
if ($groupId !== null && $groupId !== '') { foreach ($rootGroupIds as $rootId) {
$groupIds[] = $groupId; $groupIds[] = $rootId;
foreach ($getGroupChildren($groupId) as $gid) { foreach ($getGroupChildren($rootId) as $gid) {
$groupIds[] = $gid; $groupIds[] = $gid;
} }
} }
@@ -130,7 +135,7 @@ class Channel extends Backend
} }
/** /**
* 添加(重写:管理员只选顶级组;admin_group_id 后端自动写入 * 添加(重写:渠道与角色组在「角色组」侧绑定 channel_id此处不再写入 admin_group_id
* @throws Throwable * @throws Throwable
*/ */
protected function _add(): Response protected function _add(): Response
@@ -150,30 +155,10 @@ class Channel extends Backend
} }
unset($data['invite_code']); unset($data['invite_code']);
$adminId = $data['admin_id'] ?? null;
if ($adminId === null || $adminId === '') {
return $this->error(__('Parameter %s can not be empty', ['admin_id']));
}
if (array_key_exists('admin_group_id', $data)) { if (array_key_exists('admin_group_id', $data)) {
unset($data['admin_group_id']); unset($data['admin_group_id']);
} }
$topGroupId = Db::name('admin_group_access')
->alias('aga')
->join('admin_group ag', 'aga.group_id = ag.id')
->where('aga.uid', $adminId)
->where('ag.pid', 0)
->value('ag.id');
if ($topGroupId === null || $topGroupId === '') {
return $this->error(__('Record not found'));
}
$data['admin_group_id'] = $topGroupId;
if (!$this->auth->isSuperAdmin()) {
$data['admin_id'] = $this->auth->id;
}
if ($this->dataLimit && $this->dataLimitFieldAutoFill) { if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$data[$this->dataLimitField] = $this->auth->id; $data[$this->dataLimitField] = $this->auth->id;
} }
@@ -207,7 +192,7 @@ class Channel extends Backend
} }
/** /**
* 编辑(重写:管理员只选顶级组;admin_group_id 后端自动写入 * 编辑(重写:不再维护 channel.admin_group_id
* @throws Throwable * @throws Throwable
*/ */
protected function _edit(): Response protected function _edit(): Response
@@ -246,24 +231,6 @@ class Channel extends Backend
unset($data['admin_group_id']); unset($data['admin_group_id']);
} }
$nextAdminId = array_key_exists('admin_id', $data) ? $data['admin_id'] : ($row['admin_id'] ?? null);
if ($nextAdminId !== null && $nextAdminId !== '') {
$topGroupId = Db::name('admin_group_access')
->alias('aga')
->join('admin_group ag', 'aga.group_id = ag.id')
->where('aga.uid', $nextAdminId)
->where('ag.pid', 0)
->value('ag.id');
if ($topGroupId === null || $topGroupId === '') {
return $this->error(__('Record not found'));
}
$data['admin_group_id'] = $topGroupId;
}
if (!$this->auth->isSuperAdmin()) {
$data['admin_id'] = $this->auth->id;
}
$result = false; $result = false;
$this->model->startTrans(); $this->model->startTrans();
try { try {
@@ -310,9 +277,6 @@ class Channel extends Backend
$where[] = [$alias['channel'] . '.id', 'in', $this->currentChannelIds ?: [0]]; $where[] = [$alias['channel'] . '.id', 'in', $this->currentChannelIds ?: [0]];
} }
$res = $this->model $res = $this->model
->withJoin($this->withJoinTable, $this->withJoinType)
->with($this->withJoinTable)
->visible(['adminGroup' => ['name'], 'admin' => ['username']])
->alias($alias) ->alias($alias)
->where($where) ->where($where)
->order($order) ->order($order)
@@ -392,9 +356,9 @@ class Channel extends Backend
return $this->error('结算单号已存在,请稍后重试'); return $this->error('结算单号已存在,请稍后重试');
} }
$adminId = $row['admin_id'] ?? null; $adminId = $this->resolveCommissionAdminIdForChannel((int) $row['id']);
if ($adminId === null || $adminId === '' || (int) $adminId <= 0) { if ($adminId === null || $adminId <= 0) {
return $this->error('渠道未绑定代理管理员,无法生成佣金记录'); return $this->error('渠道下无归属管理员账号(请为管理员设置所属渠道),无法生成佣金记录');
} }
$now = time(); $now = time();
@@ -685,8 +649,25 @@ class Channel extends Backend
if ($admin && !empty($admin['channel_id'])) { if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id']; $ids[] = $admin['channel_id'];
} }
$byAdmin = Db::name('channel')->where('admin_id', $this->auth->id)->column('id'); return array_values(array_unique($ids));
return array_values(array_unique(array_merge($ids, $byAdmin))); }
/**
* 佣金归属管理员:取该渠道下 admin.channel_id 匹配的首个管理员(按 id 升序)。
*/
private function resolveCommissionAdminIdForChannel(int $channelId): ?int
{
if ($channelId <= 0) {
return null;
}
$aid = Db::name('admin')
->where('channel_id', $channelId)
->order('id', 'asc')
->value('id');
if ($aid === null || $aid === '') {
return null;
}
return (int) $aid;
} }
private function normalizeAgentModeFields(array $data): array private function normalizeAgentModeFields(array $data): array

View File

@@ -187,12 +187,21 @@ class Admin extends Backend
$passwd = $data['password'] ?? ''; $passwd = $data['password'] ?? '';
$data = $this->excludeFields($data); $data = $this->excludeFields($data);
$creatorChannelId = $this->getCreatorChannelId(); $creatorChannelId = $this->getCreatorChannelId();
$groupChannelId = $this->resolveChannelIdFromPrimaryGroup($data['group_arr'] ?? []);
if (!$this->auth->isSuperAdmin()) { if (!$this->auth->isSuperAdmin()) {
if ($creatorChannelId === null || $creatorChannelId === '') { if ($creatorChannelId === null || $creatorChannelId === '') {
return $this->error(__('You have no permission')); return $this->error(__('You have no permission'));
} }
if ($groupChannelId === null || $groupChannelId === '') {
return $this->error('所选角色组未绑定渠道');
}
if ((string) $groupChannelId !== (string) $creatorChannelId) {
return $this->error('所选角色组渠道与当前账号不一致');
}
$data['channel_id'] = $creatorChannelId; $data['channel_id'] = $creatorChannelId;
$data['parent_admin_id'] = $this->auth->id; $data['parent_admin_id'] = $this->auth->id;
} else {
$data['channel_id'] = ($groupChannelId === null || $groupChannelId === '') ? null : $groupChannelId;
} }
$data['invite_code'] = $this->generateUniqueInviteCode(); $data['invite_code'] = $this->generateUniqueInviteCode();
$requireCommissionRate = $this->requireCommissionRate($data['group_arr'] ?? []); $requireCommissionRate = $this->requireCommissionRate($data['group_arr'] ?? []);
@@ -343,8 +352,20 @@ class Admin extends Backend
$data = $this->excludeFields($data); $data = $this->excludeFields($data);
unset($data['invite_code']); unset($data['invite_code']);
$creatorChannelId = $this->getCreatorChannelId(); $creatorChannelId = $this->getCreatorChannelId();
if (!$this->auth->isSuperAdmin() && $creatorChannelId !== null && $creatorChannelId !== '') { $groupChannelId = $this->resolveChannelIdFromPrimaryGroup($data['group_arr'] ?? []);
if (!$this->auth->isSuperAdmin()) {
if ($creatorChannelId === null || $creatorChannelId === '') {
return $this->error(__('You have no permission'));
}
if ($groupChannelId === null || $groupChannelId === '') {
return $this->error('所选角色组未绑定渠道');
}
if ((string) $groupChannelId !== (string) $creatorChannelId) {
return $this->error('所选角色组渠道与当前账号不一致');
}
$data['channel_id'] = $creatorChannelId; $data['channel_id'] = $creatorChannelId;
} else {
$data['channel_id'] = ($groupChannelId === null || $groupChannelId === '') ? null : $groupChannelId;
} }
$requireCommissionRate = $this->requireCommissionRate($data['group_arr'] ?? []); $requireCommissionRate = $this->requireCommissionRate($data['group_arr'] ?? []);
if ($requireCommissionRate) { if ($requireCommissionRate) {
@@ -463,10 +484,24 @@ class Admin extends Backend
if ($currentAdmin && !empty($currentAdmin['channel_id'])) { if ($currentAdmin && !empty($currentAdmin['channel_id'])) {
return $currentAdmin['channel_id']; return $currentAdmin['channel_id'];
} }
$channelId = Db::name('channel')
->where('admin_id', $this->auth->id) return null;
->value('id'); }
return $channelId ?: null;
/**
* @param array<int|string> $groupIds
*/
private function resolveChannelIdFromPrimaryGroup(array $groupIds): mixed
{
if ($groupIds === []) {
return null;
}
$gid = $groupIds[0];
if ($gid === null || $gid === '') {
return null;
}
return Db::name('admin_group')->where('id', $gid)->value('channel_id');
} }
private function generateUniqueInviteCode(): string private function generateUniqueInviteCode(): string

View File

@@ -86,6 +86,10 @@ class Group extends Backend
if (!$this->auth->isSuperAdmin() && $pidInt !== 0 && !in_array($pidInt, $this->manageableGroupIds, true)) { if (!$this->auth->isSuperAdmin() && $pidInt !== 0 && !in_array($pidInt, $this->manageableGroupIds, true)) {
return $this->error(__('You have no permission')); return $this->error(__('You have no permission'));
} }
$inheritRes = $this->applyChannelInheritance($data, $pidInt);
if ($inheritRes !== null) {
return $inheritRes;
}
$shouldHandleCommissionRate = true; $shouldHandleCommissionRate = true;
if ($shouldHandleCommissionRate) { if ($shouldHandleCommissionRate) {
if (!$this->isValidCommissionRate($data['commission_rate'] ?? null)) { if (!$this->isValidCommissionRate($data['commission_rate'] ?? null)) {
@@ -165,6 +169,10 @@ class Group extends Backend
if (!$this->auth->isSuperAdmin() && $pidInt !== 0 && !in_array($pidInt, $this->manageableGroupIds, true)) { if (!$this->auth->isSuperAdmin() && $pidInt !== 0 && !in_array($pidInt, $this->manageableGroupIds, true)) {
return $this->error(__('You have no permission')); return $this->error(__('You have no permission'));
} }
$inheritRes = $this->applyChannelInheritance($data, $pidInt);
if ($inheritRes !== null) {
return $inheritRes;
}
$shouldHandleCommissionRate = true; $shouldHandleCommissionRate = true;
if ($shouldHandleCommissionRate) { if ($shouldHandleCommissionRate) {
if (!$this->isValidCommissionRate($data['commission_rate'] ?? null)) { if (!$this->isValidCommissionRate($data['commission_rate'] ?? null)) {
@@ -204,6 +212,7 @@ class Group extends Backend
return $this->error($e->getMessage()); return $this->error($e->getMessage());
} }
if ($result !== false) { if ($result !== false) {
$this->syncDescendantChannelIds(intval((string)$row['id']));
return $this->success(__('Update successful')); return $this->success(__('Update successful'));
} }
return $this->error(__('No rows updated')); return $this->error(__('No rows updated'));
@@ -223,11 +232,39 @@ class Group extends Backend
} }
$rowData = $row->toArray(); $rowData = $row->toArray();
$rowData['rules'] = array_values($rules); $rowData['rules'] = array_values($rules);
$rowData = $this->enrichChannelDisplay($rowData);
return $this->success('', [ return $this->success('', [
'row' => $rowData 'row' => $rowData
]); ]);
} }
/**
* 表单只读展示:根据 channel_id 解析渠道名称与渠道负责人admin.channel_id → admin.username取首个
*/
public function channelBindPreview(Request $request): Response
{
$response = $this->initializeBackend($request);
if ($response !== null) {
return $response;
}
$cid = $request->get('channel_id') ?? $request->post('channel_id');
if ($cid === null || $cid === '') {
return $this->success('', [
'channel_name' => '',
'channel_admin_username' => '',
]);
}
if (!Db::name('channel')->where('id', $cid)->value('id')) {
return $this->error(__('Record not found'));
}
$row = $this->enrichChannelDisplay(['channel_id' => $cid]);
return $this->success('', [
'channel_name' => $row['channel_name'] ?? '',
'channel_admin_username' => $row['channel_admin_username'] ?? '',
]);
}
public function del(Request $request): Response public function del(Request $request): Response
{ {
$response = $this->initializeBackend($request); $response = $this->initializeBackend($request);
@@ -353,7 +390,21 @@ class Group extends Backend
} }
$data = $this->model->where($where)->select()->toArray(); $data = $this->model->where($where)->select()->toArray();
$channelIds = [];
foreach ($data as $datum) {
$c = $datum['channel_id'] ?? null;
if ($c !== null && $c !== '') {
$channelIds[] = $c;
}
}
$channelNames = [];
if ($channelIds !== []) {
$channelNames = Db::name('channel')->where('id', 'in', array_unique($channelIds))->column('name', 'id');
}
foreach ($data as &$datum) { foreach ($data as &$datum) {
$c = $datum['channel_id'] ?? null;
$datum['channel_name'] = ($c !== null && $c !== '') ? ($channelNames[$c] ?? '') : '';
if ($datum['rules']) { if ($datum['rules']) {
if ($datum['rules'] == '*') { if ($datum['rules'] == '*') {
$datum['rules'] = __('Super administrator'); $datum['rules'] = __('Super administrator');
@@ -368,6 +419,7 @@ class Group extends Backend
$datum['rules'] = __('No permission'); $datum['rules'] = __('No permission');
} }
} }
unset($datum);
return $this->assembleTree ? $this->tree->assembleChild($data) : $data; return $this->assembleTree ? $this->tree->assembleChild($data) : $data;
} }
@@ -418,4 +470,85 @@ class Group extends Backend
return null; return null;
} }
/**
* 顶级角色组可选渠道;子级继承父级 channel_id不信任客户端提交的子级 channel_id
*
* @param array<string, mixed> $data
*/
private function applyChannelInheritance(array &$data, int $pidInt): ?Response
{
if ($pidInt === 0) {
if (!$this->auth->isSuperAdmin()) {
unset($data['channel_id']);
$cc = $this->getCreatorChannelId();
if ($cc !== null && $cc !== '') {
$data['channel_id'] = $cc;
}
}
$cid = $data['channel_id'] ?? null;
if ($cid !== null && $cid !== '') {
$exists = Db::name('channel')->where('id', $cid)->value('id');
if (!$exists) {
return $this->error(__('Record not found'));
}
}
return null;
}
unset($data['channel_id']);
$parent = Db::name('admin_group')->where('id', $pidInt)->find();
if (!$parent) {
return $this->error(__('Record not found'));
}
$data['channel_id'] = $parent['channel_id'];
return null;
}
/**
* @param array<string, mixed> $row
* @return array<string, mixed>
*/
private function enrichChannelDisplay(array $row): array
{
$row['channel_name'] = '';
$row['channel_admin_username'] = '';
$cid = $row['channel_id'] ?? null;
if ($cid === null || $cid === '') {
return $row;
}
$ch = Db::name('channel')->where('id', $cid)->field(['id', 'name'])->find();
if (!$ch) {
return $row;
}
$row['channel_name'] = $ch['name'] ?? '';
$row['channel_admin_username'] = (string) (Db::name('admin')->where('channel_id', $cid)->order('id', 'asc')->value('username') ?? '');
return $row;
}
private function syncDescendantChannelIds(int $groupId): void
{
$channelId = Db::name('admin_group')->where('id', $groupId)->value('channel_id');
$children = Db::name('admin_group')->where('pid', $groupId)->column('id');
foreach ($children as $childId) {
Db::name('admin_group')->where('id', $childId)->update(['channel_id' => $channelId]);
$this->syncDescendantChannelIds($childId);
}
}
private function getCreatorChannelId(): mixed
{
$currentAdmin = Db::name('admin')
->field(['id', 'channel_id'])
->where('id', $this->auth->id)
->find();
if ($currentAdmin && !empty($currentAdmin['channel_id'])) {
return $currentAdmin['channel_id'];
}
return null;
}
} }

View File

@@ -13,7 +13,7 @@ class Record extends Backend
{ {
protected ?object $model = null; protected ?object $model = null;
protected string|array $preExcludeFields = ['id', 'create_time', 'update_time']; protected string|array $preExcludeFields = ['id', 'create_time', 'update_time', 'platform_profit_amount', 'winner_user_count'];
protected string|array $quickSearchField = ['id', 'period_no']; protected string|array $quickSearchField = ['id', 'period_no'];

View File

@@ -122,7 +122,6 @@ class BetOrder extends Backend
if ($admin && !empty($admin['channel_id'])) { if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id']; $ids[] = $admin['channel_id'];
} }
$byAdmin = Db::name('channel')->where('admin_id', $this->auth->id)->column('id'); return array_values(array_unique($ids));
return array_values(array_unique(array_merge($ids, $byAdmin)));
} }
} }

View File

@@ -81,7 +81,6 @@ class DepositOrder extends Backend
if ($admin && !empty($admin['channel_id'])) { if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id']; $ids[] = $admin['channel_id'];
} }
$byAdmin = Db::name('channel')->where('admin_id', $this->auth->id)->column('id'); return array_values(array_unique($ids));
return array_values(array_unique(array_merge($ids, $byAdmin)));
} }
} }

View File

@@ -82,7 +82,6 @@ class WithdrawOrder extends Backend
if ($admin && !empty($admin['channel_id'])) { if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id']; $ids[] = $admin['channel_id'];
} }
$byAdmin = Db::name('channel')->where('admin_id', $this->auth->id)->column('id'); return array_values(array_unique($ids));
return array_values(array_unique(array_merge($ids, $byAdmin)));
} }
} }

View File

@@ -20,7 +20,7 @@ class User extends Backend
*/ */
protected ?object $model = null; protected ?object $model = null;
protected array|string $preExcludeFields = ['id', 'uuid', 'create_time', 'update_time']; protected array|string $preExcludeFields = ['id', 'uuid', 'create_time', 'update_time', 'invite_code'];
protected array $withJoinTable = ['channel', 'admin']; protected array $withJoinTable = ['channel', 'admin'];
@@ -35,7 +35,7 @@ class User extends Backend
} }
/** /**
* 添加重写password 使用 Admin 同款加密uuid 由 username+channel_id 生成 * 添加重写password 使用 Admin 同款加密uuid 为 10 位唯一对外标识
* @throws Throwable * @throws Throwable
*/ */
protected function _add(): Response protected function _add(): Response
@@ -47,6 +47,10 @@ class User extends Backend
} }
$data = $this->applyInputFilter($data); $data = $this->applyInputFilter($data);
$inviteResolved = $this->applyInviteCodeToUserChannel($data);
if ($inviteResolved !== null) {
return $inviteResolved;
}
$data = $this->excludeFields($data); $data = $this->excludeFields($data);
$password = $data['password'] ?? null; $password = $data['password'] ?? null;
@@ -60,7 +64,7 @@ class User extends Backend
if (!is_string($username) || trim($username) === '' || $channelId === null || $channelId === '') { if (!is_string($username) || trim($username) === '' || $channelId === null || $channelId === '') {
return $this->error(__('Parameter %s can not be empty', ['username/channel_id'])); return $this->error(__('Parameter %s can not be empty', ['username/channel_id']));
} }
$data['uuid'] = md5(trim($username) . '|' . $channelId); $data['uuid'] = \app\common\model\User::generateUniquePublicCode10();
if ($this->dataLimit && $this->dataLimitFieldAutoFill) { if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
$data[$this->dataLimitField] = $this->auth->id; $data[$this->dataLimitField] = $this->auth->id;
@@ -95,7 +99,7 @@ class User extends Backend
} }
/** /**
* 编辑重写password 使用 Admin 同款加密uuid 由 username+channel_id 生成 * 编辑重写password 使用 Admin 同款加密uuid 创建后不因改名改渠道自动变更
* @throws Throwable * @throws Throwable
*/ */
protected function _edit(): Response protected function _edit(): Response
@@ -130,18 +134,6 @@ class User extends Backend
} }
} }
$nextUsername = array_key_exists('username', $data) ? $data['username'] : $row['username'];
$nextChannelId = null;
if (array_key_exists('channel_id', $data)) {
$nextChannelId = $data['channel_id'];
} else {
$nextChannelId = $row['channel_id'] ?? null;
}
if (is_string($nextUsername) && trim($nextUsername) !== '' && $nextChannelId !== null && $nextChannelId !== '') {
$data['uuid'] = md5(trim($nextUsername) . '|' . $nextChannelId);
}
$result = false; $result = false;
$this->model->startTrans(); $this->model->startTrans();
try { try {
@@ -337,6 +329,63 @@ class User extends Backend
return array_values(array_unique(array_merge($own, $children))); return array_values(array_unique(array_merge($own, $children)));
} }
/**
* 请求中的 `invite_code`(子代理 admin.invite_code解析为 `channel_id`,并写入 `register_invite_code`、`admin_id`。
* 若同时提交 `channel_id` / `admin_id`,须与邀请码对应记录一致。
*/
private function applyInviteCodeToUserChannel(array &$data): ?Response
{
if (!array_key_exists('invite_code', $data)) {
return null;
}
$raw = $data['invite_code'];
unset($data['invite_code']);
$inviteCode = is_string($raw) ? trim($raw) : '';
if ($inviteCode === '') {
return null;
}
$row = Db::name('admin')->field(['id', 'channel_id'])->where('invite_code', $inviteCode)->find();
if (!$row) {
return $this->error(__('Invite code does not exist'));
}
$cid = $row['channel_id'] ?? null;
if ($cid === null || $cid === '') {
return $this->error(__('Invite code not bound to channel'));
}
$cidInt = intval(trim((string) $cid));
if ($cidInt <= 0) {
return $this->error(__('Invite code not bound to channel'));
}
if (isset($data['channel_id']) && $data['channel_id'] !== null && $data['channel_id'] !== '') {
$existing = intval(trim((string) $data['channel_id']));
if ($existing > 0 && $existing !== $cidInt) {
return $this->error(__('Parameter error'));
}
}
$data['channel_id'] = $cidInt;
$data['register_invite_code'] = $inviteCode;
$aidRaw = $row['id'] ?? null;
if ($aidRaw === null || $aidRaw === '') {
return $this->error(__('Parameter error'));
}
$aidInt = intval(trim((string) $aidRaw));
if ($aidInt <= 0) {
return $this->error(__('Parameter error'));
}
if (isset($data['admin_id']) && $data['admin_id'] !== null && $data['admin_id'] !== '') {
$reqAid = intval(trim((string) $data['admin_id']));
if ($reqAid > 0 && $reqAid !== $aidInt) {
return $this->error(__('Parameter error'));
}
}
$data['admin_id'] = $aidInt;
return null;
}
/** /**
* 若需重写查看、编辑、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写 * 若需重写查看、编辑、删除等方法,请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
*/ */

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace app\admin\controller\record; namespace app\admin\controller\user;
use app\common\controller\Backend; use app\common\controller\Backend;
use support\think\Db; use support\think\Db;
@@ -124,7 +124,6 @@ class UserWalletRecord extends Backend
if ($admin && !empty($admin['channel_id'])) { if ($admin && !empty($admin['channel_id'])) {
$ids[] = $admin['channel_id']; $ids[] = $admin['channel_id'];
} }
$byAdmin = Db::name('channel')->where('admin_id', $this->auth->id)->column('id'); return array_values(array_unique($ids));
return array_values(array_unique(array_merge($ids, $byAdmin)));
} }
} }

View File

@@ -45,6 +45,7 @@ class Account extends Frontend
'code' => 1, 'code' => 1,
'message' => __('ok'), 'message' => __('ok'),
'data' => [ 'data' => [
'uuid' => $user->uuid ?? '',
'username' => $user->username, 'username' => $user->username,
'head_image' => $user->avatar ?? '', 'head_image' => $user->avatar ?? '',
'coin' => $user->coin, 'coin' => $user->coin,

View File

@@ -34,6 +34,9 @@ class Auth extends MobileBase
if ($username === '' || $password === '') { if ($username === '' || $password === '') {
return $this->mobileError(1001, 'Missing parameters'); return $this->mobileError(1001, 'Missing parameters');
} }
if ($inviteCode === '') {
return $this->mobileError(1001, 'Invite code required');
}
if (!preg_match('/^1[3-9]\d{9}$/', $username)) { if (!preg_match('/^1[3-9]\d{9}$/', $username)) {
return $this->mobileError(1003, 'Please enter the correct mobile number'); return $this->mobileError(1003, 'Please enter the correct mobile number');
} }
@@ -41,19 +44,33 @@ class Auth extends MobileBase
$phone = $username; $phone = $username;
$email = ''; $email = '';
$extend = []; if (User::where('username', $username)->find() || User::where('phone', $username)->find()) {
if ($inviteCode !== '') { return $this->mobileError(2003, 'Account already registered', [
$inviterAdmin = Db::name('admin')->field(['id', 'channel_id'])->where('invite_code', $inviteCode)->find(); 'already_registered' => true,
if (!$inviterAdmin) { ]);
return $this->mobileError(2002, 'Invite code does not exist');
}
$extend['register_invite_code'] = $inviteCode;
$extend['admin_id'] = $inviterAdmin['id'];
$extend['channel_id'] = $inviterAdmin['channel_id'] ?? null;
} }
$extend = [];
$inviterAdmin = Db::name('admin')->field(['id', 'channel_id'])->where('invite_code', $inviteCode)->find();
if (!$inviterAdmin) {
return $this->mobileError(2002, 'Invite code does not exist');
}
$extend['register_invite_code'] = $inviteCode;
$extend['admin_id'] = $inviterAdmin['id'];
$channelId = $inviterAdmin['channel_id'] ?? null;
if ($channelId === null || $channelId === '' || (int) $channelId <= 0) {
return $this->mobileError(2002, 'Invite code not bound to channel');
}
$extend['channel_id'] = (int) $channelId;
$registered = $this->auth->register($username, $password, $phone, $email, 1, $extend); $registered = $this->auth->register($username, $password, $phone, $email, 1, $extend);
if (!$registered) { if (!$registered) {
$dup = $this->auth->getRegisterDuplicateKind();
if ($dup === 'username' || $dup === 'email' || $dup === 'phone') {
return $this->mobileError(2003, 'Account already registered', [
'already_registered' => true,
]);
}
return $this->mobileError(2000, (string) $this->auth->getError()); return $this->mobileError(2000, (string) $this->auth->getError());
} }
@@ -122,6 +139,7 @@ class Auth extends MobileBase
'expires_in' => config('buildadmin.user_token_keep_time', 259200), 'expires_in' => config('buildadmin.user_token_keep_time', 259200),
'user' => [ 'user' => [
'username' => $userInfo['username'] ?? '', 'username' => $userInfo['username'] ?? '',
'uuid' => $userInfo['uuid'] ?? '',
'coin' => $userInfo['coin'] ?? '0.0000', 'coin' => $userInfo['coin'] ?? '0.0000',
'channel_id' => $userInfo['channel_id'] ?? null, 'channel_id' => $userInfo['channel_id'] ?? null,
'risk_flags' => $userInfo['risk_flags'] ?? 0, 'risk_flags' => $userInfo['risk_flags'] ?? 0,

View File

@@ -54,7 +54,7 @@ class Game extends MobileBase
'open_at' => $openAt, 'open_at' => $openAt,
], ],
'bet_config' => [ 'bet_config' => [
'max_select_count' => $this->intValue($this->getConfigValue('max_select_count', '5')), 'pick_max_number_count' => $this->getPickMaxNumberCount(),
'chips' => ['1.0000', '5.0000', '10.0000', '25.0000', '50.0000', '100.0000'], 'chips' => ['1.0000', '5.0000', '10.0000', '25.0000', '50.0000', '100.0000'],
'single_number_max_bet' => $this->getConfigValue('single_number_max_bet', '500.0000'), 'single_number_max_bet' => $this->getConfigValue('single_number_max_bet', '500.0000'),
], ],
@@ -140,13 +140,18 @@ class Game extends MobileBase
return $response; return $response;
} }
$periodNo = trim((string) $request->post('period_no', '')); $periodNo = trim((string) $request->post('period_no', ''));
$numbers = $request->post('numbers', []); $numbersRaw = $request->post('numbers', '');
$betAmount = (string) $request->post('bet_amount', ''); $betAmount = (string) $request->post('bet_amount', '');
$idempotencyKey = trim((string) $request->post('idempotency_key', '')); $idempotencyKey = trim((string) $request->post('idempotency_key', ''));
if ($periodNo === '' || !is_array($numbers) || $betAmount === '' || $idempotencyKey === '') { if ($periodNo === '' || $betAmount === '' || $idempotencyKey === '') {
return $this->mobileError(1001, 'Missing parameters'); return $this->mobileError(1001, 'Missing parameters');
} }
if (count($numbers) < 1) { $numbers = $this->parseBetNumbersFromRequest($numbersRaw);
if ($numbers === []) {
return $this->mobileError(1003, 'Invalid parameter value');
}
$maxSelect = $this->getPickMaxNumberCount();
if (count($numbers) > $maxSelect) {
return $this->mobileError(1003, 'Invalid parameter value'); return $this->mobileError(1003, 'Invalid parameter value');
} }
@@ -285,6 +290,49 @@ class Game extends MobileBase
]); ]);
} }
/**
* 下注号码:`numbers` 为逗号分隔字符串(如 `1,8,16`);兼容旧版 JSON 数组。
*
* @return list<int>
*/
private function parseBetNumbersFromRequest($numbersRaw): array
{
if (is_array($numbersRaw)) {
$out = [];
foreach ($numbersRaw as $v) {
$n = filter_var($v, FILTER_VALIDATE_INT);
if ($n === false || $n < 1 || $n > 36) {
return [];
}
$out[] = $n;
}
$out = array_values(array_unique($out));
sort($out);
return $out;
}
$raw = trim((string) $numbersRaw);
if ($raw === '') {
return [];
}
$parts = preg_split('/\s*,\s*/', $raw);
$out = [];
foreach ($parts as $p) {
if ($p === '') {
continue;
}
$n = filter_var($p, FILTER_VALIDATE_INT);
if ($n === false || $n < 1 || $n > 36) {
return [];
}
$out[] = $n;
}
$out = array_values(array_unique($out));
sort($out);
return $out;
}
private function mapPeriodStatus($status): string private function mapPeriodStatus($status): string
{ {
if ($this->intValue($status) === 0) { if ($this->intValue($status) === 0) {
@@ -299,6 +347,22 @@ class Game extends MobileBase
return 'finished'; return 'finished';
} }
/**
* 单注最多可选号码个数:`game_config.config_key = pick_max_number_count`
*/
private function getPickMaxNumberCount(): int
{
$v = $this->intValue($this->getConfigValue('pick_max_number_count', '10'));
if ($v < 1) {
return 1;
}
if ($v > 36) {
return 36;
}
return $v;
}
private function getConfigValue(string $key, string $default): string private function getConfigValue(string $key, string $default): string
{ {
$value = GameConfig::where('config_key', $key)->value('config_value'); $value = GameConfig::where('config_key', $key)->value('config_value');

View File

@@ -81,11 +81,15 @@ class User extends Frontend
->where('invite_code', $params['invite_code']) ->where('invite_code', $params['invite_code'])
->find(); ->find();
if (!$inviterAdmin) { if (!$inviterAdmin) {
return $this->error(__('Parameter error')); return $this->error(__('Invite code does not exist'));
}
$ch = $inviterAdmin['channel_id'] ?? null;
if ($ch === null || $ch === '' || intval(trim((string) $ch)) <= 0) {
return $this->error(__('Invite code not bound to channel'));
} }
$extend['register_invite_code'] = $params['invite_code']; $extend['register_invite_code'] = $params['invite_code'];
$extend['inviter_admin_id'] = $inviterAdmin['id']; $extend['admin_id'] = $inviterAdmin['id'];
$extend['channel_id'] = $inviterAdmin['channel_id'] ?? null; $extend['channel_id'] = intval(trim((string) $ch));
} }
$res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email'], 1, $extend); $res = $this->auth->register($params['username'], $params['password'], $params['mobile'], $params['email'], 1, $extend);
} }
@@ -96,6 +100,10 @@ class User extends Frontend
'routePath' => '/user' 'routePath' => '/user'
]); ]);
} }
$dup = $this->auth->getRegisterDuplicateKind();
if ($params['tab'] === 'register' && ($dup === 'username' || $dup === 'email' || $dup === 'phone')) {
return $this->error(__('Account already registered'));
}
$msg = $this->auth->getError(); $msg = $this->auth->getError();
return $this->error($msg ?: __('Check in failed, please try again or contact the website administrator~')); return $this->error($msg ?: __('Check in failed, please try again or contact the website administrator~'));
} }

View File

@@ -23,6 +23,9 @@ return [
'Invalid timestamp' => 'Invalid timestamp', 'Invalid timestamp' => 'Invalid timestamp',
'Invite code does not exist' => 'Invite code does not exist', 'Invite code does not exist' => 'Invite code does not exist',
'Register only supports phone' => 'Register only supports phone', 'Register only supports phone' => 'Register only supports phone',
'Invite code required' => 'Invite code is required',
'Invite code not bound to channel' => 'This invite code is not bound to a valid channel',
'Account already registered' => 'This phone number is already registered. Please sign in.',
'Please enter the correct mobile number' => 'Please enter the correct mobile number', 'Please enter the correct mobile number' => 'Please enter the correct mobile number',
'Registered successfully but login failed' => 'Registered successfully but login failed', 'Registered successfully but login failed' => 'Registered successfully but login failed',
'Incorrect account or password' => 'Incorrect account or password', 'Incorrect account or password' => 'Incorrect account or password',

View File

@@ -55,6 +55,9 @@ return [
'Invalid timestamp' => '时间戳无效', 'Invalid timestamp' => '时间戳无效',
'Invite code does not exist' => '邀请码不存在', 'Invite code does not exist' => '邀请码不存在',
'Register only supports phone' => '注册仅支持手机号', 'Register only supports phone' => '注册仅支持手机号',
'Invite code required' => '请填写邀请码',
'Invite code not bound to channel' => '该邀请码未绑定有效渠道',
'Account already registered' => '该手机号已注册,请直接登录',
'Please enter the correct mobile number' => '请输入正确的手机号', 'Please enter the correct mobile number' => '请输入正确的手机号',
'Registered successfully but login failed' => '注册成功但登录失败', 'Registered successfully but login failed' => '注册成功但登录失败',
'Incorrect account or password' => '账号或密码错误', 'Incorrect account or password' => '账号或密码错误',

View File

@@ -27,7 +27,14 @@ class Auth extends \ba\Auth
protected int $keepTime = 86400; protected int $keepTime = 86400;
protected int $refreshTokenKeepTime = 2592000; protected int $refreshTokenKeepTime = 2592000;
protected array $allowFields = ['id', 'username', 'nickname', 'email', 'mobile', 'avatar', 'gender', 'birthday', 'money', 'score', 'join_time', 'motto', 'last_login_time', 'last_login_ip']; /** 注册失败原因:`username`/`email` 表示账号已占用,供接口返回友好提示 */
protected string $registerDuplicateKind = '';
protected array $allowFields = [
'id', 'username', 'nickname', 'email', 'phone', 'avatar', 'gender', 'birthday',
'coin', 'channel_id', 'risk_flags', 'uuid',
'join_time', 'motto', 'last_login_time', 'last_login_ip',
];
public function __construct(array $config = []) public function __construct(array $config = [])
{ {
@@ -73,7 +80,7 @@ class Auth extends \ba\Auth
return false; return false;
} }
$this->token = $token; $this->token = $token;
$this->loginSuccessful(); $this->loginEd = true;
return true; return true;
} }
} }
@@ -84,6 +91,7 @@ class Auth extends \ba\Auth
public function register(string $username, string $password = '', string $phone = '', string $email = '', int $group = 1, array $extend = []): bool public function register(string $username, string $password = '', string $phone = '', string $email = '', int $group = 1, array $extend = []): bool
{ {
$this->registerDuplicateKind = '';
$request = function_exists('request') ? request() : null; $request = function_exists('request') ? request() : null;
$ip = $request ? $request->getRealIp() : '0.0.0.0'; $ip = $request ? $request->getRealIp() : '0.0.0.0';
@@ -98,13 +106,20 @@ class Auth extends \ba\Auth
return false; return false;
} }
if (User::where('email', $email)->find() && $email) { if (User::where('email', $email)->find() && $email) {
$this->registerDuplicateKind = 'email';
$this->setError(__('Email') . ' ' . __('already exists')); $this->setError(__('Email') . ' ' . __('already exists'));
return false; return false;
} }
if (User::where('username', $username)->find()) { if (User::where('username', $username)->find()) {
$this->registerDuplicateKind = 'username';
$this->setError(__('Username') . ' ' . __('already exists')); $this->setError(__('Username') . ' ' . __('already exists'));
return false; return false;
} }
if ($phone !== '' && User::where('phone', $phone)->find()) {
$this->registerDuplicateKind = 'phone';
$this->setError(__('Mobile') . ' ' . __('already exists'));
return false;
}
$nickname = preg_replace_callback('/1[3-9]\d{9}/', fn($m) => substr($m[0], 0, 3) . '****' . substr($m[0], 7), $username); $nickname = preg_replace_callback('/1[3-9]\d{9}/', fn($m) => substr($m[0], 0, 3) . '****' . substr($m[0], 7), $username);
$time = time(); $time = time();
@@ -116,6 +131,8 @@ class Auth extends \ba\Auth
'last_login_ip' => $ip, 'last_login_ip' => $ip,
'last_login_time' => $time, 'last_login_time' => $time,
'status' => 1, 'status' => 1,
'uuid' => User::generateUniquePublicCode10(),
'remark' => User::formatLoginRemark($time, $ip),
]; ];
$data = array_merge(compact('username', 'password', 'phone', 'email'), $data, $extend); $data = array_merge(compact('username', 'password', 'phone', 'email'), $data, $extend);
@@ -215,6 +232,7 @@ class Auth extends \ba\Auth
$this->model->login_failure = 0; $this->model->login_failure = 0;
$this->model->last_login_time = time(); $this->model->last_login_time = time();
$this->model->last_login_ip = $ip; $this->model->last_login_ip = $ip;
$this->model->remark = User::formatLoginRemark(time(), $ip);
$this->model->save(); $this->model->save();
$this->loginEd = true; $this->loginEd = true;
$this->model->commit(); $this->model->commit();
@@ -344,6 +362,11 @@ class Auth extends \ba\Auth
return $this->error ? __($this->error) : ''; return $this->error ? __($this->error) : '';
} }
public function getRegisterDuplicateKind(): string
{
return $this->registerDuplicateKind;
}
protected function reset(bool $deleteToken = true): bool protected function reset(bool $deleteToken = true): bool
{ {
if ($deleteToken && $this->token) { if ($deleteToken && $this->token) {
@@ -353,6 +376,7 @@ class Auth extends \ba\Auth
$this->loginEd = false; $this->loginEd = false;
$this->model = null; $this->model = null;
$this->refreshToken = ''; $this->refreshToken = '';
$this->registerDuplicateKind = '';
$this->setError(''); $this->setError('');
$this->setKeepTime((int)config('buildadmin.user_token_keep_time', 86400)); $this->setKeepTime((int)config('buildadmin.user_token_keep_time', 86400));
return true; return true;

View File

@@ -29,14 +29,4 @@ class Channel extends Model
{ {
return is_null($value) ? null : (float)$value; return is_null($value) ? null : (float)$value;
} }
public function adminGroup(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\AdminGroup::class, 'admin_group_id', 'id');
}
public function admin(): \think\model\relation\BelongsTo
{
return $this->belongsTo(\app\admin\model\Admin::class, 'admin_id', 'id');
}
} }

View File

@@ -11,13 +11,15 @@ class GameRecord extends Model
protected $autoWriteTimestamp = true; protected $autoWriteTimestamp = true;
protected $type = [ protected $type = [
'create_time' => 'integer', 'create_time' => 'integer',
'update_time' => 'integer', 'update_time' => 'integer',
'period_start_at' => 'integer', 'period_start_at' => 'integer',
'status' => 'integer', 'status' => 'integer',
'draw_mode' => 'integer', 'draw_mode' => 'integer',
'preset_number' => 'integer', 'preset_number' => 'integer',
'result_number' => 'integer', 'result_number' => 'integer',
'platform_profit_amount' => 'string',
'winner_user_count' => 'integer',
]; ];
public function setPeriodStartAtAttr($value, $data = []) public function setPeriodStartAtAttr($value, $data = [])

View File

@@ -13,6 +13,30 @@ class User extends Model
protected $autoWriteTimestamp = true; protected $autoWriteTimestamp = true;
/**
* 生成 10 位唯一对外标识(大写字母与数字,排除易混淆字符)
*/
public static function generateUniquePublicCode10(): string
{
$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$len = strlen($chars);
for ($attempt = 0; $attempt < 80; $attempt++) {
$code = '';
for ($i = 0; $i < 10; $i++) {
$code .= $chars[random_int(0, $len - 1)];
}
if (!self::where('uuid', $code)->find()) {
return $code;
}
}
throw new \RuntimeException('Failed to generate unique user uuid');
}
public static function formatLoginRemark(int $timestamp, string $ip): string
{
return '最后登录:' . date('Y-m-d H:i:s', $timestamp) . ' IP:' . $ip;
}
protected $type = [ protected $type = [
'create_time' => 'integer', 'create_time' => 'integer',
'update_time' => 'integer', 'update_time' => 'integer',

View File

@@ -0,0 +1,172 @@
<?php
declare(strict_types=1);
namespace app\common\service;
use support\think\Db;
use Throwable;
/**
* 开奖后结算注单:写入 win_amount、status=已结算;中奖时入账并记 user_wallet_recordbiz_type=payout
*/
final class GameBetSettleService
{
private const BASE_ODDS = 33;
/**
* 对指定期次按开奖号码结算所有「待开奖」注单;同一注单幂等(仅 status=1 会更新)。
*
* @throws Throwable
*/
public static function settleBetsForDraw(int $recordId, int $resultNumber): void
{
if ($recordId <= 0 || $resultNumber < 1) {
return;
}
$now = time();
$bets = Db::name('bet_order')
->where('period_id', $recordId)
->where('status', 1)
->order('id', 'asc')
->select()
->toArray();
foreach ($bets as $bet) {
$betId = (int) ($bet['id'] ?? 0);
if ($betId <= 0) {
continue;
}
$win = self::computeWinAmount($bet, $resultNumber);
$jackpot = '0.0000';
$affected = Db::name('bet_order')
->where('id', $betId)
->where('status', 1)
->update([
'win_amount' => $win,
'jackpot_extra_amount' => $jackpot,
'status' => 2,
'update_time' => $now,
]);
if ($affected === 0) {
continue;
}
if (bccomp($win, '0', 4) <= 0) {
continue;
}
self::creditUserPayout($bet, $betId, $win, $now);
}
}
/**
* 补偿:库中已结束局次但注单仍为待开奖的,可重复调用(幂等)。
*/
public static function settlePendingForEndedRecords(): int
{
$rows = Db::name('game_record')
->where('status', 4)
->whereNotNull('result_number')
->field(['id', 'result_number'])
->order('id', 'asc')
->select()
->toArray();
$count = 0;
foreach ($rows as $row) {
$rid = (int) ($row['id'] ?? 0);
$rn = (int) ($row['result_number'] ?? 0);
if ($rid <= 0 || $rn < 1) {
continue;
}
$pending = Db::name('bet_order')
->where('period_id', $rid)
->where('status', 1)
->count();
if ($pending === 0) {
continue;
}
Db::startTrans();
try {
self::settleBetsForDraw($rid, $rn);
Db::commit();
$count++;
} catch (Throwable $e) {
Db::rollback();
throw $e;
}
}
return $count;
}
/**
* 单注应付派彩:命中开奖号码时 unit × (连胜+1) × 33与 GameLiveService 一致)。
*/
public static function computeWinAmount(array $bet, int $resultNumber): string
{
$pickNumbers = $bet['pick_numbers'] ?? null;
if (is_string($pickNumbers)) {
$decoded = json_decode($pickNumbers, true);
$pickNumbers = is_array($decoded) ? $decoded : [];
}
if (!is_array($pickNumbers)) {
$pickNumbers = [];
}
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
return '0.0000';
}
$unit = (string) ($bet['unit_amount'] ?? '0');
$streak = (int) ($bet['streak_at_bet'] ?? 0);
$odds = (string) (($streak + 1) * self::BASE_ODDS);
return bcmul($unit, $odds, 4);
}
private static function creditUserPayout(array $bet, int $betId, string $winAmount, int $now): void
{
$userId = (int) ($bet['user_id'] ?? 0);
if ($userId <= 0) {
return;
}
$idem = 'payout_bet_' . $betId;
if (Db::name('user_wallet_record')->where('idempotency_key', $idem)->value('id')) {
return;
}
$user = Db::name('user')->where('id', $userId)->find();
if (!$user) {
return;
}
$before = (string) ($user['coin'] ?? '0');
$after = bcadd($before, $winAmount, 4);
Db::name('user_wallet_record')->insert([
'user_id' => $userId,
'channel_id' => $bet['channel_id'] ?? null,
'biz_type' => 'payout',
'direction' => 1,
'amount' => $winAmount,
'balance_before' => $before,
'balance_after' => $after,
'ref_type' => 'bet_order',
'ref_id' => $betId,
'idempotency_key' => $idem,
'operator_admin_id' => null,
'remark' => '压注派彩',
'create_time' => $now,
]);
Db::name('user')->where('id', $userId)->update([
'coin' => $after,
'update_time' => $now,
]);
}
}

View File

@@ -17,6 +17,9 @@ final class GameLiveService
private const KEY_BET_SECONDS = 'bet_seconds'; private const KEY_BET_SECONDS = 'bet_seconds';
private const KEY_PICK_MAX_NUMBER_COUNT = 'pick_max_number_count'; private const KEY_PICK_MAX_NUMBER_COUNT = 'pick_max_number_count';
/** 开奖结果号码池1 至此上限(与单注可选号码个数配置无关) */
private const DRAW_NUMBER_MAX = 36;
public static function buildSnapshot(?int $recordId = null): array public static function buildSnapshot(?int $recordId = null): array
{ {
$record = self::resolveRecord($recordId); $record = self::resolveRecord($recordId);
@@ -30,6 +33,7 @@ final class GameLiveService
'period_seconds' => self::getConfigInt(self::KEY_PERIOD_SECONDS, 30), 'period_seconds' => self::getConfigInt(self::KEY_PERIOD_SECONDS, 30),
'bet_seconds' => self::getConfigInt(self::KEY_BET_SECONDS, 20), 'bet_seconds' => self::getConfigInt(self::KEY_BET_SECONDS, 20),
'pick_max_number_count' => self::getPickMaxNumberCount(), 'pick_max_number_count' => self::getPickMaxNumberCount(),
'draw_number_max' => self::DRAW_NUMBER_MAX,
'remaining_seconds' => 0, 'remaining_seconds' => 0,
'bet_remaining_seconds' => 0, 'bet_remaining_seconds' => 0,
'can_calculate' => false, 'can_calculate' => false,
@@ -59,7 +63,7 @@ final class GameLiveService
$status = (int) $record['status']; $status = (int) $record['status'];
$canCalculate = $elapsed >= $betSeconds && ($status === 0 || $status === 1); $canCalculate = $elapsed >= $betSeconds && ($status === 0 || $status === 1);
if ($canCalculate) { if ($canCalculate) {
for ($n = 1; $n <= $pickMax; $n++) { for ($n = 1; $n <= self::DRAW_NUMBER_MAX; $n++) {
$loss = self::estimateLossForNumber($bets, $n); $loss = self::estimateLossForNumber($bets, $n);
$candidates[] = [ $candidates[] = [
'number' => $n, 'number' => $n,
@@ -97,6 +101,7 @@ final class GameLiveService
'period_seconds' => $periodSeconds, 'period_seconds' => $periodSeconds,
'bet_seconds' => $betSeconds, 'bet_seconds' => $betSeconds,
'pick_max_number_count' => $pickMax, 'pick_max_number_count' => $pickMax,
'draw_number_max' => self::DRAW_NUMBER_MAX,
'remaining_seconds' => $remaining, 'remaining_seconds' => $remaining,
'bet_remaining_seconds' => $betRemaining, 'bet_remaining_seconds' => $betRemaining,
'can_calculate' => $canCalculate, 'can_calculate' => $canCalculate,
@@ -129,7 +134,7 @@ final class GameLiveService
} }
$pickMax = self::getPickMaxNumberCount(); $pickMax = self::getPickMaxNumberCount();
if ($manualNumber !== null && ($manualNumber < 1 || $manualNumber > $pickMax)) { if ($manualNumber !== null && ($manualNumber < 1 || $manualNumber > self::DRAW_NUMBER_MAX)) {
return ['ok' => false, 'msg' => '手动开奖号码超出允许范围']; return ['ok' => false, 'msg' => '手动开奖号码超出允许范围'];
} }
@@ -138,7 +143,7 @@ final class GameLiveService
$bestNumber = null; $bestNumber = null;
$bestLoss = null; $bestLoss = null;
$bestNumbers = []; $bestNumbers = [];
for ($n = 1; $n <= $pickMax; $n++) { for ($n = 1; $n <= self::DRAW_NUMBER_MAX; $n++) {
$loss = self::estimateLossForNumber($bets, $n); $loss = self::estimateLossForNumber($bets, $n);
$candidates[] = ['number' => $n, 'estimated_loss' => $loss]; $candidates[] = ['number' => $n, 'estimated_loss' => $loss];
if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 4) < 0) { if ($bestLoss === null || bccomp((string) $loss, (string) $bestLoss, 4) < 0) {
@@ -165,6 +170,7 @@ final class GameLiveService
'period_seconds' => $periodSeconds, 'period_seconds' => $periodSeconds,
'bet_seconds' => $betSeconds, 'bet_seconds' => $betSeconds,
'pick_max_number_count' => $pickMax, 'pick_max_number_count' => $pickMax,
'draw_number_max' => self::DRAW_NUMBER_MAX,
'candidate_numbers' => $candidates, 'candidate_numbers' => $candidates,
'ai_default_number' => $bestNumber, 'ai_default_number' => $bestNumber,
'final_number' => $finalNumber, 'final_number' => $finalNumber,
@@ -189,8 +195,10 @@ final class GameLiveService
'draw_mode' => $manualNumber === null ? 0 : 1, 'draw_mode' => $manualNumber === null ? 0 : 1,
'update_time' => $now, 'update_time' => $now,
]); ]);
GameBetSettleService::settleBetsForDraw((int) $record['id'], $finalNumber);
GameRecordService::createNextRecordAfterDraw(); GameRecordService::createNextRecordAfterDraw();
Db::commit(); Db::commit();
GameRecordStatService::refreshForRecordId((int) $record['id']);
} catch (Throwable $e) { } catch (Throwable $e) {
Db::rollback(); Db::rollback();
return ['ok' => false, 'msg' => $e->getMessage()]; return ['ok' => false, 'msg' => $e->getMessage()];

View File

@@ -0,0 +1,106 @@
<?php
declare(strict_types=1);
namespace app\common\service;
use support\think\Db;
/**
* 对局维度统计:平台盈亏、中奖人数(与 GameLiveService 单号派彩口径一致)。
*/
final class GameRecordStatService
{
private const BASE_ODDS = 33;
/**
* 根据注单与开奖号码回写 game_record 统计字段(已结束对局)。
*/
public static function refreshForRecordId(int $recordId): void
{
if ($recordId <= 0) {
return;
}
$record = Db::name('game_record')->where('id', $recordId)->find();
if (!$record) {
return;
}
$status = (int) ($record['status'] ?? 0);
$now = time();
if ($status !== 4) {
Db::name('game_record')->where('id', $recordId)->update([
'platform_profit_amount' => '0.0000',
'winner_user_count' => 0,
'update_time' => $now,
]);
return;
}
$resultRaw = $record['result_number'] ?? null;
if ($resultRaw === null || $resultRaw === '') {
return;
}
$resultNum = (int) $resultRaw;
$bets = Db::name('bet_order')->where('period_id', $recordId)->select()->toArray();
$totalBet = '0.0000';
$totalPayout = '0.0000';
$winnerUserIds = [];
foreach ($bets as $bet) {
$st = (int) ($bet['status'] ?? 0);
if ($st === 3) {
continue;
}
$tb = (string) ($bet['total_amount'] ?? '0');
$totalBet = bcadd($totalBet, $tb, 4);
if ($st === 2) {
$payout = bcadd((string) ($bet['win_amount'] ?? '0'), (string) ($bet['jackpot_extra_amount'] ?? '0'), 4);
} else {
$payout = self::estimatePayoutForBet($bet, $resultNum);
}
$totalPayout = bcadd($totalPayout, $payout, 4);
if (bccomp($payout, '0', 4) > 0) {
$uid = (int) ($bet['user_id'] ?? 0);
if ($uid > 0) {
$winnerUserIds[$uid] = true;
}
}
}
$profit = bcsub($totalBet, $totalPayout, 4);
Db::name('game_record')->where('id', $recordId)->update([
'platform_profit_amount' => $profit,
'winner_user_count' => count($winnerUserIds),
'update_time' => $now,
]);
}
/**
* 与 GameLiveService::estimateLossForNumber 中单注派彩一致:命中号码时 unit × (streak+1) × 33。
*/
private static function estimatePayoutForBet(array $bet, int $resultNumber): string
{
$pickNumbers = $bet['pick_numbers'] ?? null;
if (is_string($pickNumbers)) {
$decoded = json_decode($pickNumbers, true);
$pickNumbers = is_array($decoded) ? $decoded : [];
}
if (!is_array($pickNumbers)) {
$pickNumbers = [];
}
if (!in_array($resultNumber, array_map('intval', $pickNumbers), true)) {
return '0.0000';
}
$unit = (string) ($bet['unit_amount'] ?? '0');
$streak = (int) ($bet['streak_at_bet'] ?? 0);
$odds = (string) (($streak + 1) * self::BASE_ODDS);
return bcmul($unit, $odds, 4);
}
}

View File

@@ -15,12 +15,11 @@ class Channel extends Validate
'name' => 'require|max:255', 'name' => 'require|max:255',
'agent_mode' => 'require|in:turnover,affiliate', 'agent_mode' => 'require|in:turnover,affiliate',
'status' => 'in:0,1', 'status' => 'in:0,1',
'admin_id' => 'require|integer|gt:0',
'remark' => 'max:255', 'remark' => 'max:255',
]; ];
protected $scene = [ protected $scene = [
'add' => ['code', 'name', 'agent_mode', 'status', 'admin_id', 'remark'], 'add' => ['code', 'name', 'agent_mode', 'status', 'remark'],
'edit' => ['name', 'agent_mode', 'status', 'admin_id', 'remark'], 'edit' => ['name', 'agent_mode', 'status', 'remark'],
]; ];
} }

View File

@@ -1,6 +1,13 @@
export default { export default {
GroupName: 'Group Name', GroupName: 'Group Name',
'Group name': 'Group Name', 'Group name': 'Group Name',
channel_id: 'Channel',
channel_name: 'Channel name',
channel_admin: 'Channel admin',
channel_auto_bind: 'Will bind to the current account channel automatically',
channel_inherit_hint:
'Sub groups do not pick a channel separately: saving uses the parent group channel; changing parent syncs automatically.',
system_group_no_channel: 'System (no channel)',
commission_rate: 'Commission rate (%)', commission_rate: 'Commission rate (%)',
commission_rate_desc_title: 'Group commission notes', commission_rate_desc_title: 'Group commission notes',
commission_rate_desc_1: 'The total group commission rate under the same parent cannot exceed 100%.', commission_rate_desc_1: 'The total group commission rate under the same parent cannot exceed 100%.',

View File

@@ -58,6 +58,7 @@ export default {
admingroup__name: 'name', admingroup__name: 'name',
admin_id: 'admin_id', admin_id: 'admin_id',
admin_tree_tip: 'Admins are grouped by channel. Pick a leaf under a channel name. One channel maps to one admin.', admin_tree_tip: 'Admins are grouped by channel. Pick a leaf under a channel name. One channel maps to one admin.',
admin_select_tip: 'Only administrators within your data permission scope are listed; search by username.',
manual_settle: 'Manual settle', manual_settle: 'Manual settle',
manual_settle_confirm: 'Confirm trigger manual settlement for this channel?', manual_settle_confirm: 'Confirm trigger manual settlement for this channel?',
manual_settle_settlement_no: 'Settlement No.', manual_settle_settlement_no: 'Settlement No.',
@@ -70,8 +71,8 @@ export default {
manual_settle_calc_base: 'Settlement base', manual_settle_calc_base: 'Settlement base',
manual_settle_commission_amount: 'Commission amount', manual_settle_commission_amount: 'Commission amount',
manual_settle_remark: 'Remark', manual_settle_remark: 'Remark',
admin_id_placeholder: 'Select a channel admin account', admin_id_placeholder: 'Select an admin (within your permission scope)',
admin__username: 'username', admin__username: 'Person in charge',
create_time: 'create_time', create_time: 'create_time',
update_time: 'update_time', update_time: 'update_time',
'quick Search Fields': 'id,code,name', 'quick Search Fields': 'id,code,name',

View File

@@ -1,28 +0,0 @@
export default {
'quick Search Fields': 'Period No. / ID',
id: 'ID',
period_no: 'Period No.',
period_start_at: 'Start time',
status: 'Status',
'status 0': 'Betting open',
'status 1': 'Closed',
'status 2': 'Settling',
'status 3': 'Paying',
'status 4': 'Ended',
'status 5': 'Void',
draw_mode: 'Draw mode',
'draw_mode 0': 'Auto AI',
'draw_mode 1': 'Manual preset',
preset_number: 'Preset number',
result_number: 'Result number',
void_reason: 'Void reason',
create_time: 'Created',
update_time: 'Updated',
section_auto: 'Auto draw & new period',
auto_create_label: 'Allow auto-create next period',
auto_create_tip: 'When enabled, a background ticker inserts a new period if none is in progress',
manual_create_label: 'Allow manual create next period',
manual_create_tip: 'When enabled, the button below can create the next period',
btn_create_next: 'Create next period (manual)',
saving: 'Saving…',
}

View File

@@ -15,6 +15,8 @@ export default {
'draw_mode 1': 'Manual preset', 'draw_mode 1': 'Manual preset',
preset_number: 'Preset number', preset_number: 'Preset number',
result_number: 'Result number', result_number: 'Result number',
platform_profit_amount: 'Round P/L (platform)',
winner_user_count: 'Winners',
void_reason: 'Void reason', void_reason: 'Void reason',
create_time: 'Created', create_time: 'Created',
update_time: 'Updated', update_time: 'Updated',

View File

@@ -1,6 +1,12 @@
export default { export default {
GroupName: '组名', GroupName: '组名',
'Group name': '组别名称', 'Group name': '组别名称',
channel_id: '所属渠道',
channel_name: '渠道名称',
channel_admin: '渠道管理员',
channel_auto_bind: '将自动绑定为当前账号所属渠道',
channel_inherit_hint: '子级不单独选渠道:保存时将使用上级分组对应渠道,变更上级时会自动同步。',
system_group_no_channel: '系统级(未绑定渠道)',
commission_rate: '分红比例(%)', commission_rate: '分红比例(%)',
commission_rate_desc_title: '角色组分红说明', commission_rate_desc_title: '角色组分红说明',
commission_rate_desc_1: '同一父级下角色组分红比例总和不能超过100%。', commission_rate_desc_1: '同一父级下角色组分红比例总和不能超过100%。',

View File

@@ -58,6 +58,7 @@ export default {
admingroup__name: '组名', admingroup__name: '组名',
admin_id: '管理员', admin_id: '管理员',
admin_tree_tip: '按渠道分组展示可关联的管理员账号,请在「渠道名称」下选择具体管理员(叶子节点)。渠道负责人仅对应一名管理员。', admin_tree_tip: '按渠道分组展示可关联的管理员账号,请在「渠道名称」下选择具体管理员(叶子节点)。渠道负责人仅对应一名管理员。',
admin_select_tip: '仅列出当前账号数据权限范围内的管理员,支持搜索用户名。',
manual_settle: '手动结算', manual_settle: '手动结算',
manual_settle_confirm: '确认触发当前渠道手动结算?', manual_settle_confirm: '确认触发当前渠道手动结算?',
manual_settle_settlement_no: '结算单号', manual_settle_settlement_no: '结算单号',
@@ -70,8 +71,8 @@ export default {
manual_settle_calc_base: '结算基数', manual_settle_calc_base: '结算基数',
manual_settle_commission_amount: '佣金金额', manual_settle_commission_amount: '佣金金额',
manual_settle_remark: '备注', manual_settle_remark: '备注',
admin_id_placeholder: '请选择渠道下的管理员账号', admin_id_placeholder: '请选择管理员(仅当前权限范围内)',
admin__username: '用户名', admin__username: '负责人',
create_time: '创建时间', create_time: '创建时间',
update_time: '修改时间', update_time: '修改时间',
'quick Search Fields': 'ID、渠道标识、渠道名', 'quick Search Fields': 'ID、渠道标识、渠道名',

View File

@@ -1,28 +0,0 @@
export default {
'quick Search Fields': '期号/ID',
id: 'ID',
period_no: '期号',
period_start_at: '开始时间',
status: '状态',
'status 0': '下注开放',
'status 1': '已封盘',
'status 2': '算票中',
'status 3': '派彩中',
'status 4': '已结束',
'status 5': '已作废',
draw_mode: '开奖方式',
'draw_mode 0': '自动AI',
'draw_mode 1': '手动预设',
preset_number: '预设号码',
result_number: '开奖号码',
void_reason: '作废原因',
create_time: '创建时间',
update_time: '更新时间',
section_auto: '自动开奖与新建期',
auto_create_label: '允许自动创建下一期',
auto_create_tip: '开启后由后台定时任务在无进行中期号时自动插入新期',
manual_create_label: '允许手动创建下一期',
manual_create_tip: '开启后可在本页使用「手动创建下一期」按钮',
btn_create_next: '手动创建下一期',
saving: '保存中…',
}

View File

@@ -15,6 +15,8 @@ export default {
'draw_mode 1': '手动预设', 'draw_mode 1': '手动预设',
preset_number: '预设号码', preset_number: '预设号码',
result_number: '开奖号码', result_number: '开奖号码',
platform_profit_amount: '对局盈亏(平台)',
winner_user_count: '中奖人数',
void_reason: '作废原因', void_reason: '作废原因',
create_time: '创建时间', create_time: '创建时间',
update_time: '更新时间', update_time: '更新时间',

View File

@@ -2,7 +2,7 @@ export default {
id: 'ID', id: 'ID',
username: '用户名', username: '用户名',
password: '密码', password: '密码',
uuid: '用户唯一标识', uuid: 'uuid',
phone: '手机号', phone: '手机号',
email: '邮箱', email: '邮箱',
email_placeholder: '可选,与手机号二选一注册时填写', email_placeholder: '可选,与手机号二选一注册时填写',

View File

@@ -1,14 +1,14 @@
export default { export default {
id: 'ID', id: 'ID',
username: '用户名', username: '用户名',
password: '密码', password: '密码',
uuid: '用户唯一标识', uuid: 'uuid',
phone: '手机号', phone: '手机号',
email: '邮箱', email: '邮箱',
email_placeholder: '可选,与手机号二选一注册时填写', email_placeholder: '可选,与手机号二选一注册时填写',
head_image: '头像', head_image: '头像',
remark: '备注', remark: '备注',
coin: '游戏币余额', coin: '余额',
coin_placeholder: 'decimal(18,4),禁止业务用浮点存库', coin_placeholder: 'decimal(18,4),禁止业务用浮点存库',
total_deposit_coin: '累计充值(币)', total_deposit_coin: '累计充值(币)',
total_valid_bet_coin: '累计有效投注(币)', total_valid_bet_coin: '累计有效投注(币)',

View File

@@ -89,10 +89,16 @@ const baTable = new baTableClass(
label: t('State'), label: t('State'),
prop: 'status', prop: 'status',
align: 'center', align: 'center',
render: 'tag', operator: 'eq',
effect: 'dark', sortable: false,
custom: { disable: 'danger', enable: 'success' }, render: 'switch',
replaceValue: { disable: t('Disable'), enable: t('Enable') }, replaceValue: { disable: t('Disable'), enable: t('Enable') },
customRenderAttr: {
switch: () => ({
activeValue: 'enable',
inactiveValue: 'disable',
}),
},
}, },
{ {
label: t('Operate'), label: t('Operate'),

View File

@@ -51,7 +51,7 @@ const baTable: baTableClass = new baTableClass(
new baTableApi('/admin/auth.Group/'), new baTableApi('/admin/auth.Group/'),
{ {
expandAll: true, expandAll: true,
dblClickNotEditColumn: [undefined], dblClickNotEditColumn: [undefined, 'status'],
column: [ column: [
{ type: 'selection', align: 'center' }, { type: 'selection', align: 'center' },
{ {
@@ -60,15 +60,21 @@ const baTable: baTableClass = new baTableClass(
align: 'left', align: 'left',
minWidth: '180', minWidth: '180',
}, },
{
label: t('auth.group.channel_name'),
prop: 'channel_name',
align: 'center',
minWidth: '140',
},
{ label: t('auth.group.commission_rate'), prop: 'commission_rate', align: 'center', formatter: formatRatePercent }, { label: t('auth.group.commission_rate'), prop: 'commission_rate', align: 'center', formatter: formatRatePercent },
{ label: t('auth.group.jurisdiction'), prop: 'rules', align: 'center' }, { label: t('auth.group.jurisdiction'), prop: 'rules', align: 'center' },
{ {
label: t('State'), label: t('State'),
prop: 'status', prop: 'status',
align: 'center', align: 'center',
render: 'tag', operator: 'eq',
effect: 'dark', sortable: false,
custom: { 0: 'danger', 1: 'success' }, render: 'switch',
replaceValue: { 0: t('Disable'), 1: t('Enable') }, replaceValue: { 0: t('Disable'), 1: t('Enable') },
}, },
{ label: t('Update time'), prop: 'update_time', align: 'center', width: '160', render: 'datetime' }, { label: t('Update time'), prop: 'update_time', align: 'center', width: '160', render: 'datetime' },
@@ -86,6 +92,7 @@ const baTable: baTableClass = new baTableClass(
{ {
defaultItems: { defaultItems: {
status: 1, status: 1,
channel_id: null,
}, },
} }
) )
@@ -94,9 +101,18 @@ const baTable: baTableClass = new baTableClass(
baTable.before.onSubmit = ({ formEl, operate, items }) => { baTable.before.onSubmit = ({ formEl, operate, items }) => {
let submitCallback = () => { let submitCallback = () => {
baTable.form.submitLoading = true baTable.form.submitLoading = true
const postItems: anyObj = { ...items }
const pid = Number(postItems.pid ?? 0)
if (pid !== 0) {
delete postItems.channel_id
delete postItems.channel_name
delete postItems.channel_admin_username
} else if (!adminInfo.super) {
delete postItems.channel_id
}
baTable.api baTable.api
.postData(operate, { .postData(operate, {
...items, ...postItems,
rules: formRef.value?.getCheckeds(), rules: formRef.value?.getCheckeds(),
}) })
.then((res) => { .then((res) => {
@@ -153,6 +169,10 @@ baTable.after.toggleForm = ({ operate }) => {
// 编辑请求完成后钩子 // 编辑请求完成后钩子
baTable.after.getEditData = () => { baTable.after.getEditData = () => {
const pid = Number(baTable.form.items?.pid ?? 0)
if (pid !== 0 && baTable.form.items) {
delete baTable.form.items.channel_id
}
menuRuleTreeUpdate() menuRuleTreeUpdate()
} }

View File

@@ -41,6 +41,42 @@
valueOnClear: 0, valueOnClear: 0,
}" }"
/> />
<p
v-if="!isRootGroup"
class="group-channel-inherit-hint"
:style="{ paddingLeft: (baTable.form.labelWidth ?? 120) + 'px' }"
>
{{ t('auth.group.channel_inherit_hint') }}
</p>
<!-- 顶级+超管可选渠道展示只读渠道名称channel_id 仅由表单传给后端 -->
<FormItem
v-if="isRootGroup && adminInfo.super"
:label="t('auth.group.channel_id')"
v-model="baTable.form.items!.channel_id"
type="remoteSelect"
prop="channel_id"
:input-attr="{
pk: 'id',
field: 'name',
remoteUrl: '/admin/channel/index',
placeholder: t('Click select'),
emptyValues: ['', null, undefined, 0],
valueOnClear: null,
}"
/>
<template v-if="isRootGroup && adminInfo.super && channelPreviewName">
<el-form-item :label="t('auth.group.channel_name')">
<el-input :model-value="channelPreviewName" readonly />
</el-form-item>
</template>
<!-- 子级只读展示上级对应渠道名称不提交 channel_id由后端按父级写入 -->
<template v-if="!isRootGroup && channelPreviewName">
<el-form-item :label="t('auth.group.channel_name')">
<el-input :model-value="channelPreviewName" readonly />
</el-form-item>
</template>
<el-form-item prop="name" :label="t('auth.group.Group name')"> <el-form-item prop="name" :label="t('auth.group.Group name')">
<el-input <el-input
@@ -103,7 +139,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { reactive, inject, useTemplateRef } from 'vue' import { reactive, inject, useTemplateRef, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import type baTableClass from '/@/utils/baTable' import type baTableClass from '/@/utils/baTable'
import FormItem from '/@/components/formItem/index.vue' import FormItem from '/@/components/formItem/index.vue'
@@ -112,6 +148,7 @@ import { buildValidatorData } from '/@/utils/validate'
import type Node from 'element-plus/es/components/tree/src/model/node' import type Node from 'element-plus/es/components/tree/src/model/node'
import { useConfig } from '/@/stores/config' import { useConfig } from '/@/stores/config'
import { useAdminInfo } from '/@/stores/adminInfo' import { useAdminInfo } from '/@/stores/adminInfo'
import createAxios from '/@/utils/axios'
const config = useConfig() const config = useConfig()
const adminInfo = useAdminInfo() const adminInfo = useAdminInfo()
@@ -120,10 +157,100 @@ const treeRef = useTemplateRef('treeRef')
const baTable = inject('baTable') as baTableClass const baTable = inject('baTable') as baTableClass
const { t } = useI18n() const { t } = useI18n()
const isRootGroup = computed(() => {
const p = baTable.form.items?.pid
if (p === undefined || p === null || p === '') {
return true
}
return Number(p) === 0
})
const strFromRow = (key: string): string => {
const row = baTable.form.items
if (!row) return ''
const v = row[key]
return typeof v === 'string' ? v : ''
}
const channelPreviewName = computed(() => strFromRow('channel_name'))
const shouldDisableCommissionRate = () => { const shouldDisableCommissionRate = () => {
return false return false
} }
/**
* 子角色组选择上级分组后只拉取展示用渠道名channel_id 由后端按父级保存,不在此写入提交字段。
*/
watch(
() => baTable.form.items?.pid,
async (pid, oldPid) => {
const items = baTable.form.items
if (!items || !baTable.form.operate || !['Add', 'Edit'].includes(baTable.form.operate)) {
return
}
const pidNum = Number(pid ?? 0)
const oldNum = oldPid === undefined || oldPid === null || oldPid === '' ? null : Number(oldPid)
if (pidNum === 0) {
if (adminInfo.super && oldNum !== null && oldNum !== 0) {
items.channel_id = null
items['channel_name'] = ''
}
return
}
delete items.channel_id
try {
const res = await createAxios(
{
url: '/admin/auth.Group/edit',
method: 'get',
params: { id: pidNum },
},
{ showErrorMessage: false, showCodeMessage: false }
)
const row = res.data.row
if (row) {
items['channel_name'] = typeof row.channel_name === 'string' ? row.channel_name : ''
}
} catch {
items['channel_name'] = ''
}
}
)
/** 顶级+超管:所选渠道变更时刷新只读渠道名 */
watch(
() => baTable.form.items?.channel_id,
async (cid) => {
const items = baTable.form.items
if (!items || !baTable.form.operate || !['Add', 'Edit'].includes(baTable.form.operate)) {
return
}
if (!isRootGroup.value || !adminInfo.super) {
return
}
if (cid === null || cid === undefined || cid === '') {
items['channel_name'] = ''
return
}
try {
const res = await createAxios(
{
url: '/admin/auth.Group/channelBindPreview',
method: 'get',
params: { channel_id: cid },
},
{ showErrorMessage: false, showCodeMessage: false }
)
items['channel_name'] = typeof res.data.channel_name === 'string' ? res.data.channel_name : ''
} catch {
items['channel_name'] = ''
}
}
)
const rules: Partial<Record<string, FormItemRule[]>> = reactive({ const rules: Partial<Record<string, FormItemRule[]>> = reactive({
name: [buildValidatorData({ name: 'required', title: t('auth.group.Group name') })], name: [buildValidatorData({ name: 'required', title: t('auth.group.Group name') })],
commission_rate: [ commission_rate: [
@@ -194,6 +321,14 @@ defineExpose({
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
.group-channel-inherit-hint {
margin: -6px 0 14px;
font-size: 12px;
line-height: 1.5;
color: var(--el-text-color-secondary);
box-sizing: border-box;
}
.commission-rate-alert { .commission-rate-alert {
margin-bottom: 12px; margin-bottom: 12px;
} }

View File

@@ -394,26 +394,6 @@ const baTable = new baTableClass(
render: 'switch', render: 'switch',
replaceValue: { '0': t('channel.status 0'), '1': t('channel.status 1') }, replaceValue: { '0': t('channel.status 0'), '1': t('channel.status 1') },
}, },
{
label: t('channel.admingroup__name'),
prop: 'adminGroup.name',
align: 'center',
minWidth: 110,
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
operator: 'LIKE',
comSearchRender: 'string',
},
{
label: t('channel.admin__username'),
prop: 'admin.username',
align: 'center',
minWidth: 90,
operatorPlaceholder: t('Fuzzy query'),
render: 'tags',
operator: 'LIKE',
comSearchRender: 'string',
},
{ {
label: t('channel.create_time'), label: t('channel.create_time'),
prop: 'create_time', prop: 'create_time',

View File

@@ -172,21 +172,6 @@
@keyup.ctrl.enter="baTable.onSubmit(formRef)" @keyup.ctrl.enter="baTable.onSubmit(formRef)"
:placeholder="t('Please input field', { field: t('channel.remark') })" :placeholder="t('Please input field', { field: t('channel.remark') })"
/> />
<el-alert type="info" :closable="false" show-icon class="channel-admin-tree-tip">
{{ t('channel.admin_tree_tip') }}
</el-alert>
<el-form-item :label="t('channel.admin_id')" prop="admin_id">
<el-tree-select
v-model="baTable.form.items!.admin_id"
class="w100"
clearable
filterable
:data="channelAdminTree"
:props="channelAdminTreeProps"
:render-after-expand="false"
:placeholder="t('channel.admin_id_placeholder')"
/>
</el-form-item>
</el-form> </el-form>
</div> </div>
</el-scrollbar> </el-scrollbar>
@@ -209,7 +194,6 @@ import { useI18n } from 'vue-i18n'
import FormItem from '/@/components/formItem/index.vue' import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config' import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable' import type baTableClass from '/@/utils/baTable'
import createAxios from '/@/utils/axios'
import { buildValidatorData } from '/@/utils/validate' import { buildValidatorData } from '/@/utils/validate'
const config = useConfig() const config = useConfig()
@@ -218,23 +202,6 @@ const baTable = inject('baTable') as baTableClass
const { t } = useI18n() const { t } = useI18n()
type ChannelAdminTreeNode = {
value: string
label: string
disabled?: boolean
children?: ChannelAdminTreeNode[]
channel_id?: number
is_leaf?: boolean
}
const channelAdminTree = ref<ChannelAdminTreeNode[]>([])
const channelAdminTreeProps = {
value: 'value',
label: 'label',
children: 'children',
disabled: 'disabled',
}
type LadderRuleRow = { minLoss: number; shareRate: number } type LadderRuleRow = { minLoss: number; shareRate: number }
const ladderRuleList = ref<LadderRuleRow[]>([]) const ladderRuleList = ref<LadderRuleRow[]>([])
@@ -317,14 +284,6 @@ const onSettlePlanChange = () => {
}) })
} }
const loadChannelAdminTree = async () => {
const res = await createAxios({
url: '/admin/channel/adminTree',
method: 'get',
})
channelAdminTree.value = (res.data?.list ?? []) as ChannelAdminTreeNode[]
}
const currentAgentMode = computed(() => baTable.form.items?.agent_mode ?? 'turnover') const currentAgentMode = computed(() => baTable.form.items?.agent_mode ?? 'turnover')
const currentAgentModeDescList = computed(() => { const currentAgentModeDescList = computed(() => {
if (currentAgentMode.value === 'turnover') { if (currentAgentMode.value === 'turnover') {
@@ -390,19 +349,9 @@ const removeLadderRule = (idx: number) => {
} }
onMounted(() => { onMounted(() => {
loadChannelAdminTree()
syncSettlePlanFromItems() syncSettlePlanFromItems()
}) })
watch(
() => baTable.form.operate,
(op) => {
if (op === 'Add' || op === 'Edit') {
loadChannelAdminTree()
}
}
)
watch( watch(
() => [baTable.form.operate, baTable.form.items?.id] as const, () => [baTable.form.operate, baTable.form.items?.id] as const,
() => { () => {
@@ -410,9 +359,6 @@ watch(
if (!items || baTable.form.operate !== 'Edit') { if (!items || baTable.form.operate !== 'Edit') {
return return
} }
if (items.admin_id !== undefined && items.admin_id !== null && items.admin_id !== '') {
items.admin_id = String(items.admin_id) as any
}
items.affiliate_ladder_rules = normalizeLadderRulesToText(items.affiliate_ladder_rules) as any items.affiliate_ladder_rules = normalizeLadderRulesToText(items.affiliate_ladder_rules) as any
syncSettlePlanFromItems() syncSettlePlanFromItems()
syncLadderRuleRowsFromItems() syncLadderRuleRowsFromItems()
@@ -557,7 +503,6 @@ const rules: Partial<Record<string, FormItemRule[]>> = reactive({
settle_time: [buildValidatorData({ name: 'required', title: t('channel.settle_time') })], settle_time: [buildValidatorData({ name: 'required', title: t('channel.settle_time') })],
affiliate_effective_start_at: [buildValidatorData({ name: 'required', title: t('channel.affiliate_effective_start_at') })], affiliate_effective_start_at: [buildValidatorData({ name: 'required', title: t('channel.affiliate_effective_start_at') })],
carryover_balance: [buildValidatorData({ name: 'number', title: t('channel.carryover_balance') })], carryover_balance: [buildValidatorData({ name: 'number', title: t('channel.carryover_balance') })],
admin_id: [buildValidatorData({ name: 'required', title: t('channel.admin_id') })],
}) })
</script> </script>
@@ -571,8 +516,4 @@ const rules: Partial<Record<string, FormItemRule[]>> = reactive({
padding-left: 18px; padding-left: 18px;
line-height: 1.6; line-height: 1.6;
} }
.channel-admin-tree-tip {
margin-bottom: 12px;
}
</style> </style>

View File

@@ -11,7 +11,7 @@
<div>{{ t('game.live.countdown') }}: {{ countdownText }}</div> <div>{{ t('game.live.countdown') }}: {{ countdownText }}</div>
</div> </div>
<div class="header-actions"> <div class="header-actions">
<el-input-number v-model="manualNumber" :min="1" :max="36" :step="1" /> <el-input-number v-model="manualNumber" :min="1" :max="snapshot.draw_number_max ?? 36" :step="1" />
<el-button :loading="calcLoading" :disabled="!snapshot.can_calculate" @click="onCalculate"> <el-button :loading="calcLoading" :disabled="!snapshot.can_calculate" @click="onCalculate">
{{ t('game.live.btn_calc') }} {{ t('game.live.btn_calc') }}
</el-button> </el-button>
@@ -70,6 +70,8 @@ interface Snapshot {
period_seconds?: number period_seconds?: number
bet_seconds?: number bet_seconds?: number
pick_max_number_count?: number pick_max_number_count?: number
/** 开奖号码池上限1draw_number_max与单注可选号码上限无关 */
draw_number_max?: number
remaining_seconds?: number remaining_seconds?: number
bet_remaining_seconds?: number bet_remaining_seconds?: number
can_calculate?: boolean can_calculate?: boolean
@@ -87,7 +89,8 @@ const snapshot = reactive<Snapshot>({
ai_default_number: null, ai_default_number: null,
period_seconds: 30, period_seconds: 30,
bet_seconds: 20, bet_seconds: 20,
pick_max_number_count: 36, pick_max_number_count: 10,
draw_number_max: 36,
remaining_seconds: 0, remaining_seconds: 0,
bet_remaining_seconds: 0, bet_remaining_seconds: 0,
can_calculate: false, can_calculate: false,
@@ -121,12 +124,14 @@ async function loadSnapshot() {
snapshot.ai_default_number = res.data.ai_default_number snapshot.ai_default_number = res.data.ai_default_number
snapshot.period_seconds = res.data.period_seconds ?? 30 snapshot.period_seconds = res.data.period_seconds ?? 30
snapshot.bet_seconds = res.data.bet_seconds ?? 20 snapshot.bet_seconds = res.data.bet_seconds ?? 20
snapshot.pick_max_number_count = 36 snapshot.pick_max_number_count = res.data.pick_max_number_count ?? 10
snapshot.draw_number_max = res.data.draw_number_max ?? 36
snapshot.remaining_seconds = res.data.remaining_seconds ?? 0 snapshot.remaining_seconds = res.data.remaining_seconds ?? 0
snapshot.bet_remaining_seconds = res.data.bet_remaining_seconds ?? 0 snapshot.bet_remaining_seconds = res.data.bet_remaining_seconds ?? 0
snapshot.can_calculate = !!res.data.can_calculate snapshot.can_calculate = !!res.data.can_calculate
snapshot.can_draw = !!res.data.can_draw snapshot.can_draw = !!res.data.can_draw
if (manualNumber.value === null || manualNumber.value < 1 || manualNumber.value > 36) manualNumber.value = 1 const dmax = res.data.draw_number_max ?? 36
if (manualNumber.value === null || manualNumber.value < 1 || manualNumber.value > dmax) manualNumber.value = 1
} }
} finally { } finally {
loading.value = false loading.value = false
@@ -169,7 +174,8 @@ async function initPush() {
snapshot.ai_default_number = payload.ai_default_number ?? null snapshot.ai_default_number = payload.ai_default_number ?? null
snapshot.period_seconds = payload.period_seconds ?? 30 snapshot.period_seconds = payload.period_seconds ?? 30
snapshot.bet_seconds = payload.bet_seconds ?? 20 snapshot.bet_seconds = payload.bet_seconds ?? 20
snapshot.pick_max_number_count = 36 snapshot.pick_max_number_count = payload.pick_max_number_count ?? 10
snapshot.draw_number_max = payload.draw_number_max ?? 36
snapshot.remaining_seconds = payload.remaining_seconds ?? 0 snapshot.remaining_seconds = payload.remaining_seconds ?? 0
snapshot.bet_remaining_seconds = payload.bet_remaining_seconds ?? 0 snapshot.bet_remaining_seconds = payload.bet_remaining_seconds ?? 0
snapshot.can_calculate = !!payload.can_calculate snapshot.can_calculate = !!payload.can_calculate

View File

@@ -1,303 +0,0 @@
<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 />
<el-card v-if="canSettings" class="period-settings-card" shadow="never">
<template #header>
<span>{{ t('game.period.section_auto') }}</span>
</template>
<div v-loading="settingsLoading" class="period-settings-body">
<div class="period-setting-row">
<span class="period-setting-label">{{ t('game.period.auto_create_label') }}</span>
<el-switch v-model="autoCreate" :disabled="settingsSaving" @change="onSwitchChange" />
<span class="period-setting-tip">{{ t('game.period.auto_create_tip') }}</span>
</div>
<div class="period-setting-row">
<span class="period-setting-label">{{ t('game.period.manual_create_label') }}</span>
<el-switch v-model="manualCreate" :disabled="settingsSaving" @change="onSwitchChange" />
<span class="period-setting-tip">{{ t('game.period.manual_create_tip') }}</span>
</div>
<div v-if="canManual" class="period-setting-actions">
<el-button type="primary" :loading="createLoading" @click="onCreateNextManual">
{{ t('game.period.btn_create_next') }}
</el-button>
</div>
</div>
</el-card>
<TableHeader
:buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('game.period.quick Search Fields') })"
></TableHeader>
<Table ref="tableRef"></Table>
<PopupForm />
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, provide, ref, 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 createAxios from '/@/utils/axios'
import baTableClass from '/@/utils/baTable'
import { auth } from '/@/utils/common'
defineOptions({
name: 'game/period',
})
const { t } = useI18n()
const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit', 'delete'])
const settingsLoading = ref(false)
const settingsSaving = ref(false)
const createLoading = ref(false)
const autoCreate = ref(false)
const manualCreate = ref(false)
/** 避免初次拉取开关值时触发保存 */
const settingsReady = ref(false)
const canSettings = computed(() => auth('periodSettings'))
const canManual = computed(() => auth('createNextManual'))
const baTable = new baTableClass(
new baTableApi('/admin/game.Period/'),
{
pk: 'id',
column: [
{ type: 'selection', align: 'center', operator: false },
{ label: t('game.period.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' },
{
label: t('game.period.period_no'),
prop: 'period_no',
align: 'center',
minWidth: 180,
operatorPlaceholder: t('Fuzzy query'),
operator: 'LIKE',
},
{
label: t('game.period.period_start_at'),
prop: 'period_start_at',
align: 'center',
width: 170,
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('game.period.status'),
prop: 'status',
align: 'center',
width: 110,
operator: 'eq',
render: 'tag',
effect: 'dark',
custom: {
'0': 'success',
'1': 'warning',
'2': 'info',
'3': 'primary',
'4': 'warning',
'5': 'danger',
},
replaceValue: {
'0': t('game.period.status 0'),
'1': t('game.period.status 1'),
'2': t('game.period.status 2'),
'3': t('game.period.status 3'),
'4': t('game.period.status 4'),
'5': t('game.period.status 5'),
},
},
{
label: t('game.period.draw_mode'),
prop: 'draw_mode',
align: 'center',
width: 110,
operator: 'eq',
render: 'tag',
custom: {
'0': 'info',
'1': 'warning',
},
replaceValue: {
'0': t('game.period.draw_mode 0'),
'1': t('game.period.draw_mode 1'),
},
},
{
label: t('game.period.preset_number'),
prop: 'preset_number',
align: 'center',
width: 100,
operator: 'RANGE',
},
{
label: t('game.period.result_number'),
prop: 'result_number',
align: 'center',
width: 100,
operator: 'RANGE',
},
{
label: t('game.period.void_reason'),
prop: 'void_reason',
align: 'center',
minWidth: 140,
operatorPlaceholder: t('Fuzzy query'),
operator: 'LIKE',
showOverflowTooltip: true,
},
{
label: t('game.period.create_time'),
prop: 'create_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 170,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{
label: t('game.period.update_time'),
prop: 'update_time',
align: 'center',
render: 'datetime',
operator: 'RANGE',
comSearchRender: 'datetime',
sortable: 'custom',
width: 170,
timeFormat: 'yyyy-mm-dd hh:MM:ss',
},
{ label: t('Operate'), align: 'center', width: 100, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
],
dblClickNotEditColumn: [undefined],
},
{
defaultItems: {
status: 0,
draw_mode: 0,
void_reason: '',
},
}
)
provide('baTable', baTable)
async function loadPeriodSettings() {
if (!canSettings.value) {
return
}
settingsLoading.value = true
try {
const res = await createAxios({
url: '/admin/game.Period/periodSettings',
method: 'get',
showCodeMessage: false,
})
if (res.code === 1 && res.data) {
autoCreate.value = res.data.period_auto_create_enabled === 1
manualCreate.value = res.data.period_manual_create_enabled === 1
settingsReady.value = true
}
} catch {
// 无权限或接口异常时不打断列表
} finally {
settingsLoading.value = false
}
}
async function onSaveSettings() {
if (!canSettings.value) {
return
}
settingsSaving.value = true
try {
await createAxios({
url: '/admin/game.Period/periodSettings',
method: 'post',
data: {
period_auto_create_enabled: autoCreate.value ? 1 : 0,
period_manual_create_enabled: manualCreate.value ? 1 : 0,
},
showSuccessMessage: true,
})
} finally {
settingsSaving.value = false
}
}
function onSwitchChange() {
if (!settingsReady.value) {
return
}
void onSaveSettings()
}
async function onCreateNextManual() {
if (!canManual.value) {
return
}
createLoading.value = true
try {
await createAxios({
url: '/admin/game.Period/createNextManual',
method: 'post',
showSuccessMessage: true,
})
await baTable.getData()
} finally {
createLoading.value = false
}
}
onMounted(() => {
baTable.table.ref = tableRef.value
baTable.mount()
void loadPeriodSettings()
baTable.getData()?.then(() => {
baTable.initSort()
baTable.dragSort()
})
})
</script>
<style scoped lang="scss">
.period-settings-card {
margin-bottom: 12px;
}
.period-settings-body {
display: flex;
flex-direction: column;
gap: 12px;
}
.period-setting-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
}
.period-setting-label {
min-width: 160px;
font-weight: 500;
}
.period-setting-tip {
color: var(--el-text-color-secondary);
font-size: 13px;
flex: 1;
min-width: 200px;
}
.period-setting-actions {
margin-top: 4px;
}
</style>

View File

@@ -1,131 +0,0 @@
<template>
<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('game.period.period_no')"
type="string"
v-model="baTable.form.items!.period_no"
prop="period_no"
:placeholder="t('Please input field', { field: t('game.period.period_no') })"
/>
<FormItem
:label="t('game.period.period_start_at')"
type="datetime"
v-model="baTable.form.items!.period_start_at"
prop="period_start_at"
:placeholder="t('Please select field', { field: t('game.period.period_start_at') })"
/>
<FormItem
:label="t('game.period.status')"
type="radio"
v-model="baTable.form.items!.status"
prop="status"
:input-attr="{
content: {
'0': t('game.period.status 0'),
'1': t('game.period.status 1'),
'2': t('game.period.status 2'),
'3': t('game.period.status 3'),
'4': t('game.period.status 4'),
'5': t('game.period.status 5'),
},
}"
/>
<FormItem
:label="t('game.period.draw_mode')"
type="radio"
v-model="baTable.form.items!.draw_mode"
prop="draw_mode"
:input-attr="{
content: {
'0': t('game.period.draw_mode 0'),
'1': t('game.period.draw_mode 1'),
},
}"
/>
<FormItem
:label="t('game.period.preset_number')"
type="number"
v-model="baTable.form.items!.preset_number"
prop="preset_number"
:input-attr="{ step: 1, min: 1, max: 36 }"
/>
<FormItem
:label="t('game.period.result_number')"
type="number"
v-model="baTable.form.items!.result_number"
prop="result_number"
:input-attr="{ step: 1, min: 1, max: 36 }"
/>
<FormItem
:label="t('game.period.void_reason')"
type="textarea"
v-model="baTable.form.items!.void_reason"
prop="void_reason"
:input-attr="{ rows: 3 }"
/>
</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'
const config = useConfig()
const formRef = useTemplateRef('formRef')
const baTable = inject('baTable') as baTableClass
const { t } = useI18n()
const rules: Partial<Record<string, FormItemRule[]>> = reactive({
period_no: [buildRequired()],
})
function buildRequired(): FormItemRule {
return {
required: true,
message: t('Please input field', { field: t('game.period.period_no') }),
}
}
</script>
<style scoped lang="scss"></style>

View File

@@ -31,6 +31,13 @@ const { t } = useI18n()
const tableRef = useTemplateRef('tableRef') const tableRef = useTemplateRef('tableRef')
const optButtons: OptButton[] = defaultOptButtons(['edit']) const optButtons: OptButton[] = defaultOptButtons(['edit'])
const formatCoin = (_row: any, _column: any, cellValue: number | string | null | undefined) => {
if (cellValue === null || cellValue === undefined || cellValue === '') return '—'
const n = Number(cellValue)
if (Number.isNaN(n)) return '—'
return n.toFixed(4)
}
const baTable = new baTableClass( const baTable = new baTableClass(
new baTableApi('/admin/game.Record/'), new baTableApi('/admin/game.Record/'),
{ {
@@ -63,6 +70,23 @@ const baTable = new baTableClass(
}, },
{ label: t('game.record.preset_number'), prop: 'preset_number', align: 'center', width: 100, operator: 'RANGE' }, { label: t('game.record.preset_number'), prop: 'preset_number', align: 'center', width: 100, operator: 'RANGE' },
{ label: t('game.record.result_number'), prop: 'result_number', align: 'center', width: 100, operator: 'RANGE' }, { label: t('game.record.result_number'), prop: 'result_number', align: 'center', width: 100, operator: 'RANGE' },
{
label: t('game.record.platform_profit_amount'),
prop: 'platform_profit_amount',
align: 'center',
minWidth: 130,
operator: 'RANGE',
sortable: false,
formatter: formatCoin,
},
{
label: t('game.record.winner_user_count'),
prop: 'winner_user_count',
align: 'center',
width: 110,
operator: 'RANGE',
sortable: false,
},
{ label: t('game.record.void_reason'), prop: 'void_reason', align: 'center', minWidth: 140, operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', showOverflowTooltip: true }, { label: t('game.record.void_reason'), prop: 'void_reason', align: 'center', minWidth: 140, operatorPlaceholder: t('Fuzzy query'), operator: 'LIKE', showOverflowTooltip: true },
{ label: t('game.record.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', comSearchRender: 'datetime', sortable: 'custom', width: 170, timeFormat: 'yyyy-mm-dd hh:MM:ss' }, { label: t('game.record.create_time'), prop: 'create_time', align: 'center', render: 'datetime', operator: 'RANGE', comSearchRender: 'datetime', sortable: 'custom', width: 170, timeFormat: 'yyyy-mm-dd hh:MM:ss' },
{ label: t('game.record.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', comSearchRender: 'datetime', sortable: 'custom', width: 170, timeFormat: 'yyyy-mm-dd hh:MM:ss' }, { label: t('game.record.update_time'), prop: 'update_time', align: 'center', render: 'datetime', operator: 'RANGE', comSearchRender: 'datetime', sortable: 'custom', width: 170, timeFormat: 'yyyy-mm-dd hh:MM:ss' },

View File

@@ -26,6 +26,8 @@
/> />
<FormItem :label="t('game.record.preset_number')" type="number" v-model="baTable.form.items!.preset_number" prop="preset_number" :input-attr="{ step: 1, min: 1, max: 36 }" /> <FormItem :label="t('game.record.preset_number')" type="number" v-model="baTable.form.items!.preset_number" prop="preset_number" :input-attr="{ step: 1, min: 1, max: 36 }" />
<FormItem :label="t('game.record.result_number')" type="number" v-model="baTable.form.items!.result_number" prop="result_number" :input-attr="{ step: 1, min: 1, max: 36 }" /> <FormItem :label="t('game.record.result_number')" type="number" v-model="baTable.form.items!.result_number" prop="result_number" :input-attr="{ step: 1, min: 1, max: 36 }" />
<FormItem :label="t('game.record.platform_profit_amount')" type="string" v-model="baTable.form.items!.platform_profit_amount" prop="platform_profit_amount" />
<FormItem :label="t('game.record.winner_user_count')" type="number" v-model="baTable.form.items!.winner_user_count" prop="winner_user_count" :input-attr="{ step: 1, min: 0 }" />
<FormItem :label="t('game.record.void_reason')" type="textarea" v-model="baTable.form.items!.void_reason" prop="void_reason" :input-attr="{ rows: 3 }" /> <FormItem :label="t('game.record.void_reason')" type="textarea" v-model="baTable.form.items!.void_reason" prop="void_reason" :input-attr="{ rows: 3 }" />
</el-form> </el-form>
</div> </div>

View File

@@ -66,9 +66,8 @@ const baTable = new baTableClass(
align: 'center', align: 'center',
width: 100, width: 100,
operator: 'eq', operator: 'eq',
render: 'tag', sortable: false,
effect: 'dark', render: 'switch',
custom: { 0: 'info', 1: 'success' },
replaceValue: { replaceValue: {
'0': t('operation.operationNotice.status 0'), '0': t('operation.operationNotice.status 0'),
'1': t('operation.operationNotice.status 1'), '1': t('operation.operationNotice.status 1'),
@@ -109,6 +108,7 @@ const baTable = new baTableClass(
}, },
{ label: t('Operate'), align: 'center', minWidth: 80, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' }, { label: t('Operate'), align: 'center', minWidth: 80, render: 'buttons', buttons: optButtons, operator: false, fixed: 'right' },
], ],
dblClickNotEditColumn: [undefined, 'status'],
}, },
{ {
defaultItems: { status: 0, notice_type: 0 }, defaultItems: { status: 0, notice_type: 0 },

View File

@@ -58,23 +58,30 @@ const baTable = new baTableClass(
pk: 'id', pk: 'id',
column: [ column: [
{ label: t('order.betOrder.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' }, { label: t('order.betOrder.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' },
{ label: t('order.betOrder.period_id'), prop: 'period_id', align: 'center', width: 100, operator: 'RANGE' },
{ {
label: t('order.betOrder.period_no'), label: t('order.betOrder.period_id'),
prop: 'period_no', prop: 'period_id',
align: 'center', align: 'center',
minWidth: 160, show: false,
operatorPlaceholder: t('Fuzzy query'), width: 100,
operator: 'LIKE', operator: 'RANGE',
}, },
// {
// label: t('order.betOrder.period_no'),
// prop: 'period_no',
// align: 'center',
// minWidth: 160,
// operatorPlaceholder: t('Fuzzy query'),
// operator: 'LIKE',
// },
{ {
label: t('order.betOrder.gameRecord_period_no'), label: t('order.betOrder.gameRecord_period_no'),
prop: 'gameRecord.period_no', prop: 'gameRecord.period_no',
align: 'center', align: 'center',
minWidth: 160, minWidth: 200,
operatorPlaceholder: t('Fuzzy query'), operatorPlaceholder: t('Fuzzy query'),
operator: 'LIKE', operator: 'LIKE',
render: 'tags', render: 'tag',
}, },
{ {
label: t('order.betOrder.gameRecord_status'), label: t('order.betOrder.gameRecord_status'),

View File

@@ -75,9 +75,9 @@ const baTable = new baTableClass(
label: t('State'), label: t('State'),
prop: 'status', prop: 'status',
align: 'center', align: 'center',
render: 'tag', operator: 'eq',
effect: 'dark', sortable: false,
custom: { 0: 'danger', 1: 'success' }, render: 'switch',
replaceValue: { 0: t('Disable'), 1: t('security.dataRecycle.Deleting monitoring') }, replaceValue: { 0: t('Disable'), 1: t('security.dataRecycle.Deleting monitoring') },
}, },
{ label: t('Update time'), prop: 'update_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 }, { label: t('Update time'), prop: 'update_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },

View File

@@ -84,9 +84,9 @@ const baTable = new sensitiveDataClass(
label: t('State'), label: t('State'),
prop: 'status', prop: 'status',
align: 'center', align: 'center',
render: 'tag', operator: 'eq',
effect: 'dark', sortable: false,
custom: { 0: 'danger', 1: 'success' }, render: 'switch',
replaceValue: { 0: t('Disable'), 1: t('security.sensitiveData.Modifying monitoring') }, replaceValue: { 0: t('Disable'), 1: t('security.sensitiveData.Modifying monitoring') },
}, },
{ label: t('Update time'), prop: 'update_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 }, { label: t('Update time'), prop: 'update_time', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
@@ -101,7 +101,7 @@ const baTable = new sensitiveDataClass(
fixed: 'right', fixed: 'right',
}, },
], ],
dblClickNotEditColumn: [undefined], dblClickNotEditColumn: [undefined, 'status'],
}, },
{ {
defaultItems: { defaultItems: {

View File

@@ -1,10 +1,10 @@
<template> <template>
<div class="default-main ba-table-box"> <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 /> <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info" show-icon />
<TableHeader <TableHeader
:buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']" :buttons="['refresh', 'comSearch', 'quickSearch', 'columnDisplay']"
:quick-search-placeholder="t('Quick search placeholder', { fields: t('record.userWalletRecord.quick Search Fields') })" :quick-search-placeholder="t('Quick search placeholder', { fields: t('user.userWalletRecord.quick Search Fields') })"
></TableHeader> ></TableHeader>
<Table ref="tableRef"></Table> <Table ref="tableRef"></Table>
@@ -20,7 +20,7 @@ import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable' import baTableClass from '/@/utils/baTable'
defineOptions({ defineOptions({
name: 'record/userWalletRecord', name: 'user/userWalletRecord',
}) })
const { t } = useI18n() const { t } = useI18n()
@@ -39,19 +39,19 @@ function formatAmount(_row: anyObj, _column: any, cellValue: unknown) {
} }
const bizReplace = { const bizReplace = {
deposit: t('record.userWalletRecord.biz deposit'), deposit: t('user.userWalletRecord.biz deposit'),
withdraw: t('record.userWalletRecord.biz withdraw'), withdraw: t('user.userWalletRecord.biz withdraw'),
withdraw_freeze: t('record.userWalletRecord.biz withdraw_freeze'), withdraw_freeze: t('user.userWalletRecord.biz withdraw_freeze'),
withdraw_unfreeze: t('record.userWalletRecord.biz withdraw_unfreeze'), withdraw_unfreeze: t('user.userWalletRecord.biz withdraw_unfreeze'),
platform_in: t('record.userWalletRecord.biz platform_in'), platform_in: t('user.userWalletRecord.biz platform_in'),
platform_out: t('record.userWalletRecord.biz platform_out'), platform_out: t('user.userWalletRecord.biz platform_out'),
admin_credit: t('record.userWalletRecord.biz admin_credit'), admin_credit: t('user.userWalletRecord.biz admin_credit'),
admin_deduct: t('record.userWalletRecord.biz admin_deduct'), admin_deduct: t('user.userWalletRecord.biz admin_deduct'),
bet: t('record.userWalletRecord.biz bet'), bet: t('user.userWalletRecord.biz bet'),
payout: t('record.userWalletRecord.biz payout'), payout: t('user.userWalletRecord.biz payout'),
fee: t('record.userWalletRecord.biz fee'), fee: t('user.userWalletRecord.biz fee'),
void_refund: t('record.userWalletRecord.biz void_refund'), void_refund: t('user.userWalletRecord.biz void_refund'),
adjust: t('record.userWalletRecord.biz adjust'), adjust: t('user.userWalletRecord.biz adjust'),
} }
const bizTypeTagCustom = { const bizTypeTagCustom = {
@@ -71,18 +71,18 @@ const bizTypeTagCustom = {
} }
const dirReplace = { const dirReplace = {
'1': t('record.userWalletRecord.direction in'), '1': t('user.userWalletRecord.direction in'),
'2': t('record.userWalletRecord.direction out'), '2': t('user.userWalletRecord.direction out'),
} }
const baTable = new baTableClass( const baTable = new baTableClass(
new baTableApi('/admin/record.UserWalletRecord/'), new baTableApi('/admin/user.UserWalletRecord/'),
{ {
pk: 'id', pk: 'id',
column: [ column: [
{ label: t('record.userWalletRecord.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' }, { label: t('user.userWalletRecord.id'), prop: 'id', align: 'center', width: 100, operator: 'RANGE', sortable: 'custom' },
{ {
label: t('record.userWalletRecord.user_id'), label: t('user.userWalletRecord.user_id'),
prop: 'user_id', prop: 'user_id',
align: 'center', align: 'center',
width: 90, width: 90,
@@ -91,7 +91,7 @@ const baTable = new baTableClass(
sortable: false, sortable: false,
}, },
{ {
label: t('record.userWalletRecord.user__username'), label: t('user.userWalletRecord.user__username'),
prop: 'user.username', prop: 'user.username',
align: 'center', align: 'center',
minWidth: 110, minWidth: 110,
@@ -101,7 +101,7 @@ const baTable = new baTableClass(
comSearchRender: 'string', comSearchRender: 'string',
}, },
{ {
label: t('record.userWalletRecord.channel__name'), label: t('user.userWalletRecord.channel__name'),
prop: 'channel.name', prop: 'channel.name',
align: 'center', align: 'center',
minWidth: 100, minWidth: 100,
@@ -111,7 +111,7 @@ const baTable = new baTableClass(
comSearchRender: 'string', comSearchRender: 'string',
}, },
{ {
label: t('record.userWalletRecord.biz_type'), label: t('user.userWalletRecord.biz_type'),
prop: 'biz_type', prop: 'biz_type',
align: 'center', align: 'center',
minWidth: 120, minWidth: 120,
@@ -121,7 +121,7 @@ const baTable = new baTableClass(
replaceValue: bizReplace, replaceValue: bizReplace,
}, },
{ {
label: t('record.userWalletRecord.direction'), label: t('user.userWalletRecord.direction'),
prop: 'direction', prop: 'direction',
align: 'center', align: 'center',
width: 90, width: 90,
@@ -134,7 +134,7 @@ const baTable = new baTableClass(
replaceValue: dirReplace, replaceValue: dirReplace,
}, },
{ {
label: t('record.userWalletRecord.amount'), label: t('user.userWalletRecord.amount'),
prop: 'amount', prop: 'amount',
align: 'center', align: 'center',
minWidth: 110, minWidth: 110,
@@ -142,7 +142,7 @@ const baTable = new baTableClass(
formatter: formatAmount, formatter: formatAmount,
}, },
{ {
label: t('record.userWalletRecord.balance_before'), label: t('user.userWalletRecord.balance_before'),
prop: 'balance_before', prop: 'balance_before',
align: 'center', align: 'center',
minWidth: 110, minWidth: 110,
@@ -150,7 +150,7 @@ const baTable = new baTableClass(
formatter: formatAmount, formatter: formatAmount,
}, },
{ {
label: t('record.userWalletRecord.balance_after'), label: t('user.userWalletRecord.balance_after'),
prop: 'balance_after', prop: 'balance_after',
align: 'center', align: 'center',
minWidth: 110, minWidth: 110,
@@ -158,16 +158,16 @@ const baTable = new baTableClass(
formatter: formatAmount, formatter: formatAmount,
}, },
{ {
label: t('record.userWalletRecord.ref_type'), label: t('user.userWalletRecord.ref_type'),
prop: 'ref_type', prop: 'ref_type',
align: 'center', align: 'center',
minWidth: 100, minWidth: 100,
showOverflowTooltip: true, showOverflowTooltip: true,
operator: 'LIKE', operator: 'LIKE',
}, },
{ label: t('record.userWalletRecord.ref_id'), prop: 'ref_id', align: 'center', width: 100, operator: 'RANGE' }, { label: t('user.userWalletRecord.ref_id'), prop: 'ref_id', align: 'center', width: 100, operator: 'RANGE' },
{ {
label: t('record.userWalletRecord.idempotency_key'), label: t('user.userWalletRecord.idempotency_key'),
prop: 'idempotency_key', prop: 'idempotency_key',
align: 'center', align: 'center',
minWidth: 120, minWidth: 120,
@@ -175,7 +175,7 @@ const baTable = new baTableClass(
operator: 'LIKE', operator: 'LIKE',
}, },
{ {
label: t('record.userWalletRecord.operator_admin__username'), label: t('user.userWalletRecord.operator_admin__username'),
prop: 'operatorAdmin.username', prop: 'operatorAdmin.username',
align: 'center', align: 'center',
minWidth: 100, minWidth: 100,
@@ -185,7 +185,7 @@ const baTable = new baTableClass(
comSearchRender: 'string', comSearchRender: 'string',
}, },
{ {
label: t('record.userWalletRecord.remark'), label: t('user.userWalletRecord.remark'),
prop: 'remark', prop: 'remark',
align: 'center', align: 'center',
minWidth: 140, minWidth: 140,
@@ -193,7 +193,7 @@ const baTable = new baTableClass(
operator: 'LIKE', operator: 'LIKE',
}, },
{ {
label: t('record.userWalletRecord.create_time'), label: t('user.userWalletRecord.create_time'),
prop: 'create_time', prop: 'create_time',
align: 'center', align: 'center',
render: 'datetime', render: 'datetime',