feat(多公司): 两端接上公司身份 —— 后台公司目录页、建号必选公司、顶栏显示所属公司
- 新后台新增「公司管理」页(列/新建/改名/启停,不提供删除),路由 menuKey 与 columns 表的 admin_companies 逐字一致,由用例钉住;操作指引补该菜单一条。 - 建号弹窗对超管必须显式选一家(后端对"不传"仍落操作者自己公司,是给旧后台兜底); admin 只能落自己公司,越权直接 403。账号列表显示 company_name,可按公司筛。 - 客户端登录后把 companyId/companyName 落到 localStorage 并在顶栏显示; 两个登出出口(handleKicked 与切号/登出)连公司名一起清 —— 残留会把上一个账号 的归属显示给下一个账号。 - 契约分层:列表端点用 snake_case(company_id/company_name),current-user 与登录 回包用 camelCase;解析器读到另一套写法必须忽略,防止前后端各猜一套。 admin-frontend-vue 1678/1678、frontend-vue 672/672,两边 build(含 vue-tsc --noEmit)干净。
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
/** 公司目录 DTO(设计文档 §2.3):纯逻辑,无框架依赖。 */
|
||||
|
||||
/** company.company_name 是 varchar(128),前端同步限长,免得撞库上 1406。 */
|
||||
export const COMPANY_NAME_MAX_LENGTH = 128
|
||||
|
||||
/** company.status:1=启用 0=停用(与 V143 列注释同口径)。 */
|
||||
export const COMPANY_STATUS_ACTIVE = 1
|
||||
export const COMPANY_STATUS_DISABLED = 0
|
||||
|
||||
/** 前端公司项(camelCase,与 Java CompanyVo 的 snake_case 线上字段对应)。 */
|
||||
export interface CompanyItem {
|
||||
id: number
|
||||
companyName: string
|
||||
status: number
|
||||
remark: string | null
|
||||
createdAt: string | null
|
||||
updatedAt: string | null
|
||||
}
|
||||
|
||||
/** 新建/改名的表单草稿。 */
|
||||
export interface CompanyDraft {
|
||||
companyName: string
|
||||
status?: number
|
||||
remark?: string | null
|
||||
}
|
||||
|
||||
export function text(value: unknown): string {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
export function trimmedOrNull(value: unknown): string | null {
|
||||
const raw = text(value).trim()
|
||||
return raw || null
|
||||
}
|
||||
|
||||
/** 校验草稿,返回错误文案;合法返回空串。 */
|
||||
export function validateCompanyDraft(draft: CompanyDraft): string {
|
||||
const name = text(draft.companyName).trim()
|
||||
if (!name) return '公司名称不能为空'
|
||||
if (name.length > COMPANY_NAME_MAX_LENGTH) {
|
||||
return `公司名称长度不能超过 ${COMPANY_NAME_MAX_LENGTH} 个字符`
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** 草稿 → POST/PUT 请求体(Java 侧 CompanySaveRequest 是 camelCase,与 AdminUserCreateRequest 同口径)。 */
|
||||
export function toCompanyPayload(draft: CompanyDraft): Record<string, unknown> {
|
||||
const payload: Record<string, unknown> = { companyName: text(draft.companyName).trim() }
|
||||
if (typeof draft.status === 'number') payload.status = draft.status
|
||||
payload.remark = trimmedOrNull(draft.remark)
|
||||
return payload
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/** 公司目录响应解析:Java CompanyVo(snake_case) → 前端 CompanyItem(camelCase)。 */
|
||||
import { unwrap } from './envelope.ts'
|
||||
import {
|
||||
COMPANY_STATUS_ACTIVE,
|
||||
COMPANY_STATUS_DISABLED,
|
||||
text,
|
||||
trimmedOrNull,
|
||||
type CompanyItem,
|
||||
} from './companies-dto.ts'
|
||||
|
||||
function numberOrNull(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 单条映射;无 id 视为无效行(列表中直接丢弃,避免编辑时打到 /companies/undefined)。 */
|
||||
export function toCompanyItem(raw: unknown): CompanyItem | null {
|
||||
if (!raw || typeof raw !== 'object') return null
|
||||
const r = raw as Record<string, unknown>
|
||||
const id = numberOrNull(r.id)
|
||||
if (id === null) return null
|
||||
return {
|
||||
id,
|
||||
companyName: text(r.company_name),
|
||||
// status 列 NOT NULL,取不到就是链路异常;未知一律按停用,不把异常状态当启用。
|
||||
status: r.status === COMPANY_STATUS_ACTIVE ? COMPANY_STATUS_ACTIVE : COMPANY_STATUS_DISABLED,
|
||||
remark: trimmedOrNull(r.remark),
|
||||
createdAt: trimmedOrNull(r.created_at),
|
||||
updatedAt: trimmedOrNull(r.updated_at),
|
||||
}
|
||||
}
|
||||
|
||||
/** 解析 GET /api/admin/companies:接受 data 为数组或 {items:[...]},success=false 抛后端文案。 */
|
||||
export function parseCompanyList(payload: unknown): CompanyItem[] {
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object') return []
|
||||
const candidate = Array.isArray(core) ? core : (core as { items?: unknown }).items
|
||||
if (!Array.isArray(candidate)) return []
|
||||
return candidate
|
||||
.map((raw) => toCompanyItem(raw))
|
||||
.filter((item): item is CompanyItem => item !== null)
|
||||
}
|
||||
|
||||
/** 解析 POST/PUT 回包(data 为 CompanyVo)。 */
|
||||
export function parseCompany(payload: unknown): CompanyItem | null {
|
||||
const core = unwrap<unknown>(payload)
|
||||
if (!core || typeof core !== 'object' || Array.isArray(core)) return null
|
||||
return toCompanyItem(core)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { http } from './http'
|
||||
import { parseCompany, parseCompanyList } from './companies-model'
|
||||
import { toCompanyPayload, type CompanyDraft, type CompanyItem } from './companies-dto'
|
||||
|
||||
/** 公司目录(设计文档 §2.3)。GET 的可见范围由后端收窄:超管全部、公司内 admin 只自己公司。 */
|
||||
|
||||
export async function fetchCompanies(): Promise<CompanyItem[]> {
|
||||
const { data } = await http.get('/api/admin/companies')
|
||||
return parseCompanyList(data)
|
||||
}
|
||||
|
||||
export async function createCompany(draft: CompanyDraft): Promise<CompanyItem | null> {
|
||||
const { data } = await http.post('/api/admin/companies', toCompanyPayload(draft))
|
||||
return parseCompany(data)
|
||||
}
|
||||
|
||||
/** 改名 / 启停;后端不做删除,停用即 status=0。 */
|
||||
export async function updateCompany(id: number, draft: CompanyDraft): Promise<CompanyItem | null> {
|
||||
const { data } = await http.put(`/api/admin/companies/${id}`, toCompanyPayload(draft))
|
||||
return parseCompany(data)
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export interface UserListParams {
|
||||
adminId?: number | null
|
||||
/** 角色过滤(''=全部)。 */
|
||||
role?: string
|
||||
/** 按所属公司过滤(V143);仅超管用得到——公司内 admin 后端本来就只返回本公司账号。 */
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
|
||||
@@ -26,6 +28,7 @@ export interface UserListQuery {
|
||||
created_by_id?: number
|
||||
admin_id?: number
|
||||
role?: string
|
||||
company_id?: number
|
||||
}
|
||||
|
||||
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
|
||||
@@ -46,6 +49,12 @@ function finiteInt(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/** 公司 id 只认正整数:0/负数/NaN 一律当"没筛选",否则会下发一个必然查不到账号的过滤。 */
|
||||
function positiveId(value: unknown): number | null {
|
||||
const id = finiteInt(value)
|
||||
return id !== null && id > 0 ? id : null
|
||||
}
|
||||
|
||||
/** 归一化分页/筛选参数:页码下限 1、页大小 1..上限,空关键字视为无过滤。 */
|
||||
export function normalizeUserPageParams(raw: Partial<UserListParams>): UserListParams {
|
||||
const page = Math.max(finiteInt(raw.page) ?? USER_PAGE_MIN_PAGE, USER_PAGE_MIN_PAGE)
|
||||
@@ -61,6 +70,7 @@ export function normalizeUserPageParams(raw: Partial<UserListParams>): UserListP
|
||||
keyword,
|
||||
createdById: typeof raw.createdById === 'number' ? raw.createdById : null,
|
||||
adminId: typeof raw.adminId === 'number' ? raw.adminId : null,
|
||||
companyId: positiveId(raw.companyId),
|
||||
role: typeof raw.role === 'string' ? raw.role.trim() || undefined : undefined,
|
||||
}
|
||||
}
|
||||
@@ -72,6 +82,8 @@ export function toUserListQuery(params: UserListParams): UserListQuery {
|
||||
if (params.createdById != null) query.created_by_id = params.createdById
|
||||
if (params.adminId != null) query.admin_id = params.adminId
|
||||
if (params.role) query.role = params.role
|
||||
const companyId = positiveId(params.companyId)
|
||||
if (companyId !== null) query.company_id = companyId
|
||||
return query
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,12 @@ export function toAdminUserItem(raw: unknown): AdminUser | null {
|
||||
if (updatedAt) item.updatedAt = updatedAt
|
||||
const creator = text(r.creator_username)
|
||||
if (creator) item.creatorUsername = creator
|
||||
// 公司维度只在后端带上时才写键:留 undefined 而不是 null,好让"这版后端没带公司"
|
||||
// 与"账号确实没归属公司"在页面上是两种可读的状态。
|
||||
const companyId = numberOrNull(r.company_id)
|
||||
if (companyId !== null) item.companyId = companyId
|
||||
const companyName = text(r.company_name).trim()
|
||||
if (companyName) item.companyName = companyName
|
||||
const abbr = text(r.pinyin_abbr)
|
||||
if (abbr) item.pinyinAbbr = abbr
|
||||
return item
|
||||
|
||||
@@ -104,6 +104,9 @@ async function signOut() {
|
||||
<NotificationBell />
|
||||
<div class="admin-user-meta">
|
||||
<strong>{{ userVm.username }}</strong>
|
||||
<span v-if="userVm.company" class="admin-user-company" :title="`所属公司:${userVm.company}`">
|
||||
{{ userVm.company }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="userVm.role" class="admin-user-role">{{ userVm.role }}</span>
|
||||
<el-button class="admin-user-logout" @click="signOut">退出登录</el-button>
|
||||
|
||||
@@ -29,6 +29,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
||||
text: '用户密钥按账号绑定,列表只展示脱敏值。可对单条立即检测连通性;清空后该用户需要重新配置密钥。',
|
||||
steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'],
|
||||
},
|
||||
admin_companies: {
|
||||
text: '公司决定账号归属:建号时选哪家公司,该账号名下的数据就归哪家公司。公司只做启用/停用,不提供删除——停用后不能再用于新建账号。',
|
||||
steps: ['查看公司列表', '新建公司', '改名或启停'],
|
||||
},
|
||||
admin_dedupe_total_data: {
|
||||
text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。',
|
||||
steps: ['选择分组', '筛选或导入', '核对并导出'],
|
||||
|
||||
@@ -13,11 +13,18 @@ export function pageTitleOf(title: string | null | undefined): string {
|
||||
export interface TopbarUserViewModel {
|
||||
username: string
|
||||
role: string
|
||||
/** 所属公司名(V143);后端没带就是空串,模板据此整段不显示,不能渲染出 undefined。 */
|
||||
company: string
|
||||
hasUser: boolean
|
||||
}
|
||||
|
||||
/** 顶部栏用户模型:用户信息或未登录空态统一为可渲染视图模型。 */
|
||||
export function topbarUserOf(user: AdminUser | null | undefined): TopbarUserViewModel {
|
||||
if (!user) return { username: '当前用户', role: '', hasUser: false }
|
||||
return { username: user.username || '当前用户', role: roleLabel(user.role) || user.role || '', hasUser: true }
|
||||
if (!user) return { username: '当前用户', role: '', company: '', hasUser: false }
|
||||
return {
|
||||
username: user.username || '当前用户',
|
||||
role: roleLabel(user.role) || user.role || '',
|
||||
company: (user.companyName || '').trim(),
|
||||
hasUser: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
<script setup lang="ts">
|
||||
/** 公司管理(设计文档 §2.3):列表 + 新建 + 改名/启停。
|
||||
* 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合,
|
||||
* 真正的把关在 CompanyController,页面不得当作权限边界。 */
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { formatDateTime } from '@/utils/datetime'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import OldPagination from '@/components/OldPagination.vue'
|
||||
import CompanyEditorDialog from './CompanyEditorDialog.vue'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const loading = ref(false)
|
||||
const rows = ref<CompanyItem[]>([])
|
||||
const editorVisible = ref(false)
|
||||
const editingCompany = ref<CompanyItem | null>(null)
|
||||
const filterKeyword = ref('')
|
||||
|
||||
const canManage = computed(() => session.isSuperAdmin)
|
||||
const filteredRows = computed(() => {
|
||||
const kw = filterKeyword.value.trim().toLowerCase()
|
||||
if (!kw) return rows.value
|
||||
return rows.value.filter((c) => (c.companyName || '').toLowerCase().includes(kw))
|
||||
})
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const pagedRows = computed(() => filteredRows.value.slice((page.value - 1) * pageSize.value, page.value * pageSize.value))
|
||||
|
||||
function changePage(p: number) { page.value = p }
|
||||
function changeSize(size: number) { pageSize.value = size; page.value = 1 }
|
||||
|
||||
async function loadCompanies() {
|
||||
loading.value = true
|
||||
try {
|
||||
rows.value = await fetchCompanies()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '公司列表加载失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
editingCompany.value = null
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
function openEdit(company: CompanyItem) {
|
||||
editingCompany.value = company
|
||||
editorVisible.value = true
|
||||
}
|
||||
|
||||
onMounted(loadCompanies)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="companies-view">
|
||||
<section class="panel-box">
|
||||
<div class="companies-head">
|
||||
<h3>公司列表</h3>
|
||||
<button v-if="canManage" class="btn" type="button" @click="openCreate">新建公司</button>
|
||||
</div>
|
||||
|
||||
<div class="form-row companies-filter-row">
|
||||
<div class="form-group" style="min-width: 200px">
|
||||
<label>公司名称</label>
|
||||
<input v-model="filterKeyword" type="text" placeholder="输入公司名称" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 58px">序号</th>
|
||||
<th>公司名称</th>
|
||||
<th style="width: 90px">状态</th>
|
||||
<th style="width: 24%">备注</th>
|
||||
<th style="width: 160px">创建时间</th>
|
||||
<th style="width: 160px">修改时间</th>
|
||||
<th style="width: 90px">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template v-if="filteredRows.length">
|
||||
<tr v-for="(company, index) in pagedRows" :key="company.id">
|
||||
<td>{{ index + 1 }}</td>
|
||||
<td>{{ company.companyName || '-' }}</td>
|
||||
<td>
|
||||
<span :class="company.status === COMPANY_STATUS_ACTIVE ? 'state-on' : 'state-off'">
|
||||
{{ company.status === COMPANY_STATUS_ACTIVE ? '启用' : '停用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>{{ company.remark || '-' }}</td>
|
||||
<td>{{ formatDateTime(company.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(company.updatedAt || company.createdAt) }}</td>
|
||||
<td class="ops-cell">
|
||||
<button v-if="canManage" class="btn btn-sm" type="button" @click="openEdit(company)">编辑</button>
|
||||
<span v-else class="cell-none">-</span>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="7" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="7" class="empty-tip">{{ filterKeyword.trim() ? '暂无匹配公司' : '暂无公司' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<OldPagination
|
||||
v-if="filteredRows.length > 0"
|
||||
:total="filteredRows.length"
|
||||
:page="page"
|
||||
:page-size="pageSize"
|
||||
@change="changePage"
|
||||
@size-change="changeSize"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<CompanyEditorDialog v-model="editorVisible" :company="editingCompany" @saved="loadCompanies" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.companies-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
color: #24384d;
|
||||
}
|
||||
.panel-box {
|
||||
width: 100%;
|
||||
padding: 20px 22px 24px;
|
||||
border: 1px solid #d8e3ee;
|
||||
border-radius: 14px;
|
||||
background: linear-gradient(145deg, #ffffff, #f9fbfd);
|
||||
box-shadow: 0 1px 2px rgba(39, 67, 94, 0.04), 0 14px 30px -24px rgba(39, 67, 94, 0.28);
|
||||
}
|
||||
h3 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 650;
|
||||
}
|
||||
.companies-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.companies-filter-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 14px 18px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
.companies-filter-row .form-group {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
.form-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
}
|
||||
.form-group label {
|
||||
color: #5b6f83;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.form-group input {
|
||||
min-height: 42px;
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #cbd9e6;
|
||||
border-radius: 9px;
|
||||
background: #f8fbfd;
|
||||
color: #24384d;
|
||||
font-size: 13.5px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
}
|
||||
.form-group input:focus {
|
||||
background: #ffffff;
|
||||
border-color: #5f85ad;
|
||||
box-shadow: 0 0 0 3px rgba(95, 133, 173, 0.16);
|
||||
}
|
||||
.btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 42px;
|
||||
padding: 9px 18px;
|
||||
border: 1px solid #4f78a5;
|
||||
border-radius: 9px;
|
||||
background: linear-gradient(135deg, #5f85ad, #4f78a5);
|
||||
color: #ffffff;
|
||||
font-family: inherit;
|
||||
font-size: 13.5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.btn:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, #7094ba, #5d83ac);
|
||||
}
|
||||
.btn-sm {
|
||||
min-height: 36px;
|
||||
padding: 7px 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.table-scroll {
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
border: 1px solid #dbe5ee;
|
||||
border-radius: 10px;
|
||||
background: #ffffff;
|
||||
}
|
||||
.table-scroll table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
font-size: 13.5px;
|
||||
line-height: 1.5;
|
||||
border-bottom: 1px solid #e0e8ef;
|
||||
vertical-align: middle;
|
||||
word-break: break-word;
|
||||
}
|
||||
.table-scroll th {
|
||||
background: #edf4fa;
|
||||
color: #4e6479;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.table-scroll tbody tr:hover td {
|
||||
background: #f1f7fb;
|
||||
}
|
||||
.table-scroll tbody tr:last-child td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
.state-on {
|
||||
color: #2e7d5b;
|
||||
}
|
||||
.state-off {
|
||||
color: #b35f6a;
|
||||
}
|
||||
.ops-cell {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.cell-none {
|
||||
color: #8293a5;
|
||||
}
|
||||
.empty-tip {
|
||||
padding: 44px 24px;
|
||||
text-align: center;
|
||||
color: #8293a5;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,89 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { createCompany, updateCompany } from '@/api/companies'
|
||||
import {
|
||||
COMPANY_NAME_MAX_LENGTH,
|
||||
COMPANY_STATUS_ACTIVE,
|
||||
COMPANY_STATUS_DISABLED,
|
||||
validateCompanyDraft,
|
||||
type CompanyDraft,
|
||||
type CompanyItem,
|
||||
} from '@/api/companies-dto'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
|
||||
/** 新建/编辑公司(改名 + 启停 + 备注);写操作仅超管可用,权限由后端把关。 */
|
||||
const props = defineProps<{ modelValue: boolean; company: CompanyItem | null }>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'saved'): void }>()
|
||||
|
||||
const form = ref<CompanyDraft>({ companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '' })
|
||||
const errorText = ref('')
|
||||
const busy = ref(false)
|
||||
|
||||
watch(
|
||||
() => props.modelValue,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
form.value = props.company
|
||||
? { companyName: props.company.companyName, status: props.company.status, remark: props.company.remark || '' }
|
||||
: { companyName: '', status: COMPANY_STATUS_ACTIVE, remark: '' }
|
||||
errorText.value = ''
|
||||
},
|
||||
)
|
||||
|
||||
function close() {
|
||||
emit('update:modelValue', false)
|
||||
}
|
||||
|
||||
async function save() {
|
||||
errorText.value = validateCompanyDraft(form.value)
|
||||
if (errorText.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
if (props.company) await updateCompany(props.company.id, form.value)
|
||||
else await createCompany(form.value)
|
||||
showAdminFeedback(props.company ? '公司已更新' : '公司已创建', 'success')
|
||||
emit('saved')
|
||||
close()
|
||||
} catch (error) {
|
||||
errorText.value = actionableErrorText(error)
|
||||
showAdminFeedback(errorText.value, 'error')
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<el-dialog
|
||||
:model-value="modelValue"
|
||||
:title="company ? '编辑公司' : '新建公司'"
|
||||
width="520px"
|
||||
:close-on-click-modal="false"
|
||||
destroy-on-close
|
||||
@update:model-value="(v: boolean) => emit('update:modelValue', v)"
|
||||
>
|
||||
<el-form label-position="top" @submit.prevent>
|
||||
<el-form-item label="公司名称" :error="errorText || undefined">
|
||||
<el-input
|
||||
v-model="form.companyName"
|
||||
:maxlength="COMPANY_NAME_MAX_LENGTH"
|
||||
placeholder="请输入公司名称(全平台唯一)"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item label="状态">
|
||||
<el-select v-model="form.status" style="width: 100%">
|
||||
<el-option :value="COMPANY_STATUS_ACTIVE" label="启用" />
|
||||
<el-option :value="COMPANY_STATUS_DISABLED" label="停用" />
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="备注">
|
||||
<el-input v-model="form.remark" type="textarea" :rows="2" placeholder="可留空" />
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template #footer>
|
||||
<el-button @click="close">取消</el-button>
|
||||
<el-button type="primary" :loading="busy" @click="save">保存</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
@@ -1,12 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue'
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import { submitCreateUser } from './user-create-adapter'
|
||||
import {
|
||||
createEmptyCreateUserForm,
|
||||
initialCompanyId,
|
||||
selectableCompanies,
|
||||
type CreateOperatorScope,
|
||||
type CreateUserForm,
|
||||
type CreateUserFormErrors,
|
||||
validateCreateUserForm,
|
||||
} from './user-create-model'
|
||||
import type { CompanyItem } from '@/api/companies-dto'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import { actionableErrorText } from '@/components/admin-feedback'
|
||||
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
||||
@@ -16,6 +20,10 @@ const props = defineProps<{
|
||||
operatorSuper?: boolean
|
||||
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示)。 */
|
||||
adminOptions?: Array<{ id: number; username: string }>
|
||||
/** 整份公司目录(GET /api/admin/companies,后端已按操作者收窄)。 */
|
||||
companies?: CompanyItem[]
|
||||
/** 操作者角色与归属:决定公司下拉是否必选。 */
|
||||
operator?: CreateOperatorScope
|
||||
}>()
|
||||
const emit = defineEmits<{ (e: 'update:modelValue', v: boolean): void; (e: 'created'): void }>()
|
||||
|
||||
@@ -23,6 +31,9 @@ const form = reactive<CreateUserForm>(createEmptyCreateUserForm())
|
||||
const errors = reactive<CreateUserFormErrors>({})
|
||||
const busy = ref(false)
|
||||
|
||||
/** 可选项收窄规则与后端 resolveTargetCompanyId 同源,写在这里而不是父页模板里。 */
|
||||
const companyOptions = computed(() => selectableCompanies(props.companies || [], props.operator || {}))
|
||||
|
||||
/** 角色下拉(对齐 admin.html:普通账号/管理员;超管才显示可改)。 */
|
||||
const ROLE_CHOICES: Array<{ value: 'admin' | 'normal'; label: string }> = [
|
||||
{ value: 'normal', label: '普通账号' },
|
||||
@@ -38,8 +49,10 @@ watch(
|
||||
form.role = 'normal'
|
||||
form.columnIds = []
|
||||
form.createdBy = null
|
||||
form.companyId = initialCompanyId(props.operator || {}, props.companies || [])
|
||||
errors.username = undefined
|
||||
errors.password = undefined
|
||||
errors.company = undefined
|
||||
},
|
||||
)
|
||||
|
||||
@@ -48,7 +61,7 @@ function close(): void {
|
||||
}
|
||||
|
||||
async function create(): Promise<void> {
|
||||
const { valid, errors: errs } = validateCreateUserForm(form)
|
||||
const { valid, errors: errs } = validateCreateUserForm(form, props.operator)
|
||||
Object.assign(errors, errs)
|
||||
if (!valid) return
|
||||
busy.value = true
|
||||
@@ -107,6 +120,22 @@ async function create(): Promise<void> {
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="companyOptions.length" label="所属公司" :error="errors.company">
|
||||
<el-select
|
||||
v-model="form.companyId"
|
||||
filterable
|
||||
:placeholder="operatorSuper ? '请选择所属公司' : '所属公司'"
|
||||
style="width: 200px"
|
||||
@change="errors.company = undefined"
|
||||
>
|
||||
<el-option
|
||||
v-for="company in companyOptions"
|
||||
:key="company.id"
|
||||
:label="company.companyName"
|
||||
:value="company.id"
|
||||
/>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
|
||||
<div class="auth-tree-box">
|
||||
<UserMenuAuthTree v-model:checked="form.columnIds" />
|
||||
|
||||
@@ -8,6 +8,9 @@ import type { AdminUser } from '@/types/admin'
|
||||
import { roleLabel } from '@/types/admin'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { deleteUser, fetchUserList } from '@/api/users'
|
||||
import { fetchCompanies } from '@/api/companies'
|
||||
import type { CompanyItem } from '@/api/companies-dto'
|
||||
import type { CreateOperatorScope } from './user-create-model'
|
||||
import { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
|
||||
import { totalPageCount } from './user-pagination'
|
||||
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
|
||||
@@ -24,6 +27,12 @@ const rows = ref<AdminUser[]>([])
|
||||
const total = ref(0)
|
||||
/** 所属管理员候选(来自列表响应的 admins),供超管筛选下拉使用。 */
|
||||
const admins = ref<Array<{ id: number; username: string }>>([])
|
||||
/** 公司目录(GET /api/admin/companies):后端已按操作者收窄,前端不再自己判权限。 */
|
||||
const companies = ref<CompanyItem[]>([])
|
||||
const operatorScope = computed<CreateOperatorScope>(() => ({
|
||||
role: session.user?.role,
|
||||
companyId: session.user?.companyId ?? null,
|
||||
}))
|
||||
const filters = reactive<UserFilterState>(createUserFilterState())
|
||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||
const currentUserId = computed(() => session.user?.id ?? null)
|
||||
@@ -78,6 +87,18 @@ function retry() {
|
||||
void loadUsers()
|
||||
}
|
||||
|
||||
/**
|
||||
* 公司目录只服务下拉,不参与表格状态机:拉失败时列表照常显示,
|
||||
* 但超管建号会卡在"请选择所属公司"——所以要把原因说出来,别让人对着空下拉猜。
|
||||
*/
|
||||
async function loadCompanies() {
|
||||
try {
|
||||
companies.value = await fetchCompanies()
|
||||
} catch (error) {
|
||||
ElMessage.warning(error instanceof Error ? error.message : '公司目录加载失败')
|
||||
}
|
||||
}
|
||||
|
||||
/** 提交新筛选条件:重置回第一页再查询。 */
|
||||
function search() {
|
||||
filters.page = 1
|
||||
@@ -121,7 +142,10 @@ function goJump() {
|
||||
changePage(Math.min(Math.max(n, 1), totalPages.value))
|
||||
}
|
||||
|
||||
onMounted(loadUsers)
|
||||
onMounted(() => {
|
||||
void loadCompanies()
|
||||
void loadUsers()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -138,6 +162,12 @@ onMounted(loadUsers)
|
||||
<label>用户名(模糊搜索)</label>
|
||||
<input v-model="filters.keyword" type="text" placeholder="输入用户名关键字" @keyup.enter="search" />
|
||||
</div>
|
||||
<div v-if="isSuperAdmin" class="form-group" style="min-width: 160px">
|
||||
<label>所属公司</label>
|
||||
<el-select v-model="filters.companyId" class="admin-filter" filterable clearable placeholder="全部公司" @change="search">
|
||||
<el-option v-for="company in companies" :key="company.id" :label="company.companyName" :value="company.id" />
|
||||
</el-select>
|
||||
</div>
|
||||
<div v-if="isSuperAdmin" class="form-group" style="min-width: 160px">
|
||||
<label>所属管理员</label>
|
||||
<el-select v-model="filters.createdByAdminId" class="admin-filter" filterable clearable placeholder="全部" @change="search">
|
||||
@@ -167,6 +197,7 @@ onMounted(loadUsers)
|
||||
<th style="width: 70px">ID</th>
|
||||
<th style="width: 180px">用户名</th>
|
||||
<th style="width: 140px">角色</th>
|
||||
<th style="width: 140px">所属公司</th>
|
||||
<th style="width: 160px">所属管理员</th>
|
||||
<th style="width: 180px">创建时间</th>
|
||||
<th style="width: 180px">更新时间</th>
|
||||
@@ -179,6 +210,7 @@ onMounted(loadUsers)
|
||||
<td>{{ row.id }}</td>
|
||||
<td>{{ row.username }}</td>
|
||||
<td>{{ roleLabel(row.role) }}</td>
|
||||
<td>{{ row.companyName || '-' }}</td>
|
||||
<td>{{ row.creatorUsername || '-' }}</td>
|
||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||
@@ -205,10 +237,10 @@ onMounted(loadUsers)
|
||||
</tr>
|
||||
</template>
|
||||
<tr v-else-if="loading">
|
||||
<td colspan="7" class="empty-tip">加载中...</td>
|
||||
<td colspan="8" class="empty-tip">加载中...</td>
|
||||
</tr>
|
||||
<tr v-else>
|
||||
<td colspan="7" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
<td colspan="8" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -217,7 +249,14 @@ onMounted(loadUsers)
|
||||
<OldPagination :total="total" :page="filters.page" :page-size="filters.pageSize" @change="changePage" @size-change="changeSize" />
|
||||
</section>
|
||||
|
||||
<CreateUserDialog v-model="createVisible" :operator-super="isSuperAdmin" :admin-options="admins" @created="loadUsers" />
|
||||
<CreateUserDialog
|
||||
v-model="createVisible"
|
||||
:operator-super="isSuperAdmin"
|
||||
:admin-options="admins"
|
||||
:companies="companies"
|
||||
:operator="operatorScope"
|
||||
@created="loadUsers"
|
||||
/>
|
||||
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" @updated="loadUsers" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -374,7 +413,7 @@ h3 {
|
||||
table-layout: fixed;
|
||||
}
|
||||
.user-table-scroll > table {
|
||||
min-width: 860px;
|
||||
min-width: 1000px;
|
||||
}
|
||||
.table-scroll th,
|
||||
.table-scroll td {
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
/** 新建用户表单模型(任务 45):纯逻辑,镜像 Java AdminUserCreateRequest 字段与后端校验。 */
|
||||
|
||||
// 相对路径而非 @/ 别名:本文件被 node --test 直接 import,别名只有 vite 认。
|
||||
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '../../api/companies-dto.ts'
|
||||
|
||||
export const CREATE_USERNAME_MIN_LEN = 2
|
||||
export const CREATE_PASSWORD_MIN_LEN = 6
|
||||
|
||||
/** 新建用户可选角色:super_admin 不可由表单创建(后端只收 admin|normal)。 */
|
||||
export type CreatableUserRole = 'normal' | 'admin'
|
||||
|
||||
/** 当前操作者的公司归属(来自 /api/admin/current-user)。 */
|
||||
export interface CreateOperatorScope {
|
||||
role?: string | null
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
export interface CreateUserForm {
|
||||
username: string
|
||||
password: string
|
||||
@@ -14,11 +23,14 @@ export interface CreateUserForm {
|
||||
columnIds: number[]
|
||||
/** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */
|
||||
createdBy?: number | null
|
||||
/** 所属公司 id(V143)。超管必选;公司内 admin 由后端强制落自己公司。 */
|
||||
companyId?: number | null
|
||||
}
|
||||
|
||||
export interface CreateUserFormErrors {
|
||||
username?: string
|
||||
password?: string
|
||||
company?: string
|
||||
}
|
||||
|
||||
/** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */
|
||||
@@ -29,10 +41,11 @@ export interface CreateUserPayload {
|
||||
columnIds: number[]
|
||||
/** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */
|
||||
createdById?: number
|
||||
companyId?: number
|
||||
}
|
||||
|
||||
export function createEmptyCreateUserForm(): CreateUserForm {
|
||||
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null }
|
||||
return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, companyId: null }
|
||||
}
|
||||
|
||||
/** 未知/空白/超管角色一律归一到 normal,与后端 "admin"/"normal" 白名单一致。 */
|
||||
@@ -40,8 +53,40 @@ export function normalizeCreateRole(role: string | null | undefined): CreatableU
|
||||
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
|
||||
}
|
||||
|
||||
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填);返回逐字段错误。 */
|
||||
export function validateCreateUserForm(form: CreateUserForm): { valid: boolean; errors: CreateUserFormErrors } {
|
||||
function positiveInt(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : null
|
||||
}
|
||||
|
||||
/**
|
||||
* 建号能选哪家公司,口径与后端 AdminUserService#resolveTargetCompanyId 一致:
|
||||
* 超管 = 全部启用中的公司(后端 requireActive 会拒停用公司);
|
||||
* 其余角色 = 只有自己也那一家,且不看启停——后端对非超管直接落 operator.companyId、
|
||||
* 不校验状态,前端若跟着过滤就会出现「下拉没得选、提交却能建号」的自相矛盾。
|
||||
*/
|
||||
export function selectableCompanies(companies: CompanyItem[], operator: CreateOperatorScope): CompanyItem[] {
|
||||
const rows = Array.isArray(companies) ? companies : []
|
||||
if (operator?.role === 'super_admin') {
|
||||
return rows.filter((company) => company.status === COMPANY_STATUS_ACTIVE)
|
||||
}
|
||||
const own = positiveInt(operator?.companyId)
|
||||
if (own === null) return []
|
||||
return rows.filter((company) => company.id === own)
|
||||
}
|
||||
|
||||
/**
|
||||
* 弹窗打开时预选哪家公司:候选只有一个(公司内 admin 的本公司)就落它;
|
||||
* 多个(超管)返回 null——给超管填默认值等于替他决定账号挂在哪家,这是会写进库的判断。
|
||||
*/
|
||||
export function initialCompanyId(operator: CreateOperatorScope, companies: CompanyItem[]): number | null {
|
||||
const options = selectableCompanies(companies, operator)
|
||||
return options.length === 1 ? options[0].id : null
|
||||
}
|
||||
|
||||
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填;超管必须显式选公司);返回逐字段错误。 */
|
||||
export function validateCreateUserForm(
|
||||
form: CreateUserForm,
|
||||
operator?: CreateOperatorScope,
|
||||
): { valid: boolean; errors: CreateUserFormErrors } {
|
||||
const errors: CreateUserFormErrors = {}
|
||||
const username = (form.username || '').trim()
|
||||
if (!username) {
|
||||
@@ -55,11 +100,15 @@ export function validateCreateUserForm(form: CreateUserForm): { valid: boolean;
|
||||
} else if (password.length < CREATE_PASSWORD_MIN_LEN) {
|
||||
errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符`
|
||||
}
|
||||
if (operator?.role === 'super_admin' && positiveInt(form.companyId) === null) {
|
||||
errors.company = '请选择所属公司'
|
||||
}
|
||||
return { valid: Object.keys(errors).length === 0, errors }
|
||||
}
|
||||
|
||||
/** 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用;
|
||||
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义)。 */
|
||||
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义);
|
||||
* companyId 选了才带,未选时由后端落操作者自己公司。 */
|
||||
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
||||
const payload: CreateUserPayload = {
|
||||
username: (form.username || '').trim(),
|
||||
@@ -70,5 +119,7 @@ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
||||
if (payload.role === 'normal' && form.createdBy != null) {
|
||||
payload.createdById = form.createdBy
|
||||
}
|
||||
const companyId = positiveInt(form.companyId)
|
||||
if (companyId !== null) payload.companyId = companyId
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -9,18 +9,27 @@ export interface UserFilterState {
|
||||
createdByAdminId: number | null
|
||||
/** 角色过滤(''=全部;super_admin/admin/normal)。 */
|
||||
role: string
|
||||
/** 按所属公司过滤(null=全部);只有超管能用,公司内 admin 看到的本来就是本公司。 */
|
||||
companyId: number | null
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
export function createUserFilterState(): UserFilterState {
|
||||
return { keyword: '', createdByAdminId: null, role: '', page: USER_PAGE_MIN_PAGE, pageSize: USER_PAGE_DEFAULT_SIZE }
|
||||
return {
|
||||
keyword: '',
|
||||
createdByAdminId: null,
|
||||
role: '',
|
||||
companyId: null,
|
||||
page: USER_PAGE_MIN_PAGE,
|
||||
pageSize: USER_PAGE_DEFAULT_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
/** 修改筛选条件时重置回第一页(避免停在可能越界的旧页)。 */
|
||||
export function withFilterReset(
|
||||
state: UserFilterState,
|
||||
next: Partial<Pick<UserFilterState, 'keyword' | 'createdByAdminId' | 'role'>>,
|
||||
next: Partial<Pick<UserFilterState, 'keyword' | 'createdByAdminId' | 'role' | 'companyId'>>,
|
||||
): UserFilterState {
|
||||
return { ...state, ...next, page: USER_PAGE_MIN_PAGE }
|
||||
}
|
||||
@@ -32,7 +41,11 @@ export function withPage(state: UserFilterState, page: number): UserFilterState
|
||||
|
||||
/** 是否存在生效筛选(仅空白关键字不算)。 */
|
||||
export function isFilterActive(state: UserFilterState): boolean {
|
||||
return Boolean(state.keyword && state.keyword.trim()) || state.createdByAdminId != null
|
||||
return (
|
||||
Boolean(state.keyword && state.keyword.trim()) ||
|
||||
state.createdByAdminId != null ||
|
||||
state.companyId != null
|
||||
)
|
||||
}
|
||||
|
||||
/** 页面状态 → 查询适配层参数(空关键字不下发)。 */
|
||||
@@ -43,6 +56,7 @@ export function toUserListParams(state: UserFilterState): UserListParams {
|
||||
pageSize: state.pageSize,
|
||||
keyword: keyword || undefined,
|
||||
createdById: state.createdByAdminId,
|
||||
companyId: state.companyId,
|
||||
}
|
||||
const role = (state.role || '').trim()
|
||||
if (role) params.role = role
|
||||
|
||||
@@ -19,6 +19,7 @@ export const adminPages: AdminPageDef[] = [
|
||||
{ path: 'account/groups', menuKey: 'admin_group_manage', title: '数据权限分组', load: () => import('@/pages/account/GroupsPage.vue') },
|
||||
{ path: 'account/user-secrets', menuKey: 'admin_user_secrets', title: '密钥管理', load: () => import('@/pages/account/UserSecretsPage.vue') },
|
||||
{ path: 'account/user-secret-usage', menuKey: 'admin_user_secret_usage', title: '密钥用量统计', load: () => import('@/pages/account/UserSecretUsagePage.vue') },
|
||||
{ path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', load: () => import('@/pages/account/CompaniesPage.vue') },
|
||||
{ path: 'shop-center/duplicate-check', menuKey: 'admin_shop_data_duplicate_check', title: '店铺撞款监控', load: () => import('@/pages/tasks/DuplicateCheckPage.vue') },
|
||||
{ path: 'shop-center/keys', menuKey: 'admin_shop_keys', title: '店铺密钥管理', load: () => import('@/pages/shop/ShopKeysPage.vue') },
|
||||
{ path: 'shop-center/shops', menuKey: 'admin_shop_manage', title: '店铺管理', load: () => import('@/pages/shop/ShopManagePage.vue') },
|
||||
|
||||
@@ -106,6 +106,11 @@ button, input, textarea, select { font: inherit; }
|
||||
.admin-user { display: flex; align-items: center; gap: 14px; }
|
||||
.admin-user-meta { display: flex; align-items: flex-end; flex-direction: column; }
|
||||
.admin-user-meta strong { font-size: 13px; font-weight: 600; color: var(--admin-text); }
|
||||
.admin-user-company {
|
||||
max-width: 200px; margin-top: 3px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
color: #6b8096; font-size: 11.5px;
|
||||
}
|
||||
.admin-user-role {
|
||||
display: inline-flex; align-items: center;
|
||||
padding: 2px 10px; border-radius: 999px; font-size: 12px; line-height: 1.7;
|
||||
|
||||
@@ -11,6 +11,10 @@ export interface AdminUser {
|
||||
isAdmin?: boolean
|
||||
createdById?: number | null
|
||||
creatorUsername?: string
|
||||
/** 所属公司(V143):列表来自 AdminUserItemVo 的 company_id/company_name,
|
||||
* current-user 来自 AdminConsoleController 的 camelCase 摘要。 */
|
||||
companyId?: number | null
|
||||
companyName?: string
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
pinyinAbbr?: string
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { parseCompanyList, parseCompany } from '../src/api/companies-model.ts'
|
||||
import {
|
||||
COMPANY_NAME_MAX_LENGTH,
|
||||
toCompanyPayload,
|
||||
validateCompanyDraft,
|
||||
} from '../src/api/companies-dto.ts'
|
||||
|
||||
/** 公司目录(设计文档 §2.3)前端侧:Java VO 是 snake_case,请求 DTO 是 camelCase。 */
|
||||
|
||||
test('parseCompanyList 按 snake_case 线上字段解析公司列表', () => {
|
||||
const payload = {
|
||||
success: true,
|
||||
data: [
|
||||
{ id: 1, company_name: '厦门米椿花', status: 1, remark: '初始公司', created_at: '2026-10-04 01:00:00', updated_at: '2026-10-04 02:00:00' },
|
||||
{ id: 2, company_name: '福州数富', status: 0, remark: null },
|
||||
],
|
||||
}
|
||||
assert.deepEqual(parseCompanyList(payload), [
|
||||
{ id: 1, companyName: '厦门米椿花', status: 1, remark: '初始公司', createdAt: '2026-10-04 01:00:00', updatedAt: '2026-10-04 02:00:00' },
|
||||
{ id: 2, companyName: '福州数富', status: 0, remark: null, createdAt: null, updatedAt: null },
|
||||
])
|
||||
})
|
||||
|
||||
test('parseCompanyList 不认 camelCase:证明上一条不是在测兜底', () => {
|
||||
const rows = parseCompanyList({ success: true, data: [{ id: 3, companyName: '某某公司', status: 1 }] })
|
||||
assert.equal(rows.length, 1)
|
||||
assert.equal(rows[0].companyName, '', '线上字段是 company_name,camelCase 不该被读出来')
|
||||
})
|
||||
|
||||
test('parseCompanyList 丢弃无 id 的行并把未知 status 当停用', () => {
|
||||
const rows = parseCompanyList({ success: true, data: [
|
||||
{ company_name: '没有 id', status: 1 },
|
||||
{ id: 4, company_name: '状态未知', status: null },
|
||||
] })
|
||||
assert.deepEqual(rows, [{ id: 4, companyName: '状态未知', status: 0, remark: null, createdAt: null, updatedAt: null }])
|
||||
})
|
||||
|
||||
test('parseCompanyList 对空/异常负载返回空数组', () => {
|
||||
for (const payload of [null, undefined, {}, { success: true, data: null }, 'x']) {
|
||||
assert.deepEqual(parseCompanyList(payload), [], `负载 ${JSON.stringify(payload)} 应解析为空列表`)
|
||||
}
|
||||
})
|
||||
|
||||
test('parseCompanyList 把 success=false 的后端文案抛出来', () => {
|
||||
assert.throws(() => parseCompanyList({ success: false, message: '无权限访问公司目录' }), /无权限访问公司目录/)
|
||||
})
|
||||
|
||||
test('parseCompany 解析单条(新建/改名回包)', () => {
|
||||
const item = parseCompany({ success: true, data: { id: 5, company_name: '厦门米椿花', status: 1 } })
|
||||
assert.ok(item)
|
||||
assert.equal(item.id, 5)
|
||||
assert.equal(item.companyName, '厦门米椿花')
|
||||
assert.equal(parseCompany({ success: true, data: { company_name: '无 id' } }), null)
|
||||
})
|
||||
|
||||
test('公司名必填、去空格后不得为空,且不超过列宽', () => {
|
||||
assert.equal(validateCompanyDraft({ companyName: ' ' }), '公司名称不能为空')
|
||||
assert.equal(validateCompanyDraft({ companyName: ' 厦门米椿花 ' }), '')
|
||||
const tooLong = 'x'.repeat(COMPANY_NAME_MAX_LENGTH + 1)
|
||||
assert.match(validateCompanyDraft({ companyName: tooLong }), /长度/)
|
||||
})
|
||||
|
||||
test('toCompanyPayload 发 camelCase 且 trim 公司名', () => {
|
||||
assert.deepEqual(toCompanyPayload({ companyName: ' 福州数富 ', status: 1, remark: ' ' }), {
|
||||
companyName: '福州数富',
|
||||
status: 1,
|
||||
remark: null,
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { adminPages } from '../src/router/routes.ts'
|
||||
|
||||
/** V143 往 columns 表插了「公司管理」菜单。侧边栏/路由门禁/面包屑都按
|
||||
* column_key → adminPages.menuKey 关联(menu-route-map.ts 用注册表算出的规范路径覆盖库里的
|
||||
* route_path),所以真正的跨产物契约是「迁移插入的菜单 key 必须在注册表登记」。
|
||||
* 少登记一条 = 菜单看得见、点进去 404,且权限门禁认不出这个 key。 */
|
||||
|
||||
const MIGRATION = join(process.cwd(), '..', 'backend-java', 'src', 'main', 'resources', 'db',
|
||||
'V143__company_and_users_company_id.sql')
|
||||
|
||||
interface MigrationMenu {
|
||||
name: string
|
||||
columnKey: string
|
||||
routePath: string
|
||||
}
|
||||
|
||||
/** 从迁移里抓出插入的菜单行(name / column_key / route_path)。 */
|
||||
function menusInsertedBy(sql: string): MigrationMenu[] {
|
||||
const menus: MigrationMenu[] = []
|
||||
const re = /SELECT\s+'([^']+)',\s*'([^']+)',\s*'admin',\s*'([^']+)'/g
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = re.exec(sql))) {
|
||||
menus.push({ name: match[1], columnKey: match[2], routePath: match[3] })
|
||||
}
|
||||
return menus
|
||||
}
|
||||
|
||||
function migrationSql(): string {
|
||||
assert.ok(existsSync(MIGRATION), `迁移文件读不到,护栏无法核对菜单登记: ${MIGRATION}`)
|
||||
return readFileSync(MIGRATION, 'utf8')
|
||||
}
|
||||
|
||||
test('V143 插入的菜单 key 都必须在路由注册表登记', () => {
|
||||
const menus = menusInsertedBy(migrationSql())
|
||||
// 解析自证:正则漏抓就会恒绿,这里用独立的 INSERT INTO columns 计数交叉核对
|
||||
const insertCount = (migrationSql().match(/INSERT INTO `columns`/g) || []).length
|
||||
assert.ok(menus.length > 0, '迁移里应当插入了后台菜单,一条都没解析出来说明正则失效')
|
||||
assert.equal(menus.length, insertCount, `解析到 ${menus.length} 条,但迁移有 ${insertCount} 条 INSERT INTO columns`)
|
||||
|
||||
const registered = new Set(adminPages.map((page) => page.menuKey))
|
||||
for (const menu of menus) {
|
||||
assert.ok(registered.has(menu.columnKey),
|
||||
`菜单 key "${menu.columnKey}"(${menu.name})未在 src/router/routes.ts 登记 menuKey`)
|
||||
}
|
||||
})
|
||||
|
||||
test('V143 的「公司管理」菜单落到已注册的公司管理页', () => {
|
||||
const menus = menusInsertedBy(migrationSql())
|
||||
const companies = menus.find((menu) => menu.columnKey === 'admin_companies')
|
||||
assert.ok(companies, '迁移必须插入 admin_companies 菜单')
|
||||
const page = adminPages.find((item) => item.menuKey === 'admin_companies')
|
||||
assert.ok(page, 'routes.ts 必须有 admin_companies 页面')
|
||||
assert.equal(page.path, companies.routePath, '库里的 route_path 应与注册表路径一致')
|
||||
assert.equal(page.title, companies.name, '页面标题应与菜单名一致')
|
||||
})
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
initialCompanyId,
|
||||
selectableCompanies,
|
||||
toCreateUserRequest,
|
||||
validateCreateUserForm,
|
||||
createEmptyCreateUserForm,
|
||||
} from '../src/pages/account/user-create-model.ts'
|
||||
import { COMPANY_STATUS_ACTIVE, COMPANY_STATUS_DISABLED, type CompanyItem } from '../src/api/companies-dto.ts'
|
||||
|
||||
/** 建号表单的公司归属(设计文档 §2.2):超管必须显式选一家;公司内 admin 只能落自己公司。 */
|
||||
|
||||
const xiamen: CompanyItem = { id: 1, companyName: '厦门米椿花', status: COMPANY_STATUS_ACTIVE, remark: null, createdAt: null, updatedAt: null }
|
||||
const fuzhou: CompanyItem = { id: 2, companyName: '福州数富', status: COMPANY_STATUS_ACTIVE, remark: null, createdAt: null, updatedAt: null }
|
||||
const stopped: CompanyItem = { id: 3, companyName: '已停用公司', status: COMPANY_STATUS_DISABLED, remark: null, createdAt: null, updatedAt: null }
|
||||
const ALL = [xiamen, fuzhou, stopped]
|
||||
|
||||
const SUPER = { role: 'super_admin', companyId: 1 }
|
||||
const ADMIN = { role: 'admin', companyId: 2 }
|
||||
|
||||
function form(overrides: Record<string, unknown> = {}) {
|
||||
return { ...createEmptyCreateUserForm(), username: 'zhangsan', password: 'secret123', ...overrides }
|
||||
}
|
||||
|
||||
test('超管可选公司 = 启用中的公司,停用的不出现', () => {
|
||||
assert.deepEqual(selectableCompanies(ALL, SUPER).map((c) => c.id), [1, 2])
|
||||
})
|
||||
|
||||
test('公司内 admin 只列自己公司,不看状态', () => {
|
||||
// 后端对非超管直接落 operator.companyId、不校验启用状态;前端跟着把本公司列出,
|
||||
// 否则会出现「下拉里没得选、提交却能建号」的自相矛盾。
|
||||
assert.deepEqual(selectableCompanies(ALL, ADMIN).map((c) => c.id), [2])
|
||||
const ownStopped = [{ ...xiamen, status: COMPANY_STATUS_DISABLED }, fuzhou]
|
||||
assert.deepEqual(selectableCompanies(ownStopped, { role: 'admin', companyId: 1 }).map((c) => c.id), [1])
|
||||
})
|
||||
|
||||
test('操作者没有公司归属时不给出任何可选项', () => {
|
||||
assert.deepEqual(selectableCompanies(ALL, { role: 'admin', companyId: null }), [])
|
||||
assert.deepEqual(selectableCompanies(ALL, { role: 'admin' }), [])
|
||||
})
|
||||
|
||||
test('超管不选公司就是校验不过,不能静默落自己公司', () => {
|
||||
const missing = validateCreateUserForm(form({ companyId: null }), SUPER)
|
||||
assert.equal(missing.valid, false)
|
||||
assert.match(missing.errors.company || '', /公司/)
|
||||
assert.equal(validateCreateUserForm(form({ companyId: 2 }), SUPER).valid, true)
|
||||
})
|
||||
|
||||
test('非超管不要求选公司(后端强制落自己公司)', () => {
|
||||
assert.equal(validateCreateUserForm(form({ companyId: null }), ADMIN).valid, true)
|
||||
})
|
||||
|
||||
test('不带操作者时保持原有校验口径(老调用方不受影响)', () => {
|
||||
assert.equal(validateCreateUserForm(form()).valid, true)
|
||||
assert.equal(validateCreateUserForm(form({ username: 'a' })).errors.username !== undefined, true)
|
||||
})
|
||||
|
||||
test('请求体带 camelCase companyId,未选时不带该键', () => {
|
||||
assert.equal(toCreateUserRequest(form({ companyId: 2 })).companyId, 2)
|
||||
assert.equal('companyId' in toCreateUserRequest(form({ companyId: null })), false)
|
||||
assert.equal('companyId' in toCreateUserRequest(form({ companyId: 0 })), false)
|
||||
})
|
||||
|
||||
test('弹窗打开时的默认公司:候选只有一个就落它,多个则不替超管决定', () => {
|
||||
// 公司内 admin 只有一家在选,预选上省一步,也不会出现"没选就提交"的空值。
|
||||
assert.equal(initialCompanyId(ADMIN, ALL), 2)
|
||||
// 超管面对多家时必须自己选:默认值等于替他决定账号挂在哪家,这是会写进库的判断。
|
||||
assert.equal(initialCompanyId(SUPER, ALL), null)
|
||||
// 本公司压根不在列表里时不猜(返回 null 让后端按 operator 归属落库)。
|
||||
assert.equal(initialCompanyId(ADMIN, [xiamen]), null)
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { readSource } from './helpers.ts'
|
||||
import { normalizeUserPageParams, toUserListQuery } from '../src/api/users-dto.ts'
|
||||
import { toAdminUserItem } from '../src/api/users-model.ts'
|
||||
import {
|
||||
createUserFilterState,
|
||||
isFilterActive,
|
||||
toUserListParams,
|
||||
withFilterReset,
|
||||
} from '../src/pages/account/users-filter.ts'
|
||||
import { topbarUserOf } from '../src/layout/topbar-model.ts'
|
||||
|
||||
/** 公司维度进账号页(设计文档 §2.3/§5.1):列表列、按公司筛选(仅超管)、顶栏公司名。 */
|
||||
|
||||
test('company_user_list_item_reads_snake_case_company_columns', () => {
|
||||
const item = toAdminUserItem({
|
||||
id: 7,
|
||||
username: '张三',
|
||||
role: 'normal',
|
||||
company_id: 2,
|
||||
company_name: '福州数富',
|
||||
})
|
||||
assert.equal(item?.companyId, 2)
|
||||
assert.equal(item?.companyName, '福州数富')
|
||||
})
|
||||
|
||||
test('company_user_list_item_ignores_camel_case_company_keys', () => {
|
||||
// 反向排他:后端 AdminUserItemVo 走 @JsonProperty snake_case,解析器若跟着读 camelCase 就是双向猜。
|
||||
const item = toAdminUserItem({ id: 7, username: '张三', role: 'normal', companyId: 9, companyName: '别家' })
|
||||
assert.equal(item?.companyId, undefined)
|
||||
assert.equal(item?.companyName, undefined)
|
||||
})
|
||||
|
||||
test('company_user_list_filter_state_defaults_to_no_company', () => {
|
||||
assert.equal(createUserFilterState().companyId, null)
|
||||
// 改了公司筛选要回第一页,与其他筛选条件同规则
|
||||
const next = withFilterReset({ ...createUserFilterState(), page: 5 }, { companyId: 3 })
|
||||
assert.equal(next.companyId, 3)
|
||||
assert.equal(next.page, 1)
|
||||
assert.equal(isFilterActive({ ...createUserFilterState(), companyId: 3 }), true)
|
||||
})
|
||||
|
||||
test('company_user_list_query_sends_company_id_only_when_selected', () => {
|
||||
const withCompany = toUserListQuery(normalizeUserPageParams({ page: 1, pageSize: 10, companyId: 3 }))
|
||||
assert.equal(withCompany.company_id, 3)
|
||||
assert.equal(
|
||||
'company_id' in toUserListQuery(normalizeUserPageParams({ page: 1, pageSize: 10 })),
|
||||
false,
|
||||
'未选公司时不下发 company_id,否则后端会当成"只看这家公司"过滤',
|
||||
)
|
||||
})
|
||||
|
||||
test('company_user_list_params_adapter_carries_company_id', () => {
|
||||
const params = toUserListParams({ ...createUserFilterState(), companyId: 2 })
|
||||
assert.equal(params.companyId, 2)
|
||||
})
|
||||
|
||||
test('company_topbar_shows_company_name', () => {
|
||||
assert.equal(
|
||||
topbarUserOf({ id: 1, username: 'admin', role: 'admin', companyName: ' 厦门米椿花 ' }).company,
|
||||
'厦门米椿花',
|
||||
)
|
||||
// 未登录空态与"后端没带公司"都必须是不显示,而不是渲染出 undefined
|
||||
assert.equal(topbarUserOf(null).company, '')
|
||||
assert.equal(topbarUserOf({ id: 1, username: 'admin', role: 'admin' }).company, '')
|
||||
})
|
||||
|
||||
test('company_user_list_page_ui_wiring', () => {
|
||||
const page = readSource('src/pages/account/UsersPage.vue')
|
||||
assert.match(page, /所属公司/, '账号页要有公司这一列/筛选的中文标签')
|
||||
assert.match(page, /fetchCompanies/, '公司候选来自 /api/admin/companies')
|
||||
assert.match(page, /:companies="companies"/, '整份公司目录交给弹窗,由弹窗按操作者收窄')
|
||||
assert.match(page, /:operator="operatorScope"/, '弹窗要拿到操作者角色与归属才能判必选')
|
||||
assert.match(page, /colspan="8"/, '加了公司列后空态横跨整表')
|
||||
|
||||
const dialog = readSource('src/pages/account/CreateUserDialog.vue')
|
||||
assert.match(dialog, /selectableCompanies\(/, '下拉选项走同一条后端收窄规则')
|
||||
assert.match(dialog, /initialCompanyId\(/, '打开弹窗时的默认公司走纯函数,不在模板里现写')
|
||||
assert.match(dialog, /请选择所属公司/, '下拉占位与校验文案同源')
|
||||
assert.match(dialog, /validateCreateUserForm\(form, props\.operator\)/, '校验必须带上操作者,否则"超管必选公司"永远不触发')
|
||||
|
||||
const layout = readSource('src/layout/AdminLayout.vue')
|
||||
assert.match(layout, /userVm\.company/, '顶栏走同一条公司名视图模型')
|
||||
})
|
||||
@@ -31,6 +31,7 @@
|
||||
<div class="top-right">
|
||||
<NotificationBell />
|
||||
<BrandApiSecretSettingsButton variant="topbar" />
|
||||
<span v-if="companyName" class="company-name" :title="`所属公司:${companyName}`">{{ companyName }}</span>
|
||||
<span class="admin-name">{{ username }}</span>
|
||||
</div>
|
||||
</header>
|
||||
@@ -45,6 +46,7 @@ import { filterGroupsByPermission, TOOL_GROUPS } from '@/pages/amazon/tool-catal
|
||||
import type { VisibleGroup } from '@/pages/amazon/tool-catalog'
|
||||
import { resolvePageHref } from '@/shared/page-prefix'
|
||||
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
|
||||
import { readCompanyIdentity } from '@/shared/auth/company-identity'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
@@ -61,6 +63,8 @@ const emit = defineEmits<{ change: [key: 'front' | 'ops' | 'logi'] }>()
|
||||
const activeCat = computed(() => props.activeCat)
|
||||
const visibleCats = ref<VisibleGroup[]>(TOOL_GROUPS.map((group) => ({ ...group, tools: [...group.tools] })))
|
||||
const username = ref('admin')
|
||||
/** 所属公司名:后端未返回时为空串,该段整体不渲染(不能显示 undefined)。 */
|
||||
const companyName = ref('')
|
||||
|
||||
/** 分类 tab 点击回到工具台对应分组 */
|
||||
const toolbarHref = resolvePageHref('/new_web_source/amazon-console.html')
|
||||
@@ -84,6 +88,7 @@ function underlineStyle(cat: VisibleGroup) {
|
||||
onMounted(async () => {
|
||||
const localName = typeof window === 'undefined' ? '' : (window.localStorage.getItem('username') || '').trim()
|
||||
if (localName) username.value = localName
|
||||
companyName.value = readCompanyIdentity()
|
||||
try {
|
||||
const keys = await getCurrentUserAppColumnKeys()
|
||||
visibleCats.value = filterGroupsByPermission(TOOL_GROUPS, keys)
|
||||
@@ -253,6 +258,18 @@ onMounted(async () => {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.company-name {
|
||||
max-width: 180px;
|
||||
padding: 3px 10px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 999px;
|
||||
color: #9fb0c9;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.admin-name {
|
||||
color: #c8d2e2;
|
||||
font-size: 13px;
|
||||
|
||||
@@ -112,6 +112,7 @@ import { onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { loginWithDevice } from '@/shared/api/user'
|
||||
import { KICK_NOTICE_KEY } from '@/shared/auth/kick-handler'
|
||||
import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/company-identity'
|
||||
import { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
|
||||
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
||||
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
|
||||
@@ -432,6 +433,8 @@ async function submitLogin() {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
// 公司名随后端可选返回:没有就删键,顶栏不显示该段(见 shared/auth/company-identity)
|
||||
writeCompanyIdentity(data)
|
||||
// 登录成功即持久化记住/自动登录凭据(桌面与网页均可,密码 AES 加密落 localStorage)
|
||||
void saveCredentials(account)
|
||||
// 桌面端 Flask cookie 同步已随瘦身下线:登录态只存 localStorage(JWT 走 Bearer),无 cookie 依赖
|
||||
@@ -453,6 +456,7 @@ onMounted(() => {
|
||||
window.localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||
window.localStorage.removeItem('uid')
|
||||
window.localStorage.removeItem('username')
|
||||
window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ export interface LoginData {
|
||||
token?: string
|
||||
userId?: number | string
|
||||
username?: string
|
||||
/** 所属公司(company.id,V143 新增;旧 jar 不返回该字段) */
|
||||
companyId?: number | string
|
||||
companyName?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* 用户端公司身份(设计文档 §2.4)
|
||||
*
|
||||
* app-web 没有 Pinia,登录态一直靠 localStorage(uid/username/auth token),所以公司名也走同一通道。
|
||||
* 只信后端确认过的值:登录/check_login 的 data 里没有 companyName 时删键,而不是留着——
|
||||
* 同一台机器换账号登录时,残留的公司名会把上一个账号的归属显示给当前账号。
|
||||
*/
|
||||
|
||||
export const COMPANY_NAME_STORAGE_KEY = 'company_name'
|
||||
|
||||
function storage(): Storage | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
try {
|
||||
return window.localStorage
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 从登录/check_login 的 data 段落公司名;缺字段或空白一律清键。 */
|
||||
export function writeCompanyIdentity(data: unknown): void {
|
||||
const db = storage()
|
||||
if (!db) return
|
||||
const raw = data && typeof data === 'object' ? (data as { companyName?: unknown }).companyName : undefined
|
||||
const name = typeof raw === 'string' ? raw.trim() : ''
|
||||
if (name) db.setItem(COMPANY_NAME_STORAGE_KEY, name)
|
||||
else db.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||
}
|
||||
|
||||
/** 当前账号所属公司名;没有则空串(调用方据此不渲染该段,不得显示 undefined)。 */
|
||||
export function readCompanyIdentity(): string {
|
||||
const db = storage()
|
||||
if (!db) return ''
|
||||
try {
|
||||
return (db.getItem(COMPANY_NAME_STORAGE_KEY) || '').trim()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
*/
|
||||
|
||||
import { get } from '@/shared/api/http'
|
||||
import { writeCompanyIdentity } from './company-identity'
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const UID_KEY = 'uid'
|
||||
@@ -16,6 +17,8 @@ const UID_KEY = 'uid'
|
||||
interface CheckLoginData {
|
||||
userId?: number | string
|
||||
username?: string
|
||||
companyId?: number | string
|
||||
companyName?: string
|
||||
}
|
||||
|
||||
/** 确保当前页面具备登录态;返回是否可继续进入页面 */
|
||||
@@ -38,6 +41,7 @@ export async function ensureAuth(): Promise<boolean> {
|
||||
if (response.data.username) {
|
||||
window.localStorage.setItem('username', String(response.data.username))
|
||||
}
|
||||
writeCompanyIdentity(response.data)
|
||||
return true
|
||||
} catch {
|
||||
// token 失效:清掉本地登录态(跳转交给路由守卫)
|
||||
@@ -74,6 +78,7 @@ export async function restoreLoginUser(): Promise<{ username?: string } | null>
|
||||
if (response.data.username) {
|
||||
window.localStorage.setItem('username', String(response.data.username))
|
||||
}
|
||||
writeCompanyIdentity(response.data)
|
||||
return { username: response.data.username }
|
||||
} catch {
|
||||
return null
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
* 记住的账号密码保留,手动点一次即可重新登录(此时顶掉对方,最后登录者胜)。
|
||||
*/
|
||||
|
||||
import { COMPANY_NAME_STORAGE_KEY } from './company-identity.ts'
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const UID_KEY = 'uid'
|
||||
const USERNAME_KEY = 'username'
|
||||
@@ -69,6 +71,7 @@ export function handleKicked(): void {
|
||||
storage.removeItem(AUTH_TOKEN_KEY)
|
||||
storage.removeItem(UID_KEY)
|
||||
storage.removeItem(USERNAME_KEY)
|
||||
storage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||
storage.setItem(AUTO_LOGIN_KEY, '0')
|
||||
storage.setItem(KICK_NOTICE_KEY, '1')
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import {
|
||||
COMPANY_NAME_STORAGE_KEY,
|
||||
readCompanyIdentity,
|
||||
writeCompanyIdentity,
|
||||
} from '../src/shared/auth/company-identity.ts'
|
||||
|
||||
/** §2.4 用户端公司身份:localStorage 只存后端确认过的公司名,且不得残留上一个账号的。 */
|
||||
|
||||
interface StorageStub {
|
||||
store: Map<string, string>
|
||||
window: { localStorage: { getItem: (k: string) => string | null; setItem: (k: string, v: string) => void; removeItem: (k: string) => void } }
|
||||
}
|
||||
|
||||
function stubWindow(): StorageStub {
|
||||
const store = new Map<string, string>()
|
||||
const win = {
|
||||
localStorage: {
|
||||
getItem: (k: string) => (store.has(k) ? store.get(k)! : null),
|
||||
setItem: (k: string, v: string) => { store.set(k, v) },
|
||||
removeItem: (k: string) => { store.delete(k) },
|
||||
},
|
||||
}
|
||||
;(globalThis as Record<string, unknown>).window = win
|
||||
return { store, window: win }
|
||||
}
|
||||
|
||||
function clearWindow() {
|
||||
delete (globalThis as Record<string, unknown>).window
|
||||
}
|
||||
|
||||
test('登录数据带公司名时写入 localStorage 并可读回', () => {
|
||||
const env = stubWindow()
|
||||
writeCompanyIdentity({ userId: 42, username: 'zhangsan', companyName: ' 厦门米椿花 ' })
|
||||
assert.equal(env.store.get(COMPANY_NAME_STORAGE_KEY), '厦门米椿花')
|
||||
assert.equal(readCompanyIdentity(), '厦门米椿花')
|
||||
clearWindow()
|
||||
})
|
||||
|
||||
test('后端没带 companyName 时清掉旧值,不残留上一个账号的公司', () => {
|
||||
const env = stubWindow()
|
||||
writeCompanyIdentity({ companyName: '厦门米椿花' })
|
||||
writeCompanyIdentity({ userId: 43, username: 'lisi' })
|
||||
assert.equal(env.store.has(COMPANY_NAME_STORAGE_KEY), false, '缺字段必须删键')
|
||||
assert.equal(readCompanyIdentity(), '')
|
||||
clearWindow()
|
||||
})
|
||||
|
||||
test('公司名是空白串按未提供处理', () => {
|
||||
const env = stubWindow()
|
||||
writeCompanyIdentity({ companyName: '厦门米椿花' })
|
||||
writeCompanyIdentity({ companyName: ' ' })
|
||||
assert.equal(env.store.has(COMPANY_NAME_STORAGE_KEY), false)
|
||||
clearWindow()
|
||||
})
|
||||
|
||||
test('非浏览器环境(SSR/node)读写都不抛,读回空串', () => {
|
||||
clearWindow()
|
||||
assert.equal(readCompanyIdentity(), '')
|
||||
assert.doesNotThrow(() => writeCompanyIdentity({ companyName: '厦门米椿花' }))
|
||||
})
|
||||
|
||||
test('负载不是对象时按未提供处理,不写脏值', () => {
|
||||
const env = stubWindow()
|
||||
writeCompanyIdentity({ companyName: '厦门米椿花' })
|
||||
for (const payload of [null, undefined, 'x', 42, []]) {
|
||||
writeCompanyIdentity(payload)
|
||||
assert.equal(env.store.has(COMPANY_NAME_STORAGE_KEY), false, `负载 ${JSON.stringify(payload)} 应删键`)
|
||||
}
|
||||
clearWindow()
|
||||
})
|
||||
@@ -170,3 +170,13 @@ test('普通业务错误(403 等)不触发下线', () => {
|
||||
assert.equal(localStorage.getItem('uid'), '1095')
|
||||
assert.deepEqual(assigned, [])
|
||||
})
|
||||
|
||||
// ---------- 公司身份(设计文档 §2.4):下线必须把公司名一起清掉 ----------
|
||||
|
||||
test('handleKicked 连公司名一起清:残留会把上一账号的归属显示给下一个账号', () => {
|
||||
const { localStorage } = setupWindow({ ...loggedInStorage(), company_name: '厦门米椿花' })
|
||||
|
||||
handleKicked()
|
||||
|
||||
assert.equal(localStorage.getItem('company_name'), null, '被踢后不得残留上一账号的公司名')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user