feat: 管理端 RBAC 权限体系与员工管理
新增多角色权限控制(赛事/财务/客服管理员),支持员工 CRUD、路由菜单按权限显隐、审计日志范围过滤;登录返回角色与权限列表。玩家端赛事列表增加静默刷新避免图片闪烁。Seed 补充演示员工账号与充值相关权限。附带 RBAC/审计范围单元测试及 UAT 文档更新。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -13,10 +13,20 @@ withDefaults(
|
||||
row: PlayerActionRow;
|
||||
showDetail?: boolean;
|
||||
showLedger?: boolean;
|
||||
showEdit?: boolean;
|
||||
showDeposit?: boolean;
|
||||
showWithdraw?: boolean;
|
||||
showFreeze?: boolean;
|
||||
showDelete?: boolean;
|
||||
}>(),
|
||||
{
|
||||
showDetail: true,
|
||||
showLedger: true,
|
||||
showEdit: true,
|
||||
showDeposit: true,
|
||||
showWithdraw: true,
|
||||
showFreeze: true,
|
||||
showDelete: true,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -42,13 +52,13 @@ const { t } = useAdminLocale();
|
||||
<el-button v-if="showLedger" link type="primary" size="small" @click="emit('ledger')">
|
||||
{{ t('user.action.ledger_short') }}
|
||||
</el-button>
|
||||
<el-button link type="primary" size="small" @click="emit('edit')">{{ t('common.edit') }}</el-button>
|
||||
<el-button link type="success" size="small" @click="emit('deposit')">{{ t('common.topup') }}</el-button>
|
||||
<el-button link type="warning" size="small" @click="emit('withdraw')">
|
||||
<el-button v-if="showEdit" link type="primary" size="small" @click="emit('edit')">{{ t('common.edit') }}</el-button>
|
||||
<el-button v-if="showDeposit" link type="success" size="small" @click="emit('deposit')">{{ t('common.topup') }}</el-button>
|
||||
<el-button v-if="showWithdraw" link type="warning" size="small" @click="emit('withdraw')">
|
||||
{{ t('agent_portal.withdraw_btn_label') }}
|
||||
</el-button>
|
||||
<el-button
|
||||
v-if="row.status === 'ACTIVE'"
|
||||
v-if="showFreeze && row.status === 'ACTIVE'"
|
||||
link
|
||||
type="warning"
|
||||
size="small"
|
||||
@@ -56,26 +66,26 @@ const { t } = useAdminLocale();
|
||||
>
|
||||
{{ t('common.freeze') }}
|
||||
</el-button>
|
||||
<el-button v-else link type="primary" size="small" @click="emit('freeze')">
|
||||
<el-button v-else-if="showFreeze" link type="primary" size="small" @click="emit('freeze')">
|
||||
{{ t('common.unfreeze') }}
|
||||
</el-button>
|
||||
<el-button link type="danger" size="small" @click="emit('delete')">
|
||||
<el-button v-if="showDelete" link type="danger" size="small" @click="emit('delete')">
|
||||
{{ t('common.delete') }}
|
||||
</el-button>
|
||||
</template>
|
||||
<template #menu>
|
||||
<el-dropdown-item v-if="showDetail" @click="emit('detail')">{{ t('common.detail') }}</el-dropdown-item>
|
||||
<el-dropdown-item v-if="showLedger" @click="emit('ledger')">{{ t('user.action.view_wallet_ledger') }}</el-dropdown-item>
|
||||
<el-dropdown-item @click="emit('edit')">{{ t('common.edit') }}</el-dropdown-item>
|
||||
<el-dropdown-item divided @click="emit('deposit')">{{ t('common.topup') }}</el-dropdown-item>
|
||||
<el-dropdown-item @click="emit('withdraw')">
|
||||
<el-dropdown-item v-if="showEdit" @click="emit('edit')">{{ t('common.edit') }}</el-dropdown-item>
|
||||
<el-dropdown-item v-if="showDeposit" divided @click="emit('deposit')">{{ t('common.topup') }}</el-dropdown-item>
|
||||
<el-dropdown-item v-if="showWithdraw" @click="emit('withdraw')">
|
||||
<span class="action-warning">{{ t('agent_portal.withdraw_btn_label') }}</span>
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item v-if="row.status === 'ACTIVE'" @click="emit('freeze')">
|
||||
<el-dropdown-item v-if="showFreeze && row.status === 'ACTIVE'" @click="emit('freeze')">
|
||||
<span class="action-warning">{{ t('common.freeze') }}</span>
|
||||
</el-dropdown-item>
|
||||
<el-dropdown-item v-else @click="emit('freeze')">{{ t('common.unfreeze') }}</el-dropdown-item>
|
||||
<el-dropdown-item divided @click="emit('delete')">
|
||||
<el-dropdown-item v-else-if="showFreeze" @click="emit('freeze')">{{ t('common.unfreeze') }}</el-dropdown-item>
|
||||
<el-dropdown-item v-if="showDelete" divided @click="emit('delete')">
|
||||
<span class="action-danger">{{ t('common.delete') }}</span>
|
||||
</el-dropdown-item>
|
||||
</template>
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
import { RouterLink, useRoute } from 'vue-router';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
|
||||
const { t } = useAdminLocale();
|
||||
const route = useRoute();
|
||||
const { hasPermission, role } = usePermissions();
|
||||
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
@@ -12,10 +16,21 @@ withDefaults(
|
||||
{ embedded: false },
|
||||
);
|
||||
|
||||
const tabs = [
|
||||
{ path: '/', labelKey: 'nav.dashboard.matches' },
|
||||
{ path: '/dashboard/players', labelKey: 'nav.dashboard.players' },
|
||||
];
|
||||
const tabs = computed(() => {
|
||||
const list: { path: string; labelKey: string }[] = [];
|
||||
const code = role.value;
|
||||
if (code === 'SUPPORT') return list;
|
||||
if (hasPermission(AdminPerm.matches)) {
|
||||
list.push({ path: '/', labelKey: 'nav.dashboard.matches' });
|
||||
}
|
||||
if (
|
||||
hasPermission(AdminPerm.reports) &&
|
||||
(code === 'FINANCE_ADMIN' || code === 'SUPER_ADMIN' || list.length === 0)
|
||||
) {
|
||||
list.push({ path: '/dashboard/players', labelKey: 'nav.dashboard.players' });
|
||||
}
|
||||
return list;
|
||||
});
|
||||
|
||||
function isActive(path: string) {
|
||||
if (path === '/dashboard/players') {
|
||||
@@ -27,6 +42,7 @@ function isActive(path: string) {
|
||||
|
||||
<template>
|
||||
<nav
|
||||
v-if="tabs.length > 1"
|
||||
class="dashboard-subnav"
|
||||
:class="{ 'dashboard-subnav--embedded': embedded }"
|
||||
aria-label="Dashboard sections"
|
||||
|
||||
43
apps/admin/src/composables/usePermissions.ts
Normal file
43
apps/admin/src/composables/usePermissions.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { computed } from 'vue';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { effectivePermissions } from '../utils/admin-access';
|
||||
|
||||
export function usePermissions() {
|
||||
const auth = useAuthStore();
|
||||
|
||||
const role = computed(() => auth.user.value?.role ?? null);
|
||||
const permissions = computed(() =>
|
||||
effectivePermissions(auth.user.value?.role, auth.user.value?.permissions),
|
||||
);
|
||||
const isSuperAdmin = computed(() => role.value === 'SUPER_ADMIN');
|
||||
|
||||
function hasPermission(...codes: string[]): boolean {
|
||||
if (!auth.isAdmin.value) return false;
|
||||
if (isSuperAdmin.value) return true;
|
||||
const set = permissions.value;
|
||||
return codes.some((c) => set.includes(c));
|
||||
}
|
||||
|
||||
function hasAllPermissions(...codes: string[]): boolean {
|
||||
if (!auth.isAdmin.value) return false;
|
||||
if (isSuperAdmin.value) return true;
|
||||
const set = permissions.value;
|
||||
return codes.every((c) => set.includes(c));
|
||||
}
|
||||
|
||||
function firstAllowedPath(candidates: { path: string; permissions: string[] }[]): string | null {
|
||||
for (const item of candidates) {
|
||||
if (hasPermission(...item.permissions)) return item.path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
role,
|
||||
permissions,
|
||||
isSuperAdmin,
|
||||
hasPermission,
|
||||
hasAllPermissions,
|
||||
firstAllowedPath,
|
||||
};
|
||||
}
|
||||
24
apps/admin/src/constants/permissions.ts
Normal file
24
apps/admin/src/constants/permissions.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 与 API seed / admin-permissions 一致 */
|
||||
export const AdminPerm = {
|
||||
reports: 'reports.view',
|
||||
usersView: 'users.view',
|
||||
usersCreate: 'users.create',
|
||||
usersResetPassword: 'users.reset_password',
|
||||
settings: 'settings.manage',
|
||||
agentsView: 'agents.view',
|
||||
agentsCreate: 'agents.create',
|
||||
agentsCredit: 'agents.credit',
|
||||
walletDeposit: 'wallet.deposit',
|
||||
walletWithdraw: 'wallet.withdraw',
|
||||
matches: 'matches.manage',
|
||||
settlement: 'settlement.confirm',
|
||||
resettle: 'settlement.resettle',
|
||||
bets: 'bets.view',
|
||||
cashback: 'cashback.confirm',
|
||||
content: 'content.manage',
|
||||
audit: 'audit.view',
|
||||
depositManage: 'deposit.manage',
|
||||
depositReview: 'deposit.review',
|
||||
} as const;
|
||||
|
||||
export type AdminPermission = (typeof AdminPerm)[keyof typeof AdminPerm];
|
||||
@@ -27,6 +27,14 @@ const zh: Record<string, string> = {
|
||||
'login.quick_admin': '管理员',
|
||||
'login.quick_agent': '一级代理',
|
||||
'login.quick_agent2': '二级代理',
|
||||
'login.quick_match_admin': '赛事管理员',
|
||||
'login.quick_finance_admin': '财务管理员',
|
||||
'login.quick_support': '客服查询员',
|
||||
'staff.create_btn': '创建后台账号',
|
||||
'staff.col.role': '角色',
|
||||
'staff.col.last_login': '最近登录',
|
||||
'staff.dialog.create': '创建后台账号',
|
||||
'staff.dialog.edit': '编辑后台账号',
|
||||
'login.captcha_ph': '验证码',
|
||||
'login.captcha_refresh': '点击刷新',
|
||||
|
||||
@@ -50,6 +58,7 @@ const zh: Record<string, string> = {
|
||||
'nav.payment_methods': '收款方式',
|
||||
'nav.deposit_orders': '充值审核',
|
||||
'nav.deposit_manage': '充值管理',
|
||||
'nav.staff': '后台账号',
|
||||
'nav.players': '直属玩家',
|
||||
|
||||
'deposit.payment_methods_title': '收款方式管理',
|
||||
@@ -132,6 +141,10 @@ const zh: Record<string, string> = {
|
||||
'breadcrumb.match_markets': '盘口管理',
|
||||
'breadcrumb.outright_edit': '编辑优胜冠军',
|
||||
'role.admin': '系统管理员',
|
||||
'role.super_admin': '超级管理员',
|
||||
'role.match_admin': '赛事管理员',
|
||||
'role.finance_admin': '财务管理员',
|
||||
'role.support': '客服查询员',
|
||||
'role.agent': '代理账号',
|
||||
'role.tier1_agent': '一级代理',
|
||||
'role.tier2_agent': '二级代理',
|
||||
@@ -209,6 +222,8 @@ const zh: Record<string, string> = {
|
||||
'dash.user_direct': '直属',
|
||||
'dash.user_agents': '代理',
|
||||
'dash.section_matches_hint': '投注经营与赛事状态分布',
|
||||
'dash.section_match_ops_hint': '赛事状态与待办',
|
||||
'dash.trend_bet_count_caption': '近 7 日注单量趋势',
|
||||
'dash.section_players_hint': '玩家、代理与资金概况',
|
||||
'dash.kpi_match_total': '赛事总数',
|
||||
'dash.kpi_match_total_sub': '草稿 {draft} · 已发布 {published}',
|
||||
@@ -308,6 +323,14 @@ const en: Record<string, string> = {
|
||||
'login.quick_admin': 'Admin',
|
||||
'login.quick_agent': 'Tier-1 agent',
|
||||
'login.quick_agent2': 'Tier-2 agent',
|
||||
'login.quick_match_admin': 'Match admin',
|
||||
'login.quick_finance_admin': 'Finance admin',
|
||||
'login.quick_support': 'Support',
|
||||
'staff.create_btn': 'Create staff account',
|
||||
'staff.col.role': 'Role',
|
||||
'staff.col.last_login': 'Last login',
|
||||
'staff.dialog.create': 'Create staff account',
|
||||
'staff.dialog.edit': 'Edit staff account',
|
||||
'login.captcha_ph': 'Captcha',
|
||||
'login.captcha_refresh': 'Click to refresh',
|
||||
|
||||
@@ -331,6 +354,7 @@ const en: Record<string, string> = {
|
||||
'nav.payment_methods': 'Payment Methods',
|
||||
'nav.deposit_orders': 'Deposit Review',
|
||||
'nav.deposit_manage': 'Deposit Mgmt',
|
||||
'nav.staff': 'Staff accounts',
|
||||
'nav.players': 'My Players',
|
||||
'nav.subAgents': 'Tier-2 agents',
|
||||
'nav.myBets': 'Bet Search',
|
||||
@@ -413,6 +437,10 @@ const en: Record<string, string> = {
|
||||
'breadcrumb.match_markets': 'Markets',
|
||||
'breadcrumb.outright_edit': 'Edit outright',
|
||||
'role.admin': 'Administrator',
|
||||
'role.super_admin': 'Super admin',
|
||||
'role.match_admin': 'Match admin',
|
||||
'role.finance_admin': 'Finance admin',
|
||||
'role.support': 'Support',
|
||||
'role.agent': 'Agent',
|
||||
'role.tier1_agent': 'Tier-1 Agent',
|
||||
'role.tier2_agent': 'Tier-2 Agent',
|
||||
@@ -490,6 +518,8 @@ const en: Record<string, string> = {
|
||||
'dash.user_direct': 'Direct',
|
||||
'dash.user_agents': 'Agents',
|
||||
'dash.section_matches_hint': 'Betting performance and match distribution',
|
||||
'dash.section_match_ops_hint': 'Match status and pending work',
|
||||
'dash.trend_bet_count_caption': '7-day bet volume trend',
|
||||
'dash.section_players_hint': 'Players, agents, and wallet summary',
|
||||
'dash.kpi_match_total': 'Total matches',
|
||||
'dash.kpi_match_total_sub': 'Draft {draft} · Published {published}',
|
||||
@@ -589,6 +619,14 @@ const ms: Record<string, string> = {
|
||||
'login.quick_admin': 'Admin',
|
||||
'login.quick_agent': 'Ejen peringkat 1',
|
||||
'login.quick_agent2': 'Ejen peringkat 2',
|
||||
'login.quick_match_admin': 'Pentadbir perlawanan',
|
||||
'login.quick_finance_admin': 'Pentadbir kewangan',
|
||||
'login.quick_support': 'Sokongan',
|
||||
'staff.create_btn': 'Cipta akaun kakitangan',
|
||||
'staff.col.role': 'Peranan',
|
||||
'staff.col.last_login': 'Log masuk terakhir',
|
||||
'staff.dialog.create': 'Cipta akaun kakitangan',
|
||||
'staff.dialog.edit': 'Edit akaun kakitangan',
|
||||
'login.captcha_ph': 'Captcha',
|
||||
'login.captcha_refresh': 'Klik untuk muat semula',
|
||||
|
||||
@@ -612,6 +650,7 @@ const ms: Record<string, string> = {
|
||||
'nav.payment_methods': 'Kaedah Pembayaran',
|
||||
'nav.deposit_orders': 'Semakan Deposit',
|
||||
'nav.deposit_manage': 'Urus Deposit',
|
||||
'nav.staff': 'Akaun kakitangan',
|
||||
'nav.players': 'Pemain saya',
|
||||
'nav.subAgents': 'Ejen peringkat 2',
|
||||
'nav.myBets': 'Carian pertaruhan',
|
||||
@@ -694,6 +733,10 @@ const ms: Record<string, string> = {
|
||||
'breadcrumb.match_markets': 'Pasaran',
|
||||
'breadcrumb.outright_edit': 'Edit juara',
|
||||
'role.admin': 'Pentadbir',
|
||||
'role.super_admin': 'Super pentadbir',
|
||||
'role.match_admin': 'Pentadbir perlawanan',
|
||||
'role.finance_admin': 'Pentadbir kewangan',
|
||||
'role.support': 'Sokongan',
|
||||
'role.agent': 'Ejen',
|
||||
'role.tier1_agent': 'Ejen Peringkat 1',
|
||||
'role.tier2_agent': 'Ejen Peringkat 2',
|
||||
@@ -771,6 +814,8 @@ const ms: Record<string, string> = {
|
||||
'dash.user_direct': 'Terus',
|
||||
'dash.user_agents': 'Ejen',
|
||||
'dash.section_matches_hint': 'Prestasi pertaruhan dan taburan perlawanan',
|
||||
'dash.section_match_ops_hint': 'Status perlawanan dan tugasan',
|
||||
'dash.trend_bet_count_caption': 'Trend bilangan pertaruhan 7 hari',
|
||||
'dash.section_players_hint': 'Pemain, ejen, dan ringkasan dana',
|
||||
'dash.kpi_match_total': 'Jumlah perlawanan',
|
||||
'dash.kpi_match_total_sub': 'Draf {draft} · Diterbitkan {published}',
|
||||
|
||||
@@ -333,28 +333,42 @@ export const adminPagesMs: Record<string, string> = {
|
||||
'bet.col.result': 'Keputusan',
|
||||
|
||||
'audit.module_ph': 'cth. USERS, AGENTS',
|
||||
'audit.col.time': 'Masa',
|
||||
'audit.col.operator': 'Pengendali',
|
||||
'audit.col.action': 'Tindakan',
|
||||
'audit.col.module': 'Modul',
|
||||
'audit.col.target_id': 'ID sasaran',
|
||||
'audit.col.time': 'Masa',
|
||||
'audit.col.ip': 'IP',
|
||||
'audit.operator_system': 'Sistem',
|
||||
'audit.operator_player': 'Pemain',
|
||||
'audit.action.CREATE_PLAYER': 'Cipta pemain',
|
||||
'audit.action.UPDATE_PLAYER': 'Kemas kini pemain',
|
||||
'audit.action.DELETE_PLAYER': 'Padam pemain',
|
||||
'audit.action.RESET_PLAYER_PASSWORD': 'Set semula kata laluan pemain',
|
||||
'audit.action.RESET_DATABASE': 'Set semula pangkalan data',
|
||||
'audit.action.CREATE_AGENT': 'Cipta ejen',
|
||||
'audit.action.UPDATE_AGENT': 'Kemas kini ejen',
|
||||
'audit.action.UPDATE_PLAYER_ACCOUNT_SETTINGS': 'Kemas kini tetapan akaun pemain',
|
||||
'audit.action.UPDATE_AGENT_SUSPEND_SETTINGS': 'Kemas kini tetapan penggantungan ejen',
|
||||
'audit.action.UPDATE_AGENT_HIERARCHY_SETTINGS': 'Kemas kini tetapan hierarki ejen',
|
||||
'audit.action.UPDATE_BETTING_LIMITS': 'Kemas kini had pertaruhan',
|
||||
'audit.action.CONFIRM_SETTLEMENT': 'Sahkan penyelesaian',
|
||||
'audit.action.CONFIRM_RESETTLE': 'Sahkan penyelesaian semula',
|
||||
'audit.action.CONFIRM_CASHBACK': 'Sahkan bayaran rebat',
|
||||
'audit.action.CANCEL_CASHBACK': 'Batalkan kelompok rebat',
|
||||
'audit.action.CREATE_STAFF': 'Cipta kakitangan',
|
||||
'audit.action.UPDATE_STAFF': 'Kemas kini kakitangan',
|
||||
'audit.action.PURGE_UNUSED_FILES': 'Padam media tidak digunakan',
|
||||
'audit.action.FORGOT_PASSWORD_RESET': 'Pemain set semula kata laluan',
|
||||
'audit.module.USERS': 'Pemain',
|
||||
'audit.module.AGENTS': 'Ejen',
|
||||
'audit.module.SYSTEM': 'Sistem',
|
||||
'audit.module.SETTINGS': 'Tetapan',
|
||||
'audit.module.SETTLEMENT': 'Penyelesaian',
|
||||
'audit.module.CASHBACK': 'Rebat',
|
||||
'audit.module.STAFF': 'Kakitangan',
|
||||
'audit.module.MEDIA': 'Media',
|
||||
'audit.module.identity': 'Identiti',
|
||||
|
||||
'cashback.start_date': 'Tarikh mula',
|
||||
'cashback.end_date': 'Tarikh tamat',
|
||||
|
||||
@@ -355,28 +355,42 @@ export const adminPagesZh: Record<string, string> = {
|
||||
'bet.col.result': '赛果',
|
||||
|
||||
'audit.module_ph': '如 USERS、AGENTS',
|
||||
'audit.col.time': '时间',
|
||||
'audit.col.operator': '操作人',
|
||||
'audit.col.action': '操作',
|
||||
'audit.col.module': '模块',
|
||||
'audit.col.target_id': '目标 ID',
|
||||
'audit.col.time': '时间',
|
||||
'audit.col.ip': 'IP',
|
||||
'audit.operator_system': '系统',
|
||||
'audit.operator_player': '玩家',
|
||||
'audit.action.CREATE_PLAYER': '新建玩家',
|
||||
'audit.action.UPDATE_PLAYER': '更新玩家',
|
||||
'audit.action.DELETE_PLAYER': '删除玩家',
|
||||
'audit.action.RESET_PLAYER_PASSWORD': '重置玩家密码',
|
||||
'audit.action.RESET_DATABASE': '重置数据库',
|
||||
'audit.action.CREATE_AGENT': '新建代理',
|
||||
'audit.action.UPDATE_AGENT': '更新代理',
|
||||
'audit.action.UPDATE_PLAYER_ACCOUNT_SETTINGS': '更新玩家账号设置',
|
||||
'audit.action.UPDATE_AGENT_SUSPEND_SETTINGS': '更新代理停押设置',
|
||||
'audit.action.UPDATE_AGENT_HIERARCHY_SETTINGS': '更新代理层级设置',
|
||||
'audit.action.UPDATE_BETTING_LIMITS': '更新投注限额',
|
||||
'audit.action.CONFIRM_SETTLEMENT': '确认结算',
|
||||
'audit.action.CONFIRM_RESETTLE': '确认重结算',
|
||||
'audit.action.CONFIRM_CASHBACK': '确认发放返水',
|
||||
'audit.action.CANCEL_CASHBACK': '作废返水批次',
|
||||
'audit.action.CREATE_STAFF': '新建后台员工',
|
||||
'audit.action.UPDATE_STAFF': '更新后台员工',
|
||||
'audit.action.PURGE_UNUSED_FILES': '清理未引用媒体',
|
||||
'audit.action.FORGOT_PASSWORD_RESET': '玩家找回密码',
|
||||
'audit.module.USERS': '玩家',
|
||||
'audit.module.AGENTS': '代理',
|
||||
'audit.module.SYSTEM': '系统',
|
||||
'audit.module.SETTINGS': '系统设置',
|
||||
'audit.module.SETTLEMENT': '结算',
|
||||
'audit.module.CASHBACK': '返水',
|
||||
'audit.module.STAFF': '员工管理',
|
||||
'audit.module.MEDIA': '媒体库',
|
||||
'audit.module.identity': '身份认证',
|
||||
|
||||
'cashback.start_date': '开始日期',
|
||||
'cashback.end_date': '结束日期',
|
||||
@@ -1380,28 +1394,42 @@ export const adminPagesEn: Record<string, string> = {
|
||||
'bet.col.result': 'Result',
|
||||
|
||||
'audit.module_ph': 'e.g. USERS, AGENTS',
|
||||
'audit.col.time': 'Time',
|
||||
'audit.col.operator': 'Operator',
|
||||
'audit.col.action': 'Action',
|
||||
'audit.col.module': 'Module',
|
||||
'audit.col.target_id': 'Target ID',
|
||||
'audit.col.time': 'Time',
|
||||
'audit.col.ip': 'IP',
|
||||
'audit.operator_system': 'System',
|
||||
'audit.operator_player': 'Player',
|
||||
'audit.action.CREATE_PLAYER': 'Create player',
|
||||
'audit.action.UPDATE_PLAYER': 'Update player',
|
||||
'audit.action.DELETE_PLAYER': 'Delete player',
|
||||
'audit.action.RESET_PLAYER_PASSWORD': 'Reset player password',
|
||||
'audit.action.RESET_DATABASE': 'Reset database',
|
||||
'audit.action.CREATE_AGENT': 'Create agent',
|
||||
'audit.action.UPDATE_AGENT': 'Update agent',
|
||||
'audit.action.UPDATE_PLAYER_ACCOUNT_SETTINGS': 'Update player account settings',
|
||||
'audit.action.UPDATE_AGENT_SUSPEND_SETTINGS': 'Update agent suspend settings',
|
||||
'audit.action.UPDATE_AGENT_HIERARCHY_SETTINGS': 'Update agent hierarchy settings',
|
||||
'audit.action.UPDATE_BETTING_LIMITS': 'Update betting limits',
|
||||
'audit.action.CONFIRM_SETTLEMENT': 'Confirm settlement',
|
||||
'audit.action.CONFIRM_RESETTLE': 'Confirm resettlement',
|
||||
'audit.action.CONFIRM_CASHBACK': 'Confirm cashback payout',
|
||||
'audit.action.CANCEL_CASHBACK': 'Cancel cashback batch',
|
||||
'audit.action.CREATE_STAFF': 'Create staff account',
|
||||
'audit.action.UPDATE_STAFF': 'Update staff account',
|
||||
'audit.action.PURGE_UNUSED_FILES': 'Purge unused media',
|
||||
'audit.action.FORGOT_PASSWORD_RESET': 'Player forgot-password reset',
|
||||
'audit.module.USERS': 'Players',
|
||||
'audit.module.AGENTS': 'Agents',
|
||||
'audit.module.SYSTEM': 'System',
|
||||
'audit.module.SETTINGS': 'Settings',
|
||||
'audit.module.SETTLEMENT': 'Settlement',
|
||||
'audit.module.CASHBACK': 'Cashback',
|
||||
'audit.module.STAFF': 'Staff',
|
||||
'audit.module.MEDIA': 'Media',
|
||||
'audit.module.identity': 'Identity',
|
||||
|
||||
'cashback.start_date': 'Start date',
|
||||
'cashback.end_date': 'End date',
|
||||
|
||||
@@ -4,6 +4,8 @@ import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { useSmokeTestsAllowed } from '../composables/useSmokeTestsAllowed';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
import AdminLocaleSwitcher from '../components/AdminLocaleSwitcher.vue';
|
||||
import AdminNavIcon from '../components/AdminNavIcon.vue';
|
||||
import { resolveAdminBreadcrumb } from '../utils/admin-breadcrumb';
|
||||
@@ -13,28 +15,44 @@ const router = useRouter();
|
||||
const auth = useAuthStore();
|
||||
const { t } = useAdminLocale();
|
||||
const { allowed: smokeTestsAllowed, ensureLoaded: ensureSmokeTestsAllowed } = useSmokeTestsAllowed();
|
||||
const { hasPermission, role: adminRole } = usePermissions();
|
||||
|
||||
const sidebarOpen = ref(false);
|
||||
const isMobileNav = ref(false);
|
||||
|
||||
type AdminMenuItem = {
|
||||
path: string;
|
||||
label: string;
|
||||
icon: string;
|
||||
matchPrefix?: boolean;
|
||||
permissions: string[];
|
||||
/** Hide for these admin role codes (SUPER_ADMIN is never excluded). */
|
||||
excludeRoles?: string[];
|
||||
};
|
||||
|
||||
function menuVisible(item: AdminMenuItem): boolean {
|
||||
const code = adminRole.value;
|
||||
if (item.path === '/smoke-tests' && smokeTestsAllowed.value === false) return false;
|
||||
if (code && code !== 'SUPER_ADMIN' && item.excludeRoles?.includes(code)) return false;
|
||||
return hasPermission(...item.permissions);
|
||||
}
|
||||
|
||||
const adminMenus = computed(() => {
|
||||
const items = [
|
||||
{ path: '/', label: t('nav.dashboard'), icon: 'dashboard', matchPrefix: true },
|
||||
{ path: '/matches', label: t('nav.matches'), icon: 'matches', matchPrefix: true },
|
||||
{ path: '/users', label: t('nav.agents_players'), icon: 'users' },
|
||||
{ path: '/finance-logs', label: t('nav.finance_logs'), icon: 'finance' },
|
||||
{ path: '/deposit', label: t('nav.deposit_manage'), icon: 'deposit', matchPrefix: true },
|
||||
{ path: '/cashback', label: t('nav.cashback'), icon: 'cashback' },
|
||||
{ path: '/bets', label: t('nav.bets'), icon: 'bets' },
|
||||
{ path: '/contents', label: t('nav.contents'), icon: 'contents' },
|
||||
{ path: '/media', label: t('nav.media'), icon: 'media' },
|
||||
{ path: '/audit', label: t('nav.audit'), icon: 'audit' },
|
||||
{ path: '/smoke-tests', label: t('nav.smoke_tests'), icon: 'smoke-tests' },
|
||||
const items: AdminMenuItem[] = [
|
||||
{ path: '/', label: t('nav.dashboard'), icon: 'dashboard', matchPrefix: true, permissions: [AdminPerm.reports], excludeRoles: ['SUPPORT'] },
|
||||
{ path: '/matches', label: t('nav.matches'), icon: 'matches', matchPrefix: true, permissions: [AdminPerm.matches] },
|
||||
{ path: '/users', label: t('nav.agents_players'), icon: 'users', permissions: [AdminPerm.usersView, AdminPerm.agentsView] },
|
||||
{ path: '/finance-logs', label: t('nav.finance_logs'), icon: 'finance', permissions: [AdminPerm.reports], excludeRoles: ['MATCH_ADMIN'] },
|
||||
{ path: '/deposit', label: t('nav.deposit_manage'), icon: 'deposit', matchPrefix: true, permissions: [AdminPerm.depositManage, AdminPerm.depositReview] },
|
||||
{ path: '/cashback', label: t('nav.cashback'), icon: 'cashback', permissions: [AdminPerm.cashback], excludeRoles: ['MATCH_ADMIN', 'SUPPORT'] },
|
||||
{ path: '/bets', label: t('nav.bets'), icon: 'bets', permissions: [AdminPerm.bets] },
|
||||
{ path: '/contents', label: t('nav.contents'), icon: 'contents', permissions: [AdminPerm.content] },
|
||||
{ path: '/media', label: t('nav.media'), icon: 'media', permissions: [AdminPerm.content, AdminPerm.matches] },
|
||||
{ path: '/audit', label: t('nav.audit'), icon: 'audit', permissions: [AdminPerm.audit] },
|
||||
{ path: '/staff', label: t('nav.staff'), icon: 'users', permissions: [AdminPerm.settings] },
|
||||
{ path: '/smoke-tests', label: t('nav.smoke_tests'), icon: 'smoke-tests', permissions: [AdminPerm.settings] },
|
||||
];
|
||||
if (smokeTestsAllowed.value === false) {
|
||||
return items.filter((item) => item.path !== '/smoke-tests');
|
||||
}
|
||||
return items;
|
||||
return items.filter(menuVisible);
|
||||
});
|
||||
|
||||
const agentMenus = computed(() => [
|
||||
@@ -78,7 +96,14 @@ const currentLabel = computed(() => {
|
||||
const topbarCrumbs = computed(() => resolveAdminBreadcrumb(route.path, t));
|
||||
|
||||
const roleLabel = computed(() => {
|
||||
if (auth.isAdmin.value) return t('role.admin');
|
||||
if (auth.isAdmin.value) {
|
||||
const code = adminRole.value;
|
||||
if (code === 'MATCH_ADMIN') return t('role.match_admin');
|
||||
if (code === 'FINANCE_ADMIN') return t('role.finance_admin');
|
||||
if (code === 'SUPPORT') return t('role.support');
|
||||
if (code === 'SUPER_ADMIN') return t('role.super_admin');
|
||||
return t('role.admin');
|
||||
}
|
||||
const level = auth.user.value?.agentLevel;
|
||||
if (auth.isAgent.value && level != null && level > 0) {
|
||||
return t('role.agent_level', { n: level });
|
||||
|
||||
@@ -2,6 +2,25 @@ import { createRouter, createWebHistory } from 'vue-router';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { useSmokeTestsAllowed } from '../composables/useSmokeTestsAllowed';
|
||||
import { ensureStaffSession } from '../utils/session-hydrate';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
import { adminCanAccess, firstAdminFallback } from '../utils/admin-access';
|
||||
|
||||
/** Paths denied for specific admin roles (SUPER_ADMIN bypasses). */
|
||||
const ROLE_ROUTE_DENY: Record<string, string[]> = {
|
||||
'/finance-logs': ['MATCH_ADMIN'],
|
||||
'/cashback': ['MATCH_ADMIN', 'SUPPORT'],
|
||||
};
|
||||
|
||||
function pathDeniedForRole(path: string, role?: string): boolean {
|
||||
if (!role || role === 'SUPER_ADMIN') return false;
|
||||
const base = path.split('?')[0];
|
||||
for (const [prefix, roles] of Object.entries(ROLE_ROUTE_DENY)) {
|
||||
if ((base === prefix || base.startsWith(`${prefix}/`)) && roles.includes(role)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
@@ -15,6 +34,7 @@ const router = createRouter({
|
||||
{
|
||||
path: '',
|
||||
component: () => import('../views/HomeEntry.vue'),
|
||||
meta: { permissions: [AdminPerm.reports] },
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
@@ -33,11 +53,12 @@ const router = createRouter({
|
||||
{
|
||||
path: 'users',
|
||||
component: () => import('../views/AgentManager.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.usersView, AdminPerm.agentsView] },
|
||||
},
|
||||
{
|
||||
path: 'finance-logs',
|
||||
component: () => import('../views/FinanceLogs.vue'),
|
||||
meta: { permissions: [AdminPerm.reports] },
|
||||
},
|
||||
{
|
||||
path: 'agent-credit-transactions',
|
||||
@@ -53,72 +74,72 @@ const router = createRouter({
|
||||
{
|
||||
path: 'matches',
|
||||
component: () => import('../views/Matches.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'matches/outrights',
|
||||
component: () => import('../views/MatchesOutrights.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'matches/market-templates',
|
||||
component: () => import('../views/MarketTemplates.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'matches/:matchId/edit',
|
||||
name: 'admin-match-edit',
|
||||
component: () => import('../views/matches/MatchEventEditor.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'matches/:matchId/markets',
|
||||
name: 'admin-match-markets',
|
||||
component: () => import('../views/matches/MatchMarketsPage.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{ path: 'outrights', redirect: '/matches/outrights' },
|
||||
{
|
||||
path: 'outrights/:matchId/edit',
|
||||
name: 'admin-outright-edit',
|
||||
component: () => import('../views/outrights/OutrightEditRedirect.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.matches] },
|
||||
},
|
||||
{ path: 'world-cup-outright', redirect: '/matches/outrights' },
|
||||
{
|
||||
path: 'bets',
|
||||
component: () => import('../views/Bets.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.bets] },
|
||||
},
|
||||
{
|
||||
path: 'settlement/:id',
|
||||
component: () => import('../views/Settlement.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.settlement, AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'cashback',
|
||||
component: () => import('../views/Cashback.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.cashback] },
|
||||
},
|
||||
{
|
||||
path: 'contents',
|
||||
component: () => import('../views/Contents.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.content] },
|
||||
},
|
||||
{
|
||||
path: 'audit',
|
||||
component: () => import('../views/Audit.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.audit] },
|
||||
},
|
||||
{
|
||||
path: 'smoke-tests',
|
||||
component: () => import('../views/SmokeTests.vue'),
|
||||
meta: { adminOnly: true, smokeTestsOnly: true },
|
||||
meta: { adminOnly: true, smokeTestsOnly: true, permissions: [AdminPerm.settings] },
|
||||
},
|
||||
{
|
||||
path: 'media',
|
||||
component: () => import('../views/MediaLibrary.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.content, AdminPerm.matches] },
|
||||
},
|
||||
{
|
||||
path: 'payment-methods',
|
||||
@@ -134,7 +155,12 @@ const router = createRouter({
|
||||
{
|
||||
path: 'deposit',
|
||||
component: () => import('../views/DepositManage.vue'),
|
||||
meta: { adminOnly: true },
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.depositManage, AdminPerm.depositReview] },
|
||||
},
|
||||
{
|
||||
path: 'staff',
|
||||
component: () => import('../views/StaffManage.vue'),
|
||||
meta: { adminOnly: true, permissions: [AdminPerm.settings] },
|
||||
},
|
||||
{
|
||||
path: 'my-players',
|
||||
@@ -179,6 +205,23 @@ router.beforeEach(async (to) => {
|
||||
return '/';
|
||||
}
|
||||
|
||||
if (auth.isAdmin.value && to.meta.permissions) {
|
||||
const required = to.meta.permissions as string[];
|
||||
const role = auth.user.value?.role;
|
||||
const permissions = auth.user.value?.permissions;
|
||||
if (pathDeniedForRole(to.path, role)) {
|
||||
const fallback = firstAdminFallback(role, permissions);
|
||||
if (fallback && to.path !== fallback) return fallback;
|
||||
}
|
||||
if (!adminCanAccess(role, permissions, required)) {
|
||||
const fallback = firstAdminFallback(role, permissions);
|
||||
if (!fallback) {
|
||||
return true;
|
||||
}
|
||||
if (to.path !== fallback) return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
if (to.path.startsWith('/dashboard/') && !auth.isAdmin.value) {
|
||||
return '/';
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ export interface StaffUser {
|
||||
userType: StaffUserType;
|
||||
locale?: string;
|
||||
role?: string;
|
||||
permissions?: string[];
|
||||
agentLevel?: number | null;
|
||||
maxAgentLevel?: number | null;
|
||||
canManageSubAgents?: boolean;
|
||||
@@ -95,6 +96,7 @@ export function reconcileStaffSessionFromToken(): boolean {
|
||||
userType: claims.userType,
|
||||
locale: user.value?.locale,
|
||||
role: claims.role ?? user.value?.role,
|
||||
permissions: user.value?.permissions,
|
||||
inviteCode: user.value?.inviteCode,
|
||||
};
|
||||
user.value = next;
|
||||
|
||||
80
apps/admin/src/utils/admin-access.ts
Normal file
80
apps/admin/src/utils/admin-access.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
|
||||
/** Mirrors API seed role assignments — used when /me has not yet returned permissions. */
|
||||
export const ROLE_PERMISSIONS: Record<string, string[]> = {
|
||||
MATCH_ADMIN: [
|
||||
AdminPerm.matches,
|
||||
AdminPerm.settlement,
|
||||
AdminPerm.content,
|
||||
AdminPerm.bets,
|
||||
AdminPerm.reports,
|
||||
AdminPerm.audit,
|
||||
],
|
||||
FINANCE_ADMIN: [
|
||||
AdminPerm.walletDeposit,
|
||||
AdminPerm.walletWithdraw,
|
||||
AdminPerm.cashback,
|
||||
AdminPerm.agentsView,
|
||||
AdminPerm.agentsCredit,
|
||||
AdminPerm.usersView,
|
||||
AdminPerm.usersCreate,
|
||||
AdminPerm.depositManage,
|
||||
AdminPerm.depositReview,
|
||||
AdminPerm.reports,
|
||||
AdminPerm.bets,
|
||||
AdminPerm.audit,
|
||||
],
|
||||
SUPPORT: [
|
||||
AdminPerm.usersView,
|
||||
AdminPerm.usersResetPassword,
|
||||
AdminPerm.bets,
|
||||
AdminPerm.reports,
|
||||
AdminPerm.audit,
|
||||
],
|
||||
};
|
||||
|
||||
export function effectivePermissions(
|
||||
role: string | undefined,
|
||||
permissions: string[] | undefined,
|
||||
): string[] {
|
||||
if (permissions?.length) return permissions;
|
||||
if (role && ROLE_PERMISSIONS[role]) return ROLE_PERMISSIONS[role];
|
||||
return [];
|
||||
}
|
||||
|
||||
export function adminCanAccess(
|
||||
role: string | undefined,
|
||||
permissions: string[] | undefined,
|
||||
required: string[] | undefined,
|
||||
): boolean {
|
||||
if (!required?.length) return true;
|
||||
if (role === 'SUPER_ADMIN') return true;
|
||||
const perms = effectivePermissions(role, permissions);
|
||||
return required.some((p) => perms.includes(p));
|
||||
}
|
||||
|
||||
export const ADMIN_ROUTE_FALLBACKS: { path: string; permissions: string[]; roles?: string[] }[] = [
|
||||
{ path: '/', permissions: [AdminPerm.reports], roles: ['MATCH_ADMIN'] },
|
||||
{ path: '/dashboard/players', permissions: [AdminPerm.reports], roles: ['FINANCE_ADMIN'] },
|
||||
{ path: '/users', permissions: [AdminPerm.usersView, AdminPerm.agentsView], roles: ['SUPPORT'] },
|
||||
{ path: '/finance-logs', permissions: [AdminPerm.reports], roles: ['SUPPORT'] },
|
||||
{ path: '/', permissions: [AdminPerm.reports] },
|
||||
{ path: '/matches', permissions: [AdminPerm.matches] },
|
||||
{ path: '/bets', permissions: [AdminPerm.bets] },
|
||||
{ path: '/audit', permissions: [AdminPerm.audit] },
|
||||
];
|
||||
|
||||
export function firstAdminFallback(role?: string, permissions?: string[]) {
|
||||
if (role) {
|
||||
for (const item of ADMIN_ROUTE_FALLBACKS) {
|
||||
if (item.roles?.includes(role) && adminCanAccess(role, permissions, item.permissions)) {
|
||||
return item.path;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const item of ADMIN_ROUTE_FALLBACKS) {
|
||||
if (item.roles) continue;
|
||||
if (adminCanAccess(role, permissions, item.permissions)) return item.path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -58,6 +58,7 @@ export async function hydrateStaffSession(): Promise<boolean> {
|
||||
userType: raw.userType,
|
||||
locale: raw.locale,
|
||||
role: raw.role,
|
||||
permissions: Array.isArray(raw.permissions) ? raw.permissions : auth.user.value?.permissions,
|
||||
agentLevel: typeof raw.agentLevel === 'number' ? raw.agentLevel : null,
|
||||
maxAgentLevel: typeof raw.maxAgentLevel === 'number' ? raw.maxAgentLevel : null,
|
||||
canManageSubAgents: raw.canManageSubAgents === true,
|
||||
|
||||
@@ -7,8 +7,33 @@ import { resolveFormError, resolveApiError } from '../i18n/form-validation';
|
||||
import api from '../api';
|
||||
import { clearStaffSession } from '../stores/auth';
|
||||
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
|
||||
const { t, localeTag } = useAdminLocale();
|
||||
const router = useRouter();
|
||||
const { hasPermission, role: staffRole } = usePermissions();
|
||||
|
||||
const canViewAgents = computed(() => hasPermission(AdminPerm.agentsView));
|
||||
const canViewUsers = computed(() => hasPermission(AdminPerm.usersView));
|
||||
const canCreateUsers = computed(() => hasPermission(AdminPerm.usersCreate));
|
||||
const canCreateAgents = computed(() => hasPermission(AdminPerm.agentsCreate));
|
||||
const canResetPassword = computed(() => hasPermission(AdminPerm.usersResetPassword));
|
||||
const canDeposit = computed(() => hasPermission(AdminPerm.walletDeposit));
|
||||
const canWithdraw = computed(() => hasPermission(AdminPerm.walletWithdraw));
|
||||
const canAdjustCredit = computed(() => hasPermission(AdminPerm.agentsCredit));
|
||||
const canManageSettings = computed(() => hasPermission(AdminPerm.settings));
|
||||
const canEditPlayerProfile = computed(() => canCreateUsers.value);
|
||||
const playerActionsReadOnly = computed(
|
||||
() => canViewUsers.value && !canCreateUsers.value && !canDeposit.value && !canWithdraw.value,
|
||||
);
|
||||
const playerActionFlags = computed(() => ({
|
||||
showEdit: canViewUsers.value && (canEditPlayerProfile.value || canResetPassword.value),
|
||||
showDeposit: canDeposit.value,
|
||||
showWithdraw: canWithdraw.value,
|
||||
showFreeze: canEditPlayerProfile.value,
|
||||
showDelete: canEditPlayerProfile.value,
|
||||
}));
|
||||
|
||||
import {
|
||||
emptyPlayerCreateForm,
|
||||
@@ -387,9 +412,15 @@ function resolveCreateParentLabel(agentId: string) {
|
||||
|
||||
/* ─── Init ─── */
|
||||
onMounted(() => {
|
||||
void loadUsersPageInit();
|
||||
loadAllPlayers();
|
||||
loadTier1Agents();
|
||||
if (canManageSettings.value) {
|
||||
void loadUsersPageInit();
|
||||
}
|
||||
if (canViewUsers.value) {
|
||||
loadAllPlayers();
|
||||
}
|
||||
if (canViewAgents.value) {
|
||||
loadTier1Agents();
|
||||
}
|
||||
});
|
||||
|
||||
async function loadUsersPageInit() {
|
||||
@@ -980,6 +1011,37 @@ async function submitEditPlayer() {
|
||||
ElMessage.warning(t('err.password_min'));
|
||||
return;
|
||||
}
|
||||
const newPwd = editPlayerForm.value.newPassword.trim();
|
||||
const passwordOnly =
|
||||
newPwd &&
|
||||
!canEditPlayerProfile.value &&
|
||||
canResetPassword.value &&
|
||||
!editPlayerForm.value.useCustomCashback;
|
||||
|
||||
if (passwordOnly) {
|
||||
editPlayerLoading.value = true;
|
||||
try {
|
||||
const { data } = await api.post(`/admin/users/${editingId.value}/reset-password`, {
|
||||
password: newPwd,
|
||||
});
|
||||
const plain = data.data?.password ?? newPwd;
|
||||
editPlayerForm.value.managedPassword = plain;
|
||||
editPlayerForm.value.newPassword = '';
|
||||
ElMessage.success(t('user.msg.password_saved', { password: plain }));
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
|
||||
} finally {
|
||||
editPlayerLoading.value = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canEditPlayerProfile.value) {
|
||||
ElMessage.warning(t('msg.save_failed'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
assertPlayerUsername(editPlayerForm.value.username);
|
||||
} catch (e) {
|
||||
@@ -988,7 +1050,6 @@ async function submitEditPlayer() {
|
||||
}
|
||||
editPlayerLoading.value = true;
|
||||
try {
|
||||
const newPwd = editPlayerForm.value.newPassword.trim();
|
||||
const payload: Record<string, unknown> = {
|
||||
username: editPlayerForm.value.username.trim(),
|
||||
phone: editPlayerForm.value.phone.trim() || undefined,
|
||||
@@ -1346,7 +1407,7 @@ function creditTypeLabel(type: string) {
|
||||
<template>
|
||||
<div class="admin-list-page agent-mgr-page">
|
||||
<!-- ─── Global settings collapse ─── -->
|
||||
<el-collapse v-model="settingsCollapseOpen" class="list-settings">
|
||||
<el-collapse v-if="canManageSettings" v-model="settingsCollapseOpen" class="list-settings">
|
||||
<el-collapse-item :title="t('user.page_settings')" name="settings">
|
||||
<div class="list-settings-block">
|
||||
<p class="list-settings-title">{{ t('user.global_settings') }}</p>
|
||||
@@ -1438,12 +1499,12 @@ function creditTypeLabel(type: string) {
|
||||
<InviteManageDialog v-model="inviteDialogOpen" />
|
||||
|
||||
<div class="mgr-tabs-shell">
|
||||
<el-button type="primary" class="invite-prominent-btn" @click="inviteDialogOpen = true">
|
||||
<el-button v-if="canManageSettings" type="primary" class="invite-prominent-btn" @click="inviteDialogOpen = true">
|
||||
{{ t('invite.menu_btn') }}
|
||||
</el-button>
|
||||
<el-tabs v-model="activeViewTab" class="mgr-top-tabs mgr-top-tabs--with-invite">
|
||||
<el-tabs v-model="activeViewTab" class="mgr-top-tabs" :class="{ 'mgr-top-tabs--with-invite': canManageSettings }">
|
||||
<!-- ─── Tab: 全部玩家(默认) ─── -->
|
||||
<el-tab-pane :label="`${t('user.type.player')} (${playerTotal})`" name="players">
|
||||
<el-tab-pane v-if="canViewUsers" :label="`${t('user.type.player')} (${playerTotal})`" name="players">
|
||||
<section class="list-panel player-list-panel">
|
||||
<div class="list-panel-toolbar">
|
||||
<el-form inline class="list-chrome__grow">
|
||||
@@ -1456,7 +1517,7 @@ function creditTypeLabel(type: string) {
|
||||
@keyup.enter="searchPlayers"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('user.filter.agent')">
|
||||
<el-form-item v-if="canViewAgents" :label="t('user.filter.agent')">
|
||||
<el-select
|
||||
v-model="playerFilterAgent"
|
||||
:placeholder="t('user.filter.agent_ph')"
|
||||
@@ -1487,7 +1548,7 @@ function creditTypeLabel(type: string) {
|
||||
<el-button type="primary" @click="searchPlayers">{{ t('common.search') }}</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="list-chrome__actions">
|
||||
<div v-if="canCreateUsers" class="list-chrome__actions">
|
||||
<el-button type="primary" @click="openCreateAccount">{{ t('user.create_btn') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1530,6 +1591,7 @@ function creditTypeLabel(type: string) {
|
||||
<el-table-column :label="t('common.actions')" min-width="340" align="center">
|
||||
<template #default="{ row }">
|
||||
<AdminPlayerRowActions
|
||||
v-bind="playerActionFlags"
|
||||
:row="row"
|
||||
@detail="openDetailPlayer(row.id)"
|
||||
@ledger="openPlayerWalletLedger(row.id, row.username)"
|
||||
@@ -1559,7 +1621,7 @@ function creditTypeLabel(type: string) {
|
||||
</el-tab-pane>
|
||||
|
||||
<!-- ─── Tab: 一级代理 ─── -->
|
||||
<el-tab-pane :label="`${agentTierName(1)} (${tier1Total})`" name="tier1Agents">
|
||||
<el-tab-pane v-if="canViewAgents" :label="`${agentTierName(1)} (${tier1Total})`" name="tier1Agents">
|
||||
<section class="list-panel agent-list-panel">
|
||||
<div class="list-panel-toolbar">
|
||||
<el-form inline class="list-chrome__grow">
|
||||
@@ -1576,7 +1638,7 @@ function creditTypeLabel(type: string) {
|
||||
<el-button type="primary" @click="searchTier1Agents">{{ t('common.search') }}</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="list-chrome__actions">
|
||||
<div v-if="canCreateAgents" class="list-chrome__actions">
|
||||
<el-button type="primary" @click="openCreateTier1Agent">{{ t('agent.create_btn') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1638,6 +1700,7 @@ function creditTypeLabel(type: string) {
|
||||
<el-table-column :label="t('common.actions')" min-width="320" align="center">
|
||||
<template #default="{ row: player }">
|
||||
<AdminPlayerRowActions
|
||||
v-bind="playerActionFlags"
|
||||
:row="player"
|
||||
@detail="openDetailPlayer(player.id)"
|
||||
@ledger="openPlayerWalletLedger(player.id, player.username)"
|
||||
@@ -1709,6 +1772,7 @@ function creditTypeLabel(type: string) {
|
||||
</el-tab-pane>
|
||||
|
||||
<!-- ─── Tab: L2+ 各级代理 ─── -->
|
||||
<template v-if="canViewAgents">
|
||||
<el-tab-pane
|
||||
v-for="agentLevel in visibleSubAgentTabLevels"
|
||||
:key="agentLevel"
|
||||
@@ -1794,6 +1858,7 @@ function creditTypeLabel(type: string) {
|
||||
<el-table-column :label="t('common.actions')" min-width="280" align="center">
|
||||
<template #default="{ row: player }">
|
||||
<AdminPlayerRowActions
|
||||
v-bind="playerActionFlags"
|
||||
:row="player"
|
||||
@detail="openDetailPlayer(player.id)"
|
||||
@ledger="openPlayerWalletLedger(player.id, player.username)"
|
||||
@@ -1858,6 +1923,7 @@ function creditTypeLabel(type: string) {
|
||||
</div>
|
||||
</section>
|
||||
</el-tab-pane>
|
||||
</template>
|
||||
</el-tabs>
|
||||
</div>
|
||||
|
||||
@@ -2068,7 +2134,13 @@ function creditTypeLabel(type: string) {
|
||||
</el-dialog>
|
||||
|
||||
<!-- ── Edit Player ── -->
|
||||
<el-dialog v-model="editPlayerVisible" :title="t('user.dialog.edit')" width="560px" destroy-on-close class="user-edit-dialog">
|
||||
<el-dialog
|
||||
v-model="editPlayerVisible"
|
||||
:title="canEditPlayerProfile ? t('user.dialog.edit') : t('user.field.reset_password')"
|
||||
width="560px"
|
||||
destroy-on-close
|
||||
class="user-edit-dialog"
|
||||
>
|
||||
<el-form label-width="84px" size="small" class="compact-edit-form">
|
||||
<div class="edit-meta">
|
||||
<span>ID {{ editPlayerForm.id }}</span>
|
||||
@@ -2078,11 +2150,20 @@ function creditTypeLabel(type: string) {
|
||||
<div class="edit-form-section">
|
||||
<div class="section-title">{{ t('user.section.basic_info') }}</div>
|
||||
<el-form-item :label="t('user.col.username')">
|
||||
<el-input v-model="editPlayerForm.username" :placeholder="t('user.ph.username_player')" />
|
||||
<el-input
|
||||
v-model="editPlayerForm.username"
|
||||
:readonly="!canEditPlayerProfile"
|
||||
:placeholder="t('user.ph.username_player')"
|
||||
/>
|
||||
<div class="field-hint">{{ t('user.hint.username_player') }}</div>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div v-if="!canEditPlayerProfile" class="edit-form-section">
|
||||
<div class="section-title">{{ t('user.section.affiliation') }}</div>
|
||||
<el-tag size="small" type="info" class="affiliation-tag">{{ affiliationLabel(editPlayerForm) }}</el-tag>
|
||||
</div>
|
||||
|
||||
<div class="edit-form-section">
|
||||
<div class="password-mgmt-block">
|
||||
<div class="block-title">{{ t('user.section.password_mgmt') }}</div>
|
||||
@@ -2099,7 +2180,7 @@ function creditTypeLabel(type: string) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="edit-form-section">
|
||||
<div v-if="canEditPlayerProfile" class="edit-form-section">
|
||||
<div class="section-title">{{ t('user.section.affiliation') }}</div>
|
||||
<el-form-item :label="t('user.col.agent')">
|
||||
<el-tag size="small" type="info" class="affiliation-tag">{{ affiliationLabel(editPlayerForm) }}</el-tag>
|
||||
@@ -2121,7 +2202,7 @@ function creditTypeLabel(type: string) {
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<div class="edit-form-section">
|
||||
<div v-if="canEditPlayerProfile" class="edit-form-section">
|
||||
<div class="section-title">{{ t('user.section.contact') }}</div>
|
||||
<el-row :gutter="12" class="contact-row">
|
||||
<el-col :span="12">
|
||||
@@ -2155,7 +2236,9 @@ function creditTypeLabel(type: string) {
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button size="small" @click="editPlayerVisible = false">{{ t('common.cancel') }}</el-button>
|
||||
<el-button size="small" type="primary" :loading="editPlayerLoading" @click="submitEditPlayer">{{ t('user.btn.save_profile') }}</el-button>
|
||||
<el-button size="small" type="primary" :loading="editPlayerLoading" @click="submitEditPlayer">
|
||||
{{ canEditPlayerProfile ? t('user.btn.save_profile') : t('user.field.reset_password') }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
|
||||
@@ -12,13 +12,19 @@ interface AuditRow {
|
||||
action: string;
|
||||
module: string;
|
||||
targetId: string | null;
|
||||
operatorId: string | null;
|
||||
operatorUsername: string | null;
|
||||
operatorRole: string | null;
|
||||
operatorUserType: string | null;
|
||||
operatorType: string;
|
||||
ipAddress: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
const logs = ref<AuditRow[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(10);
|
||||
const pageSize = ref(20);
|
||||
const filterModule = ref('');
|
||||
|
||||
onMounted(load);
|
||||
@@ -56,6 +62,24 @@ function formatTime(v: string) {
|
||||
second: '2-digit',
|
||||
});
|
||||
}
|
||||
|
||||
function operatorRoleLabel(row: AuditRow): string | null {
|
||||
const code = row.operatorRole;
|
||||
if (code === 'SUPER_ADMIN') return t('role.super_admin');
|
||||
if (code === 'MATCH_ADMIN') return t('role.match_admin');
|
||||
if (code === 'FINANCE_ADMIN') return t('role.finance_admin');
|
||||
if (code === 'SUPPORT') return t('role.support');
|
||||
if (row.operatorUserType === 'ADMIN' || row.operatorType === 'ADMIN') return t('role.admin');
|
||||
if (row.operatorUserType === 'AGENT' || row.operatorType === 'AGENT') return t('role.agent');
|
||||
if (row.operatorUserType === 'PLAYER' || row.operatorType === 'PLAYER') return t('audit.operator_player');
|
||||
return null;
|
||||
}
|
||||
|
||||
function operatorDisplay(row: AuditRow): string {
|
||||
if (row.operatorUsername) return row.operatorUsername;
|
||||
if (row.operatorType === 'SYSTEM') return t('audit.operator_system');
|
||||
return '—';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -79,19 +103,30 @@ function formatTime(v: string) {
|
||||
|
||||
<el-card class="data-card" shadow="never">
|
||||
<div class="table-wrap">
|
||||
<el-table :data="logs" stripe>
|
||||
<el-table :key="locale" :data="logs" stripe>
|
||||
<template #empty>
|
||||
<AdminTableEmpty />
|
||||
</template>
|
||||
<el-table-column :label="t('audit.col.time')" min-width="168" fixed="left">
|
||||
<template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('audit.col.operator')" min-width="160">
|
||||
<template #default="{ row }">
|
||||
<div class="operator-cell">
|
||||
<span class="operator-name">{{ operatorDisplay(row) }}</span>
|
||||
<span v-if="operatorRoleLabel(row)" class="operator-role">{{ operatorRoleLabel(row) }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('audit.col.action')" min-width="140">
|
||||
<template #default="{ row }">{{ auditActionLabel(row.action) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('audit.col.module')" width="120">
|
||||
<template #default="{ row }">{{ auditModuleLabel(row.module) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="targetId" :label="t('audit.col.target_id')" min-width="100" />
|
||||
<el-table-column :label="t('audit.col.time')" min-width="160">
|
||||
<template #default="{ row }">{{ formatTime(row.createdAt) }}</template>
|
||||
<el-table-column prop="targetId" :label="t('audit.col.target_id')" min-width="100" show-overflow-tooltip />
|
||||
<el-table-column :label="t('audit.col.ip')" min-width="120" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ row.ipAddress ?? '—' }}</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
@@ -114,4 +149,21 @@ function formatTime(v: string) {
|
||||
<style scoped>
|
||||
.filter-card { border-radius: 12px; }
|
||||
.data-card { border-radius: 12px; }
|
||||
|
||||
.operator-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.operator-name {
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.operator-role {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { computed, onMounted, ref } from 'vue';
|
||||
import type { TableColumnCtx } from 'element-plus';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
import { formatAmount, formatAmountFull } from '../utils/format-amount';
|
||||
import { formatRatePercent } from '../utils/rate-percent';
|
||||
import AdminTableEmpty from '../components/AdminTableEmpty.vue';
|
||||
@@ -46,6 +48,8 @@ interface CashbackPreview {
|
||||
}
|
||||
|
||||
const { t, localeTag } = useAdminLocale();
|
||||
const { hasPermission } = usePermissions();
|
||||
const canConfirmCashback = computed(() => hasPermission(AdminPerm.cashback));
|
||||
|
||||
const preview = ref<CashbackPreview | null>(null);
|
||||
const rulesVisible = ref(false);
|
||||
@@ -418,7 +422,7 @@ onMounted(loadHistory);
|
||||
</el-table>
|
||||
</div>
|
||||
|
||||
<div v-if="preview.batch.status === 'PREVIEW'" class="preview-actions">
|
||||
<div v-if="preview.batch.status === 'PREVIEW' && canConfirmCashback" class="preview-actions">
|
||||
<el-button type="success" :disabled="previewItems.length === 0" @click="confirm">
|
||||
{{ t('cashback.confirm_issue') }}
|
||||
</el-button>
|
||||
@@ -484,7 +488,7 @@ onMounted(loadHistory);
|
||||
<el-button link type="primary" @click="openDetail(row.id)">
|
||||
{{ t('cashback.view_detail') }}
|
||||
</el-button>
|
||||
<template v-if="row.status === 'PREVIEW'">
|
||||
<template v-if="row.status === 'PREVIEW' && canConfirmCashback">
|
||||
<el-button link type="success" @click="confirmBatchId(row.id)">
|
||||
{{ t('cashback.confirm_issue') }}
|
||||
</el-button>
|
||||
@@ -577,7 +581,7 @@ onMounted(loadHistory);
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
<div v-if="detail?.batch.status === 'PREVIEW'" class="detail-actions">
|
||||
<div v-if="detail?.batch.status === 'PREVIEW' && canConfirmCashback" class="detail-actions">
|
||||
<el-button type="success" :disabled="detailItems.length === 0" @click="confirmBatchId(detail.batch.id)">
|
||||
{{ t('cashback.confirm_issue') }}
|
||||
</el-button>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { ref, computed, watch } from 'vue';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import type { TableInstance } from 'element-plus';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
import api from '../api';
|
||||
import AdminTableEmpty from '../components/AdminTableEmpty.vue';
|
||||
import {
|
||||
@@ -11,6 +13,8 @@ import {
|
||||
} from './match-form';
|
||||
|
||||
const { t, localeTag } = useAdminLocale();
|
||||
const { hasPermission } = usePermissions();
|
||||
const canManageContent = computed(() => hasPermission(AdminPerm.content));
|
||||
|
||||
/* ── Image upload helpers ── */
|
||||
const IMAGE_ACCEPT = 'image/png,image/jpeg,image/webp,image/gif,image/svg+xml';
|
||||
@@ -470,9 +474,10 @@ void load();
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" size="small" @click="load">{{ t('common.search') }}</el-button>
|
||||
<el-button type="primary" plain size="small" @click="openCreate">
|
||||
<el-button v-if="canManageContent" type="primary" plain size="small" @click="openCreate">
|
||||
{{ t('content.btn.create') }}
|
||||
</el-button>
|
||||
<template v-if="canManageContent">
|
||||
<span v-if="hasSelection" class="batch-hint">
|
||||
{{ t('content.batch.selected', { n: selectedRows.length }) }}
|
||||
</span>
|
||||
@@ -499,6 +504,7 @@ void load();
|
||||
>
|
||||
{{ t('content.batch.delete') }}
|
||||
</el-button>
|
||||
</template>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
@@ -1,17 +1,40 @@
|
||||
<script setup lang="ts">
|
||||
import { shallowRef, onBeforeMount, type Component } from 'vue';
|
||||
import { RouterView } from 'vue-router';
|
||||
import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { useAuthStore } from '../stores/auth';
|
||||
import { ensureStaffSession } from '../utils/session-hydrate';
|
||||
import DashboardSubNav from '../components/DashboardSubNav.vue';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
|
||||
const auth = useAuthStore();
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const { t } = useAdminLocale();
|
||||
const { hasPermission, role } = usePermissions();
|
||||
const agentDashboard = shallowRef<Component | null>(null);
|
||||
const booting = shallowRef(true);
|
||||
|
||||
const showSupportShortcuts = shallowRef(false);
|
||||
|
||||
onBeforeMount(async () => {
|
||||
await ensureStaffSession();
|
||||
if (!auth.isAdmin.value) {
|
||||
if (auth.isAdmin.value) {
|
||||
const code = role.value;
|
||||
if (code === 'FINANCE_ADMIN' && route.path === '/') {
|
||||
await router.replace('/dashboard/players');
|
||||
} else if (code === 'SUPPORT') {
|
||||
showSupportShortcuts.value = true;
|
||||
if (route.path === '/' || route.path === '/dashboard/players') {
|
||||
if (hasPermission(AdminPerm.usersView, AdminPerm.agentsView)) {
|
||||
await router.replace('/users');
|
||||
} else if (hasPermission(AdminPerm.bets)) {
|
||||
await router.replace('/bets');
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
agentDashboard.value = (await import('./agent/Dashboard.vue')).default;
|
||||
}
|
||||
booting.value = false;
|
||||
@@ -21,6 +44,17 @@ onBeforeMount(async () => {
|
||||
<template>
|
||||
<div v-if="booting" v-loading="true" class="home-boot" />
|
||||
<template v-else-if="auth.isAdmin.value">
|
||||
<div v-if="showSupportShortcuts" class="support-shortcuts">
|
||||
<RouterLink v-if="hasPermission(AdminPerm.usersView, AdminPerm.agentsView)" to="/users" class="support-link">
|
||||
{{ t('nav.agents_players') }}
|
||||
</RouterLink>
|
||||
<RouterLink v-if="hasPermission(AdminPerm.bets)" to="/bets" class="support-link">
|
||||
{{ t('nav.bets') }}
|
||||
</RouterLink>
|
||||
<RouterLink v-if="hasPermission(AdminPerm.reports)" to="/finance-logs" class="support-link">
|
||||
{{ t('nav.finance_logs') }}
|
||||
</RouterLink>
|
||||
</div>
|
||||
<div class="dashboard-shell">
|
||||
<div class="list-chrome">
|
||||
<div class="list-chrome__row">
|
||||
@@ -40,6 +74,28 @@ onBeforeMount(async () => {
|
||||
min-height: 240px;
|
||||
}
|
||||
|
||||
.support-shortcuts {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.support-link {
|
||||
padding: 8px 14px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--border);
|
||||
background: #fff;
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.support-link:hover {
|
||||
border-color: var(--primary);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.dashboard-shell :deep(.list-chrome) {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import { useAuthStore, type StaffUser } from '../stores/auth';
|
||||
import RobotVerify from '../components/RobotVerify.vue';
|
||||
import AdminLocaleSwitcher from '../components/AdminLocaleSwitcher.vue';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { ensureStaffSession } from '../utils/session-hydrate';
|
||||
import { effectivePermissions, firstAdminFallback } from '../utils/admin-access';
|
||||
import bgImage from '../assets/images/bg.webp';
|
||||
|
||||
const router = useRouter();
|
||||
@@ -19,13 +21,25 @@ const loading = ref(false);
|
||||
const captchaRef = ref<InstanceType<typeof RobotVerify> | null>(null);
|
||||
const isDev = import.meta.env.DEV;
|
||||
|
||||
async function finishLogin(payload: { token: string; user: StaffUser }) {
|
||||
auth.setSession(payload.token, payload.user);
|
||||
await ensureStaffSession();
|
||||
const redirectQuery = route.query.redirect as string | undefined;
|
||||
const role = auth.user.value?.role;
|
||||
const permissions = effectivePermissions(role, auth.user.value?.permissions);
|
||||
const target =
|
||||
redirectQuery ||
|
||||
firstAdminFallback(role, permissions) ||
|
||||
'/';
|
||||
await router.push(target);
|
||||
}
|
||||
|
||||
async function quickLogin(username: string, password: string) {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await api.post('/manage/auth/login', { username, password });
|
||||
const payload = data.data as { token: string; user: StaffUser };
|
||||
auth.setSession(payload.token, payload.user);
|
||||
router.push((route.query.redirect as string) || '/');
|
||||
await finishLogin(payload);
|
||||
} catch {
|
||||
ElMessage.error(t('login.err_quick'));
|
||||
} finally {
|
||||
@@ -43,8 +57,7 @@ async function login() {
|
||||
try {
|
||||
const { data } = await api.post('/manage/auth/login', form.value);
|
||||
const payload = data.data as { token: string; user: StaffUser };
|
||||
auth.setSession(payload.token, payload.user);
|
||||
router.push((route.query.redirect as string) || '/');
|
||||
await finishLogin(payload);
|
||||
} catch {
|
||||
ElMessage.error(t('login.err_failed'));
|
||||
captchaRef.value?.refresh();
|
||||
@@ -97,6 +110,18 @@ async function login() {
|
||||
<span class="quick-role">{{ t('login.quick_agent2') }}</span>
|
||||
<span class="quick-acc">agent2</span>
|
||||
</button>
|
||||
<button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('matchadmin', 'MatchAdmin@123')">
|
||||
<span class="quick-role">{{ t('login.quick_match_admin') }}</span>
|
||||
<span class="quick-acc">matchadmin</span>
|
||||
</button>
|
||||
<button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('financeadmin', 'FinanceAdmin@123')">
|
||||
<span class="quick-role">{{ t('login.quick_finance_admin') }}</span>
|
||||
<span class="quick-acc">financeadmin</span>
|
||||
</button>
|
||||
<button type="button" class="quick-btn" :disabled="loading" @click="quickLogin('support1', 'Support@123')">
|
||||
<span class="quick-role">{{ t('login.quick_support') }}</span>
|
||||
<span class="quick-acc">support1</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,8 @@ import { formatApiErrorMessage, isApiErrorCode } from '@thebet365/shared';
|
||||
import api from '../api';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import { usePermissions } from '../composables/usePermissions';
|
||||
import { AdminPerm } from '../constants/permissions';
|
||||
|
||||
const VChart = defineAsyncComponent(() =>
|
||||
import('../components/dashboard/echarts-setup').then((m) => m.VChart),
|
||||
@@ -69,6 +71,8 @@ interface SettlementBetStats {
|
||||
}
|
||||
|
||||
const { t, locale, localeTag } = useAdminLocale();
|
||||
const { hasPermission } = usePermissions();
|
||||
const canResettle = computed(() => hasPermission(AdminPerm.resettle));
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const STAT_FACT_LABELS = {
|
||||
@@ -770,7 +774,7 @@ onMounted(() => {
|
||||
isOutright ? t('settlement.outright.preview_hint') : t('settlement.preview_hint')
|
||||
}}</span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<template v-else-if="canResettle">
|
||||
<el-input
|
||||
v-model="resettleReason"
|
||||
size="small"
|
||||
@@ -787,7 +791,7 @@ onMounted(() => {
|
||||
|
||||
<!-- 智能比分弹窗已关闭(见 Settlement.vue git 历史) -->
|
||||
|
||||
<el-card v-if="resettlePreview" class="preview-card" shadow="never">
|
||||
<el-card v-if="canResettle && resettlePreview" class="preview-card" shadow="never">
|
||||
<div class="preview-title">{{ t('settlement.resettle_preview_title') }}</div>
|
||||
<el-row :gutter="20">
|
||||
<el-col :span="8">
|
||||
|
||||
294
apps/admin/src/views/StaffManage.vue
Normal file
294
apps/admin/src/views/StaffManage.vue
Normal file
@@ -0,0 +1,294 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import api from '../api';
|
||||
import { useAdminLocale } from '../composables/useAdminLocale';
|
||||
import AdminTableEmpty from '../components/AdminTableEmpty.vue';
|
||||
import AdminTableWrap from '../components/AdminTableWrap.vue';
|
||||
|
||||
interface StaffRow {
|
||||
id: string;
|
||||
username: string;
|
||||
status: string;
|
||||
role: string | null;
|
||||
roleName: string | null;
|
||||
lastLoginAt: string | null;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface RoleOption {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
const { t, localeTag } = useAdminLocale();
|
||||
|
||||
const loading = ref(false);
|
||||
const rows = ref<StaffRow[]>([]);
|
||||
const total = ref(0);
|
||||
const page = ref(1);
|
||||
const pageSize = ref(20);
|
||||
const keyword = ref('');
|
||||
const roles = ref<RoleOption[]>([]);
|
||||
|
||||
const createVisible = ref(false);
|
||||
const createLoading = ref(false);
|
||||
const createForm = ref({ username: '', password: '', confirmPassword: '', roleCode: 'MATCH_ADMIN' });
|
||||
|
||||
const editVisible = ref(false);
|
||||
const editLoading = ref(false);
|
||||
const editForm = ref({ id: '', username: '', status: 'ACTIVE', roleCode: 'MATCH_ADMIN', password: '' });
|
||||
|
||||
const roleLabel = computed(() => {
|
||||
const map: Record<string, string> = {
|
||||
SUPER_ADMIN: t('role.super_admin'),
|
||||
MATCH_ADMIN: t('role.match_admin'),
|
||||
FINANCE_ADMIN: t('role.finance_admin'),
|
||||
SUPPORT: t('role.support'),
|
||||
};
|
||||
return (code: string | null) => (code ? map[code] ?? code : '—');
|
||||
});
|
||||
|
||||
function formatTime(value: string | null) {
|
||||
if (!value) return '—';
|
||||
return new Date(value).toLocaleString(localeTag.value);
|
||||
}
|
||||
|
||||
async function loadRoles() {
|
||||
const { data } = await api.get('/admin/staff/roles');
|
||||
roles.value = (data.data ?? []) as RoleOption[];
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await api.get('/admin/staff', {
|
||||
params: {
|
||||
page: page.value,
|
||||
pageSize: pageSize.value,
|
||||
keyword: keyword.value.trim() || undefined,
|
||||
},
|
||||
});
|
||||
rows.value = data.data.items as StaffRow[];
|
||||
total.value = data.data.total;
|
||||
} catch {
|
||||
rows.value = [];
|
||||
total.value = 0;
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
createForm.value = { username: '', password: '', confirmPassword: '', roleCode: 'MATCH_ADMIN' };
|
||||
createVisible.value = true;
|
||||
}
|
||||
|
||||
async function submitCreate() {
|
||||
const f = createForm.value;
|
||||
if (!f.username.trim()) {
|
||||
ElMessage.warning(t('err.username_required'));
|
||||
return;
|
||||
}
|
||||
if (f.password.length < 8) {
|
||||
ElMessage.warning(t('err.password_min'));
|
||||
return;
|
||||
}
|
||||
if (f.password !== f.confirmPassword) {
|
||||
ElMessage.warning(t('err.password_mismatch'));
|
||||
return;
|
||||
}
|
||||
createLoading.value = true;
|
||||
try {
|
||||
await api.post('/admin/staff', {
|
||||
username: f.username.trim(),
|
||||
password: f.password,
|
||||
roleCode: f.roleCode,
|
||||
});
|
||||
ElMessage.success(t('msg.saved'));
|
||||
createVisible.value = false;
|
||||
await load();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
|
||||
} finally {
|
||||
createLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function openEdit(row: StaffRow) {
|
||||
editForm.value = {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
status: row.status,
|
||||
roleCode: row.role ?? 'MATCH_ADMIN',
|
||||
password: '',
|
||||
};
|
||||
editVisible.value = true;
|
||||
}
|
||||
|
||||
async function submitEdit() {
|
||||
const f = editForm.value;
|
||||
if (f.password && f.password.length < 8) {
|
||||
ElMessage.warning(t('err.password_min'));
|
||||
return;
|
||||
}
|
||||
editLoading.value = true;
|
||||
try {
|
||||
const payload: Record<string, string> = {
|
||||
status: f.status,
|
||||
roleCode: f.roleCode,
|
||||
};
|
||||
if (f.password.trim()) payload.password = f.password.trim();
|
||||
const { data } = await api.patch(`/admin/staff/${f.id}`, payload);
|
||||
if (data.data?.password) {
|
||||
ElMessage.success(t('user.msg.password_saved', { password: data.data.password }));
|
||||
} else {
|
||||
ElMessage.success(t('msg.saved'));
|
||||
}
|
||||
editVisible.value = false;
|
||||
await load();
|
||||
} catch (e: unknown) {
|
||||
const err = e as { response?: { data?: { error?: string } } };
|
||||
ElMessage.error(err.response?.data?.error ?? t('msg.save_failed'));
|
||||
} finally {
|
||||
editLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadRoles();
|
||||
await load();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="admin-list-page staff-page">
|
||||
<section class="list-panel">
|
||||
<div class="list-panel-toolbar">
|
||||
<el-form inline class="list-chrome__grow">
|
||||
<el-form-item :label="t('common.keyword')">
|
||||
<el-input
|
||||
v-model="keyword"
|
||||
:placeholder="t('login.username_ph')"
|
||||
clearable
|
||||
style="width: 180px"
|
||||
@keyup.enter="load"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="load">{{ t('common.search') }}</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<div class="list-chrome__actions">
|
||||
<el-button type="primary" @click="openCreate">{{ t('staff.create_btn') }}</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminTableWrap>
|
||||
<el-table v-loading="loading" :data="rows" stripe>
|
||||
<template #empty>
|
||||
<AdminTableEmpty />
|
||||
</template>
|
||||
<el-table-column prop="username" :label="t('login.username')" min-width="120" />
|
||||
<el-table-column :label="t('staff.col.role')" min-width="140">
|
||||
<template #default="{ row }">{{ roleLabel(row.role) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('common.status')" width="100">
|
||||
<template #default="{ row }">{{ row.status }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('staff.col.last_login')" min-width="160">
|
||||
<template #default="{ row }">{{ formatTime(row.lastLoginAt) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column :label="t('common.actions')" width="100" align="center">
|
||||
<template #default="{ row }">
|
||||
<el-button link type="primary" size="small" @click="openEdit(row)">{{ t('common.edit') }}</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</AdminTableWrap>
|
||||
|
||||
<div class="pager">
|
||||
<el-pagination
|
||||
v-model:current-page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="total"
|
||||
:page-sizes="[10, 20, 50]"
|
||||
layout="total, sizes, prev, pager, next"
|
||||
background
|
||||
@current-change="load"
|
||||
@size-change="load"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<el-dialog v-model="createVisible" :title="t('staff.dialog.create')" width="480px" destroy-on-close>
|
||||
<el-form label-width="120px">
|
||||
<el-form-item :label="t('login.username')" required>
|
||||
<el-input v-model="createForm.username" autocomplete="off" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('staff.col.role')" required>
|
||||
<el-select v-model="createForm.roleCode" style="width: 100%">
|
||||
<el-option
|
||||
v-for="r in roles.filter((x) => x.code !== 'SUPER_ADMIN')"
|
||||
:key="r.code"
|
||||
:label="roleLabel(r.code)"
|
||||
:value="r.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('login.password')" required>
|
||||
<el-input v-model="createForm.password" type="password" autocomplete="new-password" />
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('user.field.confirm_password')" required>
|
||||
<el-input v-model="createForm.confirmPassword" type="password" autocomplete="new-password" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="createVisible = false">{{ t('common.cancel') }}</el-button>
|
||||
<el-button type="primary" :loading="createLoading" @click="submitCreate">{{ t('common.confirm') }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
|
||||
<el-dialog v-model="editVisible" :title="t('staff.dialog.edit')" width="480px" destroy-on-close>
|
||||
<el-form label-width="120px">
|
||||
<el-form-item :label="t('login.username')">
|
||||
<el-input :model-value="editForm.username" disabled />
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('staff.col.role')">
|
||||
<el-select v-model="editForm.roleCode" style="width: 100%" :disabled="editForm.roleCode === 'SUPER_ADMIN'">
|
||||
<el-option
|
||||
v-for="r in roles"
|
||||
:key="r.code"
|
||||
:label="roleLabel(r.code)"
|
||||
:value="r.code"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('common.status')">
|
||||
<el-select v-model="editForm.status" style="width: 100%">
|
||||
<el-option label="ACTIVE" value="ACTIVE" />
|
||||
<el-option label="SUSPENDED" value="SUSPENDED" />
|
||||
<el-option label="DISABLED" value="DISABLED" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item :label="t('user.field.reset_password')">
|
||||
<el-input v-model="editForm.password" type="password" autocomplete="new-password" :placeholder="t('user.ph.reset_password_short')" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="editVisible = false">{{ t('common.cancel') }}</el-button>
|
||||
<el-button type="primary" :loading="editLoading" @click="submitEdit">{{ t('common.confirm') }}</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.staff-page .pager {
|
||||
margin-top: 12px;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
</style>
|
||||
@@ -3,11 +3,14 @@ import { computed, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useAdminDashboard } from '../../composables/useAdminDashboard';
|
||||
import EChartPanel from '../../components/dashboard/EChartPanel.vue';
|
||||
import { buildCombinedTrendOption, buildTriplePieOption } from '../../utils/dashboard-charts';
|
||||
import { buildCombinedTrendOption, buildTriplePieOption, buildBarChartOption } from '../../utils/dashboard-charts';
|
||||
import { betStatusLabel } from '../../utils/bet-labels';
|
||||
import { useAdminLocale } from '../../composables/useAdminLocale';
|
||||
import { usePermissions } from '../../composables/usePermissions';
|
||||
|
||||
const { t } = useAdminLocale();
|
||||
const { role } = usePermissions();
|
||||
const isMatchOperatorView = computed(() => role.value === 'MATCH_ADMIN');
|
||||
const router = useRouter();
|
||||
const {
|
||||
s,
|
||||
@@ -32,8 +35,16 @@ function goKpiLink(link: KpiLink) {
|
||||
router.push(link.query ? { path: link.path, query: link.query } : link.path);
|
||||
}
|
||||
|
||||
const mainTrendOption = computed(() =>
|
||||
buildCombinedTrendOption(
|
||||
const mainTrendOption = computed(() => {
|
||||
const counts = s.value?.trend7d?.map((d) => d.betCount) ?? [];
|
||||
if (isMatchOperatorView.value) {
|
||||
return buildBarChartOption(
|
||||
trendLabels.value,
|
||||
[{ name: t('dash.chart_bet_count'), color: '#956400', values: counts }],
|
||||
{ amountAxis: false },
|
||||
);
|
||||
}
|
||||
return buildCombinedTrendOption(
|
||||
trendLabels.value,
|
||||
[
|
||||
{
|
||||
@@ -52,10 +63,10 @@ const mainTrendOption = computed(() =>
|
||||
values: s.value?.trend7d?.map((d) => toNum(d.ggr)) ?? [],
|
||||
},
|
||||
],
|
||||
s.value?.trend7d?.map((d) => d.betCount) ?? [],
|
||||
counts,
|
||||
chartI18n.value,
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
const distributionOption = computed(() => {
|
||||
const m = s.value?.matches;
|
||||
@@ -146,13 +157,15 @@ const kpiMatch = computed(() => {
|
||||
<template v-else-if="s">
|
||||
<el-card class="overview-board" shadow="never">
|
||||
<div v-if="s.generatedAt" class="board-head">
|
||||
<span class="board-hint">{{ t('dash.section_matches_hint') }}</span>
|
||||
<span class="board-hint">{{
|
||||
isMatchOperatorView ? t('dash.section_match_ops_hint') : t('dash.section_matches_hint')
|
||||
}}</span>
|
||||
<span class="dash-updated">
|
||||
{{ t('common.updated_at') }} {{ formatTime(s.generatedAt) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="kpi-grid kpi-primary">
|
||||
<div v-if="!isMatchOperatorView" class="kpi-grid kpi-primary">
|
||||
<div v-for="item in kpiPrimary" :key="item.label" class="kpi-cell">
|
||||
<span class="kpi-label">{{ item.label }}</span>
|
||||
<span class="kpi-value">{{ item.value }}</span>
|
||||
@@ -166,7 +179,7 @@ const kpiMatch = computed(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kpi-grid kpi-secondary">
|
||||
<div class="kpi-grid" :class="isMatchOperatorView ? 'kpi-primary' : 'kpi-secondary'">
|
||||
<div
|
||||
v-for="item in kpiMatch"
|
||||
:key="item.label"
|
||||
@@ -185,7 +198,9 @@ const kpiMatch = computed(() => {
|
||||
|
||||
<div class="charts-stack">
|
||||
<EChartPanel title="" :option="mainTrendOption" height="300px" class="chart-main" />
|
||||
<div class="chart-main-caption">{{ t('dash.trend_caption') }}</div>
|
||||
<div class="chart-main-caption">{{
|
||||
isMatchOperatorView ? t('dash.trend_bet_count_caption') : t('dash.trend_caption')
|
||||
}}</div>
|
||||
<EChartPanel title="" :option="distributionOption" height="200px" class="chart-dist" />
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
@@ -3,6 +3,7 @@ export const P = {
|
||||
reports: 'reports.view',
|
||||
usersView: 'users.view',
|
||||
usersCreate: 'users.create',
|
||||
usersResetPassword: 'users.reset_password',
|
||||
settings: 'settings.manage',
|
||||
agentsView: 'agents.view',
|
||||
agentsCreate: 'agents.create',
|
||||
|
||||
100
apps/api/src/applications/admin/admin-rbac.spec.ts
Normal file
100
apps/api/src/applications/admin/admin-rbac.spec.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { PermissionsGuard } from '../../domains/identity/guards';
|
||||
import { isAuditListUnrestricted } from '../../domains/operations/audit/audit-list-scope';
|
||||
import { PERMISSIONS_KEY } from '../../shared/common/decorators';
|
||||
|
||||
/** Mirrors run-seed.ts role permission assignments (SEC010–SEC012). */
|
||||
const ROLE_PERMISSIONS: Record<string, string[]> = {
|
||||
SUPER_ADMIN: ['*'],
|
||||
MATCH_ADMIN: [
|
||||
'matches.manage',
|
||||
'settlement.confirm',
|
||||
'content.manage',
|
||||
'bets.view',
|
||||
'reports.view',
|
||||
'audit.view',
|
||||
],
|
||||
FINANCE_ADMIN: [
|
||||
'wallet.deposit',
|
||||
'wallet.withdraw',
|
||||
'cashback.confirm',
|
||||
'agents.view',
|
||||
'agents.credit',
|
||||
'users.view',
|
||||
'users.create',
|
||||
'deposit.manage',
|
||||
'deposit.review',
|
||||
'reports.view',
|
||||
'bets.view',
|
||||
'audit.view',
|
||||
],
|
||||
SUPPORT: ['users.view', 'users.reset_password', 'bets.view', 'reports.view', 'audit.view'],
|
||||
};
|
||||
|
||||
function mockContext(user: Record<string, unknown>): ExecutionContext {
|
||||
return {
|
||||
switchToHttp: () => ({
|
||||
getRequest: () => ({ user }),
|
||||
}),
|
||||
getHandler: () => ({}),
|
||||
getClass: () => ({}),
|
||||
} as ExecutionContext;
|
||||
}
|
||||
|
||||
function guardAllows(user: Record<string, unknown>, ...required: string[]): boolean {
|
||||
const reflector = {
|
||||
getAllAndOverride: (key: string) => (key === PERMISSIONS_KEY ? required : undefined),
|
||||
} as unknown as Reflector;
|
||||
const guard = new PermissionsGuard(reflector);
|
||||
try {
|
||||
return guard.canActivate(mockContext(user));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function userWithRole(role: string) {
|
||||
return {
|
||||
userType: 'ADMIN',
|
||||
role,
|
||||
permissions: ROLE_PERMISSIONS[role] ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
describe('Admin RBAC (SEC010–SEC012)', () => {
|
||||
it('SEC010: SUPPORT cannot perform wallet deposit', () => {
|
||||
const user = userWithRole('SUPPORT');
|
||||
expect(guardAllows(user, 'wallet.deposit')).toBe(false);
|
||||
expect(guardAllows(user, 'users.view')).toBe(true);
|
||||
expect(guardAllows(user, 'users.reset_password')).toBe(true);
|
||||
});
|
||||
|
||||
it('SEC011: FINANCE_ADMIN cannot manage matches', () => {
|
||||
const user = userWithRole('FINANCE_ADMIN');
|
||||
expect(guardAllows(user, 'matches.manage')).toBe(false);
|
||||
expect(guardAllows(user, 'wallet.deposit')).toBe(true);
|
||||
expect(guardAllows(user, 'agents.credit')).toBe(true);
|
||||
});
|
||||
|
||||
it('SEC012: MATCH_ADMIN cannot perform wallet deposit', () => {
|
||||
const user = userWithRole('MATCH_ADMIN');
|
||||
expect(guardAllows(user, 'wallet.deposit')).toBe(false);
|
||||
expect(guardAllows(user, 'settlement.confirm')).toBe(true);
|
||||
expect(guardAllows(user, 'content.manage')).toBe(true);
|
||||
expect(guardAllows(user, 'settlement.resettle')).toBe(false);
|
||||
});
|
||||
|
||||
it('SUPER_ADMIN bypasses permission checks', () => {
|
||||
const user = userWithRole('SUPER_ADMIN');
|
||||
expect(guardAllows(user, 'wallet.deposit')).toBe(true);
|
||||
expect(guardAllows(user, 'matches.manage')).toBe(true);
|
||||
expect(guardAllows(user, 'settings.manage')).toBe(true);
|
||||
});
|
||||
|
||||
it('audit list scope: only SUPER_ADMIN is unrestricted', () => {
|
||||
expect(isAuditListUnrestricted('SUPER_ADMIN')).toBe(true);
|
||||
expect(isAuditListUnrestricted('FINANCE_ADMIN')).toBe(false);
|
||||
expect(isAuditListUnrestricted('MATCH_ADMIN')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,7 @@ import { jsonResponse } from '../../shared/common/filters';
|
||||
import { appBadRequest, appForbidden } from '../../shared/common/app-error';
|
||||
import { getUploadRoot } from '../../shared/uploads/upload-paths';
|
||||
import { UsersService } from '../../domains/identity/users.service';
|
||||
import { AdminStaffService } from '../../domains/identity/admin-staff.service';
|
||||
import { AgentsService } from '../../domains/agent/agents.service';
|
||||
import { WalletService } from '../../domains/ledger/wallet.service';
|
||||
import { MatchesService } from '../../domains/catalog/matches.service';
|
||||
@@ -255,6 +256,40 @@ class UpdatePlayerAdminDto {
|
||||
cashbackRate?: number | null;
|
||||
}
|
||||
|
||||
class CreateStaffDto {
|
||||
@IsString()
|
||||
username!: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password!: string;
|
||||
|
||||
@IsString()
|
||||
roleCode!: string;
|
||||
}
|
||||
|
||||
class UpdateStaffDto {
|
||||
@IsOptional()
|
||||
@IsIn(['ACTIVE', 'SUSPENDED', 'DISABLED'])
|
||||
status?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
roleCode?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password?: string;
|
||||
}
|
||||
|
||||
class ResetPlayerPasswordDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password?: string;
|
||||
}
|
||||
|
||||
class PlatformDirectCashbackSettingsDto {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@@ -1168,6 +1203,7 @@ export class AdminController {
|
||||
private databaseReset: DatabaseResetService,
|
||||
private smokeTests: SmokeTestService,
|
||||
private depositService: DepositService,
|
||||
private staff: AdminStaffService,
|
||||
) {}
|
||||
|
||||
@Get('dashboard')
|
||||
@@ -1178,7 +1214,7 @@ export class AdminController {
|
||||
}
|
||||
|
||||
@Get('users/page-init')
|
||||
@RequirePermissions(P.agentsView)
|
||||
@RequirePermissions(P.agentsView, P.usersView)
|
||||
async getUsersPageInit() {
|
||||
const [
|
||||
playerSettings,
|
||||
@@ -1380,6 +1416,84 @@ export class AdminController {
|
||||
return jsonResponse(detail);
|
||||
}
|
||||
|
||||
@Post('users/:id/reset-password')
|
||||
@RequirePermissions(P.usersResetPassword)
|
||||
async resetPlayerPassword(
|
||||
@CurrentUser('id') operatorId: bigint,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: ResetPlayerPasswordDto,
|
||||
) {
|
||||
const { password } = await this.staff.resetPlayerPassword(BigInt(id), dto.password);
|
||||
await this.audit.log({
|
||||
operatorId,
|
||||
operatorType: 'ADMIN',
|
||||
action: 'RESET_PLAYER_PASSWORD',
|
||||
module: 'USERS',
|
||||
targetId: id,
|
||||
});
|
||||
const detail = await this.users.getPlayerAdminDetail(BigInt(id));
|
||||
return jsonResponse({ ...detail, password });
|
||||
}
|
||||
|
||||
@Get('staff/roles')
|
||||
@RequirePermissions(P.settings)
|
||||
async listStaffRoles() {
|
||||
const roles = await this.staff.listRoles();
|
||||
return jsonResponse(roles);
|
||||
}
|
||||
|
||||
@Get('staff')
|
||||
@RequirePermissions(P.settings)
|
||||
async listStaff(
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
@Query('keyword') keyword?: string,
|
||||
) {
|
||||
const result = await this.staff.listStaff(
|
||||
page ? parseInt(page, 10) : 1,
|
||||
pageSize ? parseInt(pageSize, 10) : 20,
|
||||
keyword,
|
||||
);
|
||||
return jsonResponse(result);
|
||||
}
|
||||
|
||||
@Post('staff')
|
||||
@RequirePermissions(P.settings)
|
||||
async createStaff(
|
||||
@CurrentUser('id') operatorId: bigint,
|
||||
@Body() dto: CreateStaffDto,
|
||||
) {
|
||||
const created = await this.staff.createStaff(dto);
|
||||
await this.audit.log({
|
||||
operatorId,
|
||||
operatorType: 'ADMIN',
|
||||
action: 'CREATE_STAFF',
|
||||
module: 'STAFF',
|
||||
targetId: created.id,
|
||||
afterData: { username: created.username, role: created.role },
|
||||
});
|
||||
return jsonResponse(created);
|
||||
}
|
||||
|
||||
@Patch('staff/:id')
|
||||
@RequirePermissions(P.settings)
|
||||
async updateStaff(
|
||||
@CurrentUser('id') operatorId: bigint,
|
||||
@Param('id') id: string,
|
||||
@Body() dto: UpdateStaffDto,
|
||||
) {
|
||||
const updated = await this.staff.updateStaff(BigInt(id), dto);
|
||||
await this.audit.log({
|
||||
operatorId,
|
||||
operatorType: 'ADMIN',
|
||||
action: 'UPDATE_STAFF',
|
||||
module: 'STAFF',
|
||||
targetId: id,
|
||||
afterData: JSON.stringify({ status: dto.status, roleCode: dto.roleCode }),
|
||||
});
|
||||
return jsonResponse(updated);
|
||||
}
|
||||
|
||||
@Delete('users/:id')
|
||||
@RequirePermissions(P.usersCreate)
|
||||
async deletePlayer(
|
||||
@@ -2803,6 +2917,9 @@ export class AdminController {
|
||||
@Get('audit-logs')
|
||||
@RequirePermissions(P.audit)
|
||||
async auditLogs(
|
||||
@CurrentUser('id') viewerId: bigint,
|
||||
@CurrentUser('role') viewerRole: string | undefined,
|
||||
@CurrentUser('userType') viewerUserType: string,
|
||||
@Query('page') page?: string,
|
||||
@Query('pageSize') pageSize?: string,
|
||||
@Query('module') module?: string,
|
||||
@@ -2811,6 +2928,7 @@ export class AdminController {
|
||||
page ? parseInt(page, 10) : 1,
|
||||
pageSize ? parseInt(pageSize, 10) : 10,
|
||||
module || undefined,
|
||||
{ viewerId, viewerRole, viewerUserType },
|
||||
);
|
||||
return jsonResponse(result);
|
||||
}
|
||||
|
||||
194
apps/api/src/domains/identity/admin-staff.service.ts
Normal file
194
apps/api/src/domains/identity/admin-staff.service.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { PrismaService } from '../../shared/prisma/prisma.service';
|
||||
import { appBadRequest, appNotFound } from '../../shared/common/app-error';
|
||||
import { ensureUserInviteCode } from '../../shared/common/invite-code.util';
|
||||
|
||||
const STAFF_ROLE_CODES = ['SUPER_ADMIN', 'MATCH_ADMIN', 'FINANCE_ADMIN', 'SUPPORT'] as const;
|
||||
|
||||
function generatePassword(length = 10): string {
|
||||
const raw = randomBytes(12).toString('base64url').replace(/[^a-zA-Z0-9]/g, '');
|
||||
const base = (raw + 'Aa1').slice(0, Math.max(8, length));
|
||||
return base;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminStaffService {
|
||||
constructor(private prisma: PrismaService) {}
|
||||
|
||||
async listRoles() {
|
||||
const roles = await this.prisma.role.findMany({
|
||||
where: { code: { in: [...STAFF_ROLE_CODES] } },
|
||||
orderBy: { code: 'asc' },
|
||||
select: { id: true, code: true, name: true },
|
||||
});
|
||||
return roles.map((r) => ({
|
||||
id: r.id.toString(),
|
||||
code: r.code,
|
||||
name: r.name,
|
||||
}));
|
||||
}
|
||||
|
||||
async listStaff(page = 1, pageSize = 20, keyword?: string) {
|
||||
const where = {
|
||||
userType: 'ADMIN' as const,
|
||||
deletedAt: null,
|
||||
...(keyword?.trim()
|
||||
? { username: { contains: keyword.trim(), mode: 'insensitive' as const } }
|
||||
: {}),
|
||||
};
|
||||
const [total, items] = await Promise.all([
|
||||
this.prisma.user.count({ where }),
|
||||
this.prisma.user.findMany({
|
||||
where,
|
||||
skip: (page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
include: {
|
||||
auth: { select: { lastLoginAt: true } },
|
||||
adminRole: { include: { role: { select: { code: true, name: true } } } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
total,
|
||||
items: items.map((u) => ({
|
||||
id: u.id.toString(),
|
||||
username: u.username,
|
||||
status: u.status,
|
||||
role: u.adminRole?.role?.code ?? null,
|
||||
roleName: u.adminRole?.role?.name ?? null,
|
||||
lastLoginAt: u.auth?.lastLoginAt ?? null,
|
||||
createdAt: u.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
async createStaff(data: { username: string; password: string; roleCode: string }) {
|
||||
const username = data.username.trim();
|
||||
if (!username) throw appBadRequest('USERNAME_REQUIRED');
|
||||
if (data.password.length < 8) throw appBadRequest('PASSWORD_MIN_LENGTH');
|
||||
if (!STAFF_ROLE_CODES.includes(data.roleCode as (typeof STAFF_ROLE_CODES)[number])) {
|
||||
throw appBadRequest('INVALID_ROLE');
|
||||
}
|
||||
|
||||
const existing = await this.prisma.user.findUnique({ where: { username } });
|
||||
if (existing) throw appBadRequest('USERNAME_TAKEN');
|
||||
|
||||
const role = await this.prisma.role.findUnique({ where: { code: data.roleCode } });
|
||||
if (!role) throw appBadRequest('INVALID_ROLE');
|
||||
|
||||
const hash = await bcrypt.hash(data.password, 10);
|
||||
const user = await this.prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
userType: 'ADMIN',
|
||||
auth: { create: { passwordHash: hash } },
|
||||
adminRole: { create: { roleId: role.id } },
|
||||
},
|
||||
include: {
|
||||
adminRole: { include: { role: { select: { code: true, name: true } } } },
|
||||
},
|
||||
});
|
||||
await ensureUserInviteCode(this.prisma, user.id);
|
||||
|
||||
return {
|
||||
id: user.id.toString(),
|
||||
username: user.username,
|
||||
status: user.status,
|
||||
role: user.adminRole?.role?.code ?? null,
|
||||
roleName: user.adminRole?.role?.name ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async updateStaff(
|
||||
staffId: bigint,
|
||||
data: { status?: string; roleCode?: string; password?: string },
|
||||
) {
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: { id: staffId, userType: 'ADMIN', deletedAt: null },
|
||||
include: { auth: true, adminRole: true },
|
||||
});
|
||||
if (!user) throw appNotFound('USER_NOT_FOUND');
|
||||
|
||||
if (data.status !== undefined) {
|
||||
if (!['ACTIVE', 'SUSPENDED', 'DISABLED'].includes(data.status)) {
|
||||
throw appBadRequest('INVALID_STATUS');
|
||||
}
|
||||
await this.prisma.user.update({
|
||||
where: { id: staffId },
|
||||
data: { status: data.status },
|
||||
});
|
||||
}
|
||||
|
||||
if (data.roleCode !== undefined) {
|
||||
if (!STAFF_ROLE_CODES.includes(data.roleCode as (typeof STAFF_ROLE_CODES)[number])) {
|
||||
throw appBadRequest('INVALID_ROLE');
|
||||
}
|
||||
const role = await this.prisma.role.findUnique({ where: { code: data.roleCode } });
|
||||
if (!role) throw appBadRequest('INVALID_ROLE');
|
||||
if (user.adminRole) {
|
||||
await this.prisma.adminUserRole.update({
|
||||
where: { userId: staffId },
|
||||
data: { roleId: role.id },
|
||||
});
|
||||
} else {
|
||||
await this.prisma.adminUserRole.create({
|
||||
data: { userId: staffId, roleId: role.id },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
let plainPassword: string | undefined;
|
||||
if (data.password !== undefined) {
|
||||
if (data.password.length < 8) throw appBadRequest('PASSWORD_MIN_LENGTH');
|
||||
if (!user.auth) throw appBadRequest('AUTH_INFO_MISSING');
|
||||
plainPassword = data.password;
|
||||
const hash = await bcrypt.hash(data.password, 10);
|
||||
await this.prisma.userAuth.update({
|
||||
where: { userId: staffId },
|
||||
data: { passwordHash: hash, loginFailCount: 0, lockedUntil: null },
|
||||
});
|
||||
}
|
||||
|
||||
const refreshed = await this.prisma.user.findUnique({
|
||||
where: { id: staffId },
|
||||
include: { adminRole: { include: { role: { select: { code: true, name: true } } } } },
|
||||
});
|
||||
|
||||
return {
|
||||
id: refreshed!.id.toString(),
|
||||
username: refreshed!.username,
|
||||
status: refreshed!.status,
|
||||
role: refreshed!.adminRole?.role?.code ?? null,
|
||||
roleName: refreshed!.adminRole?.role?.name ?? null,
|
||||
...(plainPassword ? { password: plainPassword } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async resetPlayerPassword(playerId: bigint, password?: string) {
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: { id: playerId, userType: 'PLAYER', deletedAt: null },
|
||||
include: { auth: true },
|
||||
});
|
||||
if (!user) throw appNotFound('PLAYER_NOT_FOUND');
|
||||
if (!user.auth) throw appBadRequest('AUTH_INFO_MISSING');
|
||||
|
||||
const nextPassword = password?.trim() || generatePassword();
|
||||
if (nextPassword.length < 8) throw appBadRequest('PASSWORD_MIN_LENGTH');
|
||||
|
||||
const hash = await bcrypt.hash(nextPassword, 10);
|
||||
await this.prisma.userAuth.update({
|
||||
where: { userId: playerId },
|
||||
data: { passwordHash: hash, loginFailCount: 0, lockedUntil: null },
|
||||
});
|
||||
await this.prisma.userPreference.upsert({
|
||||
where: { userId: playerId },
|
||||
create: { userId: playerId, managedPassword: nextPassword },
|
||||
update: { managedPassword: nextPassword },
|
||||
});
|
||||
|
||||
return { password: nextPassword };
|
||||
}
|
||||
}
|
||||
@@ -171,6 +171,7 @@ export class AuthController {
|
||||
@CurrentUser('userType') userType: string,
|
||||
@CurrentUser('locale') locale: string | undefined,
|
||||
@CurrentUser('role') role: string | undefined,
|
||||
@CurrentUser('permissions') permissions: string[] | undefined,
|
||||
@CurrentUser('agentLevel') agentLevel: number | null | undefined,
|
||||
) {
|
||||
const level = userType === 'AGENT' ? agentLevel ?? null : null;
|
||||
@@ -194,6 +195,7 @@ export class AuthController {
|
||||
userType,
|
||||
locale,
|
||||
role,
|
||||
permissions: userType === 'ADMIN' ? permissions ?? [] : undefined,
|
||||
agentLevel: level,
|
||||
maxAgentLevel,
|
||||
canManageSubAgents,
|
||||
|
||||
@@ -98,7 +98,18 @@ export class AuthService {
|
||||
} else {
|
||||
user = await this.prisma.user.findUnique({
|
||||
where: { username: username.trim() },
|
||||
include: { auth: true, adminRole: { include: { role: true } } },
|
||||
include: {
|
||||
auth: true,
|
||||
adminRole: {
|
||||
include: {
|
||||
role: {
|
||||
include: {
|
||||
permissions: { include: { permission: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -178,6 +189,15 @@ export class AuthService {
|
||||
|
||||
const token = this.jwt.sign(payload, { expiresIn });
|
||||
|
||||
const rolePerms = user.adminRole?.role as
|
||||
| { permissions?: Array<{ permission: { code: string } }> }
|
||||
| undefined
|
||||
| null;
|
||||
const adminPermissions =
|
||||
user.userType === 'ADMIN'
|
||||
? (rolePerms?.permissions?.map((rp) => rp.permission.code) ?? [])
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
token,
|
||||
user: {
|
||||
@@ -187,6 +207,7 @@ export class AuthService {
|
||||
locale: user.locale,
|
||||
role: user.adminRole?.role?.code,
|
||||
agentLevel: user.userType === 'AGENT' ? user.agentLevel : null,
|
||||
...(adminPermissions ? { permissions: adminPermissions } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { UsersService } from './users.service';
|
||||
import { AdminStaffService } from './admin-staff.service';
|
||||
import { AgentsModule } from '../agent/agents.module';
|
||||
import { CashbackModule } from '../operations/cashback/cashback.module';
|
||||
|
||||
@Module({
|
||||
imports: [AgentsModule, CashbackModule],
|
||||
providers: [UsersService],
|
||||
exports: [UsersService],
|
||||
providers: [UsersService, AdminStaffService],
|
||||
exports: [UsersService, AdminStaffService],
|
||||
})
|
||||
export class UsersModule {}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isAuditListUnrestricted } from './audit-list-scope';
|
||||
|
||||
describe('audit-list-scope', () => {
|
||||
describe('isAuditListUnrestricted', () => {
|
||||
it('allows SUPER_ADMIN to see all logs', () => {
|
||||
expect(isAuditListUnrestricted('SUPER_ADMIN')).toBe(true);
|
||||
});
|
||||
|
||||
it('scopes MATCH_ADMIN, FINANCE_ADMIN, and SUPPORT', () => {
|
||||
expect(isAuditListUnrestricted('MATCH_ADMIN')).toBe(false);
|
||||
expect(isAuditListUnrestricted('FINANCE_ADMIN')).toBe(false);
|
||||
expect(isAuditListUnrestricted('SUPPORT')).toBe(false);
|
||||
});
|
||||
|
||||
it('scopes unknown or missing role', () => {
|
||||
expect(isAuditListUnrestricted(undefined)).toBe(false);
|
||||
expect(isAuditListUnrestricted(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
45
apps/api/src/domains/operations/audit/audit-list-scope.ts
Normal file
45
apps/api/src/domains/operations/audit/audit-list-scope.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../../shared/prisma/prisma.service';
|
||||
|
||||
export type AuditViewerScope = {
|
||||
viewerId: bigint;
|
||||
viewerRole?: string | null;
|
||||
viewerUserType: string;
|
||||
};
|
||||
|
||||
/** SUPER_ADMIN (and unrestricted legacy admins) see all audit rows. */
|
||||
export function isAuditListUnrestricted(role?: string | null): boolean {
|
||||
return role === 'SUPER_ADMIN';
|
||||
}
|
||||
|
||||
/**
|
||||
* Non–super-admin staff may only see audit rows whose operator shares their admin role,
|
||||
* or (for SUPPORT) player-initiated identity actions.
|
||||
*/
|
||||
export async function buildAuditListScopeWhere(
|
||||
prisma: PrismaService,
|
||||
scope: AuditViewerScope,
|
||||
): Promise<Prisma.AuditLogWhereInput | undefined> {
|
||||
if (isAuditListUnrestricted(scope.viewerRole)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!scope.viewerRole) {
|
||||
return { operatorId: scope.viewerId };
|
||||
}
|
||||
|
||||
const sameRoleUsers = await prisma.user.findMany({
|
||||
where: { adminRole: { role: { code: scope.viewerRole } } },
|
||||
select: { id: true },
|
||||
});
|
||||
const sameRoleOperatorIds = sameRoleUsers.map((u) => u.id);
|
||||
|
||||
const or: Prisma.AuditLogWhereInput[] = [{ operatorId: { in: sameRoleOperatorIds } }];
|
||||
|
||||
// SUPPORT handles player account recovery; include player-initiated audit entries.
|
||||
if (scope.viewerRole === 'SUPPORT') {
|
||||
or.push({ operatorType: 'PLAYER' });
|
||||
}
|
||||
|
||||
return { OR: or };
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../../shared/prisma/prisma.service';
|
||||
import { AuditViewerScope, buildAuditListScopeWhere } from './audit-list-scope';
|
||||
|
||||
@Injectable()
|
||||
export class AuditService {
|
||||
@@ -31,10 +33,19 @@ export class AuditService {
|
||||
});
|
||||
}
|
||||
|
||||
async list(page = 1, pageSize = 10, module?: string) {
|
||||
async list(
|
||||
page = 1,
|
||||
pageSize = 10,
|
||||
module?: string,
|
||||
viewer?: AuditViewerScope,
|
||||
) {
|
||||
const skip = (page - 1) * pageSize;
|
||||
const where = module ? { module } : {};
|
||||
const [items, total] = await Promise.all([
|
||||
const scopeWhere = viewer ? await buildAuditListScopeWhere(this.prisma, viewer) : undefined;
|
||||
const where: Prisma.AuditLogWhereInput = {
|
||||
...(module ? { module } : {}),
|
||||
...(scopeWhere ?? {}),
|
||||
};
|
||||
const [rows, total] = await Promise.all([
|
||||
this.prisma.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { createdAt: 'desc' },
|
||||
@@ -43,6 +54,42 @@ export class AuditService {
|
||||
}),
|
||||
this.prisma.auditLog.count({ where }),
|
||||
]);
|
||||
|
||||
const operatorIds = [
|
||||
...new Set(rows.map((r) => r.operatorId).filter((id): id is bigint => id != null)),
|
||||
];
|
||||
const operators =
|
||||
operatorIds.length > 0
|
||||
? await this.prisma.user.findMany({
|
||||
where: { id: { in: operatorIds } },
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
userType: true,
|
||||
adminRole: { select: { role: { select: { code: true } } } },
|
||||
},
|
||||
})
|
||||
: [];
|
||||
const operatorById = new Map(operators.map((u) => [u.id.toString(), u]));
|
||||
|
||||
const items = rows.map((row) => {
|
||||
const op = row.operatorId ? operatorById.get(row.operatorId.toString()) : null;
|
||||
return {
|
||||
id: row.id.toString(),
|
||||
action: row.action,
|
||||
module: row.module,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
operatorId: row.operatorId?.toString() ?? null,
|
||||
operatorUsername: op?.username ?? null,
|
||||
operatorRole: op?.adminRole?.role?.code ?? null,
|
||||
operatorUserType: op?.userType ?? null,
|
||||
operatorType: row.operatorType,
|
||||
ipAddress: row.ipAddress,
|
||||
createdAt: row.createdAt,
|
||||
};
|
||||
});
|
||||
|
||||
return { items, total, page, pageSize };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,9 @@ import { ensureUserInviteCode } from '../../shared/common/invite-code.util';
|
||||
|
||||
export const DEMO_ACCOUNTS = [
|
||||
'admin / Admin@123',
|
||||
'matchadmin / MatchAdmin@123',
|
||||
'financeadmin / FinanceAdmin@123',
|
||||
'support1 / Support@123',
|
||||
'agent1 / Agent@123',
|
||||
'player1 / Player@123',
|
||||
] as const;
|
||||
@@ -40,10 +43,11 @@ async function seedRolesAndConfig() {
|
||||
});
|
||||
|
||||
const permCodes = [
|
||||
'users.create', 'users.view', 'agents.create', 'agents.view', 'agents.credit',
|
||||
'users.create', 'users.view', 'users.reset_password', 'agents.create', 'agents.view', 'agents.credit',
|
||||
'wallet.deposit', 'wallet.withdraw', 'matches.manage', 'settlement.confirm',
|
||||
'settlement.resettle', 'cashback.confirm', 'content.manage', 'reports.view',
|
||||
'bets.view', 'settings.manage', 'settings.reset_database', 'audit.view',
|
||||
'deposit.manage', 'deposit.review',
|
||||
];
|
||||
|
||||
const permIds = new Map<string, bigint>();
|
||||
@@ -79,14 +83,17 @@ async function seedRolesAndConfig() {
|
||||
return role;
|
||||
}
|
||||
|
||||
await ensureRole('MATCH_ADMIN', 'Match Admin', [
|
||||
'matches.manage', 'settlement.confirm', 'bets.view', 'reports.view', 'audit.view',
|
||||
const matchAdminRole = await ensureRole('MATCH_ADMIN', 'Match Admin', [
|
||||
'matches.manage', 'settlement.confirm', 'content.manage', 'bets.view', 'reports.view', 'audit.view',
|
||||
]);
|
||||
await ensureRole('FINANCE_ADMIN', 'Finance Admin', [
|
||||
'wallet.deposit', 'wallet.withdraw', 'cashback.confirm', 'agents.view',
|
||||
const financeAdminRole = await ensureRole('FINANCE_ADMIN', 'Finance Admin', [
|
||||
'wallet.deposit', 'wallet.withdraw', 'cashback.confirm', 'agents.view', 'agents.credit',
|
||||
'users.view', 'users.create', 'deposit.manage', 'deposit.review',
|
||||
'reports.view', 'bets.view', 'audit.view',
|
||||
]);
|
||||
await ensureRole('SUPPORT', 'Support', ['users.view', 'bets.view', 'reports.view', 'audit.view']);
|
||||
const supportRole = await ensureRole('SUPPORT', 'Support', [
|
||||
'users.view', 'users.reset_password', 'bets.view', 'reports.view', 'audit.view',
|
||||
]);
|
||||
|
||||
const defaultBettingLimits = [
|
||||
['bet.min_stake', '1', '最小单注金额'],
|
||||
@@ -104,7 +111,7 @@ async function seedRolesAndConfig() {
|
||||
});
|
||||
}
|
||||
|
||||
return superAdminRole;
|
||||
return { superAdminRole, matchAdminRole, financeAdminRole, supportRole };
|
||||
}
|
||||
|
||||
async function seedAdminUser(superAdminRole: { id: bigint }) {
|
||||
@@ -122,6 +129,51 @@ async function seedAdminUser(superAdminRole: { id: bigint }) {
|
||||
});
|
||||
}
|
||||
|
||||
async function seedStaffDemoUser(
|
||||
username: string,
|
||||
password: string,
|
||||
roleId: bigint,
|
||||
) {
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
const user = await prisma.user.upsert({
|
||||
where: { username },
|
||||
create: {
|
||||
username,
|
||||
userType: 'ADMIN',
|
||||
auth: { create: { passwordHash: hash } },
|
||||
adminRole: { create: { roleId } },
|
||||
},
|
||||
update: {
|
||||
userType: 'ADMIN',
|
||||
status: 'ACTIVE',
|
||||
},
|
||||
});
|
||||
await prisma.userAuth.upsert({
|
||||
where: { userId: user.id },
|
||||
create: { userId: user.id, passwordHash: hash },
|
||||
update: {
|
||||
passwordHash: hash,
|
||||
loginFailCount: 0,
|
||||
lockedUntil: null,
|
||||
},
|
||||
});
|
||||
await prisma.adminUserRole.upsert({
|
||||
where: { userId: user.id },
|
||||
create: { userId: user.id, roleId },
|
||||
update: { roleId },
|
||||
});
|
||||
}
|
||||
|
||||
async function seedDevStaffUsers(roles: {
|
||||
matchAdminRole: { id: bigint };
|
||||
financeAdminRole: { id: bigint };
|
||||
supportRole: { id: bigint };
|
||||
}) {
|
||||
await seedStaffDemoUser('matchadmin', 'MatchAdmin@123', roles.matchAdminRole.id);
|
||||
await seedStaffDemoUser('financeadmin', 'FinanceAdmin@123', roles.financeAdminRole.id);
|
||||
await seedStaffDemoUser('support1', 'Support@123', roles.supportRole.id);
|
||||
}
|
||||
|
||||
async function seedDevDemoUsers() {
|
||||
const agentHash = await bcrypt.hash('Agent@123', 10);
|
||||
const playerHash = await bcrypt.hash('Player@123', 10);
|
||||
@@ -356,10 +408,11 @@ export async function runSeed(client: PrismaClient, options?: RunSeedOptions) {
|
||||
const mode = resolveSeedMode(options);
|
||||
console.log(`Seeding database (mode=${mode})...`);
|
||||
|
||||
const superAdminRole = await seedRolesAndConfig();
|
||||
await seedAdminUser(superAdminRole);
|
||||
const roles = await seedRolesAndConfig();
|
||||
await seedAdminUser(roles.superAdminRole);
|
||||
|
||||
if (mode === 'dev') {
|
||||
await seedDevStaffUsers(roles);
|
||||
await seedDevDemoUsers();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed } from 'vue';
|
||||
import { ref, computed, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import api from '../../api';
|
||||
import OutrightEventSection, {
|
||||
@@ -12,6 +12,10 @@ import emptyMatchesImg from '../../assets/images/empty-matches.svg';
|
||||
import GoldSpinner from '../../components/GoldSpinner.vue';
|
||||
import { useOnLocaleChange } from '../../composables/useOnLocaleChange';
|
||||
|
||||
const props = defineProps<{
|
||||
activated?: boolean;
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
const auth = useAuthStore();
|
||||
|
||||
@@ -94,6 +98,14 @@ function mergeOddsOnly(fresh: OutrightEvent[]) {
|
||||
|
||||
useOnLocaleChange(load);
|
||||
|
||||
// 每次切回优胜冠军 Tab 时静默刷新赔率
|
||||
watch(
|
||||
() => props.activated,
|
||||
(active) => {
|
||||
if (active && events.value.length > 0) void load();
|
||||
},
|
||||
);
|
||||
|
||||
function toggle(id: string) {
|
||||
const next = new Set(expanded.value);
|
||||
if (next.has(id)) next.delete(id);
|
||||
|
||||
@@ -55,7 +55,38 @@ export function usePlayerHome() {
|
||||
loading.value = true;
|
||||
try {
|
||||
const { data } = await api.get('/player/home');
|
||||
homeRaw.value = (data.data ?? null) as HomePayload | null;
|
||||
const fresh = (data.data ?? null) as HomePayload | null;
|
||||
|
||||
if (fresh && homeRaw.value) {
|
||||
// 已有数据 → 原地更新,保留对象引用,避免图片重新加载
|
||||
const existing = homeRaw.value;
|
||||
existing.banners = fresh.banners;
|
||||
existing.announcements = fresh.announcements;
|
||||
existing.ticker = fresh.ticker;
|
||||
existing.notices = fresh.notices;
|
||||
|
||||
if (fresh.hotMatches && existing.hotMatches) {
|
||||
const freshMap = new Map(fresh.hotMatches.map((m) => [m.id, m]));
|
||||
for (const m of existing.hotMatches) {
|
||||
const f = freshMap.get(m.id);
|
||||
if (f) Object.assign(m, f);
|
||||
}
|
||||
// 处理新增或删除的比赛
|
||||
const existingIds = new Set(existing.hotMatches.map((m) => m.id));
|
||||
for (const fm of fresh.hotMatches) {
|
||||
if (!existingIds.has(fm.id)) existing.hotMatches.push(fm);
|
||||
}
|
||||
for (let i = existing.hotMatches.length - 1; i >= 0; i--) {
|
||||
if (!freshMap.has(existing.hotMatches[i].id)) {
|
||||
existing.hotMatches.splice(i, 1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
existing.hotMatches = fresh.hotMatches;
|
||||
}
|
||||
} else {
|
||||
homeRaw.value = fresh;
|
||||
}
|
||||
} catch {
|
||||
homeRaw.value = null;
|
||||
} finally {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ref, shallowRef } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
import api from '../api';
|
||||
import type { MatchPhase } from '../utils/matchPhase';
|
||||
|
||||
@@ -35,21 +35,44 @@ export interface PlayerMatchSummary {
|
||||
} | null;
|
||||
}
|
||||
|
||||
const summaryMatches = shallowRef<PlayerMatchSummary[]>([]);
|
||||
const summaryMatches = ref<PlayerMatchSummary[]>([]);
|
||||
const summaryLoading = ref(false);
|
||||
|
||||
let summaryInflight: Promise<void> | null = null;
|
||||
|
||||
async function loadSummary(force = false): Promise<void> {
|
||||
if (force) summaryMatches.value = [];
|
||||
if (!force && summaryMatches.value.length > 0) return;
|
||||
async function loadSummary(force = false, silent = false): Promise<void> {
|
||||
if (force && !silent) summaryMatches.value = [];
|
||||
if (!force && !silent && summaryMatches.value.length > 0) return;
|
||||
if (summaryInflight) return summaryInflight;
|
||||
|
||||
summaryLoading.value = true;
|
||||
if (!silent) summaryLoading.value = true;
|
||||
summaryInflight = (async () => {
|
||||
try {
|
||||
const { data } = await api.get('/player/matches');
|
||||
summaryMatches.value = (data.data ?? []) as PlayerMatchSummary[];
|
||||
const fresh = (data.data ?? []) as PlayerMatchSummary[];
|
||||
|
||||
if (silent && summaryMatches.value.length > 0) {
|
||||
// 静默模式:原地更新,保留对象引用,避免图片重新加载
|
||||
const freshMap = new Map(fresh.map((m) => [m.id, m]));
|
||||
const existingIds = new Set(summaryMatches.value.map((m) => m.id));
|
||||
|
||||
for (const fm of fresh) {
|
||||
if (!existingIds.has(fm.id)) {
|
||||
summaryMatches.value.push(fm);
|
||||
}
|
||||
}
|
||||
for (let i = summaryMatches.value.length - 1; i >= 0; i--) {
|
||||
const existing = summaryMatches.value[i];
|
||||
const f = freshMap.get(existing.id);
|
||||
if (f) {
|
||||
Object.assign(existing, f);
|
||||
} else {
|
||||
summaryMatches.value.splice(i, 1);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
summaryMatches.value = fresh;
|
||||
}
|
||||
} catch {
|
||||
if (!summaryMatches.value.length) summaryMatches.value = [];
|
||||
} finally {
|
||||
|
||||
@@ -144,7 +144,7 @@ watch(
|
||||
|
||||
<main ref="mainRef" :class="['main', { 'has-nav': showBottomNav }]">
|
||||
<RouterView v-slot="{ Component, route: viewRoute }">
|
||||
<KeepAlive v-if="viewRoute.meta.keepAlive" :max="3">
|
||||
<KeepAlive v-if="viewRoute.meta.keepAlive" :max="10">
|
||||
<component :is="Component" :key="viewRoute.path" />
|
||||
</KeepAlive>
|
||||
<component v-else :is="Component" :key="viewRoute.fullPath" />
|
||||
|
||||
@@ -64,6 +64,7 @@ const router = useRouter();
|
||||
const mainTab = ref<MainTab>('matches');
|
||||
const timeTab = ref<TimeTab>('today');
|
||||
const showAll = ref(false);
|
||||
const outrightActivated = ref(false);
|
||||
const filterNow = ref(new Date());
|
||||
const { summaryMatches, summaryLoading, loadSummary } = usePlayerMatches();
|
||||
const matches = summaryMatches;
|
||||
@@ -162,11 +163,13 @@ function toggleLeague(leagueId: string) {
|
||||
|
||||
function selectMainTab(tab: MainTab) {
|
||||
mainTab.value = tab;
|
||||
if (tab === 'outright') outrightActivated.value = true;
|
||||
}
|
||||
|
||||
onActivated(() => {
|
||||
filterNow.value = new Date();
|
||||
timeTab.value = 'today';
|
||||
void loadSummary(true, true);
|
||||
});
|
||||
|
||||
function goMatch(id: string) {
|
||||
@@ -204,7 +207,7 @@ function goMatch(id: string) {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-show="mainTab === 'matches'">
|
||||
<div :class="['tab-panel', { 'tab-panel--hidden': mainTab !== 'matches' }]">
|
||||
<div class="time-tabs">
|
||||
<button
|
||||
type="button"
|
||||
@@ -283,7 +286,11 @@ function goMatch(id: string) {
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<OutrightPanel v-if="mainTab === 'outright'" class="outright-tab" />
|
||||
<OutrightPanel
|
||||
v-if="outrightActivated"
|
||||
:class="['outright-tab', 'tab-panel', { 'tab-panel--hidden': mainTab !== 'outright' }]"
|
||||
:activated="mainTab === 'outright'"
|
||||
/>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
@@ -302,6 +309,24 @@ function goMatch(id: string) {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
/* Tab 面板切换:不用 display:none,避免浏览器释放图片资源导致重新加载 */
|
||||
.tab-panel {
|
||||
display: block;
|
||||
}
|
||||
.tab-panel--hidden {
|
||||
position: absolute !important;
|
||||
width: 1px !important;
|
||||
height: 1px !important;
|
||||
padding: 0 !important;
|
||||
margin: -1px !important;
|
||||
overflow: hidden !important;
|
||||
clip: rect(0, 0, 0, 0) !important;
|
||||
white-space: nowrap !important;
|
||||
border: 0 !important;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.main-tabs {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { onActivated } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import emptyMatchesImg from '../assets/images/empty-matches.svg';
|
||||
@@ -20,6 +21,8 @@ const { pullDistance, refreshing, spinning, progress } = usePullToRefresh({
|
||||
onRefresh: async () => { await load(true); },
|
||||
});
|
||||
|
||||
onActivated(() => { void load(true); });
|
||||
|
||||
const pullIndicatorStyle = () => ({
|
||||
height: `${pullDistance.value}px`,
|
||||
opacity: Math.min(pullDistance.value / 48, 1),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { ref, onActivated, onMounted, onUnmounted } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import api from '../api';
|
||||
import BetHistoryCard, { type BetHistoryItem } from '../components/BetHistoryCard.vue';
|
||||
@@ -73,6 +73,8 @@ const { pullDistance, refreshing, spinning, progress } = usePullToRefresh({
|
||||
onRefresh: async () => { await loadPage(1); },
|
||||
});
|
||||
|
||||
onActivated(() => { void loadPage(1); });
|
||||
|
||||
onMounted(() => {
|
||||
observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue';
|
||||
import { ref, onActivated, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import api from '../api';
|
||||
@@ -73,6 +73,7 @@ const { pullDistance, spinning, progress } = usePullToRefresh({
|
||||
});
|
||||
|
||||
onMounted(fetchData);
|
||||
onActivated(fetchData);
|
||||
|
||||
const pullIndicatorStyle = () => ({
|
||||
height: `${pullDistance.value}px`,
|
||||
|
||||
Reference in New Issue
Block a user