Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c4a35c6447 | |||
| e3913ce7e8 | |||
| 15b8e46af8 | |||
| 4dbac40ef3 | |||
| f81d89bae1 | |||
| 4ffd407c53 |
@@ -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
|
adminId?: number | null
|
||||||
/** 角色过滤(''=全部)。 */
|
/** 角色过滤(''=全部)。 */
|
||||||
role?: string
|
role?: string
|
||||||
|
/** 按所属公司过滤(V143);仅超管用得到——公司内 admin 后端本来就只返回本公司账号。 */
|
||||||
|
companyId?: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
|
/** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */
|
||||||
@@ -26,6 +28,7 @@ export interface UserListQuery {
|
|||||||
created_by_id?: number
|
created_by_id?: number
|
||||||
admin_id?: number
|
admin_id?: number
|
||||||
role?: string
|
role?: string
|
||||||
|
company_id?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
|
/** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */
|
||||||
@@ -46,6 +49,12 @@ function finiteInt(value: unknown): number | null {
|
|||||||
return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 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..上限,空关键字视为无过滤。 */
|
/** 归一化分页/筛选参数:页码下限 1、页大小 1..上限,空关键字视为无过滤。 */
|
||||||
export function normalizeUserPageParams(raw: Partial<UserListParams>): UserListParams {
|
export function normalizeUserPageParams(raw: Partial<UserListParams>): UserListParams {
|
||||||
const page = Math.max(finiteInt(raw.page) ?? USER_PAGE_MIN_PAGE, USER_PAGE_MIN_PAGE)
|
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,
|
keyword,
|
||||||
createdById: typeof raw.createdById === 'number' ? raw.createdById : null,
|
createdById: typeof raw.createdById === 'number' ? raw.createdById : null,
|
||||||
adminId: typeof raw.adminId === 'number' ? raw.adminId : null,
|
adminId: typeof raw.adminId === 'number' ? raw.adminId : null,
|
||||||
|
companyId: positiveId(raw.companyId),
|
||||||
role: typeof raw.role === 'string' ? raw.role.trim() || undefined : undefined,
|
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.createdById != null) query.created_by_id = params.createdById
|
||||||
if (params.adminId != null) query.admin_id = params.adminId
|
if (params.adminId != null) query.admin_id = params.adminId
|
||||||
if (params.role) query.role = params.role
|
if (params.role) query.role = params.role
|
||||||
|
const companyId = positiveId(params.companyId)
|
||||||
|
if (companyId !== null) query.company_id = companyId
|
||||||
return query
|
return query
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,12 @@ export function toAdminUserItem(raw: unknown): AdminUser | null {
|
|||||||
if (updatedAt) item.updatedAt = updatedAt
|
if (updatedAt) item.updatedAt = updatedAt
|
||||||
const creator = text(r.creator_username)
|
const creator = text(r.creator_username)
|
||||||
if (creator) item.creatorUsername = creator
|
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)
|
const abbr = text(r.pinyin_abbr)
|
||||||
if (abbr) item.pinyinAbbr = abbr
|
if (abbr) item.pinyinAbbr = abbr
|
||||||
return item
|
return item
|
||||||
|
|||||||
@@ -104,6 +104,9 @@ async function signOut() {
|
|||||||
<NotificationBell />
|
<NotificationBell />
|
||||||
<div class="admin-user-meta">
|
<div class="admin-user-meta">
|
||||||
<strong>{{ userVm.username }}</strong>
|
<strong>{{ userVm.username }}</strong>
|
||||||
|
<span v-if="userVm.company" class="admin-user-company" :title="`所属公司:${userVm.company}`">
|
||||||
|
{{ userVm.company }}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<span v-if="userVm.role" class="admin-user-role">{{ userVm.role }}</span>
|
<span v-if="userVm.role" class="admin-user-role">{{ userVm.role }}</span>
|
||||||
<el-button class="admin-user-logout" @click="signOut">退出登录</el-button>
|
<el-button class="admin-user-logout" @click="signOut">退出登录</el-button>
|
||||||
|
|||||||
@@ -29,6 +29,10 @@ export const OPERATION_GUIDES: Record<string, OperationGuideData> = {
|
|||||||
text: '用户密钥按账号绑定,列表只展示脱敏值。可对单条立即检测连通性;清空后该用户需要重新配置密钥。',
|
text: '用户密钥按账号绑定,列表只展示脱敏值。可对单条立即检测连通性;清空后该用户需要重新配置密钥。',
|
||||||
steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'],
|
steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'],
|
||||||
},
|
},
|
||||||
|
admin_companies: {
|
||||||
|
text: '公司决定账号归属:建号时选哪家公司,该账号名下的数据就归哪家公司。公司只做启用/停用,不提供删除——停用后不能再用于新建账号。',
|
||||||
|
steps: ['查看公司列表', '新建公司', '改名或启停'],
|
||||||
|
},
|
||||||
admin_dedupe_total_data: {
|
admin_dedupe_total_data: {
|
||||||
text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。',
|
text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。',
|
||||||
steps: ['选择分组', '筛选或导入', '核对并导出'],
|
steps: ['选择分组', '筛选或导入', '核对并导出'],
|
||||||
|
|||||||
@@ -13,11 +13,18 @@ export function pageTitleOf(title: string | null | undefined): string {
|
|||||||
export interface TopbarUserViewModel {
|
export interface TopbarUserViewModel {
|
||||||
username: string
|
username: string
|
||||||
role: string
|
role: string
|
||||||
|
/** 所属公司名(V143);后端没带就是空串,模板据此整段不显示,不能渲染出 undefined。 */
|
||||||
|
company: string
|
||||||
hasUser: boolean
|
hasUser: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 顶部栏用户模型:用户信息或未登录空态统一为可渲染视图模型。 */
|
/** 顶部栏用户模型:用户信息或未登录空态统一为可渲染视图模型。 */
|
||||||
export function topbarUserOf(user: AdminUser | null | undefined): TopbarUserViewModel {
|
export function topbarUserOf(user: AdminUser | null | undefined): TopbarUserViewModel {
|
||||||
if (!user) return { username: '当前用户', role: '', hasUser: false }
|
if (!user) return { username: '当前用户', role: '', company: '', hasUser: false }
|
||||||
return { username: user.username || '当前用户', role: roleLabel(user.role) || user.role || '', hasUser: true }
|
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">
|
<script setup lang="ts">
|
||||||
import { reactive, ref, watch } from 'vue'
|
import { computed, reactive, ref, watch } from 'vue'
|
||||||
import { submitCreateUser } from './user-create-adapter'
|
import { submitCreateUser } from './user-create-adapter'
|
||||||
import {
|
import {
|
||||||
createEmptyCreateUserForm,
|
createEmptyCreateUserForm,
|
||||||
|
initialCompanyId,
|
||||||
|
selectableCompanies,
|
||||||
|
type CreateOperatorScope,
|
||||||
type CreateUserForm,
|
type CreateUserForm,
|
||||||
type CreateUserFormErrors,
|
type CreateUserFormErrors,
|
||||||
validateCreateUserForm,
|
validateCreateUserForm,
|
||||||
} from './user-create-model'
|
} from './user-create-model'
|
||||||
|
import type { CompanyItem } from '@/api/companies-dto'
|
||||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||||
import { actionableErrorText } from '@/components/admin-feedback'
|
import { actionableErrorText } from '@/components/admin-feedback'
|
||||||
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
import UserMenuAuthTree from './UserMenuAuthTree.vue'
|
||||||
@@ -16,6 +20,10 @@ const props = defineProps<{
|
|||||||
operatorSuper?: boolean
|
operatorSuper?: boolean
|
||||||
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示)。 */
|
/** 所属管理员候选(列表响应 admins;仅超管创建普通账号时展示)。 */
|
||||||
adminOptions?: Array<{ id: number; username: string }>
|
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 }>()
|
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 errors = reactive<CreateUserFormErrors>({})
|
||||||
const busy = ref(false)
|
const busy = ref(false)
|
||||||
|
|
||||||
|
/** 可选项收窄规则与后端 resolveTargetCompanyId 同源,写在这里而不是父页模板里。 */
|
||||||
|
const companyOptions = computed(() => selectableCompanies(props.companies || [], props.operator || {}))
|
||||||
|
|
||||||
/** 角色下拉(对齐 admin.html:普通账号/管理员;超管才显示可改)。 */
|
/** 角色下拉(对齐 admin.html:普通账号/管理员;超管才显示可改)。 */
|
||||||
const ROLE_CHOICES: Array<{ value: 'admin' | 'normal'; label: string }> = [
|
const ROLE_CHOICES: Array<{ value: 'admin' | 'normal'; label: string }> = [
|
||||||
{ value: 'normal', label: '普通账号' },
|
{ value: 'normal', label: '普通账号' },
|
||||||
@@ -38,8 +49,10 @@ watch(
|
|||||||
form.role = 'normal'
|
form.role = 'normal'
|
||||||
form.columnIds = []
|
form.columnIds = []
|
||||||
form.createdBy = null
|
form.createdBy = null
|
||||||
|
form.companyId = initialCompanyId(props.operator || {}, props.companies || [])
|
||||||
errors.username = undefined
|
errors.username = undefined
|
||||||
errors.password = undefined
|
errors.password = undefined
|
||||||
|
errors.company = undefined
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -48,7 +61,7 @@ function close(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function create(): Promise<void> {
|
async function create(): Promise<void> {
|
||||||
const { valid, errors: errs } = validateCreateUserForm(form)
|
const { valid, errors: errs } = validateCreateUserForm(form, props.operator)
|
||||||
Object.assign(errors, errs)
|
Object.assign(errors, errs)
|
||||||
if (!valid) return
|
if (!valid) return
|
||||||
busy.value = true
|
busy.value = true
|
||||||
@@ -107,6 +120,22 @@ async function create(): Promise<void> {
|
|||||||
/>
|
/>
|
||||||
</el-select>
|
</el-select>
|
||||||
</el-form-item>
|
</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="菜单权限(勾选上级菜单会继承全部子菜单)">
|
<el-form-item label="菜单权限(勾选上级菜单会继承全部子菜单)">
|
||||||
<div class="auth-tree-box">
|
<div class="auth-tree-box">
|
||||||
<UserMenuAuthTree v-model:checked="form.columnIds" />
|
<UserMenuAuthTree v-model:checked="form.columnIds" />
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ import type { AdminUser } from '@/types/admin'
|
|||||||
import { roleLabel } from '@/types/admin'
|
import { roleLabel } from '@/types/admin'
|
||||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||||
import { deleteUser, fetchUserList } from '@/api/users'
|
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 { createUserFilterState, toUserListParams, type UserFilterState } from './users-filter'
|
||||||
import { totalPageCount } from './user-pagination'
|
import { totalPageCount } from './user-pagination'
|
||||||
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
|
import { deleteBlockReason, deleteConfirmMessage } from './user-delete-model'
|
||||||
@@ -24,6 +27,12 @@ const rows = ref<AdminUser[]>([])
|
|||||||
const total = ref(0)
|
const total = ref(0)
|
||||||
/** 所属管理员候选(来自列表响应的 admins),供超管筛选下拉使用。 */
|
/** 所属管理员候选(来自列表响应的 admins),供超管筛选下拉使用。 */
|
||||||
const admins = ref<Array<{ id: number; username: string }>>([])
|
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 filters = reactive<UserFilterState>(createUserFilterState())
|
||||||
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
const isSuperAdmin = computed(() => session.isSuperAdmin)
|
||||||
const currentUserId = computed(() => session.user?.id ?? null)
|
const currentUserId = computed(() => session.user?.id ?? null)
|
||||||
@@ -78,6 +87,18 @@ function retry() {
|
|||||||
void loadUsers()
|
void loadUsers()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录只服务下拉,不参与表格状态机:拉失败时列表照常显示,
|
||||||
|
* 但超管建号会卡在"请选择所属公司"——所以要把原因说出来,别让人对着空下拉猜。
|
||||||
|
*/
|
||||||
|
async function loadCompanies() {
|
||||||
|
try {
|
||||||
|
companies.value = await fetchCompanies()
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.warning(error instanceof Error ? error.message : '公司目录加载失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 提交新筛选条件:重置回第一页再查询。 */
|
/** 提交新筛选条件:重置回第一页再查询。 */
|
||||||
function search() {
|
function search() {
|
||||||
filters.page = 1
|
filters.page = 1
|
||||||
@@ -121,7 +142,10 @@ function goJump() {
|
|||||||
changePage(Math.min(Math.max(n, 1), totalPages.value))
|
changePage(Math.min(Math.max(n, 1), totalPages.value))
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(loadUsers)
|
onMounted(() => {
|
||||||
|
void loadCompanies()
|
||||||
|
void loadUsers()
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -138,6 +162,12 @@ onMounted(loadUsers)
|
|||||||
<label>用户名(模糊搜索)</label>
|
<label>用户名(模糊搜索)</label>
|
||||||
<input v-model="filters.keyword" type="text" placeholder="输入用户名关键字" @keyup.enter="search" />
|
<input v-model="filters.keyword" type="text" placeholder="输入用户名关键字" @keyup.enter="search" />
|
||||||
</div>
|
</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">
|
<div v-if="isSuperAdmin" class="form-group" style="min-width: 160px">
|
||||||
<label>所属管理员</label>
|
<label>所属管理员</label>
|
||||||
<el-select v-model="filters.createdByAdminId" class="admin-filter" filterable clearable placeholder="全部" @change="search">
|
<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: 70px">ID</th>
|
||||||
<th style="width: 180px">用户名</th>
|
<th style="width: 180px">用户名</th>
|
||||||
<th style="width: 140px">角色</th>
|
<th style="width: 140px">角色</th>
|
||||||
|
<th style="width: 140px">所属公司</th>
|
||||||
<th style="width: 160px">所属管理员</th>
|
<th style="width: 160px">所属管理员</th>
|
||||||
<th style="width: 180px">创建时间</th>
|
<th style="width: 180px">创建时间</th>
|
||||||
<th style="width: 180px">更新时间</th>
|
<th style="width: 180px">更新时间</th>
|
||||||
@@ -179,6 +210,7 @@ onMounted(loadUsers)
|
|||||||
<td>{{ row.id }}</td>
|
<td>{{ row.id }}</td>
|
||||||
<td>{{ row.username }}</td>
|
<td>{{ row.username }}</td>
|
||||||
<td>{{ roleLabel(row.role) }}</td>
|
<td>{{ roleLabel(row.role) }}</td>
|
||||||
|
<td>{{ row.companyName || '-' }}</td>
|
||||||
<td>{{ row.creatorUsername || '-' }}</td>
|
<td>{{ row.creatorUsername || '-' }}</td>
|
||||||
<td>{{ formatDateTime(row.createdAt) }}</td>
|
<td>{{ formatDateTime(row.createdAt) }}</td>
|
||||||
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
<td>{{ formatDateTime(row.updatedAt) }}</td>
|
||||||
@@ -205,10 +237,10 @@ onMounted(loadUsers)
|
|||||||
</tr>
|
</tr>
|
||||||
</template>
|
</template>
|
||||||
<tr v-else-if="loading">
|
<tr v-else-if="loading">
|
||||||
<td colspan="7" class="empty-tip">加载中...</td>
|
<td colspan="8" class="empty-tip">加载中...</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-else>
|
<tr v-else>
|
||||||
<td colspan="7" class="empty-tip">{{ userListEmptyHint() }}</td>
|
<td colspan="8" class="empty-tip">{{ userListEmptyHint() }}</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
@@ -217,7 +249,14 @@ onMounted(loadUsers)
|
|||||||
<OldPagination :total="total" :page="filters.page" :page-size="filters.pageSize" @change="changePage" @size-change="changeSize" />
|
<OldPagination :total="total" :page="filters.page" :page-size="filters.pageSize" @change="changePage" @size-change="changeSize" />
|
||||||
</section>
|
</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" />
|
<EditUserDialog v-model="editVisible" :user="editUser" :operator-super="isSuperAdmin" @updated="loadUsers" />
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
@@ -374,7 +413,7 @@ h3 {
|
|||||||
table-layout: fixed;
|
table-layout: fixed;
|
||||||
}
|
}
|
||||||
.user-table-scroll > table {
|
.user-table-scroll > table {
|
||||||
min-width: 860px;
|
min-width: 1000px;
|
||||||
}
|
}
|
||||||
.table-scroll th,
|
.table-scroll th,
|
||||||
.table-scroll td {
|
.table-scroll td {
|
||||||
|
|||||||
@@ -1,11 +1,20 @@
|
|||||||
/** 新建用户表单模型(任务 45):纯逻辑,镜像 Java AdminUserCreateRequest 字段与后端校验。 */
|
/** 新建用户表单模型(任务 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_USERNAME_MIN_LEN = 2
|
||||||
export const CREATE_PASSWORD_MIN_LEN = 6
|
export const CREATE_PASSWORD_MIN_LEN = 6
|
||||||
|
|
||||||
/** 新建用户可选角色:super_admin 不可由表单创建(后端只收 admin|normal)。 */
|
/** 新建用户可选角色:super_admin 不可由表单创建(后端只收 admin|normal)。 */
|
||||||
export type CreatableUserRole = 'normal' | 'admin'
|
export type CreatableUserRole = 'normal' | 'admin'
|
||||||
|
|
||||||
|
/** 当前操作者的公司归属(来自 /api/admin/current-user)。 */
|
||||||
|
export interface CreateOperatorScope {
|
||||||
|
role?: string | null
|
||||||
|
companyId?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
export interface CreateUserForm {
|
export interface CreateUserForm {
|
||||||
username: string
|
username: string
|
||||||
password: string
|
password: string
|
||||||
@@ -14,11 +23,14 @@ export interface CreateUserForm {
|
|||||||
columnIds: number[]
|
columnIds: number[]
|
||||||
/** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */
|
/** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */
|
||||||
createdBy?: number | null
|
createdBy?: number | null
|
||||||
|
/** 所属公司 id(V143)。超管必选;公司内 admin 由后端强制落自己公司。 */
|
||||||
|
companyId?: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CreateUserFormErrors {
|
export interface CreateUserFormErrors {
|
||||||
username?: string
|
username?: string
|
||||||
password?: string
|
password?: string
|
||||||
|
company?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */
|
/** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */
|
||||||
@@ -29,10 +41,11 @@ export interface CreateUserPayload {
|
|||||||
columnIds: number[]
|
columnIds: number[]
|
||||||
/** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */
|
/** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */
|
||||||
createdById?: number
|
createdById?: number
|
||||||
|
companyId?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createEmptyCreateUserForm(): CreateUserForm {
|
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" 白名单一致。 */
|
/** 未知/空白/超管角色一律归一到 normal,与后端 "admin"/"normal" 白名单一致。 */
|
||||||
@@ -40,8 +53,40 @@ export function normalizeCreateRole(role: string | null | undefined): CreatableU
|
|||||||
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
|
return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal'
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填);返回逐字段错误。 */
|
function positiveInt(value: unknown): number | null {
|
||||||
export function validateCreateUserForm(form: CreateUserForm): { valid: boolean; errors: CreateUserFormErrors } {
|
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 errors: CreateUserFormErrors = {}
|
||||||
const username = (form.username || '').trim()
|
const username = (form.username || '').trim()
|
||||||
if (!username) {
|
if (!username) {
|
||||||
@@ -55,11 +100,15 @@ export function validateCreateUserForm(form: CreateUserForm): { valid: boolean;
|
|||||||
} else if (password.length < CREATE_PASSWORD_MIN_LEN) {
|
} else if (password.length < CREATE_PASSWORD_MIN_LEN) {
|
||||||
errors.password = `密码至少${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 }
|
return { valid: Object.keys(errors).length === 0, errors }
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用;
|
/** 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用;
|
||||||
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义)。 */
|
* createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义);
|
||||||
|
* companyId 选了才带,未选时由后端落操作者自己公司。 */
|
||||||
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
||||||
const payload: CreateUserPayload = {
|
const payload: CreateUserPayload = {
|
||||||
username: (form.username || '').trim(),
|
username: (form.username || '').trim(),
|
||||||
@@ -70,5 +119,7 @@ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload {
|
|||||||
if (payload.role === 'normal' && form.createdBy != null) {
|
if (payload.role === 'normal' && form.createdBy != null) {
|
||||||
payload.createdById = form.createdBy
|
payload.createdById = form.createdBy
|
||||||
}
|
}
|
||||||
|
const companyId = positiveInt(form.companyId)
|
||||||
|
if (companyId !== null) payload.companyId = companyId
|
||||||
return payload
|
return payload
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,18 +9,27 @@ export interface UserFilterState {
|
|||||||
createdByAdminId: number | null
|
createdByAdminId: number | null
|
||||||
/** 角色过滤(''=全部;super_admin/admin/normal)。 */
|
/** 角色过滤(''=全部;super_admin/admin/normal)。 */
|
||||||
role: string
|
role: string
|
||||||
|
/** 按所属公司过滤(null=全部);只有超管能用,公司内 admin 看到的本来就是本公司。 */
|
||||||
|
companyId: number | null
|
||||||
page: number
|
page: number
|
||||||
pageSize: number
|
pageSize: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createUserFilterState(): UserFilterState {
|
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(
|
export function withFilterReset(
|
||||||
state: UserFilterState,
|
state: UserFilterState,
|
||||||
next: Partial<Pick<UserFilterState, 'keyword' | 'createdByAdminId' | 'role'>>,
|
next: Partial<Pick<UserFilterState, 'keyword' | 'createdByAdminId' | 'role' | 'companyId'>>,
|
||||||
): UserFilterState {
|
): UserFilterState {
|
||||||
return { ...state, ...next, page: USER_PAGE_MIN_PAGE }
|
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 {
|
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,
|
pageSize: state.pageSize,
|
||||||
keyword: keyword || undefined,
|
keyword: keyword || undefined,
|
||||||
createdById: state.createdByAdminId,
|
createdById: state.createdByAdminId,
|
||||||
|
companyId: state.companyId,
|
||||||
}
|
}
|
||||||
const role = (state.role || '').trim()
|
const role = (state.role || '').trim()
|
||||||
if (role) params.role = role
|
if (role) params.role = role
|
||||||
|
|||||||
@@ -304,7 +304,7 @@ onUnmounted(() => {
|
|||||||
客户端任务 <span class="t-count" title="当前在跑任务数,与上方「进行中任务」同源">{{ runningBadge ?? '—' }}</span>
|
客户端任务 <span class="t-count" title="当前在跑任务数,与上方「进行中任务」同源">{{ runningBadge ?? '—' }}</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="tab" :class="{ active: activeTab === 'variant' }" type="button" @click="switchTab('variant')">
|
<button class="tab" :class="{ active: activeTab === 'variant' }" type="button" @click="switchTab('variant')">
|
||||||
变体采集 <span class="t-count" title="麦象批量任务条数(全部状态),「—」= 还没查到">{{ variantTotal ?? '—' }}</span>
|
变体采集 <span class="t-count" title="麦象在跑批量任务条数(等待执行∪处理中),「—」= 还没查到">{{ variantTotal ?? '—' }}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="tc-head-tools">
|
<div class="tc-head-tools">
|
||||||
@@ -484,7 +484,9 @@ onUnmounted(() => {
|
|||||||
<span>{{ progressText(row) }}</span>
|
<span>{{ progressText(row) }}</span>
|
||||||
<span v-if="row.progressFailed > 0" class="badge danger">失败 {{ row.progressFailed }}</span>
|
<span v-if="row.progressFailed > 0" class="badge danger">失败 {{ row.progressFailed }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="p-track"><div class="p-fill" :style="{ width: progressPercent(row) + '%' }"></div></div>
|
<div class="p-track" v-if="row.progressTotal > 0">
|
||||||
|
<div class="p-fill" :style="{ width: progressPercent(row) + '%' }"></div>
|
||||||
|
</div>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
</template>
|
</template>
|
||||||
@@ -512,7 +514,7 @@ onUnmounted(() => {
|
|||||||
<section class="panel-box">
|
<section class="panel-box">
|
||||||
<div class="box-head">
|
<div class="box-head">
|
||||||
<h3>变体采集(麦象批量任务)</h3>
|
<h3>变体采集(麦象批量任务)</h3>
|
||||||
<span class="box-note">数据来自麦象平台,范围限本组账号</span>
|
<span class="box-note">数据来自麦象平台,范围限本组账号,只看在跑(历史不展示)</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-row">
|
<div class="form-row">
|
||||||
<div class="form-group" style="min-width: 150px">
|
<div class="form-group" style="min-width: 150px">
|
||||||
@@ -569,7 +571,7 @@ onUnmounted(() => {
|
|||||||
<td colspan="6" class="empty-tip">加载中...</td>
|
<td colspan="6" class="empty-tip">加载中...</td>
|
||||||
</tr>
|
</tr>
|
||||||
<tr v-else>
|
<tr v-else>
|
||||||
<td colspan="6" class="empty-tip">暂无变体采集任务</td>
|
<td colspan="6" class="empty-tip">暂无在跑的变体采集任务</td>
|
||||||
</tr>
|
</tr>
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export interface TaskCenterTaskFilter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface TaskCenterVariantFilter {
|
export interface TaskCenterVariantFilter {
|
||||||
/** 麦象状态码字符串(''=全部 / 0 等待 / 1 处理中 / 2 已完成 / 3 失败)。 */
|
/** 麦象状态码字符串(''=在跑(0∪1,后端合并)/ 0 等待 / 1 处理中);历史状态不再可选。 */
|
||||||
status: string
|
status: string
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,12 +54,14 @@ export const TASK_STATUS_OPTIONS: Array<{ value: string; label: string }> = [
|
|||||||
{ value: 'CANCELLED', label: '已取消' },
|
{ value: 'CANCELLED', label: '已取消' },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 变体采集只看「在跑」:空值即后端合并口径(0 等待 ∪ 1 处理中),
|
||||||
|
* 已完成 / 处理失败按用户要求彻底不再提供入口(历史不展示)。
|
||||||
|
*/
|
||||||
export const VARIANT_STATUS_OPTIONS: Array<{ value: string; label: string }> = [
|
export const VARIANT_STATUS_OPTIONS: Array<{ value: string; label: string }> = [
|
||||||
{ value: '', label: '全部状态' },
|
{ value: '', label: '在跑' },
|
||||||
{ value: '0', label: '等待执行' },
|
{ value: '0', label: '等待执行' },
|
||||||
{ value: '1', label: '处理中' },
|
{ value: '1', label: '处理中' },
|
||||||
{ value: '2', label: '已完成' },
|
|
||||||
{ value: '3', label: '处理失败' },
|
|
||||||
]
|
]
|
||||||
|
|
||||||
const TASK_STATUS_LABELS: Record<string, string> = {
|
const TASK_STATUS_LABELS: Record<string, string> = {
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export const adminPages: AdminPageDef[] = [
|
|||||||
{ path: 'account/groups', menuKey: 'admin_group_manage', title: '数据权限分组', load: () => import('@/pages/account/GroupsPage.vue') },
|
{ 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-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/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/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/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') },
|
{ 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 { display: flex; align-items: center; gap: 14px; }
|
||||||
.admin-user-meta { display: flex; align-items: flex-end; flex-direction: column; }
|
.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-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 {
|
.admin-user-role {
|
||||||
display: inline-flex; align-items: center;
|
display: inline-flex; align-items: center;
|
||||||
padding: 2px 10px; border-radius: 999px; font-size: 12px; line-height: 1.7;
|
padding: 2px 10px; border-radius: 999px; font-size: 12px; line-height: 1.7;
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ export interface AdminUser {
|
|||||||
isAdmin?: boolean
|
isAdmin?: boolean
|
||||||
createdById?: number | null
|
createdById?: number | null
|
||||||
creatorUsername?: string
|
creatorUsername?: string
|
||||||
|
/** 所属公司(V143):列表来自 AdminUserItemVo 的 company_id/company_name,
|
||||||
|
* current-user 来自 AdminConsoleController 的 camelCase 摘要。 */
|
||||||
|
companyId?: number | null
|
||||||
|
companyName?: string
|
||||||
createdAt?: string
|
createdAt?: string
|
||||||
updatedAt?: string
|
updatedAt?: string
|
||||||
pinyinAbbr?: 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/, '顶栏走同一条公司名视图模型')
|
||||||
|
})
|
||||||
@@ -110,7 +110,27 @@ test('task_center_variant_status_map_follows_maixiang_semantics', () => {
|
|||||||
assert.equal(variantStatusLabel(9), '未知')
|
assert.equal(variantStatusLabel(9), '未知')
|
||||||
assert.equal(variantStatusLabel(null), '未知')
|
assert.equal(variantStatusLabel(null), '未知')
|
||||||
assert.equal(variantStatusLabel('2'), '已完成', '字符串数字同样识别')
|
assert.equal(variantStatusLabel('2'), '已完成', '字符串数字同样识别')
|
||||||
assert.equal(VARIANT_STATUS_OPTIONS.length, 5)
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 变体采集页签只讲「在跑」(2026-10-04 用户口径:历史彻底不看):
|
||||||
|
* 状态下拉必须收掉 2 已完成 / 3 处理失败 两个入口,空值改成「在跑」而不是「全部状态」——
|
||||||
|
* 文案留着「全部状态」会让用户以为后端还在给他合并历史。
|
||||||
|
*/
|
||||||
|
test('task_center_variant_status_options_drop_history_states', () => {
|
||||||
|
assert.deepEqual(VARIANT_STATUS_OPTIONS, [
|
||||||
|
{ value: '', label: '在跑' },
|
||||||
|
{ value: '0', label: '等待执行' },
|
||||||
|
{ value: '1', label: '处理中' },
|
||||||
|
])
|
||||||
|
const values = VARIANT_STATUS_OPTIONS.map((o) => o.value)
|
||||||
|
assert.equal(values.includes('2'), false, '已完成不再是可选项')
|
||||||
|
assert.equal(values.includes('3'), false, '处理失败不再是可选项')
|
||||||
|
|
||||||
|
const page = readSource(PAGE)
|
||||||
|
assert.match(page, /只看在跑/, '面板说明写明只看在跑')
|
||||||
|
assert.match(page, /title="麦象在跑批量任务条数/, '徽章 tooltip 是在跑口径不是全部状态')
|
||||||
|
assert.equal(/麦象批量任务条数(全部状态)/.test(page), false)
|
||||||
})
|
})
|
||||||
|
|
||||||
test('task_center_device_display_falls_back_to_truncated_id', () => {
|
test('task_center_device_display_falls_back_to_truncated_id', () => {
|
||||||
@@ -146,6 +166,15 @@ test('task_center_progress_counts_done_rows_like_the_client', () => {
|
|||||||
assert.equal(progressPercent({ progressSuccess: -5, progressFailed: 0, progressTotal: 10 }), 0, '脏负数不按负进度画')
|
assert.equal(progressPercent({ progressSuccess: -5, progressFailed: 0, progressTotal: 10 }), 0, '脏负数不按负进度画')
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后端把「客户端没有进度条」的模块(跟价/定时匹配)progressTotal 置 0 ⇒ 前端只画「—」:
|
||||||
|
* 留一条 0% 空进度轨会被读成「进度 0%」,和「这里没有进度可看」是两件事。
|
||||||
|
*/
|
||||||
|
test('task_center_progress_bar_is_dropped_when_there_is_no_progress', () => {
|
||||||
|
const page = readSource(PAGE)
|
||||||
|
assert.match(page, /<div class="p-track" v-if="row\.progressTotal > 0">/, '无进度时不画进度轨')
|
||||||
|
})
|
||||||
|
|
||||||
test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
|
test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
|
||||||
const query = buildTaskQuery(
|
const query = buildTaskQuery(
|
||||||
{ username: ' 张三 ', moduleType: 'COLLECT_DATA', status: 'RUNNING', shop: '林芳旗舰店', startTime: '2026-09-28T10:00', endTime: '' },
|
{ username: ' 张三 ', moduleType: 'COLLECT_DATA', status: 'RUNNING', shop: '林芳旗舰店', startTime: '2026-09-28T10:00', endTime: '' },
|
||||||
@@ -167,10 +196,11 @@ test('task_center_query_builder_omits_blanks_and_normalizes_time', () => {
|
|||||||
|
|
||||||
test('task_center_variant_query_builder_keeps_paging', () => {
|
test('task_center_variant_query_builder_keeps_paging', () => {
|
||||||
const empty = buildVariantQuery({ status: '' }, 1, 20)
|
const empty = buildVariantQuery({ status: '' }, 1, 20)
|
||||||
assert.equal(empty.status, undefined)
|
assert.equal(empty.status, undefined, '空状态不下传 status ⇒ 后端按在跑(0∪1)合并')
|
||||||
assert.equal(empty.page, 1)
|
assert.equal(empty.page, 1)
|
||||||
const filtered = buildVariantQuery({ status: '3' }, 3, 50)
|
const filtered = buildVariantQuery({ status: '1' }, 3, 50)
|
||||||
assert.equal(filtered.status, 3)
|
assert.equal(filtered.status, 1)
|
||||||
|
assert.equal(buildVariantQuery({ status: '0' }, 1, 20).status, 0, '状态 0 是 falsy,不能被当成「没选」')
|
||||||
assert.equal(filtered.page, 3)
|
assert.equal(filtered.page, 3)
|
||||||
assert.equal(filtered.pageSize, 50)
|
assert.equal(filtered.pageSize, 50)
|
||||||
})
|
})
|
||||||
@@ -189,7 +219,7 @@ test('task_center_page_handles_empty_and_error_states', () => {
|
|||||||
const page = readSource(PAGE)
|
const page = readSource(PAGE)
|
||||||
assert.match(page, /暂无符合条件的任务/, '任务空态')
|
assert.match(page, /暂无符合条件的任务/, '任务空态')
|
||||||
assert.match(page, /暂无在跑店铺/, '店铺面板空态')
|
assert.match(page, /暂无在跑店铺/, '店铺面板空态')
|
||||||
assert.match(page, /暂无变体采集任务/, '变体空态')
|
assert.match(page, /暂无在跑的变体采集任务/, '变体空态:口径是在跑不是全部')
|
||||||
assert.match(page, /ElMessage\.error/, '接口失败提示')
|
assert.match(page, /ElMessage\.error/, '接口失败提示')
|
||||||
assert.match(page, /resetFilter/, '筛选重置接线')
|
assert.match(page, /resetFilter/, '筛选重置接线')
|
||||||
assert.match(page, /@size-change="changeTaskSize"/, '分页每页条数切换')
|
assert.match(page, /@size-change="changeTaskSize"/, '分页每页条数切换')
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
# Flyway 迁移盘点(task-193)
|
# Flyway 迁移盘点(task-193)
|
||||||
|
|
||||||
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
|
> 生成方式:`src/test/java/com/nanri/aiimage/config/MigrationInventoryTest.java`(只读审计,可重复)。
|
||||||
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点。
|
> 快照日期:2026-10-01;2026-10-03 随 V142 追加时同步过概览数字与取号起点;2026-10-04 随 V143 同步。
|
||||||
|
|
||||||
## 概览
|
## 概览
|
||||||
|
|
||||||
- 版本化迁移文件数:**141**(`src/main/resources/db/V*.sql`,其中整数版本 140 个 + 小版本 V25_1)
|
- 版本化迁移文件数:**142**(`src/main/resources/db/V*.sql`,其中整数版本 141 个 + 小版本 V25_1)
|
||||||
- 整数版本范围:**V1..V142**,其中 V132/V133 为已退役空号(见下),其余连续
|
- 整数版本范围:**V1..V143**,其中 V132/V133 为已退役空号(见下),其余连续
|
||||||
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
|
- 历史遗留小版本:**V25_1__shop_manage_group_bind_user.sql**(Flyway 语义 25.1,紧跟在 V25 之后、V26 之前执行,属历史命名,保留)
|
||||||
- 最新版本:**V142__web_config_sha256.sql**(V141 已于 2026-10-03 随 jar 上线两台;V142 待下一次发版执行)
|
- 最新版本:**V143__company_and_users_company_id.sql**(V141 已于 2026-10-03 随 jar 上线两台;V142/V143 待下一次发版执行)
|
||||||
- 重复版本:无
|
- 重复版本:无
|
||||||
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
|
- 迁移命名:全部符合 `V<整数>(_<子版本>)?__<描述>.sql`,无空格
|
||||||
|
|
||||||
@@ -20,7 +20,7 @@
|
|||||||
|
|
||||||
本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。
|
本地曾存在 `V132__web_config_add_is_latest.sql`、`V133__hide_redundant_indexes_invisible.sql`,与另一分支已在生产落库的 V134/V135 冲突。因 Flyway 未开启 `out-of-order`,把任何迁移编到 132/133 会在启动期报 "resolved migration not applied";因此这两条改为 **V136/V137**,132/133 永久退役,不可回填。
|
||||||
|
|
||||||
后续新增迁移从 **V143** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。
|
后续新增迁移从 **V144** 起取号(只认"当前最大值 + 1",不要为还没写出来的迁移预留号段——预留会在 1..max 里留洞,`integerVersionsSequentialFromOne` 会红)。
|
||||||
|
|
||||||
原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。
|
原先挂在待办里的"V137 冗余索引 DROP"迁移计划取 V139,该号已被 `V139__asin_result_cache.sql` 占用,顺延到 V140;V140 已被品牌补测队列表 `V140__collectdata_brand_recheck.sql` 落用。
|
||||||
|
|
||||||
@@ -28,3 +28,5 @@
|
|||||||
|
|
||||||
- 审计测试断言:整数版本从 1 到当前最大值连续(`RETIRED_HOLES = {132, 133}` 内的号段除外)、无重复文件名、命名正则合规、历史文件校验和可复算稳定。
|
- 审计测试断言:整数版本从 1 到当前最大值连续(`RETIRED_HOLES = {132, 133}` 内的号段除外)、无重复文件名、命名正则合规、历史文件校验和可复算稳定。
|
||||||
- 修改任何已部署历史迁移会破坏 Flyway checksum,属违规;由本盘点测试 + code review 把关(git 层是否改动由 CI/review 校验)。
|
- 修改任何已部署历史迁移会破坏 Flyway checksum,属违规;由本盘点测试 + code review 把关(git 层是否改动由 CI/review 校验)。
|
||||||
|
- **回滚不得写成版本化迁移。** 本目录是 Flyway 扫描路径,任何 `V*.sql` 都会在应用下次启动时自动执行;把回滚编成 `V{N+1}__rollback_*.sql` 等于让"决定回滚"这件事在没有人工执行的情况下自己发生。回滚一律是本目录之外的人工补丁脚本(首例:`docs/rollback-V143-company.sql`),并要按"停应用 → 跑脚本 → 删 `flyway_schema_history` 对应版本行 → 回滚 jar"的顺序做,漏掉删历史那步会让将来重装时 Flyway 判定"已应用"而跳过重建。
|
||||||
|
- **迁移必须可重跑。** MySQL 的 DDL 不进事务:迁移中途失败时前面的语句已经落库,而 `flyway repair` + 重启会让 Flyway 从第一条语句重跑整个文件。所以建表用 `IF NOT EXISTS`、插种子行用 `INSERT IGNORE` 或 `WHERE NOT EXISTS`、`ADD COLUMN/INDEX` 先查 `information_schema` 再 `PREPARE`(首例:V142 的条件 DDL、V143 全文件)。写成裸 `CREATE TABLE` / 裸 `INSERT ... VALUES` 的迁移,恢复路径本身会撞 1050/1060/1062,把"补数据后重启"变成"必须手工清库"。
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- =============================================================
|
||||||
|
-- V143 回滚补丁:撤销多公司一期(company 主表 + users.company_id + 后台「公司管理」菜单)
|
||||||
|
--
|
||||||
|
-- 【为什么是一个手工脚本,而不是一条 V144 迁移】
|
||||||
|
-- src/main/resources/db/ 是 Flyway 的扫描路径,放进去的任何 V*.sql 都会在应用下次启动时
|
||||||
|
-- 被自动执行。把回滚写成 V144__rollback_company.sql 的后果是:哪怕没人打算回滚,
|
||||||
|
-- 只要集群里还起着带这个文件的 jar,Flyway 就会静默撤销 V143——表没了、列没了、
|
||||||
|
-- 已归属公司的账号全变回无公司状态。回滚必须是一个"只有决定回滚时才有人跑"的东西。
|
||||||
|
--
|
||||||
|
-- 前置事实:V143 从未给任何业务表加列,所以业务数据不受影响,回滚面只有 users 这一列。
|
||||||
|
-- 回滚后已建的 company_id 值一并丢失,账号本身、密码、角色、权限都不受影响。
|
||||||
|
--
|
||||||
|
-- 执行顺序(缺一都会留下不一致状态):
|
||||||
|
-- 1. 停两台 java 应用 —— 否则回滚窗口里新代码还在往 users.company_id 写,会报 unknown column
|
||||||
|
-- 2. 在 MySQL 上按本文件顺序执行(先删索引再删列,反了会 ER_CANT_DROP_FIELD_OR_KEY 之外还留残索引)
|
||||||
|
-- 3. 把 flyway_schema_history 里本版本那行删掉(本文件最后一条语句)
|
||||||
|
-- 不删的后果:将来重新部署带 V143 的 jar 时,Flyway 认为"已应用"直接跳过,
|
||||||
|
-- 表和列都不会重建,而 Java 侧实体照常读写 company_id ⇒ 运行期报 unknown column
|
||||||
|
-- 4. 回滚 jar 到 V142 版本,再起应用
|
||||||
|
-- 5. 若两台不能同时停(滚动回退),必须保证第 2、3 步在**两台都已停下**之后才做
|
||||||
|
-- =============================================================
|
||||||
|
|
||||||
|
ALTER TABLE `users` DROP INDEX `idx_users_company_id`;
|
||||||
|
|
||||||
|
ALTER TABLE `users` DROP COLUMN `company_id`;
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS `company`;
|
||||||
|
|
||||||
|
DELETE FROM `columns` WHERE `column_key` = 'admin_companies';
|
||||||
|
|
||||||
|
DELETE FROM `flyway_schema_history` WHERE `version` = '143';
|
||||||
|
|
||||||
|
-- =============================================================
|
||||||
|
-- 验证(回滚后执行)
|
||||||
|
-- SHOW COLUMNS FROM `users` LIKE 'company_id'; -> 期望 0 行
|
||||||
|
-- SHOW INDEX FROM `users` WHERE Key_name = 'idx_users_company_id';
|
||||||
|
-- -> 期望 0 行
|
||||||
|
-- SHOW TABLES LIKE 'company'; -> 期望 0 行
|
||||||
|
-- SELECT COUNT(*) AS menu_rows FROM `columns` WHERE `column_key` = 'admin_companies';
|
||||||
|
-- -> 期望 0
|
||||||
|
-- SELECT `version` FROM `flyway_schema_history` WHERE `version` = '143';
|
||||||
|
-- -> 期望 0 行
|
||||||
|
-- SELECT COUNT(*) AS max_version FROM `flyway_schema_history`
|
||||||
|
-- WHERE CAST(`version` AS UNSIGNED) > 142; -> 期望 0
|
||||||
|
-- =============================================================
|
||||||
@@ -23,6 +23,9 @@ public class AdminUserEntity {
|
|||||||
private String role;
|
private String role;
|
||||||
@TableField("created_by_id")
|
@TableField("created_by_id")
|
||||||
private Long createdById;
|
private Long createdById;
|
||||||
|
/** 所属公司(company.id,V143 新增)。列 NOT NULL,建号必须显式写,见 AdminUserService#createUser。 */
|
||||||
|
@TableField("company_id")
|
||||||
|
private Long companyId;
|
||||||
@TableField("created_at")
|
@TableField("created_at")
|
||||||
private LocalDateTime createdAt;
|
private LocalDateTime createdAt;
|
||||||
/**
|
/**
|
||||||
|
|||||||
+6
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.admin.controller;
|
|||||||
import com.nanri.aiimage.common.api.ApiResponse;
|
import com.nanri.aiimage.common.api.ApiResponse;
|
||||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
|
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
|
||||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
import com.nanri.aiimage.modules.permission.service.support.AdminMenuTreeBuilder;
|
import com.nanri.aiimage.modules.permission.service.support.AdminMenuTreeBuilder;
|
||||||
@@ -36,6 +37,7 @@ public class AdminConsoleController {
|
|||||||
|
|
||||||
private final AdminAuthSupport adminAuthSupport;
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
private final PermissionMenuService permissionMenuService;
|
||||||
|
private final CompanyService companyService;
|
||||||
|
|
||||||
@GetMapping("/")
|
@GetMapping("/")
|
||||||
@Operation(summary = "根路径跳管理后台", hidden = true)
|
@Operation(summary = "根路径跳管理后台", hidden = true)
|
||||||
@@ -69,6 +71,10 @@ public class AdminConsoleController {
|
|||||||
item.put("id", operator.getId());
|
item.put("id", operator.getId());
|
||||||
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
|
item.put("username", operator.getUsername() == null ? "" : operator.getUsername());
|
||||||
item.put("role", adminAuthSupport.currentRole(operator));
|
item.put("role", adminAuthSupport.currentRole(operator));
|
||||||
|
// 键名固定 camelCase:session.ts 把 item 原样当 AdminUser 用,没有字段映射层,
|
||||||
|
// 拼错只会让顶栏静默少一行字(前端 || '' 兜底),不会报错。
|
||||||
|
item.put("companyId", operator.getCompanyId());
|
||||||
|
item.put("companyName", companyService.nameOrEmpty(operator.getCompanyId()));
|
||||||
return ApiResponse.success(Map.of("item", item));
|
return ApiResponse.success(Map.of("item", item));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -39,11 +39,12 @@ public class AdminUserController {
|
|||||||
@RequestParam(name = "search", required = false) String search,
|
@RequestParam(name = "search", required = false) String search,
|
||||||
@RequestParam(name = "created_by_id", required = false) Long createdById,
|
@RequestParam(name = "created_by_id", required = false) Long createdById,
|
||||||
@RequestParam(name = "admin_id", required = false) Long adminId,
|
@RequestParam(name = "admin_id", required = false) Long adminId,
|
||||||
@RequestParam(name = "role", required = false) String role) {
|
@RequestParam(name = "role", required = false) String role,
|
||||||
|
@RequestParam(name = "company_id", required = false) Long companyId) {
|
||||||
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
|
AdminUserEntity currentUser = adminAuthSupport.requireAdminOrInternal(request);
|
||||||
String kw = (username == null || username.isBlank()) ? search : username;
|
String kw = (username == null || username.isBlank()) ? search : username;
|
||||||
Long filterCreatedBy = createdById != null ? createdById : adminId;
|
Long filterCreatedBy = createdById != null ? createdById : adminId;
|
||||||
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role);
|
AdminUserListVo vo = adminUserService.listUsers(currentUser, page, pageSize, kw, filterCreatedBy, role, companyId);
|
||||||
return ApiResponse.success(vo);
|
return ApiResponse.success(vo);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
@@ -10,5 +10,6 @@ public class AdminUserCreateRequest {
|
|||||||
private String password;
|
private String password;
|
||||||
private String role;
|
private String role;
|
||||||
private Long createdById;
|
private Long createdById;
|
||||||
|
private Long companyId;
|
||||||
private List<Long> columnIds;
|
private List<Long> columnIds;
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -9,4 +9,6 @@ public class AdminUserUpdateRequest {
|
|||||||
private String password;
|
private String password;
|
||||||
private String role;
|
private String role;
|
||||||
private List<Long> columnIds;
|
private List<Long> columnIds;
|
||||||
|
/** 移人目标公司(V143 §2.2,仅超管可用);null 或与账号现公司相同都表示「不动」。 */
|
||||||
|
private Long companyId;
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -12,6 +12,10 @@ public class AdminUserItemVo {
|
|||||||
private String role;
|
private String role;
|
||||||
@JsonProperty("created_by_id")
|
@JsonProperty("created_by_id")
|
||||||
private Long createdById;
|
private Long createdById;
|
||||||
|
@JsonProperty("company_id")
|
||||||
|
private Long companyId;
|
||||||
|
@JsonProperty("company_name")
|
||||||
|
private String companyName;
|
||||||
@JsonProperty("creator_username")
|
@JsonProperty("creator_username")
|
||||||
private String creatorUsername;
|
private String creatorUsername;
|
||||||
@JsonProperty("created_at")
|
@JsonProperty("created_at")
|
||||||
|
|||||||
+124
-5
@@ -14,6 +14,7 @@ import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
|||||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||||
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
|
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
|
||||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -44,9 +45,11 @@ public class AdminUserService {
|
|||||||
private final AdminAuthSupport adminAuthSupport;
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
private final PermissionMenuService permissionMenuService;
|
private final PermissionMenuService permissionMenuService;
|
||||||
private final UserSecretCleanupPort userSecretCleanupPort;
|
private final UserSecretCleanupPort userSecretCleanupPort;
|
||||||
|
private final CompanyService companyService;
|
||||||
|
|
||||||
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
|
public AdminUserListVo listUsers(AdminUserEntity currentUser, Integer page, Integer pageSize,
|
||||||
String username, Long createdById, String roleFilter) {
|
String username, Long createdById, String roleFilter,
|
||||||
|
Long companyIdFilter) {
|
||||||
String role = adminAuthSupport.currentRole(currentUser);
|
String role = adminAuthSupport.currentRole(currentUser);
|
||||||
if (role == null) {
|
if (role == null) {
|
||||||
throw new BusinessException(403, "需要管理员权限");
|
throw new BusinessException(403, "需要管理员权限");
|
||||||
@@ -68,13 +71,24 @@ public class AdminUserService {
|
|||||||
if (!roleFilterValue.isEmpty()) {
|
if (!roleFilterValue.isEmpty()) {
|
||||||
query.eq(AdminUserEntity::getRole, roleFilterValue);
|
query.eq(AdminUserEntity::getRole, roleFilterValue);
|
||||||
}
|
}
|
||||||
if ("super_admin".equals(role)) {
|
boolean isSuperAdmin = "super_admin".equals(role);
|
||||||
|
if (companyIdFilter != null && !isSuperAdmin) {
|
||||||
|
// 公司内管理员:筛自己公司 = 不加条件(他的可见范围本来就只有本公司),
|
||||||
|
// 筛别家公司 = 直接空页。这里故意不报错也不越权(设计文档 §2.3)。
|
||||||
|
if (!companyIdFilter.equals(currentUser.getCompanyId())) {
|
||||||
|
return emptyListVo(currentUser, role, safePage, safeSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (isSuperAdmin) {
|
||||||
if (!kw.isEmpty()) {
|
if (!kw.isEmpty()) {
|
||||||
query.like(AdminUserEntity::getUsername, kw);
|
query.like(AdminUserEntity::getUsername, kw);
|
||||||
}
|
}
|
||||||
if (filterCreatedBy != null) {
|
if (filterCreatedBy != null) {
|
||||||
query.eq(AdminUserEntity::getCreatedById, filterCreatedBy);
|
query.eq(AdminUserEntity::getCreatedById, filterCreatedBy);
|
||||||
}
|
}
|
||||||
|
if (companyIdFilter != null) {
|
||||||
|
query.eq(AdminUserEntity::getCompanyId, companyIdFilter);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
Long adminId = currentUser.getId();
|
Long adminId = currentUser.getId();
|
||||||
query.and(w -> w
|
query.and(w -> w
|
||||||
@@ -94,8 +108,9 @@ public class AdminUserService {
|
|||||||
List<AdminUserEntity> rows = adminUserMapper.selectList(query);
|
List<AdminUserEntity> rows = adminUserMapper.selectList(query);
|
||||||
|
|
||||||
Map<Long, String> creatorMap = loadCreatorMap(rows);
|
Map<Long, String> creatorMap = loadCreatorMap(rows);
|
||||||
|
Map<Long, String> companyMap = loadCompanyNameMap(rows);
|
||||||
|
|
||||||
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap)).toList();
|
List<AdminUserItemVo> items = rows.stream().map(r -> toItem(r, creatorMap, companyMap)).toList();
|
||||||
List<AdminBriefVo> admins = "super_admin".equals(role)
|
List<AdminBriefVo> admins = "super_admin".equals(role)
|
||||||
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
? adminUserMapper.selectList(new LambdaQueryWrapper<AdminUserEntity>()
|
||||||
.eq(AdminUserEntity::getRole, "admin")
|
.eq(AdminUserEntity::getRole, "admin")
|
||||||
@@ -166,6 +181,7 @@ public class AdminUserService {
|
|||||||
entity.setIsAdmin(isAdmin);
|
entity.setIsAdmin(isAdmin);
|
||||||
entity.setRole(wantRole);
|
entity.setRole(wantRole);
|
||||||
entity.setCreatedById(wantCreatedBy);
|
entity.setCreatedById(wantCreatedBy);
|
||||||
|
entity.setCompanyId(resolveTargetCompanyId(role, currentUser, request.getCompanyId()));
|
||||||
try {
|
try {
|
||||||
adminUserMapper.insert(entity);
|
adminUserMapper.insert(entity);
|
||||||
} catch (DuplicateKeyException e) {
|
} catch (DuplicateKeyException e) {
|
||||||
@@ -175,6 +191,68 @@ public class AdminUserService {
|
|||||||
return entity.getId();
|
return entity.getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 建号落哪家公司(设计文档 §2.2,与 createdById 同构):超管可指定任意启用中的公司,
|
||||||
|
* 其余角色只能落自己所属公司——显式传别家即 403,不静默改写。
|
||||||
|
*
|
||||||
|
* <p>永远返回一个具体值并写进实体:列 DEFAULT 1 只为发布期的旧 jar 存在(§8.2),
|
||||||
|
* 新代码不靠它,否则第二家公司开通后每个未传公司的建号都会被静默塞进厦门米椿花。</p>
|
||||||
|
*/
|
||||||
|
private Long resolveTargetCompanyId(String operatorRole, AdminUserEntity operator, Long requestedCompanyId) {
|
||||||
|
if (!"super_admin".equals(operatorRole)) {
|
||||||
|
if (requestedCompanyId != null && !requestedCompanyId.equals(operator.getCompanyId())) {
|
||||||
|
throw new BusinessException(403, "只能在本公司名下创建账号");
|
||||||
|
}
|
||||||
|
return operator.getCompanyId();
|
||||||
|
}
|
||||||
|
if (requestedCompanyId == null) {
|
||||||
|
return operator.getCompanyId();
|
||||||
|
}
|
||||||
|
companyService.requireActive(requestedCompanyId);
|
||||||
|
return requestedCompanyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移人(设计文档 §2.2):返回要把账号移去的公司 id,返回 null 表示「这次没动公司」。
|
||||||
|
*
|
||||||
|
* <p>只有超管能移;传的正好是账号现属公司按"没动"处理(跟建号那条同构,别把幂等请求判成越权)。
|
||||||
|
* 公司内 admin 传别家一律 403,不静默改写——静默改写会让操作者以为移成功了。</p>
|
||||||
|
*/
|
||||||
|
private Long resolveCompanyMove(String operatorRole, AdminUserEntity target, Long requestedCompanyId) {
|
||||||
|
if (requestedCompanyId == null || requestedCompanyId.equals(target.getCompanyId())) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!"super_admin".equals(operatorRole)) {
|
||||||
|
throw new BusinessException(403, "只有超级管理员可以把账号移到其他公司");
|
||||||
|
}
|
||||||
|
companyService.requireActive(requestedCompanyId);
|
||||||
|
return requestedCompanyId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移人之后的不变式:账号的 {@code created_by_id} 必须与它同一家公司,除非创建人是超管。
|
||||||
|
*
|
||||||
|
* <p>这条是二期不回改 77 处 {@code eq(getUserId, userId)} 过滤点的前提(§7.2):数据按账号归属,
|
||||||
|
* 而公司内 admin 的可编辑范围判的是 {@code created_by_id}。一旦允许把账号移进一家它创建人不在的公司,
|
||||||
|
* "同公司"和"同一人"两套口径就会交叉,越权只能逐出口重新补。</p>
|
||||||
|
*/
|
||||||
|
private void ensureCreatorSharesCompany(AdminUserEntity target, Long newCompanyId) {
|
||||||
|
Long createdById = target.getCreatedById();
|
||||||
|
if (createdById == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
AdminUserEntity creator = adminUserMapper.selectById(createdById);
|
||||||
|
if (creator == null) {
|
||||||
|
throw new BusinessException(403, "该账号的创建人已不存在,无法确认同公司,不能移入其他公司");
|
||||||
|
}
|
||||||
|
if ("super_admin".equals(creator.getRole())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!newCompanyId.equals(creator.getCompanyId())) {
|
||||||
|
throw new BusinessException(403, "只能把账号移到其创建人所在的公司");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Transactional
|
@Transactional
|
||||||
public void updateUser(AdminUserEntity currentUser, Long uid, AdminUserUpdateRequest request) {
|
public void updateUser(AdminUserEntity currentUser, Long uid, AdminUserUpdateRequest request) {
|
||||||
String role = adminAuthSupport.currentRole(currentUser);
|
String role = adminAuthSupport.currentRole(currentUser);
|
||||||
@@ -187,7 +265,8 @@ public class AdminUserService {
|
|||||||
|
|
||||||
if ((password == null || password.isEmpty())
|
if ((password == null || password.isEmpty())
|
||||||
&& (wantRole == null || wantRole.isEmpty())
|
&& (wantRole == null || wantRole.isEmpty())
|
||||||
&& request.getColumnIds() == null) {
|
&& request.getColumnIds() == null
|
||||||
|
&& request.getCompanyId() == null) {
|
||||||
throw new BusinessException("请提供要修改的内容");
|
throw new BusinessException("请提供要修改的内容");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,9 +293,19 @@ public class AdminUserService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 移人先于写库:先确认目标公司可用,再确认 created_by_id 不变式没被破坏
|
||||||
|
Long moveCompanyId = resolveCompanyMove(role, target, request.getCompanyId());
|
||||||
|
if (moveCompanyId != null) {
|
||||||
|
ensureCreatorSharesCompany(target, moveCompanyId);
|
||||||
|
}
|
||||||
|
|
||||||
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
|
LambdaUpdateWrapper<AdminUserEntity> update = new LambdaUpdateWrapper<AdminUserEntity>()
|
||||||
.eq(AdminUserEntity::getId, uid);
|
.eq(AdminUserEntity::getId, uid);
|
||||||
boolean dirty = false;
|
boolean dirty = false;
|
||||||
|
if (moveCompanyId != null) {
|
||||||
|
update.set(AdminUserEntity::getCompanyId, moveCompanyId);
|
||||||
|
dirty = true;
|
||||||
|
}
|
||||||
if (password != null && !password.isEmpty()) {
|
if (password != null && !password.isEmpty()) {
|
||||||
if (password.length() < 6) {
|
if (password.length() < 6) {
|
||||||
throw new BusinessException("密码至少6个字符");
|
throw new BusinessException("密码至少6个字符");
|
||||||
@@ -307,6 +396,31 @@ public class AdminUserService {
|
|||||||
log.info("[admin-user] 用户已删除 uid={} 级联清理密钥行={}", uid, secretRows);
|
log.info("[admin-user] 用户已删除 uid={} 级联清理密钥行={}", uid, secretRows);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Map<Long, String> loadCompanyNameMap(List<AdminUserEntity> rows) {
|
||||||
|
Set<Long> companyIds = new LinkedHashSet<>();
|
||||||
|
for (AdminUserEntity r : rows) {
|
||||||
|
if (r.getCompanyId() != null) {
|
||||||
|
companyIds.add(r.getCompanyId());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 空页不去查公司表;一次批量查而不是每行一次(一行一次就是 N+1)
|
||||||
|
return companyIds.isEmpty() ? Map.of() : companyService.namesByIds(companyIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 公司内管理员筛了别家公司:返回一个"这一页什么都没有"的正常响应,不报错、也不去碰表。 */
|
||||||
|
private AdminUserListVo emptyListVo(AdminUserEntity currentUser, String role, int page, int pageSize) {
|
||||||
|
AdminUserListVo vo = new AdminUserListVo();
|
||||||
|
vo.setItems(List.of());
|
||||||
|
vo.setTotal(0L);
|
||||||
|
vo.setPage(page);
|
||||||
|
vo.setPageSize(pageSize);
|
||||||
|
vo.setCurrentUserRole(role);
|
||||||
|
vo.setCurrentUserId(currentUser.getId());
|
||||||
|
vo.setCurrentUserUsername(currentUser.getUsername() == null ? "" : currentUser.getUsername());
|
||||||
|
vo.setAdmins(List.of());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
private Map<Long, String> loadCreatorMap(List<AdminUserEntity> rows) {
|
private Map<Long, String> loadCreatorMap(List<AdminUserEntity> rows) {
|
||||||
Set<Long> creatorIds = new LinkedHashSet<>();
|
Set<Long> creatorIds = new LinkedHashSet<>();
|
||||||
for (AdminUserEntity r : rows) {
|
for (AdminUserEntity r : rows) {
|
||||||
@@ -326,7 +440,8 @@ public class AdminUserService {
|
|||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap) {
|
private AdminUserItemVo toItem(AdminUserEntity entity, Map<Long, String> creatorMap,
|
||||||
|
Map<Long, String> companyMap) {
|
||||||
AdminUserItemVo vo = new AdminUserItemVo();
|
AdminUserItemVo vo = new AdminUserItemVo();
|
||||||
vo.setId(entity.getId());
|
vo.setId(entity.getId());
|
||||||
vo.setUsername(entity.getUsername());
|
vo.setUsername(entity.getUsername());
|
||||||
@@ -336,6 +451,10 @@ public class AdminUserService {
|
|||||||
// 不可变 Map(Map.of) 的 getOrDefault 不允许 null key:createdById 为 null 时直接空串。
|
// 不可变 Map(Map.of) 的 getOrDefault 不允许 null key:createdById 为 null 时直接空串。
|
||||||
Long creatorId = entity.getCreatedById();
|
Long creatorId = entity.getCreatedById();
|
||||||
vo.setCreatorUsername(creatorId == null ? "" : creatorMap.getOrDefault(creatorId, ""));
|
vo.setCreatorUsername(creatorId == null ? "" : creatorMap.getOrDefault(creatorId, ""));
|
||||||
|
Long companyId = entity.getCompanyId();
|
||||||
|
vo.setCompanyId(companyId);
|
||||||
|
// 账号挂着公司表里查不到的 id(脏数据/回滚残留)时留空串,前端显示 '-',整页不能因此 500
|
||||||
|
vo.setCompanyName(companyId == null ? "" : companyMap.getOrDefault(companyId, ""));
|
||||||
LocalDateTime createdAt = entity.getCreatedAt();
|
LocalDateTime createdAt = entity.getCreatedAt();
|
||||||
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
|
vo.setCreatedAt(createdAt == null ? "" : createdAt.format(CREATED_AT_FORMATTER));
|
||||||
LocalDateTime updatedAt = entity.getUpdatedAt();
|
LocalDateTime updatedAt = entity.getUpdatedAt();
|
||||||
|
|||||||
+8
@@ -21,4 +21,12 @@ public class LoginUserEntity {
|
|||||||
private String role;
|
private String role;
|
||||||
@TableField("created_by_id")
|
@TableField("created_by_id")
|
||||||
private Long createdById;
|
private Long createdById;
|
||||||
|
/**
|
||||||
|
* 所属公司(V143 新增,company.id)。
|
||||||
|
*
|
||||||
|
* <p>本类与 {@code AdminUserEntity} 都映射 {@code users}:给 users 加列必须同改两处,
|
||||||
|
* 漏一处就是半边链路(登录 vs 后台用户管理)读不到公司。由 UsersCompanyIdMappingTest 钉住。</p>
|
||||||
|
*/
|
||||||
|
@TableField("company_id")
|
||||||
|
private Long companyId;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ public class LoginResultVo {
|
|||||||
private String username;
|
private String username;
|
||||||
private String role;
|
private String role;
|
||||||
private Boolean isAdmin;
|
private Boolean isAdmin;
|
||||||
|
/** 所属公司 id(V143);账号没有公司归属时为 null。 */
|
||||||
|
private Long companyId;
|
||||||
|
/** 所属公司名,只显示用;查不到公司一律空串,绝不拿它当登录条件。 */
|
||||||
|
private String companyName;
|
||||||
private String deviceId;
|
private String deviceId;
|
||||||
private String token;
|
private String token;
|
||||||
private Long expiresIn;
|
private Long expiresIn;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
|||||||
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||||
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
|
||||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
@@ -33,6 +34,7 @@ public class AuthService {
|
|||||||
private final JwtService jwtService;
|
private final JwtService jwtService;
|
||||||
private final PermissionMenuService permissionMenuService;
|
private final PermissionMenuService permissionMenuService;
|
||||||
private final AuthProperties authProperties;
|
private final AuthProperties authProperties;
|
||||||
|
private final CompanyService companyService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 登录失败计数与锁定(2026-09 全维度审查补):生产是公网域名,此前无任何失败限制
|
* 登录失败计数与锁定(2026-09 全维度审查补):生产是公网域名,此前无任何失败限制
|
||||||
@@ -180,6 +182,9 @@ public class AuthService {
|
|||||||
vo.setUsername(user.getUsername());
|
vo.setUsername(user.getUsername());
|
||||||
vo.setRole(user.getRole());
|
vo.setRole(user.getRole());
|
||||||
vo.setIsAdmin(isAdmin);
|
vo.setIsAdmin(isAdmin);
|
||||||
|
// 公司身份只做显示:nameOrEmpty 查不到就空串,登录不因此被打回
|
||||||
|
vo.setCompanyId(user.getCompanyId());
|
||||||
|
vo.setCompanyName(companyService.nameOrEmpty(user.getCompanyId()));
|
||||||
vo.setDeviceId(deviceId);
|
vo.setDeviceId(deviceId);
|
||||||
vo.setToken(token);
|
vo.setToken(token);
|
||||||
vo.setExpiresIn(jwtService.ttlSeconds());
|
vo.setExpiresIn(jwtService.ttlSeconds());
|
||||||
|
|||||||
+60
@@ -0,0 +1,60 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.controller;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.api.ApiResponse;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||||
|
import com.nanri.aiimage.modules.company.model.vo.CompanyVo;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
import org.springframework.web.bind.annotation.PostMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PutMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestBody;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录(设计文档 §2.3)。可见范围与写入边界都在 CompanyService 里判,
|
||||||
|
* 这里只负责"先解析出操作者"——鉴权必须在调 service 之前,不能靠 service 兜。
|
||||||
|
*/
|
||||||
|
@RestController
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RequestMapping("/api/admin")
|
||||||
|
@Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名与启停")
|
||||||
|
public class CompanyController {
|
||||||
|
|
||||||
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
|
private final CompanyService companyService;
|
||||||
|
|
||||||
|
@GetMapping("/companies")
|
||||||
|
@Operation(summary = "公司目录:超管看全部,公司内管理员只看到自己公司")
|
||||||
|
public ApiResponse<List<CompanyVo>> listCompanies(HttpServletRequest request) {
|
||||||
|
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||||
|
List<CompanyVo> items = companyService.listVisible(operator).stream().map(CompanyVo::from).toList();
|
||||||
|
return ApiResponse.success(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
@PostMapping("/companies")
|
||||||
|
@Operation(summary = "新增公司(仅超级管理员)")
|
||||||
|
public ApiResponse<CompanyVo> createCompany(HttpServletRequest request, @RequestBody CompanySaveRequest body) {
|
||||||
|
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||||
|
return ApiResponse.success("公司创建成功", CompanyVo.from(companyService.create(operator, body)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 没有 DELETE:账号挂着的公司删不掉,停用(status=0)就是终态。 */
|
||||||
|
@PutMapping("/companies/{id}")
|
||||||
|
@Operation(summary = "改名与启停(仅超级管理员)")
|
||||||
|
public ApiResponse<CompanyVo> updateCompany(HttpServletRequest request,
|
||||||
|
@PathVariable Long id,
|
||||||
|
@RequestBody CompanySaveRequest body) {
|
||||||
|
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
|
||||||
|
return ApiResponse.success("更新成功", CompanyVo.from(companyService.update(operator, id, body)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
|
||||||
|
@Mapper
|
||||||
|
public interface CompanyMapper extends BaseMapper<CompanyEntity> {
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.model.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新建/编辑公司的请求体(前端 companies-dto.ts#toCompanyPayload 的 camelCase 对齐)。
|
||||||
|
*
|
||||||
|
* <p>校验刻意放在 service 而不是 {@code @Valid} 注解上:一期只有这一个写入口,
|
||||||
|
* 而"名称非空 + 长度 = 列宽"这两条要和 company 表定义同源维护。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CompanySaveRequest {
|
||||||
|
private String companyName;
|
||||||
|
/** 1=启用 0=停用;null 按启用(与 company.status 的 DEFAULT 1 一致)。 */
|
||||||
|
private Integer status;
|
||||||
|
private String remark;
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.model.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司(租户)主表实体(V143)。与紫鸟语义的 `biz_shop_manage`/`biz_publish_file.company_name` 无关。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@TableName("company")
|
||||||
|
public class CompanyEntity {
|
||||||
|
|
||||||
|
@TableId(type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
@TableField("company_name")
|
||||||
|
private String companyName;
|
||||||
|
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */
|
||||||
|
private Integer status;
|
||||||
|
private String remark;
|
||||||
|
@TableField("created_at")
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
@TableField("updated_at")
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.model.vo;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录条目。线上字段名是 snake_case,与 admin-frontend-vue/src/api/companies-model.ts 的
|
||||||
|
* 读法一致(实体是 camelCase,直接序列化实体前端解析不到 company_name)。
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CompanyVo {
|
||||||
|
|
||||||
|
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
|
||||||
|
|
||||||
|
private Long id;
|
||||||
|
@JsonProperty("company_name")
|
||||||
|
private String companyName;
|
||||||
|
private Integer status;
|
||||||
|
private String remark;
|
||||||
|
@JsonProperty("created_at")
|
||||||
|
private String createdAt;
|
||||||
|
@JsonProperty("updated_at")
|
||||||
|
private String updatedAt;
|
||||||
|
|
||||||
|
public static CompanyVo from(CompanyEntity entity) {
|
||||||
|
CompanyVo vo = new CompanyVo();
|
||||||
|
vo.setId(entity.getId());
|
||||||
|
vo.setCompanyName(entity.getCompanyName());
|
||||||
|
vo.setStatus(entity.getStatus());
|
||||||
|
vo.setRemark(entity.getRemark());
|
||||||
|
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
|
||||||
|
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「半套发布」哨兵(设计文档 §6.3):第二家公司已经开通,但 {@code users.company_id} 还带着
|
||||||
|
* {@code DEFAULT 1}——启动期打 ERROR。
|
||||||
|
*
|
||||||
|
* <p>这个组合不会报错、不会丢数据,只会让每个没显式传公司的建号被静默塞进默认那家(§8.2 里
|
||||||
|
* DEFAULT 存在的唯一理由已经过去了)。正因为它安静,所以由代码来喊,而不是靠人记得。</p>
|
||||||
|
*
|
||||||
|
* <p>标记串({@link #ALARM} / {@link #PROBE_FAILED})是纯 ASCII:巡检脚本要在 docker logs 里
|
||||||
|
* grep 它,中文一旦在容器里变了编码就整条签名失效。</p>
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class CompanyDefaultGuard {
|
||||||
|
|
||||||
|
/** 巡检签名用:出现即代表"多家公司已上线但 DEFAULT 未摘"。 */
|
||||||
|
public static final String ALARM = "COMPANY_DEFAULT_STILL_PRESENT";
|
||||||
|
|
||||||
|
/** 巡检签名用:哨兵自己没跑成(例如没有 information_schema 读权限),不能当成"检查过了"。 */
|
||||||
|
public static final String PROBE_FAILED = "COMPANY_DEFAULT_PROBE_FAILED";
|
||||||
|
|
||||||
|
private static final String COLUMN_DEFAULT_SQL = """
|
||||||
|
SELECT COLUMN_DEFAULT FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'company_id'
|
||||||
|
""";
|
||||||
|
|
||||||
|
private final CompanyMapper companyMapper;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void checkOnStartup() {
|
||||||
|
check();
|
||||||
|
}
|
||||||
|
|
||||||
|
void check() {
|
||||||
|
long companies;
|
||||||
|
String columnDefault;
|
||||||
|
try {
|
||||||
|
companies = countCompanies();
|
||||||
|
if (companies <= 1) {
|
||||||
|
// 一期只有一家公司:DEFAULT 是混合版本窗口的兜底,此时它是正确的,不该喊
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
columnDefault = jdbcTemplate.queryForObject(COLUMN_DEFAULT_SQL, String.class);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
log.warn("[company] {} 哨兵没能确认 users.company_id 的 DEFAULT,请手工核查:{}",
|
||||||
|
PROBE_FAILED, ex.getMessage());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (columnDefault == null || columnDefault.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log.error("[company] {} 已有 {} 家公司,但 users.company_id 仍带 DEFAULT={}:"
|
||||||
|
+ "不传公司的建号会被静默塞进默认那家。请执行 "
|
||||||
|
+ "ALTER TABLE users ALTER COLUMN company_id DROP DEFAULT",
|
||||||
|
ALARM, companies, columnDefault);
|
||||||
|
}
|
||||||
|
|
||||||
|
private long countCompanies() {
|
||||||
|
Long count = companyMapper.selectCount(null);
|
||||||
|
return count == null ? 0L : count;
|
||||||
|
}
|
||||||
|
}
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CompanyService {
|
||||||
|
|
||||||
|
/** company.status:1=启用,0=停用(V143 列注释同口径)。 */
|
||||||
|
public static final int STATUS_ACTIVE = 1;
|
||||||
|
public static final int STATUS_DISABLED = 0;
|
||||||
|
|
||||||
|
/** 后台「公司管理」菜单的 column_key(V143 插入 columns 表那一行的值)。 */
|
||||||
|
public static final String MENU_KEY = "admin_companies";
|
||||||
|
|
||||||
|
/** 列宽取自 V143:company_name varchar(128)、remark varchar(255)。超长先进校验,别让 MySQL 报 1406 变 500。 */
|
||||||
|
private static final int NAME_MAX_LENGTH = 128;
|
||||||
|
private static final int REMARK_MAX_LENGTH = 255;
|
||||||
|
|
||||||
|
private final CompanyMapper companyMapper;
|
||||||
|
private final AdminAuthSupport adminAuthSupport;
|
||||||
|
private final PermissionMenuService permissionMenuService;
|
||||||
|
|
||||||
|
/** 建号指定的公司必须真实存在且启用:否则账号挂在查不到的公司上,按公司筛选时整体失明。 */
|
||||||
|
public CompanyEntity requireActive(Long companyId) {
|
||||||
|
CompanyEntity company = companyMapper.selectById(companyId);
|
||||||
|
if (company == null) {
|
||||||
|
throw new BusinessException("公司不存在");
|
||||||
|
}
|
||||||
|
if (company.getStatus() == null || company.getStatus() != STATUS_ACTIVE) {
|
||||||
|
throw new BusinessException("公司已停用");
|
||||||
|
}
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录(设计文档 §2.3):超管看全部,公司内管理员只看自己那一家。
|
||||||
|
*
|
||||||
|
* <p>读口径必须和写口径一起收窄——只把写拦成超管、列表仍返回全部公司,等于把别家公司的
|
||||||
|
* 名字泄露给本公司管理员。管理员没有公司归属时是拒绝,不是"那就不过滤"。</p>
|
||||||
|
*/
|
||||||
|
public List<CompanyEntity> listVisible(AdminUserEntity operator) {
|
||||||
|
ensureCompanyMenu(operator);
|
||||||
|
String role = adminAuthSupport.currentRole(operator);
|
||||||
|
if (role == null) {
|
||||||
|
throw new BusinessException(403, "需要管理员权限");
|
||||||
|
}
|
||||||
|
if ("super_admin".equals(role)) {
|
||||||
|
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
|
||||||
|
.orderByAsc(CompanyEntity::getId));
|
||||||
|
}
|
||||||
|
Long ownCompanyId = operator.getCompanyId();
|
||||||
|
if (ownCompanyId == null) {
|
||||||
|
throw new BusinessException(403, "当前账号没有所属公司,无法查看公司目录");
|
||||||
|
}
|
||||||
|
return companyMapper.selectList(new LambdaQueryWrapper<CompanyEntity>()
|
||||||
|
.eq(CompanyEntity::getId, ownCompanyId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按 id 批量补公司名(§2.3 账号列表、§2.4 登录态都用它,别写成逐行查的 N+1)。
|
||||||
|
*
|
||||||
|
* <p><b>这个方法不做权限判断</b>:它只是把调用方已经拿在手里的那些 id 换成名字,
|
||||||
|
* 谁能看到哪些行由调用方的查询范围决定(同 {@code AdminUserService.loadCreatorMap} 的口径)。
|
||||||
|
* 要给前端列公司目录请走 {@link #listVisible},它才带收窄与菜单闸门。</p>
|
||||||
|
*/
|
||||||
|
public Map<Long, String> namesByIds(Collection<Long> companyIds) {
|
||||||
|
if (companyIds == null || companyIds.isEmpty()) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
List<Long> ids = new ArrayList<>(new LinkedHashSet<>(companyIds));
|
||||||
|
List<CompanyEntity> rows = companyMapper.selectList(
|
||||||
|
new LambdaQueryWrapper<CompanyEntity>().in(CompanyEntity::getId, ids));
|
||||||
|
Map<Long, String> nameById = new HashMap<>(rows.size() * 2);
|
||||||
|
for (CompanyEntity row : rows) {
|
||||||
|
nameById.put(row.getId(), row.getCompanyName() == null ? "" : row.getCompanyName());
|
||||||
|
}
|
||||||
|
return nameById;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单个公司的显示名(设计文档 §2.4):查不到就回空串,绝不为难调用方。
|
||||||
|
*
|
||||||
|
* <p>每次登录都会走这里一次,所以它不是校验入口——用 {@link #requireActive} 的话,
|
||||||
|
* 停用一家公司等于把它名下所有账号锁在门外。</p>
|
||||||
|
*/
|
||||||
|
public String nameOrEmpty(Long companyId) {
|
||||||
|
if (companyId == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
CompanyEntity company = companyMapper.selectById(companyId);
|
||||||
|
if (company == null || company.getCompanyName() == null) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return company.getCompanyName();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 新增公司:只有超管能建,一期也只有超管需要建(开通第二家公司是人工动作)。 */
|
||||||
|
public CompanyEntity create(AdminUserEntity operator, CompanySaveRequest request) {
|
||||||
|
ensureSuperAdmin(operator);
|
||||||
|
String companyName = requireValidName(request.getCompanyName());
|
||||||
|
int status = resolveStatus(request.getStatus());
|
||||||
|
String remark = normalizeRemark(request.getRemark());
|
||||||
|
ensureNameAvailable(companyName, null);
|
||||||
|
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setCompanyName(companyName);
|
||||||
|
entity.setStatus(status);
|
||||||
|
entity.setRemark(remark);
|
||||||
|
companyMapper.insert(entity);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 改名 + 启停一起改;不提供删除,账号挂着的公司删不掉。 */
|
||||||
|
public CompanyEntity update(AdminUserEntity operator, Long id, CompanySaveRequest request) {
|
||||||
|
ensureSuperAdmin(operator);
|
||||||
|
CompanyEntity company = companyMapper.selectById(id);
|
||||||
|
if (company == null) {
|
||||||
|
throw new BusinessException("公司不存在");
|
||||||
|
}
|
||||||
|
String companyName = requireValidName(request.getCompanyName());
|
||||||
|
int status = resolveStatus(request.getStatus());
|
||||||
|
String remark = normalizeRemark(request.getRemark());
|
||||||
|
// 排除自己:只改备注时名字没变,不排除就会把合法编辑判成重名
|
||||||
|
ensureNameAvailable(companyName, id);
|
||||||
|
|
||||||
|
company.setCompanyName(companyName);
|
||||||
|
company.setStatus(status);
|
||||||
|
company.setRemark(remark);
|
||||||
|
companyMapper.updateById(company);
|
||||||
|
return company;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** uk_company_name 只能兜底并发,不能当校验用:撞索引抛的是"用户名已存在"这类看不懂的文案。 */
|
||||||
|
private void ensureNameAvailable(String companyName, Long excludeId) {
|
||||||
|
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<CompanyEntity>()
|
||||||
|
.eq(CompanyEntity::getCompanyName, companyName);
|
||||||
|
if (excludeId != null) {
|
||||||
|
query.ne(CompanyEntity::getId, excludeId);
|
||||||
|
}
|
||||||
|
Long matched = companyMapper.selectCount(query);
|
||||||
|
if (matched != null && matched > 0) {
|
||||||
|
throw new BusinessException("公司名称已存在");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String requireValidName(String rawCompanyName) {
|
||||||
|
String companyName = rawCompanyName == null ? "" : rawCompanyName.trim();
|
||||||
|
if (companyName.isEmpty()) {
|
||||||
|
throw new BusinessException("公司名称不能为空");
|
||||||
|
}
|
||||||
|
if (companyName.length() > NAME_MAX_LENGTH) {
|
||||||
|
throw new BusinessException("公司名称长度不能超过 " + NAME_MAX_LENGTH + " 个字符");
|
||||||
|
}
|
||||||
|
return companyName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int resolveStatus(Integer status) {
|
||||||
|
if (status == null) {
|
||||||
|
return STATUS_ACTIVE;
|
||||||
|
}
|
||||||
|
if (status != STATUS_ACTIVE && status != STATUS_DISABLED) {
|
||||||
|
throw new BusinessException("公司状态只能是 1(启用)或 0(停用)");
|
||||||
|
}
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 空备注归一成 null:列本身可空,写空串会让后台表格里"无"和"空"两种值混在一起。 */
|
||||||
|
private String normalizeRemark(String rawRemark) {
|
||||||
|
if (rawRemark == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
String remark = rawRemark.trim();
|
||||||
|
if (remark.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (remark.length() > REMARK_MAX_LENGTH) {
|
||||||
|
throw new BusinessException("备注长度不能超过 " + REMARK_MAX_LENGTH + " 个字符");
|
||||||
|
}
|
||||||
|
return remark;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureCompanyMenu(AdminUserEntity operator) {
|
||||||
|
if (!permissionMenuService.hasAnyAdminMenu(operator, List.of(MENU_KEY))) {
|
||||||
|
throw new BusinessException(403, "无权访问公司管理模块");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureSuperAdmin(AdminUserEntity operator) {
|
||||||
|
if (!"super_admin".equals(adminAuthSupport.currentRole(operator))) {
|
||||||
|
throw new BusinessException(403, "只有超级管理员可以新增或修改公司");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-2
@@ -94,9 +94,10 @@ public class AdminTaskCenterController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping("/variant-tasks")
|
@GetMapping("/variant-tasks")
|
||||||
@Operation(summary = "变体采集列表",
|
@Operation(summary = "变体采集列表(只看在跑)",
|
||||||
description = "代理麦象 console 批量任务(默认只看 variant-collection):非超管按可见用户 uid 过滤,"
|
description = "代理麦象 console 批量任务(默认只看 variant-collection):非超管按可见用户 uid 过滤,"
|
||||||
+ "超管看全部;麦象未配置或不可达时返回空页。status 为麦象状态码:0 等待/1 处理中/2 已完成/3 失败。")
|
+ "超管看全部;麦象未配置或不可达时返回空页。status 为麦象状态码:0 等待/1 处理中/2 已完成/3 失败;"
|
||||||
|
+ "不传 status = 只看在跑(0∪1 合并,历史不再展示)。")
|
||||||
public ApiResponse<TaskCenterVariantPageVo> variantTasks(HttpServletRequest request,
|
public ApiResponse<TaskCenterVariantPageVo> variantTasks(HttpServletRequest request,
|
||||||
@RequestParam(required = false) Integer status,
|
@RequestParam(required = false) Integer status,
|
||||||
@RequestParam(required = false) String taskType,
|
@RequestParam(required = false) String taskType,
|
||||||
|
|||||||
+18
@@ -1,5 +1,6 @@
|
|||||||
package com.nanri.aiimage.modules.taskcenter.mapper;
|
package com.nanri.aiimage.modules.taskcenter.mapper;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterCollectStatsRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
||||||
@@ -327,6 +328,23 @@ public interface TaskCenterQueryMapper {
|
|||||||
+ "</script>")
|
+ "</script>")
|
||||||
List<TaskCenterSnapshotRow> selectSnapshots(@Param("taskIds") List<Long> taskIds);
|
List<TaskCenterSnapshotRow> selectSnapshots(@Param("taskIds") List<Long> taskIds);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集数据任务的关键词级进度(客户端回写的 {@code result_json} 里只抽
|
||||||
|
* {@code $.totalRows / $.processedRows} 两个数,不把大 JSON 拉回服务层)。
|
||||||
|
*
|
||||||
|
* <p>列是原生 JSON 类型,缺键只会得到 NULL(服务层按「无进度」读),不会让整页查询报错。</p>
|
||||||
|
*/
|
||||||
|
@Select("<script>"
|
||||||
|
+ "SELECT t.id AS taskId,"
|
||||||
|
+ " JSON_UNQUOTE(JSON_EXTRACT(t.result_json, '$.totalRows')) AS totalRows,"
|
||||||
|
+ " JSON_UNQUOTE(JSON_EXTRACT(t.result_json, '$.processedRows')) AS processedRows"
|
||||||
|
+ " FROM biz_file_task t"
|
||||||
|
+ " WHERE t.id IN <foreach collection='taskIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>"
|
||||||
|
+ " AND UPPER(t.module_type) = 'COLLECT_DATA'"
|
||||||
|
+ " AND t.result_json IS NOT NULL"
|
||||||
|
+ "</script>")
|
||||||
|
List<TaskCenterCollectStatsRow> selectCollectDataKeywordStats(@Param("taskIds") List<Long> taskIds);
|
||||||
|
|
||||||
/** 详情:按任务号取单行(只认 12 个客户端模块,其余模块不在看板范围)。 */
|
/** 详情:按任务号取单行(只认 12 个客户端模块,其余模块不在看板范围)。 */
|
||||||
@Select("SELECT t.id AS id, t.task_no AS taskNo, UPPER(t.module_type) AS moduleType,"
|
@Select("SELECT t.id AS id, t.task_no AS taskNo, UPPER(t.module_type) AS moduleType,"
|
||||||
+ " " + STATUS_T + " AS status, t.user_id AS userId, t.device_id AS deviceId,"
|
+ " " + STATUS_T + " AS status, t.user_id AS userId, t.device_id AS deviceId,"
|
||||||
|
|||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package com.nanri.aiimage.modules.taskcenter.model.dto;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集数据任务的关键词级进度:从 {@code biz_file_task.result_json} 抽出的两个数,
|
||||||
|
* 与客户端进度条同源(collectStage 等其余字段看板不读)。
|
||||||
|
*
|
||||||
|
* <p>JSON_UNQUOTE 的产物是字符串,脏值(非数字/缺失)由服务层按无进度处理。</p>
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class TaskCenterCollectStatsRow {
|
||||||
|
|
||||||
|
private Long taskId;
|
||||||
|
private String totalRows;
|
||||||
|
private String processedRows;
|
||||||
|
}
|
||||||
+73
-5
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.taskcenter.service;
|
|||||||
|
|
||||||
import com.nanri.aiimage.common.module.TaskModuleRegistry;
|
import com.nanri.aiimage.common.module.TaskModuleRegistry;
|
||||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||||
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterCollectStatsRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
||||||
@@ -259,9 +260,11 @@ public class TaskCenterQueryService {
|
|||||||
: toUserNames(safe(queryMapper.selectUsernames(userIds)));
|
: toUserNames(safe(queryMapper.selectUsernames(userIds)));
|
||||||
Map<String, TaskCenterSnapshotRow> snapshots = row.getId() == null ? Map.of()
|
Map<String, TaskCenterSnapshotRow> snapshots = row.getId() == null ? Map.of()
|
||||||
: toSnapshots(safe(queryMapper.selectSnapshots(List.of(row.getId()))));
|
: toSnapshots(safe(queryMapper.selectSnapshots(List.of(row.getId()))));
|
||||||
|
Map<Long, TaskCenterCollectStatsRow> collectStats = row.getId() == null ? Map.of()
|
||||||
|
: selectCollectStats(List.of(row), snapshots);
|
||||||
|
|
||||||
TaskCenterTaskDetailVo vo = fillRow(new TaskCenterTaskDetailVo(), row, usernames, deviceNames,
|
TaskCenterTaskDetailVo vo = fillRow(new TaskCenterTaskDetailVo(), row, usernames, deviceNames,
|
||||||
snapshots, collectShops(bizIds), LocalDateTime.now());
|
snapshots, collectStats, collectShops(bizIds), LocalDateTime.now());
|
||||||
vo.setShops(shopStats(row));
|
vo.setShops(shopStats(row));
|
||||||
vo.setErrorMessage(row.getErrorMessage());
|
vo.setErrorMessage(row.getErrorMessage());
|
||||||
return vo;
|
return vo;
|
||||||
@@ -311,12 +314,14 @@ public class TaskCenterQueryService {
|
|||||||
: toUserNames(safe(queryMapper.selectUsernames(userIds)));
|
: toUserNames(safe(queryMapper.selectUsernames(userIds)));
|
||||||
Map<String, TaskCenterSnapshotRow> snapshots = rowIds.isEmpty() ? Map.of()
|
Map<String, TaskCenterSnapshotRow> snapshots = rowIds.isEmpty() ? Map.of()
|
||||||
: toSnapshots(safe(queryMapper.selectSnapshots(rowIds)));
|
: toSnapshots(safe(queryMapper.selectSnapshots(rowIds)));
|
||||||
|
Map<Long, TaskCenterCollectStatsRow> collectStats = selectCollectStats(rows, snapshots);
|
||||||
Map<Long, List<String>> shops = collectShops(bizIds);
|
Map<Long, List<String>> shops = collectShops(bizIds);
|
||||||
|
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
List<TaskCenterTaskRowVo> items = new ArrayList<>(rows.size());
|
List<TaskCenterTaskRowVo> items = new ArrayList<>(rows.size());
|
||||||
for (TaskCenterTaskRow row : rows) {
|
for (TaskCenterTaskRow row : rows) {
|
||||||
items.add(fillRow(new TaskCenterTaskRowVo(), row, usernames, Map.of(), snapshots, shops, now));
|
items.add(fillRow(new TaskCenterTaskRowVo(), row, usernames, Map.of(), snapshots,
|
||||||
|
collectStats, shops, now));
|
||||||
}
|
}
|
||||||
return items;
|
return items;
|
||||||
}
|
}
|
||||||
@@ -398,6 +403,7 @@ public class TaskCenterQueryService {
|
|||||||
Map<Long, String> usernames,
|
Map<Long, String> usernames,
|
||||||
Map<String, String> deviceNames,
|
Map<String, String> deviceNames,
|
||||||
Map<String, TaskCenterSnapshotRow> snapshots,
|
Map<String, TaskCenterSnapshotRow> snapshots,
|
||||||
|
Map<Long, TaskCenterCollectStatsRow> collectStats,
|
||||||
Map<Long, List<String>> shops,
|
Map<Long, List<String>> shops,
|
||||||
LocalDateTime now) {
|
LocalDateTime now) {
|
||||||
vo.setId(row.getId());
|
vo.setId(row.getId());
|
||||||
@@ -423,9 +429,7 @@ public class TaskCenterQueryService {
|
|||||||
vo.setCurrentScope(snapshot.getCurrentScopeKey());
|
vo.setCurrentScope(snapshot.getCurrentScopeKey());
|
||||||
vo.setMessage(snapshot.getMessage());
|
vo.setMessage(snapshot.getMessage());
|
||||||
} else {
|
} else {
|
||||||
vo.setProgressTotal(nullToZero(row.getTotalCount()));
|
fillFallbackProgress(vo, row, collectStats.get(row.getId()));
|
||||||
vo.setProgressSuccess(nullToZero(row.getSuccessCount()));
|
|
||||||
vo.setProgressFailed(nullToZero(row.getFailedCount()));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 品牌检测按关键字执行、不落店铺;品牌行的 current_scope_key 是品牌名,不能当店铺用。
|
// 品牌检测按关键字执行、不落店铺;品牌行的 current_scope_key 是品牌名,不能当店铺用。
|
||||||
@@ -439,6 +443,70 @@ public class TaskCenterQueryService {
|
|||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 无快照时的进度回退,口径 = 客户端画不画进度条(用户 2026-10-04 定案):
|
||||||
|
* <ul>
|
||||||
|
* <li>采集数据:客户端进度条是关键词进度(result_json 的 processedRows/totalRows),看板用同一份数;</li>
|
||||||
|
* <li>上架 / 删除ASIN / 品牌行:客户端进度条的单位本就是文件数 / 品牌行数,沿用行内计数;</li>
|
||||||
|
* <li>其余(跟价、定时匹配等):客户端没有进度条,进度置 0,前端画「—」——
|
||||||
|
* 旧的「输入文件数」回退让单文件任务恒显示 0/1,是误导。</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
private static void fillFallbackProgress(TaskCenterTaskRowVo vo, TaskCenterTaskRow row,
|
||||||
|
TaskCenterCollectStatsRow collectStat) {
|
||||||
|
String module = row.getModuleType();
|
||||||
|
if (row.isBrand() || "PUBLISH".equals(module) || "DELETE_BRAND".equals(module)) {
|
||||||
|
vo.setProgressTotal(nullToZero(row.getTotalCount()));
|
||||||
|
vo.setProgressSuccess(nullToZero(row.getSuccessCount()));
|
||||||
|
vo.setProgressFailed(nullToZero(row.getFailedCount()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if ("COLLECT_DATA".equals(module)) {
|
||||||
|
long total = parseStatNumber(collectStat == null ? null : collectStat.getTotalRows());
|
||||||
|
long processed = parseStatNumber(collectStat == null ? null : collectStat.getProcessedRows());
|
||||||
|
vo.setProgressTotal(Math.max(0, total));
|
||||||
|
// 已完成 = 已处理关键词数(与客户端「关键词进度:第 X/N 个」同数)
|
||||||
|
vo.setProgressSuccess(total <= 0 ? 0 : Math.min(Math.max(0, processed), total));
|
||||||
|
vo.setProgressFailed(0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
vo.setProgressTotal(0);
|
||||||
|
vo.setProgressSuccess(0);
|
||||||
|
vo.setProgressFailed(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** JSON_UNQUOTE 的产物是字符串:非数字/缺失一律按无进度(0),不猜。 */
|
||||||
|
private static long parseStatNumber(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return Long.parseLong(value.trim());
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 采集数据且无快照的行才需要关键词进度;页内没有这种行就不发查询。 */
|
||||||
|
private Map<Long, TaskCenterCollectStatsRow> selectCollectStats(List<TaskCenterTaskRow> rows,
|
||||||
|
Map<String, TaskCenterSnapshotRow> snapshots) {
|
||||||
|
List<Long> ids = rows.stream()
|
||||||
|
.filter(row -> !row.isBrand() && "COLLECT_DATA".equals(row.getModuleType()))
|
||||||
|
.filter(row -> row.getId() != null
|
||||||
|
&& !snapshots.containsKey(snapshotKey(row.getId(), row.getModuleType())))
|
||||||
|
.map(TaskCenterTaskRow::getId).distinct().toList();
|
||||||
|
if (ids.isEmpty()) {
|
||||||
|
return Map.of();
|
||||||
|
}
|
||||||
|
Map<Long, TaskCenterCollectStatsRow> stats = new HashMap<>();
|
||||||
|
for (TaskCenterCollectStatsRow row : safe(queryMapper.selectCollectDataKeywordStats(ids))) {
|
||||||
|
if (row.getTaskId() != null) {
|
||||||
|
stats.put(row.getTaskId(), row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
}
|
||||||
|
|
||||||
private static boolean isStuck(TaskCenterTaskRow row, LocalDateTime now) {
|
private static boolean isStuck(TaskCenterTaskRow row, LocalDateTime now) {
|
||||||
if (row.getStatus() == null || !ACTIVE_STATUSES.contains(row.getStatus())) {
|
if (row.getStatus() == null || !ACTIVE_STATUSES.contains(row.getStatus())) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
+41
-1
@@ -12,6 +12,7 @@ import lombok.extern.slf4j.Slf4j;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
import java.util.LinkedHashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@@ -24,6 +25,9 @@ import java.util.stream.Collectors;
|
|||||||
*
|
*
|
||||||
* <p>可见范围靠 uid 过滤实现:非超管把可见用户号拼成逗号分隔的 uid 参数(麦象侧拆分后 IN),
|
* <p>可见范围靠 uid 过滤实现:非超管把可见用户号拼成逗号分隔的 uid 参数(麦象侧拆分后 IN),
|
||||||
* 超管不传 uid(看全部)。麦象未配置或不可达时返回空页并记日志,页面不因外部依赖炸掉。</p>
|
* 超管不传 uid(看全部)。麦象未配置或不可达时返回空页并记日志,页面不因外部依赖炸掉。</p>
|
||||||
|
*
|
||||||
|
* <p>不传 status 时只看在跑(等待 0 ∪ 处理中 1):麦象一次只能筛一个状态,
|
||||||
|
* 服务层各拉一页合并;历史终态不再作为页签默认口径(徽章说的必须是「在跑几条」)。</p>
|
||||||
*/
|
*/
|
||||||
@Service
|
@Service
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@@ -33,6 +37,12 @@ public class TaskCenterVariantService {
|
|||||||
/** 页签默认只看变体采集这一类批量任务;传 taskType 可覆盖。 */
|
/** 页签默认只看变体采集这一类批量任务;传 taskType 可覆盖。 */
|
||||||
public static final String VARIANT_TASK_TYPE = "variant-collection";
|
public static final String VARIANT_TASK_TYPE = "variant-collection";
|
||||||
|
|
||||||
|
/** 麦象状态码:0 等待 / 1 处理中,两者合起来才是「在跑」。 */
|
||||||
|
private static final int STATUS_WAITING = 0;
|
||||||
|
private static final int STATUS_PROCESSING = 1;
|
||||||
|
/** 在跑任务正常在几十量级;触顶时 total 仍按麦象回值,但翻页尾部会缺行(记 warn)。 */
|
||||||
|
private static final int ACTIVE_FETCH_SIZE = 200;
|
||||||
|
|
||||||
private static final long DEFAULT_PAGE_SIZE = 20;
|
private static final long DEFAULT_PAGE_SIZE = 20;
|
||||||
private static final long MAX_PAGE_SIZE = 100;
|
private static final long MAX_PAGE_SIZE = 100;
|
||||||
|
|
||||||
@@ -60,13 +70,43 @@ public class TaskCenterVariantService {
|
|||||||
|
|
||||||
String uidsCsv = scope.allUsers() ? null
|
String uidsCsv = scope.allUsers() ? null
|
||||||
: scope.visibleUserIds().stream().sorted().map(String::valueOf).collect(Collectors.joining(","));
|
: scope.visibleUserIds().stream().sorted().map(String::valueOf).collect(Collectors.joining(","));
|
||||||
|
int size = (int) normalizedSize;
|
||||||
|
if (status != null) {
|
||||||
BatchTaskPage maixiang = consoleClient.batchTasksPage(uidsCsv, status, type,
|
BatchTaskPage maixiang = consoleClient.batchTasksPage(uidsCsv, status, type,
|
||||||
(int) normalizedPage, (int) normalizedSize);
|
(int) normalizedPage, size);
|
||||||
vo.setTotal(maixiang.total());
|
vo.setTotal(maixiang.total());
|
||||||
vo.setItems(assemble(maixiang.items()));
|
vo.setItems(assemble(maixiang.items()));
|
||||||
return vo;
|
return vo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 不传状态 = 只看在跑(用户 2026-10-04 定案:历史的不看了)。
|
||||||
|
// 麦象一次只能筛一个状态,等待(0) 与处理中(1) 各拉一页后在内存合并分页。
|
||||||
|
BatchTaskPage waiting = consoleClient.batchTasksPage(uidsCsv, STATUS_WAITING, type, 1, ACTIVE_FETCH_SIZE);
|
||||||
|
BatchTaskPage processing = consoleClient.batchTasksPage(uidsCsv, STATUS_PROCESSING, type, 1, ACTIVE_FETCH_SIZE);
|
||||||
|
List<BatchTaskItem> active = new ArrayList<>(waiting.items());
|
||||||
|
active.addAll(processing.items());
|
||||||
|
active.sort(Comparator.comparing(BatchTaskItem::createTime,
|
||||||
|
Comparator.nullsLast(Comparator.reverseOrder())));
|
||||||
|
// total 用麦象回值(-1 哨兵或缺字段时回落为已拉到的行数),保证徽章说的是「在跑」而不是历史全量。
|
||||||
|
long total = effectiveTotal(waiting) + effectiveTotal(processing);
|
||||||
|
vo.setTotal(total);
|
||||||
|
if (total > active.size()) {
|
||||||
|
log.warn("[task-center] 变体采集在跑数 {} 超过单状态拉取上限 {},翻页尾部会缺行",
|
||||||
|
total, ACTIVE_FETCH_SIZE);
|
||||||
|
}
|
||||||
|
long from = (normalizedPage - 1) * normalizedSize;
|
||||||
|
if (from >= active.size()) {
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
long to = Math.min(from + normalizedSize, active.size());
|
||||||
|
vo.setItems(assemble(active.subList((int) from, (int) to)));
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static long effectiveTotal(BatchTaskPage page) {
|
||||||
|
return Math.max(page.total(), page.items().size());
|
||||||
|
}
|
||||||
|
|
||||||
/** uid → 账号名映射只对数字 uid 生效;麦象任务可能带非数字伪 uid(如 collect-27475)。 */
|
/** uid → 账号名映射只对数字 uid 生效;麦象任务可能带非数字伪 uid(如 collect-27475)。 */
|
||||||
private List<TaskCenterVariantTaskVo> assemble(List<BatchTaskItem> items) {
|
private List<TaskCenterVariantTaskVo> assemble(List<BatchTaskItem> items) {
|
||||||
Set<Long> userIds = new LinkedHashSet<>();
|
Set<Long> userIds = new LinkedHashSet<>();
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
-- =============================================================
|
||||||
|
-- 迁移 V143__company_and_users_company_id
|
||||||
|
-- 模板:docs/flyway-migration-template.md
|
||||||
|
-- 设计:crawler-plugin/docs/ops/company-multi-tenant-design-2026-10-04.md
|
||||||
|
--
|
||||||
|
-- 1. 变更目的:为多公司(租户)场景引入主表 company,给 users 挂 company_id,并把现有全部
|
||||||
|
-- 账号归属「厦门米椿花」。业务表零 DDL——公司维度一律由 user_id → users.company_id 派生,
|
||||||
|
-- 不给 57 张业务表冗余 company_id(与"数据按账号归属、公司维度跟着账号走"的定案一致)。
|
||||||
|
-- 2. 影响表与数据量:company(新建,1 行);users(全表 UPDATE 一次,行数以生产实查为准——
|
||||||
|
-- aiimage.sql 快照的 AUTO_INCREMENT 有跳号,不等于行数);columns(+1 行后台菜单)。
|
||||||
|
-- 三张表都是百行量级,业务表 0 张受影响。
|
||||||
|
-- 3. 锁表风险:低。MySQL 8 的 ADD COLUMN 为 INSTANT;ADD INDEX 为 INPLACE;
|
||||||
|
-- MODIFY ... NOT NULL 触发 COPY 重建,但 users 只百行量级(毫秒级)。
|
||||||
|
-- 不碰 biz_task_file_job 等锁热点表。
|
||||||
|
-- 4. 验证 SQL:见文件末尾「验证」段。
|
||||||
|
-- 5. 回滚步骤:执行人工补丁脚本 docs/rollback-V143-company.sql(在 Flyway 扫描路径之外)。
|
||||||
|
-- 顺序:停两台应用 → 跑脚本 → 删 flyway_schema_history 的本版本行 → 回滚 jar → 起应用。
|
||||||
|
-- 6. 上线窗口:随 jar 双节点滚动发布,Flyway 在应用启动期执行,第二节点见"已应用"即跳过。
|
||||||
|
-- 建议业务低峰 02:00-06:00。
|
||||||
|
--
|
||||||
|
-- 【可重跑性】MySQL 的 DDL 不进事务。本迁移若在 NOT NULL 闸门处失败,前面的建表/插数/加列
|
||||||
|
-- 已经落库;按「补数据 → flyway repair → 重启」恢复时 Flyway 会从第一条语句重跑整个文件,
|
||||||
|
-- 所以每一条都写成幂等形式(IF NOT EXISTS / INSERT IGNORE / information_schema 条件 DDL /
|
||||||
|
-- WHERE 限定 / NOT EXISTS 守卫)。
|
||||||
|
-- =============================================================
|
||||||
|
|
||||||
|
-- ---------- 1. 公司(租户)主表 ----------
|
||||||
|
-- 与紫鸟语义的 company_name 字段(biz_ziniao_memory_store / biz_publish_file,自由文本无外键)
|
||||||
|
-- 不是同一回事,那两个保持原名不动。
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `company` (
|
||||||
|
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||||
|
`company_name` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '公司名称',
|
||||||
|
`status` tinyint NOT NULL DEFAULT 1 COMMENT '1=启用 0=停用',
|
||||||
|
`remark` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '备注',
|
||||||
|
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
PRIMARY KEY (`id`) USING BTREE,
|
||||||
|
UNIQUE INDEX `uk_company_name`(`company_name` ASC) USING BTREE,
|
||||||
|
INDEX `idx_company_status`(`status` ASC) USING BTREE
|
||||||
|
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '公司(租户)主表' ROW_FORMAT = Dynamic;
|
||||||
|
|
||||||
|
-- id 显式钉为 1:下一步 users.company_id 的 DEFAULT 只能是字面量(MySQL 不允许 DEFAULT 子查询),
|
||||||
|
-- 存量回填也写死 = 1。id 若由 AUTO_INCREMENT 决定,这两处就会指向一个不存在的公司。
|
||||||
|
-- IGNORE 只为重跑服务:id 已钉死 + 公司名唯一,能撞上的只有一模一样的这一行。
|
||||||
|
INSERT IGNORE INTO `company` (`id`, `company_name`, `status`, `remark`)
|
||||||
|
VALUES (1, '厦门米椿花', 1, '初始公司:现有全部账号与数据归属');
|
||||||
|
|
||||||
|
-- ---------- 2. users 挂所属公司 ----------
|
||||||
|
|
||||||
|
SET @db_name = DATABASE();
|
||||||
|
|
||||||
|
SET @col_exists := (
|
||||||
|
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = @db_name AND TABLE_NAME = 'users' AND COLUMN_NAME = 'company_id'
|
||||||
|
);
|
||||||
|
-- 先建成可空:下一节的 UPDATE 才有行可回填,再靠 MODIFY 收成 NOT NULL。
|
||||||
|
-- 列与索引在同一条 ALTER 里,MySQL 保证整条原子,故只需按列存在性判一次。
|
||||||
|
SET @sql := IF(@col_exists = 0,
|
||||||
|
'ALTER TABLE `users` ADD COLUMN `company_id` bigint NULL DEFAULT NULL COMMENT ''所属公司(company.id)'' AFTER `created_by_id`, ADD INDEX `idx_users_company_id`(`company_id` ASC) USING BTREE',
|
||||||
|
'SELECT 1'
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
-- ---------- 3. 存量账号全部归厦门米椿花 ----------
|
||||||
|
-- WHERE 限定 NULL,重跑时是 no-op;不会覆盖任何已经人工指定过公司的行。
|
||||||
|
|
||||||
|
UPDATE `users` SET `company_id` = 1 WHERE `company_id` IS NULL;
|
||||||
|
|
||||||
|
-- 自检闸门:上一句若漏掉任何一行,这里抛 ER_INVALID_USE_OF_NULL 让迁移失败,
|
||||||
|
-- 而不是留一堆 NULL 静默通过(NULL 意味着这些账号在公司维度上整体失明)。
|
||||||
|
--
|
||||||
|
-- DEFAULT 1 是【临时】的,唯一存在理由是混合版本窗口:发布期间一台新 jar、一台旧 jar,
|
||||||
|
-- /api 经主机 B 的 clb 打到两台,旧 jar 的 AdminUserService.create 不给 company_id 赋值,
|
||||||
|
-- 列若无 DEFAULT,严格模式报 "Field 'company_id' doesn't have a default value",
|
||||||
|
-- 打到旧节点的建号请求全失败。两台同版后新代码永远显式写 company_id,DEFAULT 变成死重,
|
||||||
|
-- 但必须在第二家公司开通前摘除——否则之后每个不传公司的建号都被静默塞进厦门米椿花。
|
||||||
|
-- 摘除时机由启动期巡检盯(见设计文档 §6.3),不在本迁移里处理。
|
||||||
|
ALTER TABLE `users`
|
||||||
|
MODIFY COLUMN `company_id` bigint NOT NULL DEFAULT 1 COMMENT '所属公司(company.id)';
|
||||||
|
|
||||||
|
-- ---------- 4. 后台「公司管理」菜单 ----------
|
||||||
|
-- 挂在「账号与权限」分组(admin_group_account,V103 建)下,与
|
||||||
|
-- admin_users→account/users、admin_group_manage→account/groups 同一命名口径(V109)。
|
||||||
|
-- route_path 必须与 admin-frontend-vue/src/router/routes.ts 的 path 逐字一致,否则菜单点进去 404。
|
||||||
|
-- sort_order 按同级最大值 +5 自算:现有子菜单的 sort_order 来自初始数据,从未被任何迁移设定过,
|
||||||
|
-- 写字面量等于猜。幂等写法照 V103/V106(columns.column_key 上有 uk_column_key,重复插会直接报错)。
|
||||||
|
|
||||||
|
INSERT INTO `columns` (`name`, `column_key`, `menu_type`, `route_path`, `sort_order`, `parent_id`)
|
||||||
|
SELECT '公司管理', 'admin_companies', 'admin', 'account/companies',
|
||||||
|
(SELECT COALESCE(MAX(sib.sort_order), 0) + 5
|
||||||
|
FROM `columns` sib
|
||||||
|
WHERE sib.parent_id = parent.id),
|
||||||
|
parent.id
|
||||||
|
FROM `columns` parent
|
||||||
|
WHERE parent.`column_key` = 'admin_group_account'
|
||||||
|
AND NOT EXISTS (SELECT 1 FROM `columns` x WHERE x.`column_key` = 'admin_companies');
|
||||||
|
|
||||||
|
-- =============================================================
|
||||||
|
-- 验证 SQL(迁移后在库上执行)
|
||||||
|
-- SELECT COUNT(*) AS company_rows FROM `company`;
|
||||||
|
-- -> 期望 1
|
||||||
|
-- SELECT `id`, `company_name`, `status` FROM `company`;
|
||||||
|
-- -> 期望 1 | 厦门米椿花 | 1(id 必须是 1,DEFAULT 1 与回填都指着它)
|
||||||
|
-- SELECT COUNT(*) AS users_total,
|
||||||
|
-- SUM(company_id IS NULL) AS null_company,
|
||||||
|
-- SUM(company_id = 1) AS in_xiamen_michunghua
|
||||||
|
-- FROM `users`;
|
||||||
|
-- -> 期望 null_company = 0 且 users_total = in_xiamen_michunghua
|
||||||
|
-- SHOW COLUMNS FROM `users` LIKE 'company_id';
|
||||||
|
-- -> 期望 Null = NO,Default = 1(Default 一旦不该再是 1,说明公司已 >1 家而临时 DEFAULT 未摘)
|
||||||
|
-- SHOW INDEX FROM `users` WHERE Key_name = 'idx_users_company_id';
|
||||||
|
-- -> 期望 1 行
|
||||||
|
-- SELECT c.`id`, c.`name`, c.`column_key`, c.`route_path`, c.`sort_order`, p.`column_key` AS parent_key
|
||||||
|
-- FROM `columns` c LEFT JOIN `columns` p ON p.`id` = c.`parent_id`
|
||||||
|
-- WHERE c.`column_key` = 'admin_companies';
|
||||||
|
-- -> 期望 1 行,parent_key = admin_group_account,route_path = account/companies
|
||||||
|
-- =============================================================
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
package com.nanri.aiimage.config;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Matcher;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期 V143 迁移契约(设计文档 docs/ops/company-multi-tenant-design-2026-10-04.md §3/§6)。
|
||||||
|
*
|
||||||
|
* 本环境无 H2 / testcontainers(见 pom.xml),迁移不能真跑,因此按仓库既有口径做文件审计
|
||||||
|
* (对照 MigrationInventoryTest / IndexMigrationV101Test)。与它们不同的是:断言一律打在
|
||||||
|
* **剥掉注释后的可执行 SQL** 上,避免"注释里写了这句话就算通过";解析用的正则不匹配即红。
|
||||||
|
*/
|
||||||
|
class CompanyMigrationV143Test {
|
||||||
|
|
||||||
|
private static final Path ROOT = Path.of(System.getProperty("user.dir"));
|
||||||
|
private static final Path DB_DIR = ROOT.resolve("src/main/resources/db");
|
||||||
|
private static final Pattern VERSION_FILE = Pattern.compile("^V(\\d+)(?:_(\\d+))?__.*\\.sql$");
|
||||||
|
private static final String ROLLBACK_RELATIVE = "docs/rollback-V143-company.sql";
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- 取文件
|
||||||
|
|
||||||
|
private static List<Path> versionFiles() throws IOException {
|
||||||
|
try (Stream<Path> s = Files.list(DB_DIR)) {
|
||||||
|
return s.filter(p -> VERSION_FILE.matcher(p.getFileName().toString()).matches())
|
||||||
|
.sorted()
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int versionOf(Path p) {
|
||||||
|
Matcher m = VERSION_FILE.matcher(p.getFileName().toString());
|
||||||
|
return m.matches() ? Integer.parseInt(m.group(1)) : -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int maxVersionOnDisk() throws IOException {
|
||||||
|
return versionFiles().stream().mapToInt(CompanyMigrationV143Test::versionOf).max().orElse(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Path migration() throws IOException {
|
||||||
|
List<Path> hits = versionFiles().stream()
|
||||||
|
.filter(p -> p.getFileName().toString().startsWith("V143__"))
|
||||||
|
.toList();
|
||||||
|
assertFalse(hits.isEmpty(), "缺少 V143__*.sql:多公司迁移还没落盘");
|
||||||
|
assertEquals(1, hits.size(), "V143 只允许一个迁移文件(撞号会让 Flyway 启动失败)");
|
||||||
|
return hits.get(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String rawMigration() throws IOException {
|
||||||
|
return Files.readString(migration(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String statements() throws IOException {
|
||||||
|
return normalize(stripComments(rawMigration()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ SQL 预处理
|
||||||
|
|
||||||
|
/** 去掉 -- 行注释与块注释,保留单引号字符串字面量(避免把字面量里的 -- 当注释吃掉)。 */
|
||||||
|
private static String stripComments(String sql) {
|
||||||
|
StringBuilder out = new StringBuilder(sql.length());
|
||||||
|
int i = 0;
|
||||||
|
while (i < sql.length()) {
|
||||||
|
char c = sql.charAt(i);
|
||||||
|
if (c == '\'') {
|
||||||
|
int end = i + 1;
|
||||||
|
while (end < sql.length()) {
|
||||||
|
if (sql.charAt(end) == '\'') {
|
||||||
|
if (end + 1 < sql.length() && sql.charAt(end + 1) == '\'') {
|
||||||
|
end += 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
end++;
|
||||||
|
}
|
||||||
|
out.append(sql, i, Math.min(end + 1, sql.length()));
|
||||||
|
i = end + 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '-' && i + 1 < sql.length() && sql.charAt(i + 1) == '-') {
|
||||||
|
while (i < sql.length() && sql.charAt(i) != '\n') {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '/' && i + 1 < sql.length() && sql.charAt(i + 1) == '*') {
|
||||||
|
int end = sql.indexOf("*/", i + 2);
|
||||||
|
i = end < 0 ? sql.length() : end + 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
out.append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalize(String sql) {
|
||||||
|
return sql.replaceAll("\\s+", " ").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按顶层逗号切分(跳过括号内与字符串内的逗号)。 */
|
||||||
|
private static List<String> splitTopLevel(String s) {
|
||||||
|
List<String> parts = new ArrayList<>();
|
||||||
|
StringBuilder cur = new StringBuilder();
|
||||||
|
int depth = 0;
|
||||||
|
boolean inQuote = false;
|
||||||
|
for (int i = 0; i < s.length(); i++) {
|
||||||
|
char c = s.charAt(i);
|
||||||
|
if (inQuote) {
|
||||||
|
cur.append(c);
|
||||||
|
if (c == '\'') {
|
||||||
|
if (i + 1 < s.length() && s.charAt(i + 1) == '\'') {
|
||||||
|
cur.append(s.charAt(++i));
|
||||||
|
} else {
|
||||||
|
inQuote = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '\'') {
|
||||||
|
inQuote = true;
|
||||||
|
cur.append(c);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (c == '(') {
|
||||||
|
depth++;
|
||||||
|
} else if (c == ')') {
|
||||||
|
depth--;
|
||||||
|
} else if (c == ',' && depth == 0) {
|
||||||
|
parts.add(cur.toString().trim());
|
||||||
|
cur.setLength(0);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cur.append(c);
|
||||||
|
}
|
||||||
|
if (!cur.toString().trim().isEmpty()) {
|
||||||
|
parts.add(cur.toString().trim());
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void assertMatches(String sql, String regex, String message) {
|
||||||
|
assertTrue(Pattern.compile(regex).matcher(sql).find(), message + "(未匹配到 " + regex + ")");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------ 用例
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:版本号取错。V132/V133 是永久退役洞,取到它们或取到已被占用的号,
|
||||||
|
* Flyway 启动期直接 "resolved migration not applied" / 撞号失败。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void migrationIsVersionedOneFourThree() throws IOException {
|
||||||
|
Path file = migration();
|
||||||
|
assertEquals(143, versionOf(file), "多公司迁移必须是 V143(V142 之后的下一号)");
|
||||||
|
assertTrue(file.getFileName().toString().matches("^V143__[A-Za-z0-9_.-]+$"),
|
||||||
|
"命名应 V143__<snake 描述>.sql: " + file.getFileName());
|
||||||
|
assertEquals(maxVersionOnDisk(), 143,
|
||||||
|
"V143 必须是当前最大版本;若磁盘上已有更大的号,说明本迁移被插到了历史中间");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 破坏点:头注释缺项 → 上线评审拿不到锁表风险与回滚口径。 */
|
||||||
|
@Test
|
||||||
|
void headerCarriesSixMandatoryTemplateFields() throws IOException {
|
||||||
|
String raw = rawMigration();
|
||||||
|
assertTrue(raw.contains("V143"), "头注释应标明迁移版本 V143");
|
||||||
|
for (int i = 1; i <= 6; i++) {
|
||||||
|
assertTrue(raw.contains(i + ". "), "头注释应含模板第 " + i + " 项必填");
|
||||||
|
}
|
||||||
|
for (String field : List.of("变更目的", "影响表与数据量", "锁表风险", "验证 SQL", "回滚步骤", "上线窗口")) {
|
||||||
|
assertTrue(raw.contains(field), "头注释应含必填项:" + field);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:company_name 不唯一。公司名是二期登录定位({@code UNIQUE(company_id, username)})
|
||||||
|
* 与后台公司下拉的唯一人类可读标识,重名会让"选公司"这一步不可判定。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void createsCompanyTableWithUniqueCompanyName() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
assertMatches(sql, "CREATE TABLE (IF NOT EXISTS )?`company`\\s*\\(", "应新建 company 主表");
|
||||||
|
assertMatches(sql, "`company_name`\\s+varchar\\(\\d+\\)[^,]*NOT NULL", "company_name 应为非空 varchar");
|
||||||
|
assertMatches(sql, "UNIQUE INDEX `uk_company_name`\\s*\\(\\s*`company_name`",
|
||||||
|
"company_name 上应有唯一索引 uk_company_name");
|
||||||
|
assertMatches(sql, "PRIMARY KEY \\(`id`\\)", "company 应有主键 id");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:初始公司 id 不是字面量 1。users.company_id 的 DEFAULT 只能是字面量
|
||||||
|
* (MySQL 不允许 DEFAULT 子查询),回填也写死 = 1;id 一旦不是 1,
|
||||||
|
* 混合版本窗口里旧 jar 建的号与全部存量账号都会指向一个不存在的公司。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void seedsInitialCompanyPinnedToIdOne() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
Matcher m = Pattern.compile("INSERT(?: IGNORE)? INTO `company`\\s*\\(([^)]*)\\)\\s*VALUES\\s*\\((.*?)\\)\\s*;")
|
||||||
|
.matcher(sql);
|
||||||
|
assertTrue(m.find(), "应有一条显式插入初始公司的 INSERT(未匹配到 INSERT INTO `company` (...) VALUES (...);)");
|
||||||
|
|
||||||
|
List<String> columns = splitTopLevel(m.group(1)).stream()
|
||||||
|
.map(c -> c.replace("`", "").trim())
|
||||||
|
.toList();
|
||||||
|
List<String> values = splitTopLevel(m.group(2));
|
||||||
|
assertEquals(columns.size(), values.size(),
|
||||||
|
"INSERT 的列数与值数应一致,否则解析口径变了、本用例的断言已失效");
|
||||||
|
|
||||||
|
int idIdx = columns.indexOf("id");
|
||||||
|
assertTrue(idIdx >= 0, "初始公司必须显式指定 id 列,不能交给 AUTO_INCREMENT");
|
||||||
|
assertEquals("1", values.get(idIdx), "初始公司 id 必须钉死为 1(users.company_id DEFAULT 1 依赖它)");
|
||||||
|
|
||||||
|
int nameIdx = columns.indexOf("company_name");
|
||||||
|
assertTrue(nameIdx >= 0, "初始公司必须写入 company_name");
|
||||||
|
assertEquals("'厦门米椿花'", values.get(nameIdx), "存量数据归属的初始公司名");
|
||||||
|
|
||||||
|
int statusIdx = columns.indexOf("status");
|
||||||
|
assertTrue(statusIdx >= 0, "初始公司必须写入 status");
|
||||||
|
assertEquals("1", values.get(statusIdx), "初始公司应为启用状态");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:users 没挂 company_id 或没建索引。公司维度全靠 user_id → users.company_id 派生,
|
||||||
|
* 缺列则整个方案不成立;缺索引则二期每次 scope 展开都要全表扫 users。
|
||||||
|
* 另一半破坏点是"顺手给业务表也加了 company_id"——那与定案(数据按账号归属、公司维度跟着账号走)
|
||||||
|
* 相反,且会把一期从"业务表零 DDL"变成 57 张表的回填工程。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void addsUsersCompanyIdColumnAndIndex() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
assertMatches(sql, "ALTER TABLE `users`\\s+ADD COLUMN `company_id`\\s+bigint",
|
||||||
|
"users 应新增 bigint 列 company_id");
|
||||||
|
assertMatches(sql, "ADD INDEX `idx_users_company_id`\\s*\\(\\s*`company_id`",
|
||||||
|
"company_id 上应建索引 idx_users_company_id");
|
||||||
|
|
||||||
|
List<String> altered = new ArrayList<>();
|
||||||
|
Matcher alter = Pattern.compile("ALTER TABLE `([A-Za-z0-9_]+)`").matcher(sql);
|
||||||
|
while (alter.find()) {
|
||||||
|
altered.add(alter.group(1));
|
||||||
|
}
|
||||||
|
assertFalse(altered.isEmpty(), "应有 ALTER TABLE 语句(否则本用例的前两条断言是被注释喂绿的)");
|
||||||
|
assertEquals(List.of("users"), altered.stream().distinct().toList(),
|
||||||
|
"一期业务表零 DDL:只允许改 users,实际改到了 " + altered);
|
||||||
|
|
||||||
|
List<String> created = new ArrayList<>();
|
||||||
|
Matcher create = Pattern.compile("CREATE TABLE (?:IF NOT EXISTS )?`([A-Za-z0-9_]+)`").matcher(sql);
|
||||||
|
while (create.find()) {
|
||||||
|
created.add(create.group(1));
|
||||||
|
}
|
||||||
|
assertEquals(List.of("company"), created, "只应新建 company 一张表,实际 " + created);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:回填缺失或顺序颠倒。
|
||||||
|
* 顺序颠倒(先 MODIFY NOT NULL 再 UPDATE)在严格模式下直接 ER_INVALID_USE_OF_NULL 让迁移失败;
|
||||||
|
* 回填缺失而 NOT NULL 闸门也缺失,则存量账号 company_id 静默为 NULL——公司维度对老数据整体失明。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void backfillsExistingAccountsBeforeNotNullGate() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
Pattern backfill = Pattern.compile(
|
||||||
|
"UPDATE `users`\\s+SET\\s+`company_id`\\s*=\\s*1\\s+WHERE\\s+`company_id`\\s+IS\\s+NULL");
|
||||||
|
Pattern gate = Pattern.compile(
|
||||||
|
"ALTER TABLE `users`\\s+MODIFY COLUMN `company_id`\\s+bigint\\s+NOT NULL\\s+DEFAULT 1");
|
||||||
|
|
||||||
|
Matcher b = backfill.matcher(sql);
|
||||||
|
Matcher g = gate.matcher(sql);
|
||||||
|
assertTrue(b.find(), "应把存量账号回填到公司 1(厦门米椿花)");
|
||||||
|
assertTrue(g.find(), "应有 MODIFY ... NOT NULL 自检闸门:回填漏行时让迁移失败,而不是留一堆 NULL 静默通过");
|
||||||
|
assertTrue(b.start() < g.start(), "回填必须在 NOT NULL 闸门之前,否则闸门会先撞上存量 NULL");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:DEFAULT 1 被提前摘掉。滚动发布期间一台新 jar、一台旧 jar,/api 经 clb 打到两台;
|
||||||
|
* 旧 jar 的 AdminUserService.create 不给 company_id 赋值,列若无 DEFAULT,
|
||||||
|
* 严格模式报 "Field 'company_id' doesn't have a default value",打到旧节点的建号请求全失败(约一半)。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void notNullGateKeepsTemporaryDefaultOne() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
assertMatches(sql, "MODIFY COLUMN `company_id`\\s+bigint\\s+NOT NULL\\s+DEFAULT 1",
|
||||||
|
"company_id 应落为 NOT NULL DEFAULT 1(DEFAULT 只为混合版本窗口存在,摘除时机由启动期巡检盯)");
|
||||||
|
assertTrue(rawMigration().contains("混合版本"),
|
||||||
|
"头注释应写清 DEFAULT 的存在理由与摘除时机,否则后人会当它是永久默认值");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:菜单行插重、挂错父级、route_path 与前端路由不一致。
|
||||||
|
* route_path 必须与 admin-frontend-vue/src/router/routes.ts 的 path 逐字一致,否则菜单点进去 404;
|
||||||
|
* 非幂等写法在重跑或补数时会插出两行"公司管理"。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void insertsAdminCompaniesMenuIdempotently() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
Matcher m = Pattern.compile("INSERT INTO `columns`\\s*\\(([^)]*)\\)(.*?);").matcher(sql);
|
||||||
|
assertTrue(m.find(), "应插入后台「公司管理」菜单(未匹配到 INSERT INTO `columns`)");
|
||||||
|
|
||||||
|
List<String> columns = splitTopLevel(m.group(1)).stream()
|
||||||
|
.map(c -> c.replace("`", "").trim())
|
||||||
|
.toList();
|
||||||
|
for (String required : List.of("name", "column_key", "menu_type", "route_path", "parent_id")) {
|
||||||
|
assertTrue(columns.contains(required), "菜单插入应显式给出列 " + required);
|
||||||
|
}
|
||||||
|
assertTrue(columns.contains("sort_order"), "菜单插入应给出 sort_order,否则同级顺序不确定");
|
||||||
|
|
||||||
|
String body = m.group(2);
|
||||||
|
assertTrue(body.contains("'admin_companies'"), "column_key 必须是 admin_companies(前端 menuKey 与权限判定都用它)");
|
||||||
|
assertTrue(body.contains("'account/companies'"), "route_path 必须是 account/companies(与前端路由逐字一致)");
|
||||||
|
assertTrue(body.contains("'admin_group_account'"), "父级应取「账号与权限」分组 admin_group_account");
|
||||||
|
assertMatches(body, "NOT EXISTS\\s*\\(", "菜单插入必须幂等:按 column_key 判存在");
|
||||||
|
assertTrue(body.contains("SELECT"), "菜单插入应为 INSERT ... SELECT ... WHERE NOT EXISTS,裸 VALUES 重跑必重行");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:迁移不可重跑。MySQL 的 DDL 不进事务 —— V143 若在 NOT NULL 闸门处失败,
|
||||||
|
* 前面的 CREATE TABLE / INSERT / ADD COLUMN 已经落库。按 §8.1 的恢复步骤
|
||||||
|
* (补齐漏行 → flyway repair → 重启)Flyway 会**从第一条语句重跑整个文件**,
|
||||||
|
* 届时非幂等语句依次报 1050 table exists / 1060 duplicate column / 1062 duplicate entry,
|
||||||
|
* 把"补数据后重启"变成"必须手工清库"。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void migrationIsRerunnableAfterPartialFailure() throws IOException {
|
||||||
|
String sql = statements();
|
||||||
|
assertMatches(sql, "CREATE TABLE IF NOT EXISTS `company`",
|
||||||
|
"建表必须带 IF NOT EXISTS:重跑时表已在库里");
|
||||||
|
assertMatches(sql, "INSERT IGNORE INTO `company`",
|
||||||
|
"初始公司必须 INSERT IGNORE(id 钉死 + 公司名唯一,重复即本次重跑)");
|
||||||
|
assertMatches(sql, "information_schema\\.COLUMNS",
|
||||||
|
"ADD COLUMN 必须先查 information_schema 判存在(对齐 V142 的条件 DDL 写法)");
|
||||||
|
assertMatches(sql, "TABLE_NAME\\s*=\\s*'users'", "存在性检查要按 TABLE_NAME='users' 筛");
|
||||||
|
assertMatches(sql, "COLUMN_NAME\\s*=\\s*'company_id'", "存在性检查要按 COLUMN_NAME='company_id' 筛");
|
||||||
|
assertMatches(sql, "SET\\s+@sql\\s*:=\\s*IF\\s*\\(\\s*@col_exists\\s*=\\s*0",
|
||||||
|
"条件 DDL 必须真的用存在性标志分支:查了 information_schema 却无条件执行 ALTER,重跑照样报 1060");
|
||||||
|
assertMatches(sql, "PREPARE\\s+stmt\\s+FROM", "条件 DDL 要用 PREPARE/EXECUTE 执行");
|
||||||
|
assertMatches(sql, "DEALLOCATE\\s+PREPARE\\s+stmt", "游标语句用完必须 DEALLOCATE,否则同名 stmt 二次 PREPARE 报错");
|
||||||
|
assertMatches(sql, "INSERT INTO `columns`[\\s\\S]*NOT EXISTS\\s*\\(\\s*SELECT",
|
||||||
|
"菜单行必须按 column_key 判存在后再插");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:文件内没留验证 SQL。上线的人只能凭"启动没报错"判断迁移成功,
|
||||||
|
* 而本迁移最需要核实的三件事(回填有没有漏行、NOT NULL 与 DEFAULT 有没有真落上、
|
||||||
|
* 菜单挂对父级没有)都不体现在启动日志里。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void migrationShipsPostDeployVerificationSql() throws IOException {
|
||||||
|
String raw = rawMigration();
|
||||||
|
assertTrue(raw.contains("验证 SQL"), "头注释应含「验证 SQL」段(模板第 4 项)");
|
||||||
|
assertTrue(raw.contains("company_id IS NULL"),
|
||||||
|
"验证 SQL 应能查出回填漏行的计数,这是 NOT NULL 闸门之外唯一的复核手段");
|
||||||
|
assertTrue(raw.contains("SHOW COLUMNS FROM `users` LIKE 'company_id'")
|
||||||
|
|| raw.contains("SHOW COLUMNS FROM users LIKE 'company_id'"),
|
||||||
|
"验证 SQL 应核对 company_id 的 Null / Default,DEFAULT 1 被摘没摘一眼可见");
|
||||||
|
assertTrue(raw.contains("admin_companies"), "验证 SQL 应核对「公司管理」菜单行");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:回滚被写成 Flyway 版本化迁移(例如 V144__rollback_company.sql)放进 src/main/resources/db。
|
||||||
|
* 那样它会在下次启动时被 Flyway 自动执行,静默把 V143 撤销掉,同时打乱版本连续性审计。
|
||||||
|
* 回滚必须是扫描路径之外、由人按顺序执行的补丁脚本。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void rollbackLivesOutsideFlywayScanPath() throws IOException {
|
||||||
|
Path rollback = ROOT.resolve(ROLLBACK_RELATIVE);
|
||||||
|
assertTrue(Files.isRegularFile(rollback),
|
||||||
|
"回滚脚本应存在于 " + ROLLBACK_RELATIVE + "(Flyway 扫描路径之外),否则事故时无从回退");
|
||||||
|
|
||||||
|
String rb = normalize(stripComments(Files.readString(rollback, StandardCharsets.UTF_8)));
|
||||||
|
assertMatches(rb, "ALTER TABLE `users`\\s+DROP INDEX `idx_users_company_id`", "回滚应删掉索引");
|
||||||
|
assertMatches(rb, "DROP COLUMN `company_id`", "回滚应删掉 users.company_id");
|
||||||
|
assertMatches(rb, "DROP TABLE (IF EXISTS )?`company`", "回滚应删掉 company 表");
|
||||||
|
assertTrue(rb.contains("flyway_schema_history") && rb.contains("143"),
|
||||||
|
"回滚必须清掉 flyway_schema_history 里 V143 的记录,否则重装 jar 时 Flyway 认为已应用而跳过");
|
||||||
|
assertTrue(rb.contains("admin_companies"), "回滚应删掉后台「公司管理」菜单行");
|
||||||
|
|
||||||
|
assertTrue(rawMigration().contains(ROLLBACK_RELATIVE),
|
||||||
|
"V143 头注释的「回滚步骤」必须点名该脚本,否则值班的人找不到它");
|
||||||
|
assertFalse(rawMigration().contains("db/V144"),
|
||||||
|
"回滚不得写成版本化迁移 V144:Flyway 会在下次启动时自动执行它,静默撤销 V143");
|
||||||
|
|
||||||
|
for (Path f : versionFiles()) {
|
||||||
|
String name = f.getFileName().toString().toLowerCase();
|
||||||
|
assertFalse(name.contains("rollback"), "Flyway 扫描路径内不得出现回滚迁移: " + f.getFileName());
|
||||||
|
String ex = normalize(stripComments(Files.readString(f, StandardCharsets.UTF_8)));
|
||||||
|
assertFalse(ex.contains("DROP COLUMN `company_id`"),
|
||||||
|
"扫描路径内的迁移不得撤销 company_id: " + f.getFileName());
|
||||||
|
assertFalse(Pattern.compile("DROP TABLE (IF EXISTS )?`company`").matcher(ex).find(),
|
||||||
|
"扫描路径内的迁移不得删掉 company 表: " + f.getFileName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 破坏点:docs/migration-inventory.md 的数字没跟着改。
|
||||||
|
* 下一个人按文档里的"取号起点"取号就会撞号(Flyway 启动失败),或以为 V143 还没被占用。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void inventoryDocTracksTheNewMigration() throws IOException {
|
||||||
|
Path doc = ROOT.resolve("docs/migration-inventory.md");
|
||||||
|
assertTrue(Files.isRegularFile(doc), "盘点文档应存在");
|
||||||
|
String text = Files.readString(doc, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
List<Path> files = versionFiles();
|
||||||
|
int maxOnDisk = files.stream().mapToInt(CompanyMigrationV143Test::versionOf).max().orElse(0);
|
||||||
|
|
||||||
|
assertTrue(text.contains(migration().getFileName().toString()),
|
||||||
|
"盘点文档应记录最新迁移文件名 " + migration().getFileName());
|
||||||
|
|
||||||
|
Matcher count = Pattern.compile("版本化迁移文件数:\\*\\*(\\d+)\\*\\*").matcher(text);
|
||||||
|
assertTrue(count.find(), "盘点文档应给出版本化迁移文件数");
|
||||||
|
assertEquals(files.size(), Integer.parseInt(count.group(1)),
|
||||||
|
"文档记录的迁移文件数与磁盘不符");
|
||||||
|
|
||||||
|
Matcher range = Pattern.compile("整数版本范围:\\*\\*V1\\.\\.V(\\d+)\\*\\*").matcher(text);
|
||||||
|
assertTrue(range.find(), "盘点文档应给出整数版本范围");
|
||||||
|
assertEquals(maxOnDisk, Integer.parseInt(range.group(1)),
|
||||||
|
"文档记录的整数版本上界与磁盘不符");
|
||||||
|
|
||||||
|
Matcher next = Pattern.compile("从 \\*\\*V(\\d+)\\*\\* 起取号").matcher(text);
|
||||||
|
assertTrue(next.find(), "盘点文档应给出取号起点");
|
||||||
|
assertEquals(maxOnDisk + 1, Integer.parseInt(next.group(1)),
|
||||||
|
"取号起点必须 = 磁盘最大版本 + 1,否则会撞号或留洞");
|
||||||
|
}
|
||||||
|
}
|
||||||
+70
@@ -0,0 +1,70 @@
|
|||||||
|
package com.nanri.aiimage.modules.admin;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.nanri.aiimage.modules.admin.controller.AdminUserController;
|
||||||
|
import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Objects;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 账号列表的公司列是**跨仓契约**(设计文档 §2.3):Java 侧 `AdminUserItemVo` 出 snake_case,
|
||||||
|
* Vue 侧 `toAdminUserItem` 只认 `company_id`/`company_name`(见 admin-frontend-vue
|
||||||
|
* `tests/company-user-list.test.ts` 的反向排他用例)。这里改一个字母,前端不会报错——
|
||||||
|
* 只会把每一行都显示成 '-'。所以两头都得有闸。
|
||||||
|
*/
|
||||||
|
class AdminUserListCompanyContractTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void itemVoSerializesCompanyColumnsInSnakeCase() {
|
||||||
|
AdminUserItemVo vo = new AdminUserItemVo();
|
||||||
|
vo.setId(11L);
|
||||||
|
vo.setUsername("u11");
|
||||||
|
vo.setRole("normal");
|
||||||
|
vo.setCompanyId(5L);
|
||||||
|
vo.setCompanyName("厦门米椿花");
|
||||||
|
|
||||||
|
Map<String, Object> json = new ObjectMapper()
|
||||||
|
.convertValue(vo, new TypeReference<Map<String, Object>>() { });
|
||||||
|
|
||||||
|
assertThat(json).containsEntry("company_id", 5L);
|
||||||
|
assertThat(json).containsEntry("company_name", "厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void listEndpointTakesCompanyIdAsAnOptionalQueryParamWithoutDefault() throws Exception {
|
||||||
|
Method list = Arrays.stream(AdminUserController.class.getDeclaredMethods())
|
||||||
|
.filter(m -> "listUsers".equals(m.getName()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new AssertionError("AdminUserController 上没有 listUsers 方法"));
|
||||||
|
|
||||||
|
Set<RequestParam> params = Arrays.stream(list.getParameters())
|
||||||
|
.map(p -> AnnotatedElementUtils.findMergedAnnotation(p, RequestParam.class))
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.collect(Collectors.toSet());
|
||||||
|
|
||||||
|
RequestParam companyId = params.stream()
|
||||||
|
.filter(p -> "company_id".equals(p.name()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new AssertionError("GET /api/admin/users 没有 company_id 查询参数"));
|
||||||
|
// required=false 是 §5.3「前端与后端可各自先发」的前提:旧后台不带这个键也要照常返回全部
|
||||||
|
assertThat(companyId.required()).isFalse();
|
||||||
|
// 缺省必须真的"没有缺省":写 defaultValue="1" 就变成"默认只查厦门米椿花",筛选框清不掉。
|
||||||
|
// 拿同为可选无缺省的 role 做参照,比引用 Spring 的内部哨兵常量稳。
|
||||||
|
RequestParam role = params.stream()
|
||||||
|
.filter(p -> "role".equals(p.name()))
|
||||||
|
.findFirst()
|
||||||
|
.orElseThrow(() -> new AssertionError("参照参数 role 不在了,这条对照失效"));
|
||||||
|
assertThat(companyId.defaultValue()).isEqualTo(role.defaultValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
package com.nanri.aiimage.modules.admin.controller;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.api.ApiResponse;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 后台顶栏的公司身份(设计文档 §2.4 / §1.4):admin-frontend-vue 的
|
||||||
|
* {@code api/session.ts} 把 {@code /api/admin/current-user} 的 item 原样当 AdminUser 用,
|
||||||
|
* 没有字段映射层——所以这两个键名必须逐字对上 {@code types/admin.ts} 的
|
||||||
|
* {@code companyId} / {@code companyName}。
|
||||||
|
*
|
||||||
|
* <p>这里拼错一个字母不会报错,只会让顶栏那行公司名永远不显示(前端 {@code || ''} 兜底),
|
||||||
|
* 所以只能由用例盯着键名,而不是盯着"有没有抛异常"。</p>
|
||||||
|
*/
|
||||||
|
class AdminConsoleCurrentUserCompanyTest {
|
||||||
|
|
||||||
|
private AdminAuthSupport adminAuthSupport;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private AdminConsoleController controller;
|
||||||
|
private HttpServletRequest request;
|
||||||
|
private AdminUserEntity operator;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
adminAuthSupport = mock(AdminAuthSupport.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
controller = new AdminConsoleController(adminAuthSupport, mock(PermissionMenuService.class),
|
||||||
|
companyService);
|
||||||
|
request = mock(HttpServletRequest.class);
|
||||||
|
operator = new AdminUserEntity();
|
||||||
|
operator.setId(10L);
|
||||||
|
operator.setUsername("op");
|
||||||
|
operator.setRole("admin");
|
||||||
|
|
||||||
|
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
|
||||||
|
when(adminAuthSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> item() {
|
||||||
|
ApiResponse<Map<String, Object>> response = controller.currentUser(request);
|
||||||
|
return (Map<String, Object>) response.getData().get("item");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("current-user 带 camelCase 的 companyId / companyName")
|
||||||
|
void currentUserCarriesCompanyIdentityInCamelCase() {
|
||||||
|
operator.setCompanyId(5L);
|
||||||
|
when(companyService.nameOrEmpty(5L)).thenReturn("厦门米椿花");
|
||||||
|
|
||||||
|
assertThat(item())
|
||||||
|
.containsEntry("companyId", 5L)
|
||||||
|
.containsEntry("companyName", "厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("原有的 id / username / role 一个都不能少")
|
||||||
|
void keepsTheExistingSelfDescriptionKeys() {
|
||||||
|
operator.setCompanyId(5L);
|
||||||
|
when(companyService.nameOrEmpty(5L)).thenReturn("厦门米椿花");
|
||||||
|
|
||||||
|
assertThat(item())
|
||||||
|
.containsEntry("id", 10L)
|
||||||
|
.containsEntry("username", "op")
|
||||||
|
.containsEntry("role", "admin");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("没有公司归属的账号:两个键照样写,值为 null / 空串")
|
||||||
|
void accountWithoutACompanyStillWritesBothKeys() {
|
||||||
|
operator.setCompanyId(null);
|
||||||
|
when(companyService.nameOrEmpty(null)).thenReturn("");
|
||||||
|
|
||||||
|
assertThat(item())
|
||||||
|
.containsKeys("companyId", "companyName")
|
||||||
|
.containsEntry("companyId", null)
|
||||||
|
.containsEntry("companyName", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司行查不到时不挡接口:顶栏少一行字,账号还能用后台")
|
||||||
|
void missingCompanyRowDoesNotBreakCurrentUser() {
|
||||||
|
operator.setCompanyId(9L);
|
||||||
|
when(companyService.nameOrEmpty(9L)).thenReturn("");
|
||||||
|
|
||||||
|
assertThat(item())
|
||||||
|
.containsEntry("companyName", "")
|
||||||
|
.containsEntry("username", "op");
|
||||||
|
}
|
||||||
|
}
|
||||||
+195
@@ -0,0 +1,195 @@
|
|||||||
|
package com.nanri.aiimage.modules.admin.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.admin.model.vo.AdminUserItemVo;
|
||||||
|
import com.nanri.aiimage.modules.admin.model.vo.AdminUserListVo;
|
||||||
|
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||||
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期(设计文档 §2.3):账号列表的公司列与「按公司筛选」。
|
||||||
|
*
|
||||||
|
* <p>筛选参数的口径是"超管可筛任意公司;公司内 admin 传别家公司 = 无结果"。后者故意不报错也不越权,
|
||||||
|
* 所以断言必须打在"有没有碰表"上——只断言返回空集合的话,把条件写反(拿别家公司的 id 去查)也是空。</p>
|
||||||
|
*/
|
||||||
|
class AdminUserListCompanyTest {
|
||||||
|
|
||||||
|
private AdminUserMapper userMapper;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private AdminAuthSupport authSupport;
|
||||||
|
private AdminUserService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void setUp() {
|
||||||
|
TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
|
||||||
|
userMapper = mock(AdminUserMapper.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
authSupport = mock(AdminAuthSupport.class);
|
||||||
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
|
service = new AdminUserService(userMapper, mock(WerkzeugPasswordEncoder.class), authSupport,
|
||||||
|
permissionService, mock(UserSecretCleanupPort.class), companyService);
|
||||||
|
// 菜单可见性与本组用例无关,全部放开:否则"被 403 挡住"会伪装成"筛选没生效"
|
||||||
|
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
|
||||||
|
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(0L);
|
||||||
|
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void superAdminCompanyFilterBecomesAQueryCondition() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
|
||||||
|
service.listUsers(operator, 1, 10, null, null, null, 7L);
|
||||||
|
|
||||||
|
LambdaQueryWrapper<AdminUserEntity> query = capturedCountQuery();
|
||||||
|
assertThat(query.getSqlSegment()).isNotEmpty();
|
||||||
|
assertThat(query.getParamNameValuePairs()).containsValue(7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void superAdminWithoutCompanyFilterAddsNoCondition() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
|
||||||
|
service.listUsers(operator, 1, 10, null, null, null, null);
|
||||||
|
|
||||||
|
// 与上一条对照才有意义:不带筛选时查询条件必须一个都没有(不传 != 传 0/传自己公司)
|
||||||
|
assertThat(capturedCountQuery().getParamNameValuePairs()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void adminAskingAnotherCompanyGetsEmptyPageWithoutTouchingTheTable() {
|
||||||
|
AdminUserEntity operator = operator(10L, "admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(99L);
|
||||||
|
|
||||||
|
AdminUserListVo vo = service.listUsers(operator, 1, 10, null, null, null, 99L);
|
||||||
|
|
||||||
|
assertThat(vo.getTotal()).isZero();
|
||||||
|
assertThat(vo.getItems()).isEmpty();
|
||||||
|
verify(userMapper, never()).selectCount(any(LambdaQueryWrapper.class));
|
||||||
|
verify(userMapper, never()).selectList(any(LambdaQueryWrapper.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void adminFilteringItsOwnCompanyBehavesLikeNoFilter() {
|
||||||
|
AdminUserEntity operator = operator(10L, "admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(2L);
|
||||||
|
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(
|
||||||
|
List.of(row(11L, 5L), row(12L, 5L)), List.of(), List.of());
|
||||||
|
|
||||||
|
AdminUserListVo vo = service.listUsers(operator, 1, 10, null, null, null, 5L);
|
||||||
|
|
||||||
|
// 真风险是"自己公司也被判成跨公司"⇒ 整个 admin 的列表恒空。这里必须还是他看得见的那两行。
|
||||||
|
assertThat(vo.getTotal()).isEqualTo(2L);
|
||||||
|
assertThat(vo.getItems()).hasSize(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void itemsCarryCompanyIdAndBatchFetchedCompanyName() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(3L);
|
||||||
|
// 同一次请求里 selectList 被用到三次:分页行 → 创建人行 → 超管的 admin 候选
|
||||||
|
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(
|
||||||
|
List.of(row(11L, 5L), row(12L, 5L), row(13L, 7L)),
|
||||||
|
List.of(row(1L, 5L)),
|
||||||
|
List.of());
|
||||||
|
when(companyService.namesByIds(any())).thenReturn(Map.of(5L, "厦门米椿花", 7L, "福州数富"));
|
||||||
|
|
||||||
|
AdminUserListVo vo = service.listUsers(operator, 1, 10, null, null, null, null);
|
||||||
|
|
||||||
|
assertThat(vo.getItems()).extracting(AdminUserItemVo::getCompanyId).containsExactly(5L, 5L, 7L);
|
||||||
|
assertThat(vo.getItems()).extracting(AdminUserItemVo::getCompanyName)
|
||||||
|
.containsExactly("厦门米椿花", "厦门米椿花", "福州数富");
|
||||||
|
ArgumentCaptor<Collection<Long>> ids = ArgumentCaptor.forClass((Class) Collection.class);
|
||||||
|
verify(companyService).namesByIds(ids.capture());
|
||||||
|
// 三行两个公司 ⇒ 只查一次、且 id 去过重(逐行查就是 N+1)
|
||||||
|
assertThat(ids.getValue()).containsExactlyInAnyOrder(5L, 7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void rowHangingOnAnUnknownCompanyIsStillListedWithEmptyName() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
when(userMapper.selectCount(any(LambdaQueryWrapper.class))).thenReturn(1L);
|
||||||
|
when(userMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(
|
||||||
|
List.of(row(11L, 404L)), List.of(), List.of());
|
||||||
|
when(companyService.namesByIds(any())).thenReturn(Map.of());
|
||||||
|
|
||||||
|
AdminUserListVo vo = service.listUsers(operator, 1, 10, null, null, null, null);
|
||||||
|
|
||||||
|
// 脏数据(账号挂在公司表查不到的 id 上)不能让整页 500;缺名字就空着,前端显示 '-'
|
||||||
|
assertThat(vo.getItems()).hasSize(1);
|
||||||
|
assertThat(vo.getItems().get(0).getCompanyId()).isEqualTo(404L);
|
||||||
|
assertThat(vo.getItems().get(0).getCompanyName()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void emptyPageDoesNotAskTheCompanyTableForNames() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
|
||||||
|
service.listUsers(operator, 1, 10, "不存在的关键字", null, null, null);
|
||||||
|
|
||||||
|
verify(companyService, never()).namesByIds(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
private LambdaQueryWrapper<AdminUserEntity> capturedCountQuery() {
|
||||||
|
ArgumentCaptor<LambdaQueryWrapper> captor = ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||||
|
verify(userMapper).selectCount(captor.capture());
|
||||||
|
return captor.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity row(Long id, Long companyId) {
|
||||||
|
AdminUserEntity entity = new AdminUserEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setUsername("u" + id);
|
||||||
|
entity.setRole("normal");
|
||||||
|
entity.setIsAdmin(0);
|
||||||
|
entity.setCompanyId(companyId);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity operator(Long id, String role, Long companyId) {
|
||||||
|
AdminUserEntity operator = new AdminUserEntity();
|
||||||
|
operator.setId(id);
|
||||||
|
operator.setUsername("op");
|
||||||
|
operator.setRole(role);
|
||||||
|
operator.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||||
|
operator.setCompanyId(companyId);
|
||||||
|
return operator;
|
||||||
|
}
|
||||||
|
}
|
||||||
+231
@@ -0,0 +1,231 @@
|
|||||||
|
package com.nanri.aiimage.modules.admin.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||||
|
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||||
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.isNull;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移人(改账号所属公司)的公司边界不变式(设计文档 §2.2 / §6.2)。
|
||||||
|
*
|
||||||
|
* <p>要守住的是一条推论:账号被移进 X 公司后,它的 {@code created_by_id} 要么仍是 X 公司的人,
|
||||||
|
* 要么是超管。这条不变式一旦破口,二期就得回到 77 处 {@code eq(getUserId, userId)} 逐个叠公司边界
|
||||||
|
* (§7.2),一期"业务代码零改动"的前提就没了。所以断言全部打在真正落库的那条 UPDATE 上。</p>
|
||||||
|
*/
|
||||||
|
class AdminUserMoveCompanyTest {
|
||||||
|
|
||||||
|
private AdminUserMapper userMapper;
|
||||||
|
private AdminAuthSupport authSupport;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private AdminUserService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void setUp() {
|
||||||
|
TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), AdminUserEntity.class);
|
||||||
|
userMapper = mock(AdminUserMapper.class);
|
||||||
|
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
|
||||||
|
authSupport = mock(AdminAuthSupport.class);
|
||||||
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
service = new AdminUserService(userMapper, passwordEncoder, authSupport, permissionService,
|
||||||
|
mock(UserSecretCleanupPort.class), companyService);
|
||||||
|
when(permissionService.hasAnyAdminMenu(any(), anyList())).thenReturn(true);
|
||||||
|
when(passwordEncoder.hash(anyString())).thenReturn("hashed");
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity operator(String role, Long companyId) {
|
||||||
|
AdminUserEntity user = new AdminUserEntity();
|
||||||
|
user.setId("super_admin".equals(role) ? 1L : 10L);
|
||||||
|
user.setUsername("op");
|
||||||
|
user.setRole(role);
|
||||||
|
user.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||||
|
user.setCreatedById(1L);
|
||||||
|
user.setCompanyId(companyId);
|
||||||
|
when(authSupport.currentRole(user)).thenReturn(role);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 被编辑的账号:normal、挂在 companyId 上、由 createdById 创建。 */
|
||||||
|
private AdminUserEntity target(Long companyId, Long createdById) {
|
||||||
|
AdminUserEntity user = new AdminUserEntity();
|
||||||
|
user.setId(20L);
|
||||||
|
user.setUsername("moved-user");
|
||||||
|
user.setRole("normal");
|
||||||
|
user.setIsAdmin(0);
|
||||||
|
user.setCompanyId(companyId);
|
||||||
|
user.setCreatedById(createdById);
|
||||||
|
when(userMapper.selectById(20L)).thenReturn(user);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity creator(Long id, String role, Long companyId) {
|
||||||
|
AdminUserEntity user = new AdminUserEntity();
|
||||||
|
user.setId(id);
|
||||||
|
user.setRole(role);
|
||||||
|
user.setCompanyId(companyId);
|
||||||
|
when(userMapper.selectById(id)).thenReturn(user);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserUpdateRequest moveOnly(Long companyId) {
|
||||||
|
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||||
|
request.setCompanyId(companyId);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
private LambdaUpdateWrapper<AdminUserEntity> capturedUpdate() {
|
||||||
|
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass((Class) LambdaUpdateWrapper.class);
|
||||||
|
verify(userMapper).update(isNull(), captor.capture());
|
||||||
|
return captor.getValue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* SET 子句才是"这次真的改了哪一列"。LambdaUpdateWrapper 的 getSqlSegment() 只含 WHERE,
|
||||||
|
* 拿它断言列名会永远假绿。
|
||||||
|
*/
|
||||||
|
private String setClause() {
|
||||||
|
String set = capturedUpdate().getSqlSet();
|
||||||
|
return set == null ? "" : set;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("只改公司、不改密码/角色/权限,也是合法编辑")
|
||||||
|
void movingAloneIsAValidEdit() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, 88L);
|
||||||
|
creator(88L, "admin", 7L);
|
||||||
|
|
||||||
|
assertThatCode(() -> service.updateUser(op, 20L, moveOnly(7L))).doesNotThrowAnyException();
|
||||||
|
|
||||||
|
assertThat(setClause()).contains("company_id");
|
||||||
|
assertThat(capturedUpdate().getParamNameValuePairs().containsValue(7L)).isTrue();
|
||||||
|
verify(companyService).requireActive(7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("创建人在第三家公司:移人必须被拒,且一条 UPDATE 都不发")
|
||||||
|
void moveIsRefusedWhenTheCreatorLivesInAnotherCompany() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, 88L);
|
||||||
|
creator(88L, "admin", 9L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updateUser(op, 20L, moveOnly(7L)))
|
||||||
|
.isInstanceOfSatisfying(BusinessException.class, ex -> {
|
||||||
|
assertThat(ex.getCode()).isEqualTo(403);
|
||||||
|
// 钉「创建人不变式」这道闸门自己:只写 contains("公司") 的话,
|
||||||
|
// 移人闸门删掉后由这条接着抛 403,用例照样绿(变异实测栽过)。
|
||||||
|
assertThat(ex.getMessage()).contains("创建人");
|
||||||
|
});
|
||||||
|
verify(userMapper, never()).update(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("创建人是超管:不受同公司约束,随便移")
|
||||||
|
void creatorSuperAdminIsExemptFromTheCompanyMatch() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, 88L);
|
||||||
|
creator(88L, "super_admin", 1L);
|
||||||
|
|
||||||
|
assertThatCode(() -> service.updateUser(op, 20L, moveOnly(7L))).doesNotThrowAnyException();
|
||||||
|
|
||||||
|
assertThat(setClause()).contains("company_id");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司内 admin 不许移人:改成别家公司直接 403")
|
||||||
|
void onlySuperAdminMayMoveAccounts() {
|
||||||
|
AdminUserEntity op = operator("admin", 5L);
|
||||||
|
target(5L, op.getId());
|
||||||
|
creator(op.getId(), "admin", 5L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updateUser(op, 20L, moveOnly(6L)))
|
||||||
|
.isInstanceOfSatisfying(BusinessException.class, ex -> {
|
||||||
|
assertThat(ex.getCode()).isEqualTo(403);
|
||||||
|
// 必须钉到「移人闸门」这句话:创建人不变式的文案也含「公司」,
|
||||||
|
// 只断 contains("公司") 时闸门被删掉仍然绿(变异 12 实测存活的原因)。
|
||||||
|
assertThat(ex.getMessage()).contains("超级管理员");
|
||||||
|
});
|
||||||
|
verify(userMapper, never()).update(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("admin 传的正好是账号现在这家公司:按「没移」处理,照常改密码")
|
||||||
|
void namingTheCurrentCompanyIsNotAMove() {
|
||||||
|
AdminUserEntity op = operator("admin", 5L);
|
||||||
|
target(5L, op.getId());
|
||||||
|
creator(op.getId(), "admin", 5L);
|
||||||
|
AdminUserUpdateRequest request = moveOnly(5L);
|
||||||
|
request.setPassword("secret9");
|
||||||
|
|
||||||
|
service.updateUser(op, 20L, request);
|
||||||
|
|
||||||
|
assertThat(setClause()).contains("password_hash");
|
||||||
|
assertThat(setClause()).doesNotContain("company_id");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("移进去的公司必须存在且启用:先校验再落库")
|
||||||
|
void destinationCompanyMustExistAndBeActive() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, 88L);
|
||||||
|
creator(88L, "admin", 9L);
|
||||||
|
when(companyService.requireActive(9L)).thenThrow(new BusinessException("公司已停用"));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updateUser(op, 20L, moveOnly(9L)))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
verify(userMapper, never()).update(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("创建人被删掉了(悬空 created_by_id):无法确认同公司,不移")
|
||||||
|
void danglingCreatorBlocksTheMove() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, 88L);
|
||||||
|
when(userMapper.selectById(88L)).thenReturn(null);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.updateUser(op, 20L, moveOnly(7L)))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
verify(userMapper, never()).update(any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("created_by_id 本来就是空的账号:没有冲突可校验,照移")
|
||||||
|
void nullCreatedByIdMovesWithoutComplaint() {
|
||||||
|
AdminUserEntity op = operator("super_admin", 5L);
|
||||||
|
target(5L, null);
|
||||||
|
|
||||||
|
assertThatCode(() -> service.updateUser(op, 20L, moveOnly(7L))).doesNotThrowAnyException();
|
||||||
|
|
||||||
|
assertThat(setClause()).contains("company_id");
|
||||||
|
}
|
||||||
|
}
|
||||||
+151
@@ -0,0 +1,151 @@
|
|||||||
|
package com.nanri.aiimage.modules.admin.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.admin.spi.UserSecretCleanupPort;
|
||||||
|
import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
|
||||||
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期(设计文档 §2.2):建号时账号落进哪家公司,与现有 createdById 规则同构。
|
||||||
|
*
|
||||||
|
* <p>断言一律打在 `insert` 捕获到的实体上,而不是打在"有没有抛异常"上。这样把
|
||||||
|
* `entity.setCompanyId(...)` 删掉,用例必须红(§6.1 的变异自证);若改成断言库里的列
|
||||||
|
* DEFAULT,删掉那行照样绿——那等于没验。</p>
|
||||||
|
*/
|
||||||
|
class AdminUserServiceCompanyTest {
|
||||||
|
|
||||||
|
private AdminUserMapper userMapper;
|
||||||
|
private AdminAuthSupport authSupport;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private AdminUserService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
userMapper = mock(AdminUserMapper.class);
|
||||||
|
WerkzeugPasswordEncoder passwordEncoder = mock(WerkzeugPasswordEncoder.class);
|
||||||
|
authSupport = mock(AdminAuthSupport.class);
|
||||||
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
service = new AdminUserService(userMapper, passwordEncoder, authSupport, permissionService,
|
||||||
|
mock(UserSecretCleanupPort.class), companyService);
|
||||||
|
// 菜单可见性与本组用例无关,全部放开:否则"被 403 挡住"会伪装成"公司校验生效"
|
||||||
|
when(permissionService.hasAnyAdminMenu(any(), any())).thenReturn(true);
|
||||||
|
when(passwordEncoder.hash(anyString())).thenReturn("hashed");
|
||||||
|
when(userMapper.insert(any(AdminUserEntity.class))).thenAnswer(invocation -> {
|
||||||
|
invocation.<AdminUserEntity>getArgument(0).setId(20L);
|
||||||
|
return 1;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void superAdminPlacesNewUserInSpecifiedCompany() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 1L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
AdminUserCreateRequest request = request(7L);
|
||||||
|
|
||||||
|
service.createUser(operator, request);
|
||||||
|
|
||||||
|
assertThat(insertedCompany()).isEqualTo(7L);
|
||||||
|
verify(companyService).requireActive(7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void superAdminWithoutCompanyFallsBackToItsOwnCompany() {
|
||||||
|
// 操作者所属公司故意取 3:实现里写死 1(照抄列 DEFAULT)必须被这条抓到
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 3L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
|
||||||
|
service.createUser(operator, request(null));
|
||||||
|
|
||||||
|
assertThat(insertedCompany()).isEqualTo(3L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminWithoutCompanyFallsBackToItsOwnCompany() {
|
||||||
|
AdminUserEntity operator = operator(10L, "admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
|
||||||
|
service.createUser(operator, request(null));
|
||||||
|
|
||||||
|
assertThat(insertedCompany()).isEqualTo(5L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminMayNameItsOwnCompanyExplicitly() {
|
||||||
|
AdminUserEntity operator = operator(10L, "admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
|
||||||
|
service.createUser(operator, request(5L));
|
||||||
|
|
||||||
|
assertThat(insertedCompany()).isEqualTo(5L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminCannotPlaceNewUserInAnotherCompany() {
|
||||||
|
AdminUserEntity operator = operator(10L, "admin", 5L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("admin");
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.createUser(operator, request(6L)))
|
||||||
|
.isInstanceOfSatisfying(BusinessException.class, ex -> {
|
||||||
|
assertThat(ex.getCode()).isEqualTo(403);
|
||||||
|
// 排他:必须是被公司边界挡下,而不是菜单/角色那两条 403
|
||||||
|
assertThat(ex.getMessage()).contains("公司");
|
||||||
|
});
|
||||||
|
verify(userMapper, never()).insert(any(AdminUserEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void companyExistenceIsCheckedBeforeTheRowIsInserted() {
|
||||||
|
AdminUserEntity operator = operator(1L, "super_admin", 1L);
|
||||||
|
when(authSupport.currentRole(operator)).thenReturn("super_admin");
|
||||||
|
when(companyService.requireActive(9L)).thenThrow(new BusinessException("公司不存在"));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service.createUser(operator, request(9L)))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
// 先校验后插入:反过来就会留下一条挂在不存在公司上的账号
|
||||||
|
verify(userMapper, never()).insert(any(AdminUserEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserCreateRequest request(Long companyId) {
|
||||||
|
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
||||||
|
request.setUsername("created-user");
|
||||||
|
request.setPassword("secret1");
|
||||||
|
request.setRole("normal");
|
||||||
|
request.setCompanyId(companyId);
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity operator(Long id, String role, Long companyId) {
|
||||||
|
AdminUserEntity operator = new AdminUserEntity();
|
||||||
|
operator.setId(id);
|
||||||
|
operator.setUsername("op");
|
||||||
|
operator.setRole(role);
|
||||||
|
operator.setIsAdmin("normal".equals(role) ? 0 : 1);
|
||||||
|
operator.setCreatedById(1L);
|
||||||
|
operator.setCompanyId(companyId);
|
||||||
|
return operator;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Long insertedCompany() {
|
||||||
|
ArgumentCaptor<AdminUserEntity> captor = ArgumentCaptor.forClass(AdminUserEntity.class);
|
||||||
|
verify(userMapper).insert(captor.capture());
|
||||||
|
return captor.getValue().getCompanyId();
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-4
@@ -5,6 +5,7 @@ import com.nanri.aiimage.modules.admin.model.dto.AdminUserCreateRequest;
|
|||||||
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
import com.nanri.aiimage.modules.admin.model.dto.AdminUserUpdateRequest;
|
||||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
import com.nanri.aiimage.common.mapper.AdminUserMapper;
|
||||||
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
|
import com.nanri.aiimage.modules.permission.model.dto.UserColumnPermissionUpdateRequest;
|
||||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
@@ -37,7 +38,8 @@ class AdminUserServiceTest {
|
|||||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||||
AdminUserService service = new AdminUserService(
|
AdminUserService service = new AdminUserService(
|
||||||
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService);
|
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService,
|
||||||
|
mock(CompanyService.class));
|
||||||
AdminUserEntity operator = user(10L, "admin", 1, null);
|
AdminUserEntity operator = user(10L, "admin", 1, null);
|
||||||
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
AdminUserCreateRequest request = new AdminUserCreateRequest();
|
||||||
request.setUsername("created-user");
|
request.setUsername("created-user");
|
||||||
@@ -83,7 +85,8 @@ class AdminUserServiceTest {
|
|||||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||||
AdminUserService service = new AdminUserService(
|
AdminUserService service = new AdminUserService(
|
||||||
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService);
|
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService,
|
||||||
|
mock(CompanyService.class));
|
||||||
AdminUserEntity operator = user(10L, "admin", 1, null);
|
AdminUserEntity operator = user(10L, "admin", 1, null);
|
||||||
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
||||||
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
AdminUserUpdateRequest request = new AdminUserUpdateRequest();
|
||||||
@@ -123,7 +126,8 @@ class AdminUserServiceTest {
|
|||||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||||
AdminUserService service = new AdminUserService(
|
AdminUserService service = new AdminUserService(
|
||||||
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService);
|
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService,
|
||||||
|
mock(CompanyService.class));
|
||||||
AdminUserEntity operator = user(10L, "admin", 1, null);
|
AdminUserEntity operator = user(10L, "admin", 1, null);
|
||||||
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
||||||
|
|
||||||
@@ -150,7 +154,8 @@ class AdminUserServiceTest {
|
|||||||
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
PermissionMenuService permissionService = mock(PermissionMenuService.class);
|
||||||
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||||
AdminUserService service = new AdminUserService(
|
AdminUserService service = new AdminUserService(
|
||||||
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService);
|
userMapper, passwordEncoder, authSupport, permissionService, userApiSecretService,
|
||||||
|
mock(CompanyService.class));
|
||||||
AdminUserEntity operator = user(10L, "admin", 1, null);
|
AdminUserEntity operator = user(10L, "admin", 1, null);
|
||||||
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
AdminUserEntity target = user(20L, "normal", 0, 10L);
|
||||||
|
|
||||||
|
|||||||
+146
@@ -0,0 +1,146 @@
|
|||||||
|
package com.nanri.aiimage.modules.auth.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.security.AuthProperties;
|
||||||
|
import com.nanri.aiimage.common.security.JwtService;
|
||||||
|
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
|
||||||
|
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
|
||||||
|
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||||
|
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||||
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import io.jsonwebtoken.Claims;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户端(app-web)登录回包里的公司身份(设计文档 §2.4)。
|
||||||
|
*
|
||||||
|
* <p>前端 {@code src/shared/auth/company-identity.ts} 读的是 {@code data.companyName},
|
||||||
|
* 拿到空串就清 localStorage 键。所以这里要保证两件事:① 有公司时名字带得出去;
|
||||||
|
* ② <b>公司这一环永远不能把登录本身弄失败</b>——公司查不到、公司停用、账号压根没有公司,
|
||||||
|
* 都只能让公司名变空。②用一条"把 requireActive 桩成必抛"的用例钉住:
|
||||||
|
* 谁把显示口径改成准入口径,这条立刻红。</p>
|
||||||
|
*/
|
||||||
|
class AuthServiceCompanyTest {
|
||||||
|
|
||||||
|
private LoginUserMapper loginUserMapper;
|
||||||
|
private WerkzeugPasswordEncoder passwordEncoder;
|
||||||
|
private JwtService jwtService;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private AuthService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||||
|
LoginUserEntity.class);
|
||||||
|
loginUserMapper = mock(LoginUserMapper.class);
|
||||||
|
passwordEncoder = mock(WerkzeugPasswordEncoder.class);
|
||||||
|
jwtService = mock(JwtService.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
AuthProperties authProperties = mock(AuthProperties.class);
|
||||||
|
// 本组用例只关心公司身份,单设备互踢那条路径留给 AuthServiceTest
|
||||||
|
when(authProperties.isSingleDeviceEnabled()).thenReturn(false);
|
||||||
|
when(jwtService.ttlSeconds()).thenReturn(604800L);
|
||||||
|
service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
|
||||||
|
mock(PermissionMenuService.class), authProperties, companyService);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LoginUserEntity user(Long companyId) {
|
||||||
|
LoginUserEntity user = new LoginUserEntity();
|
||||||
|
user.setId(7L);
|
||||||
|
user.setUsername("u7");
|
||||||
|
user.setPasswordHash("hash");
|
||||||
|
user.setIsAdmin(0);
|
||||||
|
user.setRole("normal");
|
||||||
|
user.setCompanyId(companyId);
|
||||||
|
user.setMachine("devA");
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private LoginRequest loginRequest() {
|
||||||
|
LoginRequest request = new LoginRequest();
|
||||||
|
request.setUsername("u7");
|
||||||
|
request.setPassword("pwd");
|
||||||
|
request.setDeviceId("devA");
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubSuccessfulLogin(LoginUserEntity user) {
|
||||||
|
when(loginUserMapper.selectOne(any())).thenReturn(user);
|
||||||
|
when(passwordEncoder.matches("pwd", "hash")).thenReturn(true);
|
||||||
|
when(jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("登录回包带 companyId 与公司名")
|
||||||
|
void loginCarriesCompanyIdentity() {
|
||||||
|
stubSuccessfulLogin(user(5L));
|
||||||
|
when(companyService.nameOrEmpty(5L)).thenReturn("厦门米椿花");
|
||||||
|
|
||||||
|
LoginResultVo vo = service.login(loginRequest());
|
||||||
|
|
||||||
|
assertThat(vo.getCompanyId()).isEqualTo(5L);
|
||||||
|
assertThat(vo.getCompanyName()).isEqualTo("厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司行查不到:登录照样成功,只是公司名为空")
|
||||||
|
void loginSucceedsWhenTheCompanyRowIsGone() {
|
||||||
|
stubSuccessfulLogin(user(9L));
|
||||||
|
when(companyService.nameOrEmpty(9L)).thenReturn("");
|
||||||
|
// 实现一旦改成"登录要校验公司可用"(requireActive),这条立刻红:
|
||||||
|
// 停用一家公司就等于把它的账号全部锁在门外。
|
||||||
|
when(companyService.requireActive(any())).thenThrow(new BusinessException("公司已停用"));
|
||||||
|
|
||||||
|
LoginResultVo vo = service.login(loginRequest());
|
||||||
|
|
||||||
|
assertThat(vo.getToken()).isEqualTo("jwt-token");
|
||||||
|
assertThat(vo.getCompanyName()).isEmpty();
|
||||||
|
verify(companyService, never()).requireActive(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("账号没有公司归属:companyId 为 null、公司名为空串,不是 null 字符串")
|
||||||
|
void userWithoutACompanyLogsInWithEmptyCompanyName() {
|
||||||
|
stubSuccessfulLogin(user(null));
|
||||||
|
when(companyService.nameOrEmpty(null)).thenReturn("");
|
||||||
|
|
||||||
|
LoginResultVo vo = service.login(loginRequest());
|
||||||
|
|
||||||
|
assertThat(vo.getCompanyId()).isNull();
|
||||||
|
assertThat(vo.getCompanyName()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("check_login 同样带公司身份:刷新页面后顶栏不能空")
|
||||||
|
void checkLoginCarriesCompanyIdentity() {
|
||||||
|
LoginUserEntity user = user(5L);
|
||||||
|
Claims claims = mock(Claims.class);
|
||||||
|
when(claims.getSubject()).thenReturn("7");
|
||||||
|
when(claims.get("deviceId")).thenReturn("devA");
|
||||||
|
when(jwtService.parse("t")).thenReturn(claims);
|
||||||
|
when(loginUserMapper.selectById(7L)).thenReturn(user);
|
||||||
|
when(jwtService.issue(eq(7L), anyString(), anyString())).thenReturn("jwt-token");
|
||||||
|
when(companyService.nameOrEmpty(5L)).thenReturn("厦门米椿花");
|
||||||
|
|
||||||
|
LoginResultVo vo = service.checkLogin("t", null);
|
||||||
|
|
||||||
|
assertThat(vo.getCompanyId()).isEqualTo(5L);
|
||||||
|
assertThat(vo.getCompanyName()).isEqualTo("厦门米椿花");
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-1
@@ -9,6 +9,7 @@ import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
|
|||||||
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||||
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
|
||||||
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
import io.jsonwebtoken.Claims;
|
import io.jsonwebtoken.Claims;
|
||||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
@@ -157,7 +158,7 @@ class AuthServiceTest {
|
|||||||
when(authProperties.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
|
when(authProperties.isSingleDeviceEnabled()).thenReturn(singleDeviceEnabled);
|
||||||
when(jwtService.ttlSeconds()).thenReturn(604800L);
|
when(jwtService.ttlSeconds()).thenReturn(604800L);
|
||||||
AuthService service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
|
AuthService service = new AuthService(loginUserMapper, passwordEncoder, jwtService,
|
||||||
permissionMenuService, authProperties);
|
permissionMenuService, authProperties, mock(CompanyService.class));
|
||||||
return new Fixture(service, loginUserMapper, passwordEncoder, jwtService);
|
return new Fixture(service, loginUserMapper, passwordEncoder, jwtService);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package com.nanri.aiimage.modules.company;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfo;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期:`company` 是本仓第一个真正的租户表,实体一旦映射错(表名拼错、列名对不上 V143),
|
||||||
|
* 报错发生在运行期第一次调用上,本地 mvn 全绿也拦不住。这例把实体与 V143 的表结构对齐。
|
||||||
|
*/
|
||||||
|
class CompanyEntityMappingTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void companyEntityMapsToV143CompanyTableColumns() {
|
||||||
|
TableInfo tableInfo = TableInfoHelper.getTableInfo(CompanyEntity.class);
|
||||||
|
if (tableInfo == null) {
|
||||||
|
tableInfo = TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
|
||||||
|
}
|
||||||
|
assertThat(tableInfo.getTableName())
|
||||||
|
.as("必须映射 V143 建的那张 company 表")
|
||||||
|
.isEqualTo("company");
|
||||||
|
|
||||||
|
Map<String, String> columnByProperty = tableInfo.getFieldList().stream()
|
||||||
|
.collect(Collectors.toMap(TableFieldInfo::getProperty, TableFieldInfo::getColumn, (a, b) -> a));
|
||||||
|
assertThat(columnByProperty)
|
||||||
|
.as("实体列名必须与 V143 的 company 表逐字一致")
|
||||||
|
.containsEntry("companyName", "company_name")
|
||||||
|
.containsEntry("status", "status")
|
||||||
|
.containsEntry("remark", "remark");
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
package com.nanri.aiimage.modules.company;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfo;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期(设计文档 §1.5):`users` 被两个实体同时映射,加 company_id 时漏改任意一处,
|
||||||
|
* 后果是半边链路(后台用户管理 / 登录)静默读不到所属公司,不报错、不失败。
|
||||||
|
* 这两例把「两处都要有这一列」钉住。
|
||||||
|
*
|
||||||
|
* <p>断言打在 MyBatis-Plus 实际解析出的列名上,而不是打在注解字符串上:
|
||||||
|
* 写成 `@TableField("companyid")` 这类拼错也必须红,而只靠驼峰推导映射正确的实现同样绿。</p>
|
||||||
|
*/
|
||||||
|
class UsersCompanyIdMappingTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void adminUserEntityResolvesCompanyIdToCompanyIdColumn() {
|
||||||
|
assertThat(columnOf(AdminUserEntity.class, "companyId"))
|
||||||
|
.as("AdminUserEntity(后台用户管理用的 users 映射)必须有 companyId → company_id")
|
||||||
|
.isEqualTo("company_id");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void loginUserEntityResolvesCompanyIdToCompanyIdColumn() {
|
||||||
|
assertThat(columnOf(LoginUserEntity.class, "companyId"))
|
||||||
|
.as("LoginUserEntity(登录链路用的 users 映射)必须有 companyId → company_id")
|
||||||
|
.isEqualTo("company_id");
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 属性不存在时返回 null(用例红),而不是反射抛 NoSuchFieldException——失败信息要说清是哪个实体少了列。 */
|
||||||
|
private static String columnOf(Class<?> entityType, String property) {
|
||||||
|
TableInfo tableInfo = TableInfoHelper.getTableInfo(entityType);
|
||||||
|
if (tableInfo == null) {
|
||||||
|
tableInfo = TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), entityType);
|
||||||
|
}
|
||||||
|
assertThat(tableInfo.getTableName())
|
||||||
|
.as(entityType.getSimpleName() + " 必须仍映射 users 表")
|
||||||
|
.isEqualTo("users");
|
||||||
|
return tableInfo.getFieldList().stream()
|
||||||
|
.filter(field -> property.equals(field.getProperty()))
|
||||||
|
.map(TableFieldInfo::getColumn)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.controller;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.api.ApiResponse;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import com.nanri.aiimage.modules.company.model.vo.CompanyVo;
|
||||||
|
import com.nanri.aiimage.modules.company.service.CompanyService;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.InOrder;
|
||||||
|
import org.springframework.core.annotation.AnnotatedElementUtils;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
|
||||||
|
import java.lang.reflect.Method;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.inOrder;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录端点的对外契约(设计文档 §2.3)。
|
||||||
|
*
|
||||||
|
* <p>钉的是 admin-frontend-vue/src/api/companies.ts 实际会打的三个地址,以及"先鉴权、
|
||||||
|
* 再碰目录"的顺序。路径写错时前端只会拿到空列表、不报错,所以只能由用例盯着。</p>
|
||||||
|
*/
|
||||||
|
class CompanyControllerEndpointTest {
|
||||||
|
|
||||||
|
private AdminAuthSupport adminAuthSupport;
|
||||||
|
private CompanyService companyService;
|
||||||
|
private CompanyController controller;
|
||||||
|
private HttpServletRequest request;
|
||||||
|
private AdminUserEntity operator;
|
||||||
|
private CompanySaveRequest body;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
adminAuthSupport = mock(AdminAuthSupport.class);
|
||||||
|
companyService = mock(CompanyService.class);
|
||||||
|
controller = new CompanyController(adminAuthSupport, companyService);
|
||||||
|
request = mock(HttpServletRequest.class);
|
||||||
|
operator = new AdminUserEntity();
|
||||||
|
operator.setId(1L);
|
||||||
|
operator.setCompanyId(1L);
|
||||||
|
body = new CompanySaveRequest();
|
||||||
|
body.setCompanyName("福州数富");
|
||||||
|
body.setStatus(CompanyService.STATUS_ACTIVE);
|
||||||
|
body.setRemark("二期");
|
||||||
|
|
||||||
|
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
|
||||||
|
when(companyService.listVisible(operator)).thenReturn(List.of(company(1L, "厦门米椿花")));
|
||||||
|
when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富"));
|
||||||
|
when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanyEntity company(Long id, String name) {
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setCompanyName(name);
|
||||||
|
entity.setStatus(CompanyService.STATUS_ACTIVE);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("每个端点先鉴权再进 service,顺序不能反")
|
||||||
|
void everyEndpointAuthenticatesBeforeTouchingTheDirectory() {
|
||||||
|
controller.listCompanies(request);
|
||||||
|
controller.createCompany(request, body);
|
||||||
|
controller.updateCompany(request, 2L, body);
|
||||||
|
|
||||||
|
InOrder order = inOrder(adminAuthSupport, companyService);
|
||||||
|
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||||
|
order.verify(companyService).listVisible(operator);
|
||||||
|
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||||
|
order.verify(companyService).create(operator, body);
|
||||||
|
order.verify(adminAuthSupport).requireAdminOrInternal(request);
|
||||||
|
order.verify(companyService).update(operator, 2L, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("挂在 /api/admin 前缀下,路径与前端 companies.ts 逐字一致")
|
||||||
|
void routesMatchWhatTheAdminConsoleCalls() {
|
||||||
|
assertThat(rootPaths()).contains("/api/admin");
|
||||||
|
assertThat(pathsOf("listCompanies")).contains("/companies");
|
||||||
|
assertThat(pathsOf("createCompany")).contains("/companies");
|
||||||
|
assertThat(pathsOf("updateCompany")).contains("/companies/{id}");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("不提供删除公司的端点:账号挂着的公司删不掉,只能停用")
|
||||||
|
void exposesNoDeleteEndpoint() {
|
||||||
|
for (Method method : CompanyController.class.getDeclaredMethods()) {
|
||||||
|
assertThat(AnnotatedElementUtils.findMergedAnnotation(method, DeleteMapping.class))
|
||||||
|
.as("方法 %s 不该是 DELETE", method.getName())
|
||||||
|
.isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("列表回包是 CompanyVo 而不是实体:实体字段是 camelCase,前端解析不到公司名")
|
||||||
|
void listReturnsVoItemsNotEntities() {
|
||||||
|
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request);
|
||||||
|
|
||||||
|
assertThat(response.getData()).hasSize(1);
|
||||||
|
assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("新建/改名把落库后的那一条回给前端,省一次重新拉列表")
|
||||||
|
void writeEndpointsReturnTheSavedCompany() {
|
||||||
|
assertThat(controller.createCompany(request, body).getData().getId()).isEqualTo(2L);
|
||||||
|
assertThat(controller.updateCompany(request, 2L, body).getData().getCompanyName())
|
||||||
|
.isEqualTo("福州数富科技");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GetMapping/PostMapping/PutMapping 都是 @RequestMapping 的派生注解,
|
||||||
|
* findMergedAnnotation 会顺着元注解找到并把 path/value 归一(@AliasFor 只在合成注解上生效,
|
||||||
|
* 所以不能直接 getAnnotation(...).path(),那会读到没被别名填上的空数组)。
|
||||||
|
*/
|
||||||
|
private List<String> pathsOf(String methodName) {
|
||||||
|
for (Method method : CompanyController.class.getDeclaredMethods()) {
|
||||||
|
if (method.getName().equals(methodName)) {
|
||||||
|
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
|
||||||
|
assertThat(mapping).as("方法 %s 上没有 HTTP 映射注解", methodName).isNotNull();
|
||||||
|
return collect(mapping);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new AssertionError("找不到端点方法:" + methodName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> rootPaths() {
|
||||||
|
RequestMapping mapping = AnnotatedElementUtils.findMergedAnnotation(CompanyController.class, RequestMapping.class);
|
||||||
|
assertThat(mapping).isNotNull();
|
||||||
|
return collect(mapping);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> collect(RequestMapping mapping) {
|
||||||
|
List<String> paths = new ArrayList<>(Arrays.asList(mapping.value()));
|
||||||
|
paths.addAll(Arrays.asList(mapping.path()));
|
||||||
|
return paths;
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.model.vo;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CompanyVo 的线上字段名 = admin-frontend-vue/src/api/companies-model.ts 的读法。
|
||||||
|
*
|
||||||
|
* <p>前端那条用例只能证明"前端按 company_name 解析",证明不了后端发的是不是这个名字;
|
||||||
|
* 两边都在、且各测各的,才是这条跨产物契约唯一的实跑闸。</p>
|
||||||
|
*/
|
||||||
|
class CompanyVoTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("序列化成 snake_case,时间按 'yyyy-MM-dd HH:mm' 出字符串")
|
||||||
|
void serializesWithTheColumnNamesTheConsoleParses() throws Exception {
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setId(2L);
|
||||||
|
entity.setCompanyName("福州数富");
|
||||||
|
entity.setStatus(0);
|
||||||
|
entity.setRemark("改名并停用");
|
||||||
|
entity.setCreatedAt(LocalDateTime.of(2026, 10, 4, 14, 5));
|
||||||
|
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
Map<String, Object> json = mapper.readValue(
|
||||||
|
mapper.writeValueAsString(CompanyVo.from(entity)),
|
||||||
|
new TypeReference<Map<String, Object>>() {
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThat(json.keySet()).containsExactlyInAnyOrder(
|
||||||
|
"id", "company_name", "status", "remark", "created_at", "updated_at");
|
||||||
|
assertThat(json.get("company_name")).isEqualTo("福州数富");
|
||||||
|
assertThat(json.get("created_at")).isEqualTo("2026-10-04 14:05");
|
||||||
|
// 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined
|
||||||
|
assertThat(json.get("updated_at")).isEqualTo("");
|
||||||
|
}
|
||||||
|
}
|
||||||
+170
@@ -0,0 +1,170 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import ch.qos.logback.classic.Level;
|
||||||
|
import ch.qos.logback.classic.Logger;
|
||||||
|
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||||
|
import ch.qos.logback.core.read.ListAppender;
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 「半套发布」哨兵(设计文档 §6.3)。
|
||||||
|
*
|
||||||
|
* <p>{@code users.company_id DEFAULT 1} 只为发布期的旧 jar 存在(§8.2)。第二家公司一旦开通而 DEFAULT
|
||||||
|
* 还没摘,此后每个没显式传公司的建号都会被静默塞进默认那家——不报错、不丢数据,只在后台列表里
|
||||||
|
* 表现成"这个人怎么在别家公司"。所以必须用代码在启动期喊出来,而不是写在注释里等人记得。</p>
|
||||||
|
*/
|
||||||
|
class CompanyDefaultGuardTest {
|
||||||
|
|
||||||
|
private CompanyMapper companyMapper;
|
||||||
|
private JdbcTemplate jdbcTemplate;
|
||||||
|
private CompanyDefaultGuard guard;
|
||||||
|
private ListAppender<ILoggingEvent> appender;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
companyMapper = mock(CompanyMapper.class);
|
||||||
|
jdbcTemplate = mock(JdbcTemplate.class);
|
||||||
|
guard = new CompanyDefaultGuard(companyMapper, jdbcTemplate);
|
||||||
|
Logger logger = (Logger) LoggerFactory.getLogger(CompanyDefaultGuard.class);
|
||||||
|
appender = new ListAppender<>();
|
||||||
|
appender.setContext(logger.getLoggerContext());
|
||||||
|
appender.start();
|
||||||
|
logger.addAppender(appender);
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
((Logger) LoggerFactory.getLogger(CompanyDefaultGuard.class)).detachAppender(appender);
|
||||||
|
appender.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void companies(long count) {
|
||||||
|
when(companyMapper.selectCount(null)).thenReturn(count);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void columnDefault(String value) {
|
||||||
|
when(jdbcTemplate.queryForObject(anyString(), eq(String.class))).thenReturn(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String messageAt(Level level) {
|
||||||
|
return appender.list.stream()
|
||||||
|
.filter(e -> e.getLevel() == level)
|
||||||
|
.map(ILoggingEvent::getFormattedMessage)
|
||||||
|
.findFirst()
|
||||||
|
.orElse("");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("第二家公司已开通、DEFAULT 还在:打 ERROR 并带上哨兵标记")
|
||||||
|
void secondCompanyWithDefaultStillOnShoutsError() {
|
||||||
|
companies(2);
|
||||||
|
columnDefault("1");
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR))
|
||||||
|
.contains(CompanyDefaultGuard.ALARM)
|
||||||
|
.contains("2");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("只有一家公司:DEFAULT 是发布期故意留的,不许报警")
|
||||||
|
void singleCompanyKeepsQuiet() {
|
||||||
|
companies(1);
|
||||||
|
columnDefault("1");
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("DEFAULT 已经摘掉:一声不响")
|
||||||
|
void droppedDefaultKeepsQuiet() {
|
||||||
|
companies(3);
|
||||||
|
columnDefault(null);
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("DEFAULT 是空串也按「已摘除」处理,别把空值读成还在")
|
||||||
|
void blankDefaultCountsAsDropped() {
|
||||||
|
companies(2);
|
||||||
|
columnDefault(" ");
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("查不到一家公司:没到多公司阶段,不猜也不报")
|
||||||
|
void noCompanyAtAllKeepsQuiet() {
|
||||||
|
companies(0);
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR)).isEmpty();
|
||||||
|
verify(jdbcTemplate, org.mockito.Mockito.never()).queryForObject(anyString(), eq(String.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("探针本身失败:不许静默——降级成 WARN 说明哨兵没跑成")
|
||||||
|
void probeFailureIsAnnouncedNotSwallowed() {
|
||||||
|
when(companyMapper.selectCount(null)).thenThrow(new RuntimeException("没有 information_schema 读权限"));
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
assertThat(messageAt(Level.ERROR)).isEmpty();
|
||||||
|
assertThat(messageAt(Level.WARN))
|
||||||
|
.contains(CompanyDefaultGuard.PROBE_FAILED)
|
||||||
|
.contains("没有 information_schema 读权限");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("探的是 users.company_id 这一列,表名列名写错就等于没探")
|
||||||
|
void probeReadsTheRightColumn() {
|
||||||
|
companies(2);
|
||||||
|
columnDefault("1");
|
||||||
|
|
||||||
|
guard.check();
|
||||||
|
|
||||||
|
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(jdbcTemplate).queryForObject(sql.capture(), eq(String.class));
|
||||||
|
assertThat(sql.getValue())
|
||||||
|
.contains("information_schema.COLUMNS")
|
||||||
|
.contains("DATABASE()")
|
||||||
|
.contains("'users'")
|
||||||
|
.contains("'company_id'");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("哨兵挂在 ApplicationReadyEvent 上:漏了这个注解它就永远不跑")
|
||||||
|
void guardRunsWhenTheApplicationIsReady() throws NoSuchMethodException {
|
||||||
|
EventListener listener = CompanyDefaultGuard.class
|
||||||
|
.getDeclaredMethod("checkOnStartup")
|
||||||
|
.getAnnotation(EventListener.class);
|
||||||
|
|
||||||
|
assertThat(listener).isNotNull();
|
||||||
|
assertThat(listener.value()).containsExactly(ApplicationReadyEvent.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
+299
@@ -0,0 +1,299 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyList;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 公司目录(设计文档 §2.3)的可见范围与写入边界。
|
||||||
|
*
|
||||||
|
* <p>读口径与写口径必须一起收窄:只把写拦成超管、列表仍返回全部公司,等于把别家公司的
|
||||||
|
* 名字泄露给本公司管理员。</p>
|
||||||
|
*/
|
||||||
|
class CompanyServiceDirectoryTest {
|
||||||
|
|
||||||
|
private CompanyMapper companyMapper;
|
||||||
|
private AdminAuthSupport adminAuthSupport;
|
||||||
|
private PermissionMenuService permissionMenuService;
|
||||||
|
private CompanyService companyService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
// LambdaQueryWrapper 的列名解析依赖 TableInfo 缓存,单测没有 Spring 上下文,手工钉一次。
|
||||||
|
TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
|
||||||
|
companyMapper = mock(CompanyMapper.class);
|
||||||
|
adminAuthSupport = mock(AdminAuthSupport.class);
|
||||||
|
permissionMenuService = mock(PermissionMenuService.class);
|
||||||
|
when(permissionMenuService.hasAnyAdminMenu(any(), anyList())).thenReturn(true);
|
||||||
|
companyService = new CompanyService(companyMapper, adminAuthSupport, permissionMenuService);
|
||||||
|
}
|
||||||
|
|
||||||
|
private AdminUserEntity operator(String role, Long companyId) {
|
||||||
|
AdminUserEntity user = new AdminUserEntity();
|
||||||
|
user.setId(100L);
|
||||||
|
user.setUsername("op");
|
||||||
|
user.setRole(role);
|
||||||
|
user.setCompanyId(companyId);
|
||||||
|
when(adminAuthSupport.currentRole(user)).thenReturn(role);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanyEntity company(long id, String name, int status) {
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setCompanyName(name);
|
||||||
|
entity.setStatus(status);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanySaveRequest request(String name, Integer status, String remark) {
|
||||||
|
CompanySaveRequest req = new CompanySaveRequest();
|
||||||
|
req.setCompanyName(name);
|
||||||
|
req.setStatus(status);
|
||||||
|
req.setRemark(remark);
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private LambdaQueryWrapper<CompanyEntity> capturedSelectList() {
|
||||||
|
ArgumentCaptor<LambdaQueryWrapper<CompanyEntity>> captor =
|
||||||
|
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||||
|
verify(companyMapper).selectList(captor.capture());
|
||||||
|
return materialize(captor.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private LambdaQueryWrapper<CompanyEntity> capturedSelectCount() {
|
||||||
|
ArgumentCaptor<LambdaQueryWrapper<CompanyEntity>> captor =
|
||||||
|
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||||
|
verify(companyMapper).selectCount(captor.capture());
|
||||||
|
return materialize(captor.getValue());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MP 的 paramNameValuePairs 要把条件渲染进 sqlSegment 才落值,所以读参数前先摸一次
|
||||||
|
* getSqlSegment()(仓库里 DedupeTotalDataServiceTest 同样这么绕)。
|
||||||
|
*/
|
||||||
|
private LambdaQueryWrapper<CompanyEntity> materialize(LambdaQueryWrapper<CompanyEntity> query) {
|
||||||
|
assertThat(query.getSqlSegment()).isNotNull();
|
||||||
|
return query;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 断言的是"有没有带值的查询条件",不是某个列名。
|
||||||
|
*
|
||||||
|
* <p>不要写成 contains("company_id"):company 表压根没有这一列(它是主表,自己的主键叫 id),
|
||||||
|
* 那样写无论实现怎么做都恒绿。MP 只在 eq/in/like 这类带值条件里往 paramNameValuePairs
|
||||||
|
* 塞参数,orderBy 不塞,所以"超管为空、管理员恰好是自己公司"是能咬住实现的读法。</p>
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
@DisplayName("超管的公司目录不带任何过滤条件")
|
||||||
|
void superAdminDirectoryHasNoCompanyFilter() {
|
||||||
|
when(companyMapper.selectList(any())).thenReturn(List.of(company(1, "厦门米椿花", 1), company(2, "福州数富", 1)));
|
||||||
|
|
||||||
|
List<CompanyEntity> visible = companyService.listVisible(operator("super_admin", 1L));
|
||||||
|
|
||||||
|
assertThat(visible).hasSize(2);
|
||||||
|
assertThat(capturedSelectList().getParamNameValuePairs()).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司内管理员的目录只查自己公司:读口径必须跟写口径一起收窄")
|
||||||
|
void companyScopedAdminDirectoryIsFilteredToOwnCompany() {
|
||||||
|
when(companyMapper.selectList(any())).thenReturn(List.of(company(2, "福州数富", 1)));
|
||||||
|
|
||||||
|
List<CompanyEntity> visible = companyService.listVisible(operator("admin", 2L));
|
||||||
|
|
||||||
|
assertThat(visible).hasSize(1);
|
||||||
|
LambdaQueryWrapper<CompanyEntity> query = capturedSelectList();
|
||||||
|
assertThat(query.getSqlSegment()).contains("id");
|
||||||
|
assertThat(query.getParamNameValuePairs()).containsValue(2L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("非管理员账号一律拒绝读目录(不能只靠 controller 的菜单门)")
|
||||||
|
void nonAdminCallerIsRejected() {
|
||||||
|
assertThatThrownBy(() -> companyService.listVisible(operator(null, 2L)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("管理员");
|
||||||
|
verify(companyMapper, never()).selectList(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("管理员没有公司归属时直接拒绝,而不是退化成看到全部公司")
|
||||||
|
void adminWithoutCompanyIsRejectedInsteadOfSeeingEverything() {
|
||||||
|
assertThatThrownBy(() -> companyService.listVisible(operator("admin", null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("公司");
|
||||||
|
verify(companyMapper, never()).selectList(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("没有被授予 admin_companies 菜单的人一律 403")
|
||||||
|
void callerWithoutCompanyMenuIsRejected() {
|
||||||
|
when(permissionMenuService.hasAnyAdminMenu(any(), anyList())).thenReturn(false);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> companyService.listVisible(operator("admin", 2L)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("公司");
|
||||||
|
verify(companyMapper, never()).selectList(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("新增公司仅超管:公司内管理员即使拿到菜单也不能建第二家公司")
|
||||||
|
void companyAdminCannotCreate() {
|
||||||
|
assertThatThrownBy(() -> companyService.create(operator("admin", 2L), request("福州数富", null, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("超级管理员");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("超管新建公司:名称去空格,未指定状态时落启用")
|
||||||
|
void superAdminCreateTrimsNameAndActivates() {
|
||||||
|
when(companyMapper.selectCount(any())).thenReturn(0L);
|
||||||
|
|
||||||
|
companyService.create(operator("super_admin", 1L), request(" 福州数富 ", null, " 二期 "));
|
||||||
|
|
||||||
|
ArgumentCaptor<CompanyEntity> captor = ArgumentCaptor.forClass(CompanyEntity.class);
|
||||||
|
verify(companyMapper).insert(captor.capture());
|
||||||
|
assertThat(captor.getValue().getCompanyName()).isEqualTo("福州数富");
|
||||||
|
assertThat(captor.getValue().getStatus()).isEqualTo(CompanyService.STATUS_ACTIVE);
|
||||||
|
assertThat(captor.getValue().getRemark()).isEqualTo("二期");
|
||||||
|
// 查重必须拿 trim 后的名字去比,否则 " 厦门米椿花" 会绕过 uk_company_name 建成第二家长得一样的公司
|
||||||
|
assertThat(capturedSelectCount().getParamNameValuePairs()).containsValue("福州数富");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司名超过列宽 128 时先拒,别把 1406 抛成 500")
|
||||||
|
void createRejectsNameLongerThanColumn() {
|
||||||
|
assertThatThrownBy(() -> companyService.create(
|
||||||
|
operator("super_admin", 1L), request("长".repeat(129), null, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("128");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("备注超过列宽 255 时先拒")
|
||||||
|
void createRejectsRemarkLongerThanColumn() {
|
||||||
|
assertThatThrownBy(() -> companyService.create(
|
||||||
|
operator("super_admin", 1L), request("福州数富", null, "备".repeat(256))))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("备注");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("公司名空白一律拒绝(company_name 是 NOT NULL + 唯一索引)")
|
||||||
|
void createRejectsBlankName() {
|
||||||
|
assertThatThrownBy(() -> companyService.create(operator("super_admin", 1L), request(" ", null, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("不能为空");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("重名公司在写库前就被拒(uk_company_name 只能兜底,不能当校验用)")
|
||||||
|
void createRejectsDuplicateName() {
|
||||||
|
when(companyMapper.selectCount(any())).thenReturn(1L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> companyService.create(operator("super_admin", 1L), request("厦门米椿花", null, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("已存在");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("状态只认 0/1,别的值不写进 tinyint 列")
|
||||||
|
void createRejectsStatusOutsideZeroAndOne() {
|
||||||
|
assertThatThrownBy(() -> companyService.create(operator("super_admin", 1L), request("福州数富", 5, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("状态");
|
||||||
|
verify(companyMapper, never()).insert(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("改名/启停仅超管")
|
||||||
|
void companyAdminCannotUpdate() {
|
||||||
|
assertThatThrownBy(() -> companyService.update(operator("admin", 2L), 1L, request("厦门米椿花", 0, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("超级管理员");
|
||||||
|
verify(companyMapper, never()).updateById(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("改一家不存在的公司是失败的,不能静默新建")
|
||||||
|
void updateRejectsUnknownCompany() {
|
||||||
|
when(companyMapper.selectById(9L)).thenReturn(null);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> companyService.update(operator("super_admin", 1L), 9L, request("福州数富", 1, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("不存在");
|
||||||
|
verify(companyMapper, never()).updateById(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("改成别家公司已有的名字被拒(唯一性排除自己)")
|
||||||
|
void updateRejectsNameTakenByAnotherCompany() {
|
||||||
|
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
|
||||||
|
when(companyMapper.selectCount(any())).thenReturn(1L);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> companyService.update(operator("super_admin", 1L), 2L, request("厦门米椿花", 1, null)))
|
||||||
|
.isInstanceOf(BusinessException.class)
|
||||||
|
.hasMessageContaining("已存在");
|
||||||
|
verify(companyMapper, never()).updateById(any(CompanyEntity.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("查重排除自己:只改备注/状态时不能被判成重名")
|
||||||
|
void duplicateCheckOnUpdateExcludesTheCompanyItself() {
|
||||||
|
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
|
||||||
|
when(companyMapper.selectCount(any())).thenReturn(0L);
|
||||||
|
|
||||||
|
companyService.update(operator("super_admin", 1L), 2L, request("福州数富", 1, "只改备注"));
|
||||||
|
|
||||||
|
LambdaQueryWrapper<CompanyEntity> query = capturedSelectCount();
|
||||||
|
assertThat(query.getParamNameValuePairs()).containsValues("福州数富", 2L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("超管改名 + 停用一起落库,按 id 更新这一条")
|
||||||
|
void updateWritesNameStatusAndRemark() {
|
||||||
|
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
|
||||||
|
when(companyMapper.selectCount(any())).thenReturn(0L);
|
||||||
|
|
||||||
|
companyService.update(operator("super_admin", 1L), 2L, request(" 福州数富科技 ", 0, " 改名并停用 "));
|
||||||
|
|
||||||
|
ArgumentCaptor<CompanyEntity> captor = ArgumentCaptor.forClass(CompanyEntity.class);
|
||||||
|
verify(companyMapper).updateById(captor.capture());
|
||||||
|
assertThat(captor.getValue().getId()).isEqualTo(2L);
|
||||||
|
assertThat(captor.getValue().getCompanyName()).isEqualTo("福州数富科技");
|
||||||
|
assertThat(captor.getValue().getStatus()).isEqualTo(CompanyService.STATUS_DISABLED);
|
||||||
|
assertThat(captor.getValue().getRemark()).isEqualTo("改名并停用");
|
||||||
|
}
|
||||||
|
}
|
||||||
+128
@@ -0,0 +1,128 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.never;
|
||||||
|
import static org.mockito.Mockito.verify;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 登录/顶栏要显示公司名(设计文档 §2.4),所以这条读路径的口径是「显示」,不是「校验」。
|
||||||
|
*
|
||||||
|
* <p>它被每次登录调用,因此绝不能挡路:查不到公司、公司停用,都只让名字变空,
|
||||||
|
* 不抛异常。要是这里改成 {@code requireActive},停用一个公司就会把它的账号全部锁在门外。</p>
|
||||||
|
*/
|
||||||
|
class CompanyServiceNameLookupTest {
|
||||||
|
|
||||||
|
private CompanyMapper companyMapper;
|
||||||
|
private CompanyService companyService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
void setUp() {
|
||||||
|
// namesByIds 用 LambdaQueryWrapper.in(CompanyEntity::getId, ...),取列名依赖 TableInfo 缓存,
|
||||||
|
// 单测没有 Spring 上下文,手工钉一次(否则 lambda 解析在 CI 上取决于类执行顺序)。
|
||||||
|
TableInfoHelper.initTableInfo(
|
||||||
|
new MapperBuilderAssistant(new MybatisConfiguration(), ""), CompanyEntity.class);
|
||||||
|
companyMapper = mock(CompanyMapper.class);
|
||||||
|
companyService = new CompanyService(companyMapper, mock(AdminAuthSupport.class),
|
||||||
|
mock(PermissionMenuService.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanyEntity company(Long id, String name, int status) {
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setCompanyName(name);
|
||||||
|
entity.setStatus(status);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("没有公司归属的账号:直接空串,不去查表")
|
||||||
|
void nullCompanyAddsNoQuery() {
|
||||||
|
assertThat(companyService.nameOrEmpty(null)).isEmpty();
|
||||||
|
// 用 any() 而不是 anyLong():null 入参不会被 anyLong() 记成一次匹配,
|
||||||
|
// 那样「实现其实查了库、还把 null 传进去」这条反而验不出来。
|
||||||
|
verify(companyMapper, never()).selectById(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("账号挂在已被删掉的公司 id 上:名字读成空串,不许抛")
|
||||||
|
void unknownCompanyReadsAsEmptyNameNotAnError() {
|
||||||
|
when(companyMapper.selectById(9L)).thenReturn(null);
|
||||||
|
|
||||||
|
assertThatCode(() -> companyService.nameOrEmpty(9L)).doesNotThrowAnyException();
|
||||||
|
assertThat(companyService.nameOrEmpty(9L)).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("查得到就回公司名")
|
||||||
|
void returnsTheStoredCompanyName() {
|
||||||
|
when(companyMapper.selectById(5L))
|
||||||
|
.thenReturn(company(5L, "厦门米椿花", CompanyService.STATUS_ACTIVE));
|
||||||
|
|
||||||
|
assertThat(companyService.nameOrEmpty(5L)).isEqualTo("厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("停用的公司照样显示名字:这里是显示口径,不是准入口径")
|
||||||
|
void disabledCompanyStillShowsItsName() {
|
||||||
|
when(companyMapper.selectById(5L))
|
||||||
|
.thenReturn(company(5L, "厦门米椿花", CompanyService.STATUS_DISABLED));
|
||||||
|
|
||||||
|
assertThat(companyService.nameOrEmpty(5L)).isEqualTo("厦门米椿花");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表页批量取名走这个方法(§2.3)。AdminUserListCompanyTest 把 CompanyService mock 掉了,
|
||||||
|
* 它捕获的是调用方传出的参数,摸不到这里的实现——所以去重/空输入这两条只能在本类用真实对象钉。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
@DisplayName("批量取名:重复 id 折成一次查询,IN 条件里每个公司只出现一遍")
|
||||||
|
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||||
|
void batchLookupSendsEachCompanyIdOnce() {
|
||||||
|
when(companyMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(
|
||||||
|
List.of(company(5L, "厦门米椿花", CompanyService.STATUS_ACTIVE),
|
||||||
|
company(7L, "福州数富", CompanyService.STATUS_ACTIVE)));
|
||||||
|
|
||||||
|
assertThat(companyService.namesByIds(List.of(5L, 5L, 7L, 5L)))
|
||||||
|
.containsEntry(5L, "厦门米椿花")
|
||||||
|
.containsEntry(7L, "福州数富");
|
||||||
|
|
||||||
|
ArgumentCaptor<LambdaQueryWrapper<CompanyEntity>> query =
|
||||||
|
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
|
||||||
|
verify(companyMapper).selectList(query.capture());
|
||||||
|
// 先碰一次 getSqlSegment(),MP 才把条件参数铺进 paramNameValuePairs
|
||||||
|
query.getValue().getSqlSegment();
|
||||||
|
assertThat(query.getValue().getParamNameValuePairs().values())
|
||||||
|
.containsExactlyInAnyOrder(5L, 7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("批量取名:空列表(含 null)不碰公司表,一页没有账号就该一条 SQL 都不发")
|
||||||
|
void batchLookupOnEmptyInputSkipsTheTable() {
|
||||||
|
when(companyMapper.selectList(any(LambdaQueryWrapper.class))).thenReturn(List.of());
|
||||||
|
|
||||||
|
assertThat(companyService.namesByIds(List.of())).isEmpty();
|
||||||
|
assertThat(companyService.namesByIds(null)).isEmpty();
|
||||||
|
|
||||||
|
verify(companyMapper, never()).selectList(any(LambdaQueryWrapper.class));
|
||||||
|
}
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package com.nanri.aiimage.modules.company.service;
|
||||||
|
|
||||||
|
import com.nanri.aiimage.common.exception.BusinessException;
|
||||||
|
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||||
|
import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
|
||||||
|
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
|
||||||
|
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.Mockito.mock;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多公司一期(设计文档 §2.2):建号指定的公司必须真实存在且处于启用态,
|
||||||
|
* 否则账号会挂在一个查不到的公司上(列表按公司筛选时它整体失明)。
|
||||||
|
*/
|
||||||
|
class CompanyServiceRequireActiveTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unknownCompanyIsRejected() {
|
||||||
|
CompanyMapper mapper = mock(CompanyMapper.class);
|
||||||
|
when(mapper.selectById(9L)).thenReturn(null);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service(mapper).requireActive(9L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void disabledCompanyIsRejected() {
|
||||||
|
CompanyMapper mapper = mock(CompanyMapper.class);
|
||||||
|
when(mapper.selectById(9L)).thenReturn(company(9L, 0));
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> service(mapper).requireActive(9L))
|
||||||
|
.isInstanceOf(BusinessException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 正例必须存在:否则上面两条红会被"requireActive 无条件抛"的实现骗过去。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void activeCompanyIsReturned() {
|
||||||
|
CompanyMapper mapper = mock(CompanyMapper.class);
|
||||||
|
when(mapper.selectById(7L)).thenReturn(company(7L, 1));
|
||||||
|
|
||||||
|
CompanyEntity company = service(mapper).requireActive(7L);
|
||||||
|
|
||||||
|
assertThat(company.getId()).isEqualTo(7L);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanyService service(CompanyMapper mapper) {
|
||||||
|
return new CompanyService(mapper, mock(AdminAuthSupport.class), mock(PermissionMenuService.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private CompanyEntity company(Long id, Integer status) {
|
||||||
|
CompanyEntity entity = new CompanyEntity();
|
||||||
|
entity.setId(id);
|
||||||
|
entity.setStatus(status);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -290,6 +290,27 @@ class TaskCenterQueryMapperSqlTest {
|
|||||||
assertEquals(2, boundSql.getParameterMappings().size());
|
assertEquals(2, boundSql.getParameterMappings().size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关键词进度只从 result_json 抽两个数:整列拉回服务层会把 30s 轮询的载荷撑爆
|
||||||
|
* (result_json 装的是采集统计 + 明细),所以选列必须钉死成这三列。
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
void collectDataKeywordStatsReadsOnlyTwoJsonPaths() {
|
||||||
|
BoundSql boundSql = render("selectCollectDataKeywordStats", params("taskIds", List.of(1L, 2L)));
|
||||||
|
String sql = sqlOf(boundSql);
|
||||||
|
|
||||||
|
assertTrue(sql.startsWith("SELECT t.id AS taskId,"
|
||||||
|
+ "JSON_UNQUOTE(JSON_EXTRACT(t.result_json,'$.totalRows')) AS totalRows,"
|
||||||
|
+ "JSON_UNQUOTE(JSON_EXTRACT(t.result_json,'$.processedRows')) AS processedRows"
|
||||||
|
+ " FROM biz_file_task t"), "只回三列,大 JSON 不出库:" + sql);
|
||||||
|
assertTrue(sql.contains("UPPER(t.module_type) = 'COLLECT_DATA'"), "只有采集数据有关键词进度");
|
||||||
|
assertTrue(sql.contains("AND t.result_json IS NOT NULL"), "没有回写过统计的任务不参与");
|
||||||
|
assertFalse(sql.contains("JSON_VALID"), "列是原生 JSON,不需要文本合法性守卫");
|
||||||
|
assertEquals(2, boundSql.getParameterMappings().size(), "一次批量按任务号取");
|
||||||
|
assertEquals(1L, boundSql.getAdditionalParameter("__frch_tid_0"));
|
||||||
|
assertEquals(2L, boundSql.getAdditionalParameter("__frch_tid_1"));
|
||||||
|
}
|
||||||
|
|
||||||
/** 店铺只有两个真来源:上架结果文件的 shop_name、逐店落行的模块的 source_filename。 */
|
/** 店铺只有两个真来源:上架结果文件的 shop_name、逐店落行的模块的 source_filename。 */
|
||||||
@Test
|
@Test
|
||||||
void shopSourcesAreBatchedByTaskId() {
|
void shopSourcesAreBatchedByTaskId() {
|
||||||
|
|||||||
+71
-1
@@ -1,6 +1,7 @@
|
|||||||
package com.nanri.aiimage.modules.taskcenter.service;
|
package com.nanri.aiimage.modules.taskcenter.service;
|
||||||
|
|
||||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||||
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterCollectStatsRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterDeviceRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterShopStatRow;
|
||||||
@@ -47,7 +48,9 @@ import static org.mockito.Mockito.when;
|
|||||||
* ① 卡住只有一个窗口(进行中且 10 分钟无上报);
|
* ① 卡住只有一个窗口(进行中且 10 分钟无上报);
|
||||||
* ② 汇总卡的「在跑店铺」与店铺面板行数同源,且都不把「不挂店铺」桶算成店铺;
|
* ② 汇总卡的「在跑店铺」与店铺面板行数同源,且都不把「不挂店铺」桶算成店铺;
|
||||||
* ③ 每个进行中任务必须在面板里出现(无店铺归属的落合成桶,不许静默消失);
|
* ③ 每个进行中任务必须在面板里出现(无店铺归属的落合成桶,不许静默消失);
|
||||||
* ④ 店铺只认真来源(上架文件 / 逐店落行文件),快照的 {@code current_scope_key} 是实例锁,不是店铺。
|
* ④ 店铺只认真来源(上架文件 / 逐店落行文件),快照的 {@code current_scope_key} 是实例锁,不是店铺;
|
||||||
|
* ⑤ 无快照的进度回退跟客户端「有没有进度条」对齐(用户 2026-10-04 定案):采集数据用关键词进度,
|
||||||
|
* 上架/删除ASIN/品牌沿用文件·行计数,客户端压根不画条的业务不许回退成误导的 0/1。
|
||||||
* SQL 本身由 TaskCenterQueryMapperSqlTest 守。
|
* SQL 本身由 TaskCenterQueryMapperSqlTest 守。
|
||||||
*/
|
*/
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
@@ -132,6 +135,14 @@ class TaskCenterQueryServiceTest {
|
|||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static TaskCenterCollectStatsRow collectStatsRow(long taskId, String totalRows, String processedRows) {
|
||||||
|
TaskCenterCollectStatsRow row = new TaskCenterCollectStatsRow();
|
||||||
|
row.setTaskId(taskId);
|
||||||
|
row.setTotalRows(totalRows);
|
||||||
|
row.setProcessedRows(processedRows);
|
||||||
|
return row;
|
||||||
|
}
|
||||||
|
|
||||||
private static TaskCenterDeviceRow deviceNameRow(String deviceId, String deviceName) {
|
private static TaskCenterDeviceRow deviceNameRow(String deviceId, String deviceName) {
|
||||||
TaskCenterDeviceRow row = new TaskCenterDeviceRow();
|
TaskCenterDeviceRow row = new TaskCenterDeviceRow();
|
||||||
row.setDeviceId(deviceId);
|
row.setDeviceId(deviceId);
|
||||||
@@ -480,6 +491,65 @@ class TaskCenterQueryServiceTest {
|
|||||||
assertEquals(0L, second.getShopCount());
|
assertEquals(0L, second.getShopCount());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void collectDataRowWithoutSnapshotUsesKeywordProgress() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
TaskCenterTaskRow row = taskRow(1L, "COLLECT_DATA", "RUNNING", now, now);
|
||||||
|
row.setTotalCount(1L);
|
||||||
|
row.setSuccessCount(0L);
|
||||||
|
|
||||||
|
stubPage(List.of(row));
|
||||||
|
when(queryMapper.selectSnapshots(any())).thenReturn(List.of());
|
||||||
|
when(queryMapper.selectCollectDataKeywordStats(List.of(1L)))
|
||||||
|
.thenReturn(List.of(collectStatsRow(1L, "60", "12")));
|
||||||
|
stubPublishShops(List.of());
|
||||||
|
stubFileResultShops(List.of());
|
||||||
|
|
||||||
|
TaskCenterTaskRowVo vo = item(service.tasks(superScope(), new TaskCenterTaskQuery()), 1L);
|
||||||
|
|
||||||
|
assertEquals(60L, vo.getProgressTotal(), "总 = 关键词数(与客户端「关键词进度:第 X/N 个」同源)");
|
||||||
|
assertEquals(12L, vo.getProgressSuccess(), "已完成 = 已处理关键词数,不是输入文件数");
|
||||||
|
assertEquals(0L, vo.getProgressFailed());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void modulesWithoutClientProgressBarHaveNoFallbackCount() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
TaskCenterTaskRow priceTrack = taskRow(1L, "PRICE_TRACK", "RUNNING", now, now);
|
||||||
|
priceTrack.setTotalCount(1L);
|
||||||
|
priceTrack.setSuccessCount(0L);
|
||||||
|
TaskCenterTaskRow shopMatch = taskRow(2L, "SHOP_MATCH", "RUNNING", now, now);
|
||||||
|
shopMatch.setTotalCount(1L);
|
||||||
|
|
||||||
|
stubPage(List.of(priceTrack, shopMatch));
|
||||||
|
when(queryMapper.selectSnapshots(any())).thenReturn(List.of());
|
||||||
|
stubPublishShops(List.of());
|
||||||
|
stubFileResultShops(List.of());
|
||||||
|
|
||||||
|
TaskCenterTaskPageVo page = service.tasks(superScope(), new TaskCenterTaskQuery());
|
||||||
|
|
||||||
|
assertEquals(0L, item(page, 1L).getProgressTotal(), "跟价客户端没进度条 → 不回退文件数,前端画「—」");
|
||||||
|
assertEquals(0L, item(page, 2L).getProgressTotal(), "定时匹配同理");
|
||||||
|
verify(queryMapper, never()).selectCollectDataKeywordStats(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void collectDataWithoutStatsPayloadDegradesToNoProgress() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
TaskCenterTaskRow row = taskRow(1L, "COLLECT_DATA", "PENDING", now, now);
|
||||||
|
row.setTotalCount(1L);
|
||||||
|
|
||||||
|
stubPage(List.of(row));
|
||||||
|
when(queryMapper.selectSnapshots(any())).thenReturn(List.of());
|
||||||
|
when(queryMapper.selectCollectDataKeywordStats(List.of(1L))).thenReturn(List.of(
|
||||||
|
collectStatsRow(1L, "abc", null)));
|
||||||
|
stubPublishShops(List.of());
|
||||||
|
stubFileResultShops(List.of());
|
||||||
|
|
||||||
|
assertEquals(0L, item(service.tasks(superScope(), new TaskCenterTaskQuery()), 1L).getProgressTotal(),
|
||||||
|
"脏值/缺字段按无进度处理,不拿文件数兜底");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void shopSourcesDedupeAcrossBothTables() {
|
void shopSourcesDedupeAcrossBothTables() {
|
||||||
LocalDateTime now = LocalDateTime.now();
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|||||||
+57
-7
@@ -6,6 +6,7 @@ import com.nanri.aiimage.modules.notification.client.MaixiangConsoleClient.Batch
|
|||||||
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
import com.nanri.aiimage.modules.taskcenter.mapper.TaskCenterQueryMapper;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterUserRow;
|
import com.nanri.aiimage.modules.taskcenter.model.dto.TaskCenterUserRow;
|
||||||
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterVariantPageVo;
|
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterVariantPageVo;
|
||||||
|
import com.nanri.aiimage.modules.taskcenter.model.vo.TaskCenterVariantTaskVo;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
import org.mockito.InjectMocks;
|
import org.mockito.InjectMocks;
|
||||||
@@ -29,7 +30,8 @@ import static org.mockito.Mockito.when;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 变体采集页签的 Java 侧口径:可见用户 → uid 集合(逗号拼接、排序稳定)、
|
* 变体采集页签的 Java 侧口径:可见用户 → uid 集合(逗号拼接、排序稳定)、
|
||||||
* 分页归一化、uid → 账号名映射、麦象不可达/未配置时返回空页。
|
* 分页归一化、uid → 账号名映射、麦象不可达/未配置时返回空页;
|
||||||
|
* 不传 status = 只看在跑(等待 0 ∪ 处理中 1 合并,历史终态不进默认口径)。
|
||||||
*/
|
*/
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
class TaskCenterVariantServiceTest {
|
class TaskCenterVariantServiceTest {
|
||||||
@@ -52,6 +54,11 @@ class TaskCenterVariantServiceTest {
|
|||||||
resMes, "{\"file_url\": \"https://oss.aishufu.top/a.xlsx\"}");
|
resMes, "{\"file_url\": \"https://oss.aishufu.top/a.xlsx\"}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static BatchTaskItem item(String taskId, String uid, int status, String resMes, LocalDateTime createTime) {
|
||||||
|
return new BatchTaskItem(taskId, "variant-collection", uid, status,
|
||||||
|
createTime, createTime, resMes, "{\"file_url\": \"https://oss.aishufu.top/a.xlsx\"}");
|
||||||
|
}
|
||||||
|
|
||||||
private static TaskCenterUserRow userRow(Long id, String username) {
|
private static TaskCenterUserRow userRow(Long id, String username) {
|
||||||
TaskCenterUserRow row = new TaskCenterUserRow();
|
TaskCenterUserRow row = new TaskCenterUserRow();
|
||||||
row.setUserId(id);
|
row.setUserId(id);
|
||||||
@@ -106,17 +113,58 @@ class TaskCenterVariantServiceTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void superAdminPassesNoUidFilterAndDefaultPaging() {
|
void superAdminWithoutStatusSeesOnlyActiveMergedFromBothStatuses() {
|
||||||
when(consoleClient.configured()).thenReturn(true);
|
when(consoleClient.configured()).thenReturn(true);
|
||||||
when(consoleClient.batchTasksPage(isNull(), isNull(), eq("variant-collection"), eq(1), eq(20)))
|
when(consoleClient.batchTasksPage(isNull(), eq(0), eq("variant-collection"), eq(1), eq(200)))
|
||||||
.thenReturn(BatchTaskPage.EMPTY);
|
.thenReturn(new BatchTaskPage(1, List.of(item("t-wait", "5", 0, "已添加至任务队列,等待执行"))));
|
||||||
|
when(consoleClient.batchTasksPage(isNull(), eq(1), eq("variant-collection"), eq(1), eq(200)))
|
||||||
|
.thenReturn(new BatchTaskPage(2, List.of(item("t-run", "5", 1, "已采集 12 条"))));
|
||||||
|
when(queryMapper.selectUsernames(List.of(5L))).thenReturn(List.of(userRow(5L, "ali")));
|
||||||
|
|
||||||
TaskCenterVariantPageVo page = service.variantTasks(superScope(), null, null, null, null);
|
TaskCenterVariantPageVo page = service.variantTasks(superScope(), null, null, null, null);
|
||||||
|
|
||||||
assertEquals(0, page.getItems().size());
|
assertEquals(3, page.getTotal(), "不传 status = 在跑(等待+处理中)之和,不再是历史全量 106");
|
||||||
|
assertEquals(2, page.getItems().size());
|
||||||
assertEquals(1, page.getPage());
|
assertEquals(1, page.getPage());
|
||||||
assertEquals(20, page.getPageSize());
|
assertEquals(20, page.getPageSize());
|
||||||
verify(queryMapper, never()).selectUsernames(any());
|
assertEquals("等待执行", page.getItems().get(0).getStatusLabel());
|
||||||
|
verify(consoleClient, never()).batchTasksPage(any(), isNull(), any(), anyInt(), anyInt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeMergeSortsByCreateTimeDescAndSlicesPages() {
|
||||||
|
when(consoleClient.configured()).thenReturn(true);
|
||||||
|
when(consoleClient.batchTasksPage(isNull(), eq(0), any(), eq(1), eq(200)))
|
||||||
|
.thenReturn(new BatchTaskPage(2, List.of(
|
||||||
|
item("t-old", "5", 0, "等待", LocalDateTime.of(2026, 10, 4, 1, 0)),
|
||||||
|
item("t-mid", "5", 0, "等待", LocalDateTime.of(2026, 10, 4, 2, 0)))));
|
||||||
|
when(consoleClient.batchTasksPage(isNull(), eq(1), any(), eq(1), eq(200)))
|
||||||
|
.thenReturn(new BatchTaskPage(1, List.of(
|
||||||
|
item("t-new", "5", 1, "处理中", LocalDateTime.of(2026, 10, 4, 3, 0)))));
|
||||||
|
|
||||||
|
TaskCenterVariantPageVo first = service.variantTasks(superScope(), null, null, 1, 2);
|
||||||
|
assertEquals(List.of("t-new", "t-mid"),
|
||||||
|
first.getItems().stream().map(TaskCenterVariantTaskVo::getTaskId).toList(),
|
||||||
|
"两个状态合并后按创建时间倒序,不是先等待后处理中的拼接序");
|
||||||
|
TaskCenterVariantPageVo second = service.variantTasks(superScope(), null, null, 2, 2);
|
||||||
|
assertEquals(List.of("t-old"),
|
||||||
|
second.getItems().stream().map(TaskCenterVariantTaskVo::getTaskId).toList());
|
||||||
|
TaskCenterVariantPageVo beyond = service.variantTasks(superScope(), null, null, 3, 2);
|
||||||
|
assertEquals(0, beyond.getItems().size(), "越界页给空列表");
|
||||||
|
assertEquals(3, beyond.getTotal(), "total 不随空页归零");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void activeTotalFallsBackToItemCountWhenMaixiangTotalIsSentinel() {
|
||||||
|
when(consoleClient.configured()).thenReturn(true);
|
||||||
|
when(consoleClient.batchTasksPage(isNull(), eq(0), any(), eq(1), eq(200)))
|
||||||
|
.thenReturn(new BatchTaskPage(-1, List.of(item("t-1", "5", 0, "等待"))));
|
||||||
|
when(consoleClient.batchTasksPage(isNull(), eq(1), any(), eq(1), eq(200)))
|
||||||
|
.thenReturn(new BatchTaskPage(-1, List.of()));
|
||||||
|
|
||||||
|
TaskCenterVariantPageVo page = service.variantTasks(superScope(), null, null, 1, 20);
|
||||||
|
|
||||||
|
assertEquals(1, page.getTotal(), "-1 哨兵不能把在跑数算成负数");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -133,10 +181,12 @@ class TaskCenterVariantServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
void nonNumericUidAndUnknownStatusDegradeGracefully() {
|
void nonNumericUidAndUnknownStatusDegradeGracefully() {
|
||||||
when(consoleClient.configured()).thenReturn(true);
|
when(consoleClient.configured()).thenReturn(true);
|
||||||
when(consoleClient.batchTasksPage("5", null, "variant-collection", 1, 20))
|
when(consoleClient.batchTasksPage("5", 0, "variant-collection", 1, 200))
|
||||||
.thenReturn(new BatchTaskPage(3, List.of(
|
.thenReturn(new BatchTaskPage(3, List.of(
|
||||||
item("t-1", "collect-27475", 0, "已添加至任务队列,等待执行"),
|
item("t-1", "collect-27475", 0, "已添加至任务队列,等待执行"),
|
||||||
item("t-2", "5", 9, ""))));
|
item("t-2", "5", 9, ""))));
|
||||||
|
when(consoleClient.batchTasksPage("5", 1, "variant-collection", 1, 200))
|
||||||
|
.thenReturn(BatchTaskPage.EMPTY);
|
||||||
when(queryMapper.selectUsernames(List.of(5L))).thenReturn(List.of(userRow(5L, "ali")));
|
when(queryMapper.selectUsernames(List.of(5L))).thenReturn(List.of(userRow(5L, "ali")));
|
||||||
|
|
||||||
TaskCenterVariantPageVo page = service.variantTasks(scoped(5L), null, null, 1, 20);
|
TaskCenterVariantPageVo page = service.variantTasks(scoped(5L), null, null, 1, 20);
|
||||||
|
|||||||
@@ -0,0 +1,478 @@
|
|||||||
|
# 多公司(租户)改造设计
|
||||||
|
|
||||||
|
> 日期:2026-10-04 状态:**待审** 决策确认:brainstorm 流程(用户逐条拍定)
|
||||||
|
> 适用范围:`crawler-plugin/backend-java` + `crawler-plugin/admin-frontend-vue`(后台 admin-vue)+ `crawler-plugin/frontend-vue`(用户端 app-web)
|
||||||
|
> **不修改** `app_client`(Python 桌面端零改动,见 §2.4)
|
||||||
|
> 关联:`backend-java/docs/flyway-migration-template.md`、`backend-java/docs/migration-inventory.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 一句话结论
|
||||||
|
|
||||||
|
一期只做**账号归属**:新建 `company` 主表、给 `users` 挂 `company_id`、现有全部账号归属「厦门米椿花」。
|
||||||
|
业务表**一张不碰、一行不回填**——57 张表里 26 张带 `user_id`,公司维度全部由 `user_id → users.company_id` 派生。
|
||||||
|
唯一索引、登录定位、89 个数据过滤出口**一律不动**,因此一期对线上行为是零变化。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 现状取证(每条均可复查)
|
||||||
|
|
||||||
|
### 1.1 现有「公司」字样全是紫鸟语义,不可复用
|
||||||
|
|
||||||
|
| 位置 | 语义 |
|
||||||
|
|---|---|
|
||||||
|
| `biz_ziniao_memory_store.company_name`(`V8__add_company_name_to_ziniao_memory_store.sql`) | 紫鸟 ERP 侧浏览器配置文件的公司,自由文本、无外键 |
|
||||||
|
| `biz_publish_file.company_name`(`V77__publish_task.sql:12`) | 同上,快照字段 |
|
||||||
|
| `ZiniaoProperties.companyId` / `ClientCredentialProperties.ziniaoCompany` | 紫鸟自动化账号所属公司 |
|
||||||
|
|
||||||
|
读写点仅 `modules/ziniao/memory/service/ZiniaoMemoryStoreService.java:129-151`、`ZiniaoShopIndexService.java:219/329`。
|
||||||
|
**全库无 company / tenant / organization 主表**,`biz_shop_manage` 也没有公司列。新建 `company` 表不与上述任何字段冲突,但命名上必须避免歧义:新表叫 `company`,紫鸟那两个字段保持原名不动。
|
||||||
|
|
||||||
|
### 1.2 没有任何框架级租户机制
|
||||||
|
|
||||||
|
`TenantLineHandler`、`DataPermissionInterceptor`、`MetaObjectHandler`、`@InterceptorIgnore` —— **全仓 0 命中**。
|
||||||
|
隔离靠 service 层手写 wrapper:
|
||||||
|
|
||||||
|
- `.eq/.in(Entity::getUserId, …)` 共 **89 处**,分布在 **34 个文件**
|
||||||
|
- 构成:`userId`(方法参数)**77 处**、`request.getUserId()` **8 处**、集合式(`allowedUserIds`/`uniqueIds`/`createdById`)**3 处**、`createdById` **1 处**
|
||||||
|
- 热点两张表吃掉一半:`FileTaskEntity` 25 处、`FileResultEntity` 19 处
|
||||||
|
- 另有约 **125 处**其他归属口径的引用(`created_by_id`、`"user:"+id` 字符串、`group_id`)——这是 grep 命中数,**不全是过滤条件**,二期逐个接入口时要重新按"是否构成数据范围判定"分类,不能直接当工作量
|
||||||
|
- 「admin 看全部 / normal 看自己」的角色判定在 `common/security/DeviceSessionPolicy.java:26-36 resolveRole()`,经 `AdminAuthSupport.java:104-119` 暴露;`super_admin` 分支散在 **27 个文件、219 处**
|
||||||
|
- 唯一的统一工具 `modules/permission/support/UserDataScopeSupport.java:33` 只服务 3 个模块,且带 `FALLBACK_LIMIT = 2000` 兜底
|
||||||
|
- 并行存在 5 套各自实现的 scope(9 个文件、37 处引用):`TaskCenterScopeService`、`DedupeTotalDataService`、`ShopDataCrawlAdminTasksService`、`ShopDataDuplicateCheckQueryService`、`UserDataScopeSupport`
|
||||||
|
|
||||||
|
### 1.3 请求体里的 `user_id` 不校验归属
|
||||||
|
|
||||||
|
`validateUserId` 只判 `> 0`,**不判是不是登录人本人**:
|
||||||
|
|
||||||
|
- `modules/patroldelete/service/PatrolDeleteResolveService.java:244-248`
|
||||||
|
- `modules/similarasin/service/SimilarAsinTaskService.java:1679-1683`
|
||||||
|
|
||||||
|
controller 原样透传 `request.getUserId()`(`patroldelete`/`pricetrack`/`productrisk`/`shopdatacrawl`/`shopmatch`/`similarasin`/`withdraw` 七个模块均如此)。
|
||||||
|
|
||||||
|
`config/AdminApiGuardFilter.java` 的 `USER_TOOL_PREFIXES` 列了 **14 个用户态前缀**(`/api/patrol-delete`、`/api/price-track`、`/api/similar-asin`、`/api/withdraw`、`/api/shop-match`、`/api/product-risk-resolve`、`/api/shop-data-crawl`、`/api/query-asin`、`/api/appearance-patent`、`/api/brand`、`/api/files`、`/api/digital-human`、`/api/collect-data`、`/api/tasks`),受 `aiimage.security.user-tool-guard-enabled` 控制,**默认 `false` = 匿名可达**(`AdminApiGuardFilter.java:128`)。
|
||||||
|
|
||||||
|
客户端确实带 `X-Internal-Token`(`app_client/amazon/tool.py:32 internal_token_or_empty()`),但那是**共享静态密钥**,过滤器注释自己写明「能证明走了内部通道,证明不了这个 user_id 是谁」(`AdminApiGuardFilter.java:48`)。
|
||||||
|
→ **这 14 个前缀上的公司隔离,在阶段B(设备令牌)落地前无法真正强制。** 见 §7.3。
|
||||||
|
|
||||||
|
### 1.4 登录链路按 username 单列定位
|
||||||
|
|
||||||
|
- `modules/auth/service/AuthService.java:94` —— `selectOne(eq(username))`,依赖 `users.username` 的**全局唯一索引**
|
||||||
|
- `AuthService.java:50-78` —— 登录失败锁定 map 的 key 是**裸 `username`**
|
||||||
|
- `LoginResultVo.java:11-23` —— 改造前返回 `userId/username/role/isAdmin/deviceId/token/expiresIn/appColumns/adminColumns`,**无公司**(本轮按 §4 加了 `companyId`:16 / `companyName`:18)
|
||||||
|
- `JwtService.issue()` claims 只有 `subject(userId)` / `username` / `deviceId`
|
||||||
|
- 前端两套登录态机制不同:**用户端 `frontend-vue` 无 Pinia**,登录态存 localStorage(`shared/auth/ensure-auth.ts` 的 `AUTH_TOKEN_KEY = 'aiimage_auth_token'`,`uid`/`username` 由 `ensureAuth()` 与 `restoreLoginUser()` 两个函数各自回写),`shared/api/user.ts` 的 `getCurrentUserId()` 直接读 `localStorage.uid`;**后台 `admin-frontend-vue` 是 Pinia**(`src/stores/admin-session.ts` 的 `defineStore('admin-session')`),用户信息走 `src/api/session.ts` 的 `fetchCurrentUser()` → `/api/admin/current-user`
|
||||||
|
- `/api/admin/current-user` 的返回体是 `AdminConsoleController.java:70-77` 里**手搭的 `Map<String,Object>`**(`id`/`username`/`role`/…),不是 VO 类 → 后台顶栏要显示公司名,改的是这个 Map,**不是** `LoginResultVo`
|
||||||
|
|
||||||
|
### 1.5 `users` 表映射了两个实体
|
||||||
|
|
||||||
|
`common/model/entity/AdminUserEntity.java` 与 `modules/auth/model/entity/LoginUserEntity.java` **都** `@TableName("users")`。加列必须同步改两处,漏一处就是半边链路读不到公司。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 一期范围
|
||||||
|
|
||||||
|
### 2.1 数据模型(V143)
|
||||||
|
|
||||||
|
见 §3 迁移全文。要点:
|
||||||
|
|
||||||
|
- `company` 主表,`company_name` 唯一
|
||||||
|
- `users.company_id BIGINT NOT NULL DEFAULT 1` + 索引
|
||||||
|
- **业务表零 DDL**
|
||||||
|
|
||||||
|
### 2.2 建号:公司必选,超管可指定
|
||||||
|
|
||||||
|
规则与现有 `createdById` 完全同构(`AdminUserService.java:161-175`:超管可指定创建人,非超管强制落自己名下):
|
||||||
|
|
||||||
|
| 操作者 | `companyId` 传了 | 不传 |
|
||||||
|
|---|---|---|
|
||||||
|
| `super_admin` | 落指定公司(校验公司存在且启用) | 落自己所属公司 |
|
||||||
|
| `admin`(公司内) | **只允许等于自己所属公司**,否则 403 | 落自己所属公司 |
|
||||||
|
| `normal` | 不可建号(现状即如此:`POST /api/admin/user` 需管理员 + `admin_users` 菜单,`AdminUserService.java:136-140`) | — |
|
||||||
|
|
||||||
|
`AdminUserService.createUser` **永远显式写入** `company_id`,不依赖列 DEFAULT。DEFAULT 只为混合版本窗口存在(§8.2)。
|
||||||
|
|
||||||
|
**前端比后端严**:新后台的建号弹窗对超管**必须显式选一家**(`validateCreateUserForm(form, operator)`),
|
||||||
|
而后端对"不传"仍落操作者自己公司。这不是矛盾——后端那条口径是给尚未升级的旧后台兜底的(§5.3),
|
||||||
|
超管手里同时有 N 家公司时"静默落我自己那家"是危险默认。别把前端的必选当成冗余逻辑删掉。
|
||||||
|
|
||||||
|
移人(改账号所属公司):一期**仅超管**可做,且必须校验不变式——账号的 `created_by_id` 必须与自己同公司或为超管,否则拒绝。这条不变式是二期省掉逐个改 77 处过滤点的前提(§7.2)。
|
||||||
|
|
||||||
|
### 2.3 公司目录接口
|
||||||
|
|
||||||
|
新建 `modules/company/`:
|
||||||
|
|
||||||
|
| 方法 | 路径 | 权限 |
|
||||||
|
|---|---|---|
|
||||||
|
| GET | `/api/admin/companies` | 超管列全部;公司内 admin 只列自己公司 |
|
||||||
|
| POST | `/api/admin/companies` | 仅超管 |
|
||||||
|
| PUT | `/api/admin/companies/{id}` | 仅超管(改名 / 启停) |
|
||||||
|
|
||||||
|
**不做删除**:有账号挂着的公司删不掉,用 `status=0` 停用代替。
|
||||||
|
菜单权限走现有口径:`columns` 表插 `admin_companies`,controller 用 `permissionMenuService.hasAnyAdminMenu(operator, List.of("admin_companies"))`(同 `AdminUserService.java:466-470`)。
|
||||||
|
|
||||||
|
账号列表(`AdminUserService.listUsers`)一期加 `companyId` **可选**筛选参数:超管可筛任意公司,admin 只能筛自己公司(传别家公司 → 视为无结果,不报错也不越权)。不传时行为与现状完全一致。若你只要"列表显示公司列"而不要筛选,去掉这个参数即可,其余设计不受影响(见 §9.3)。
|
||||||
|
|
||||||
|
### 2.4 登录态与前端显示公司名
|
||||||
|
|
||||||
|
- `LoginResultVo` + `check_login` 返回 `companyId` / `companyName`
|
||||||
|
- **JWT 不加 claim**:`AdminAuthSupport.requireUser()` 每次都 `selectById` 回库,公司随实体自然带出;加 claim 反而要处理旧 token 无该 claim 的兼容
|
||||||
|
- 前端两个部署物都要动(后台建号表单 + 公司目录在 `admin-frontend-vue`,用户端顶栏显示公司名在 `frontend-vue`),逐文件清单见 §5
|
||||||
|
- **`app_client` 零改动**:桌面端窗口直载线上 app-web,前端发布即全端生效,无客户端版本碎片化
|
||||||
|
|
||||||
|
### 2.5 一期明确不做
|
||||||
|
|
||||||
|
| 推迟项 | 触发条件 |
|
||||||
|
|---|---|
|
||||||
|
| `users.username` 唯一索引 → `(company_id, username)` | 第二家公司开通时 |
|
||||||
|
| 登录定位改造 + 锁定 key 改造 | 同上(两者必须同批,见 §7.1) |
|
||||||
|
| 89 个数据过滤出口叠公司边界 | 同上 |
|
||||||
|
| 14 个用户态前缀的越权收口 | 阶段B 设备令牌落地 |
|
||||||
|
| 跨公司汇总 / 对比报表 | 用户已明确一期不要 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. V143 迁移
|
||||||
|
|
||||||
|
**正文以 `backend-java/src/main/resources/db/V143__company_and_users_company_id.sql` 为准**(已由
|
||||||
|
`CompanyMigrationV143Test` 12 例 + 16 条变异自证钉住),本节只记不落进代码就丢失的决策。
|
||||||
|
语句顺序共六步:建表 → 插初始公司 → 加列与索引 → 回填 → 收 NOT NULL 闸门 → 插后台菜单。
|
||||||
|
|
||||||
|
| 决策 | 为什么 |
|
||||||
|
|---|---|
|
||||||
|
| 初始公司 `id` 显式钉为 1 | `users.company_id` 的 DEFAULT 只能是字面量(MySQL 不允许 DEFAULT 子查询),回填也写死 `= 1`。id 交给 AUTO_INCREMENT,这两处就会指向一个不存在的公司 |
|
||||||
|
| 加列 → 回填 → 再 `MODIFY NOT NULL`,不是一步建成 NOT NULL | `MODIFY ... NOT NULL` 本身就是自检闸门:回填漏任何一行就抛 `ER_INVALID_USE_OF_NULL` 让迁移失败,而不是留一堆 NULL 静默通过(NULL = 该账号在公司维度整体失明) |
|
||||||
|
| 闸门留 `DEFAULT 1` | 只为混合版本窗口存在,见 §8.2;摘除时机由 §6.3 的启动期巡检盯,不在迁移里处理 |
|
||||||
|
| 每条语句都写成幂等(`IF NOT EXISTS` / `INSERT IGNORE` / 查 `information_schema` 后 `PREPARE` / `WHERE` 限定 / `NOT EXISTS` 守卫) | MySQL 的 DDL 不进事务。迁移中途失败时前面的语句已落库,而 §8.1 的恢复步骤(补数据 → `flyway repair` → 重启)会让 Flyway **从第一条语句重跑整个文件**;写成裸 `CREATE TABLE` / 裸 `INSERT ... VALUES`,恢复路径自己会撞 1050/1060/1062,把"补数据后重启"变成"必须手工清库" |
|
||||||
|
| 菜单 `sort_order` 按同级 `MAX+5` 自算 | 现有子菜单的 sort_order 来自初始数据、从未被任何迁移设定过,写字面量等于猜 |
|
||||||
|
| 菜单 `route_path = 'account/companies'`、`column_key = 'admin_companies'` | 真正的跨产物契约是 **`column_key` 必须在 `admin-frontend-vue/src/router/routes.ts` 登记为 `menuKey`**:侧边栏跳转、面包屑与路由门禁都按 key 关联,且 `menu-route-map.ts` 会用注册表算出的规范路径**覆盖**库里的 `route_path`——所以 `route_path` 写错并不会 404,没登记 menuKey 才会。两边都按现有值保持一致,由 `admin-frontend-vue/tests/company-menu-route.test.ts` 逐条核对;`columns.column_key` 上有 `uk_column_key`,非幂等插入会直接报错 |
|
||||||
|
| 回滚是 `backend-java/docs/rollback-V143-company.sql`,**不是一条 V144 迁移** | 见 §8.3 |
|
||||||
|
|
||||||
|
条件 DDL 的写法照 V142(本仓首例),幂等插菜单照 V103/V106。
|
||||||
|
|
||||||
|
> 菜单与公司表放同一条迁移,是因为取号存在真实争用风险(V138/V139/V140 已被其他计划占用,见 `migration-inventory.md`),一条迁移少占一个号。
|
||||||
|
|
||||||
|
**验证 SQL**
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT COUNT(*) AS company_rows FROM company; -- 期望 1
|
||||||
|
SELECT id, company_name, status FROM company; -- 期望 1 | 厦门米椿花 | 1
|
||||||
|
SELECT COUNT(*) AS users_total,
|
||||||
|
SUM(company_id IS NULL) AS null_company,
|
||||||
|
SUM(company_id = 1) AS in_xiamen_michunghua
|
||||||
|
FROM users; -- 期望 null_company=0 且 users_total=in_xiamen_michunghua
|
||||||
|
SHOW COLUMNS FROM users LIKE 'company_id'; -- 期望 Null=NO, Default=1
|
||||||
|
SHOW INDEX FROM users WHERE Key_name = 'idx_users_company_id'; -- 期望 1 行
|
||||||
|
SELECT c.id, c.name, c.column_key, c.route_path, c.sort_order, p.column_key AS parent_key
|
||||||
|
FROM columns c LEFT JOIN columns p ON p.id = c.parent_id
|
||||||
|
WHERE c.column_key = 'admin_companies'; -- 期望 1 行,parent_key=admin_group_account
|
||||||
|
```
|
||||||
|
|
||||||
|
同步更新 `backend-java/docs/migration-inventory.md`:文件数 141→142、范围 V1..V142→V1..V143、最新版本行、取号起点 V143→V144。审计测试 `MigrationInventoryTest` 会校验整数版本从 1 连续到最大值(`RETIRED_HOLES = {132,133}` 除外)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 后端改动清单
|
||||||
|
|
||||||
|
| 文件 | 改动 |
|
||||||
|
|---|---|
|
||||||
|
| `common/model/entity/AdminUserEntity.java` | +`companyId` |
|
||||||
|
| `modules/auth/model/entity/LoginUserEntity.java` | +`companyId`(§1.5:两个实体都映射 users,必须同改) |
|
||||||
|
| `modules/company/`(新建) | `CompanyEntity` / `CompanyMapper` / `CompanyService` / `CompanyController`;`CompanyService` 除目录读写外还有三条只读口径:`requireActive`(准入)、`namesByIds`(批量显示名,不做权限判定)、`nameOrEmpty`(单条显示名,查不到回空串) |
|
||||||
|
| `modules/admin/service/AdminUserService.java` | `createUser` 写 `companyId`(§2.2 规则);`update` 支持超管移人 + 不变式校验;`listUsers` 加 `companyId` 可选筛选 + 批量取公司名 |
|
||||||
|
| `modules/admin/controller/AdminUserController.java` | `GET /api/admin/users` +`@RequestParam(name = "company_id")` |
|
||||||
|
| `modules/admin/model/vo/AdminUserItemVo.java` | +`company_id` / `company_name`(前端账号列的数据源,snake_case 与其余字段同规则) |
|
||||||
|
| `modules/admin/model/dto/*` | 建号/改号请求 +`companyId` |
|
||||||
|
| `modules/auth/model/vo/LoginResultVo.java` | +`companyId` / `companyName`(**用户端** app-web 走这条) |
|
||||||
|
| `modules/admin/controller/AdminConsoleController.java:76-77` | `current-user` 的手搭 Map +`companyId` / `companyName`(**后台** admin-vue 顶栏走这条,见 §1.4) |
|
||||||
|
| `modules/auth/service/AuthService.java` | `login` 与 `checkLogin` 回填公司名(**不改** username 定位逻辑) |
|
||||||
|
| 启动期巡检 | `modules/company/service/CompanyDefaultGuard.java`(新建):`company` 表 >1 行 **且** `users.company_id` 仍带 DEFAULT → `log.error` 带 ASCII 标记 `COMPANY_DEFAULT_STILL_PRESENT`,探针自身失败降级为 `COMPANY_DEFAULT_PROBE_FAILED` 的 WARN(不许静默当成"查过了")。`scripts/_prod_watch.py` 的 `SIGNATURES` 收第一条并计入 ALERTS(§6.3) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 前端改动清单
|
||||||
|
|
||||||
|
**两个前端是两个独立部署物,别混**:后台是 `admin-frontend-vue`(部署为 admin-vue),用户端是 `frontend-vue`(构建到 `new_web_source/`,部署为 app-web,桌面客户端窗口直载它)。建号表单和公司目录在**后台**,"用户登录后看到公司名"在**用户端**。
|
||||||
|
|
||||||
|
### 5.1 `admin-frontend-vue`(后台)
|
||||||
|
|
||||||
|
| 文件 | 改动 |
|
||||||
|
|---|---|
|
||||||
|
| `src/router/routes.ts` | 注册 `{ path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', load: () => import('@/pages/account/CompaniesPage.vue') }`——`menuKey` 必须与菜单的 `column_key` 一致(否则菜单点进去 404,见 §3),`path` 与库里 `route_path` 保持一致 |
|
||||||
|
| `src/pages/account/CompaniesPage.vue`(新建) | 公司列表 + 新建 + 改名/启停 |
|
||||||
|
| `src/api/companies.ts`(新建,配 `-dto.ts`/`-model.ts`) | 按 `src/api/users.ts` 的现有 DTO/model 分层写,不另发明一套 |
|
||||||
|
| `src/pages/account/UsersPage.vue` | 建号表单加公司下拉(必选,超管可选任意公司、admin 锁死自己公司);列表加公司列与筛选 |
|
||||||
|
| `src/api/users-dto.ts` / `users-model.ts` / `users.ts` | +`companyId` / `companyName` |
|
||||||
|
| `src/api/session.ts` + `src/stores/admin-session.ts` | **不改**:`fetchCurrentUser` 直接把 `/api/admin/current-user` 的 `item` 当 `AdminUser` 用(`session.ts:6`),不经解析器,所以 `companyId`/`companyName` 自动落到对象上;顶栏 `AdminLayout.vue:35` 的 `topbarUserOf(session.user)` 读它即可 |
|
||||||
|
| `src/types/admin.ts` | `AdminUser` 类型 +`companyId`/`companyName` |
|
||||||
|
| `src/layout/topbar-model.ts` + `AdminLayout.vue` | 顶栏显示当前公司名 |
|
||||||
|
|
||||||
|
### 5.2 `frontend-vue`(用户端 app-web)
|
||||||
|
|
||||||
|
| 文件 | 改动 |
|
||||||
|
|---|---|
|
||||||
|
| `src/shared/api/user.ts` | `LoginData` +`companyId` / `companyName` |
|
||||||
|
| `src/shared/auth/company-identity.ts`(新建) | 公司名的 localStorage 读写:后端没带 `companyName` 就删键,避免换账号后残留上一个账号的公司 |
|
||||||
|
| `src/shared/auth/ensure-auth.ts` | `check_login` 恢复登录态时一并回写公司名(该文件原本只恢复 `uid`/`username`,见 `:25-39`) |
|
||||||
|
| `src/pages/login/DesktopLoginPage.vue` | 登录成功后写入公司名;`?logout=1 / ?switch=1` 那段清登录态时**连 `company_name` 一起清**(原本只清 token/uid/username) |
|
||||||
|
| `src/shared/auth/kick-handler.ts` | 被顶下线(`handleKicked`)时连 `company_name` 一起清,与 uid/username 同一批 |
|
||||||
|
| `src/pages/amazon/components/AmazonTopBar.vue` | 顶栏用户名左侧显示公司名;为空则整段不渲染 |
|
||||||
|
|
||||||
|
### 5.3 发布耦合
|
||||||
|
|
||||||
|
`admin-frontend-vue` 与后端 jar **不必同批**——因为 §2.2 把 `companyId` 做成"缺省 = 操作者所属公司",旧后台建号仍然可用(落操作者自己公司)。这是刻意的设计,目的就是消掉 §8.2 那个混合版本窗口。
|
||||||
|
`frontend-vue` 同理可独立发布:后端未返回 `companyName` 时顶栏不显示该段即可,不要写成 `undefined`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 护栏与验收
|
||||||
|
|
||||||
|
### 6.1 建号必写 company_id
|
||||||
|
|
||||||
|
用例:建号后断言落库行的 `company_id` 等于期望值(超管指定 / admin 落自己公司 / admin 指定他司被拒)。
|
||||||
|
**变异自证**:把 `entity.setCompanyId(...)` 删掉,用例必须红——若仍绿说明用例在验 DEFAULT 而不是验代码,等于没验。
|
||||||
|
|
||||||
|
### 6.2 公司边界不变式
|
||||||
|
|
||||||
|
`AdminUserMoveCompanyTest` 8 例(建号那批用例见 §6.1;移人写进 `AdminUserService.updateUser`):
|
||||||
|
|
||||||
|
| 用例 | 钉住的行为 |
|
||||||
|
|---|---|
|
||||||
|
| `movingAloneIsAValidEdit` | 只传 `companyId`、不改密码/角色/权限,也是合法编辑(原代码的"请提供要修改的内容"会把这种请求打回) |
|
||||||
|
| `moveIsRefusedWhenTheCreatorLivesInAnotherCompany` | 创建人在第三家公司 ⇒ 403 且**一条 UPDATE 都不发** |
|
||||||
|
| `creatorSuperAdminIsExemptFromTheCompanyMatch` | 创建人是超管 ⇒ 不受同公司约束 |
|
||||||
|
| `onlySuperAdminMayMoveAccounts` | 公司内 admin 传别家公司 ⇒ 403,不静默改写 |
|
||||||
|
| `namingTheCurrentCompanyIsNotAMove` | 传的正好是账号现属公司按"没动"处理,照常改密码(幂等请求不该被判越权) |
|
||||||
|
| `destinationCompanyMustExistAndBeActive` | 目标公司先 `requireActive` 再落库 |
|
||||||
|
| `danglingCreatorBlocksTheMove` | `created_by_id` 悬空(创建人已删)⇒ 无法确认同公司,不移 |
|
||||||
|
| `nullCreatedByIdMovesWithoutComplaint` | `created_by_id` 本来就空 ⇒ 没有冲突可校验,照移 |
|
||||||
|
|
||||||
|
不变式内容:**账号被移进 X 公司后,它的 `created_by_id` 要么仍是 X 公司的人,要么是超管**。
|
||||||
|
这条是 §7.2 里"77 处 `eq(getUserId, userId)` 无需逐个改"的前提,破口就得回到逐出口补边界那条路。
|
||||||
|
|
||||||
|
一期**没做移人的前端入口**:账号列表只有公司列 + 超管筛选(§5.1),移人是后台手工动作,
|
||||||
|
接口 `PUT /api/admin/user` 的 `companyId` 字段已就绪,UI 留给二期和公司目录一起出。
|
||||||
|
|
||||||
|
> 踩过的坑(写下一条同类用例前先看):`LambdaUpdateWrapper.getSqlSegment()` **只含 WHERE**,
|
||||||
|
> SET 子句在 `getSqlSet()` 里。最初四条断言打在 `getSqlSegment()` 上,实际拿到的是
|
||||||
|
> `(id = #{ew.paramNameValuePairs.MPGENVAL2})`——"改了哪一列"这一整组断言恒假红,
|
||||||
|
> 而"没移人不许带 company_id"那条恒绿。断"这次真的写了哪一列"只能取 `getSqlSet()`。
|
||||||
|
|
||||||
|
### 6.3 DEFAULT 摘除告警(防「半套发布」)
|
||||||
|
|
||||||
|
`users.company_id DEFAULT 1` 是**临时**的,只为混合版本窗口存在。第二家公司开通后若不摘除,此后每个不显式传公司的建号都会被静默塞进厦门米椿花。
|
||||||
|
启动期巡检:`SELECT COUNT(*) FROM company` > 1 **且** `users.company_id` 仍有 DEFAULT → 打 ERROR(纳入 `_prod_watch.py` 巡检 ALERTS)。用代码执行,不写进注释。
|
||||||
|
|
||||||
|
`CompanyDefaultGuard`(`@EventListener(ApplicationReadyEvent.class)`)8 例:
|
||||||
|
|
||||||
|
| 用例 | 钉住的行为 |
|
||||||
|
|---|---|
|
||||||
|
| `secondCompanyWithDefaultStillOnShoutsError` | 2 家公司 + DEFAULT="1" ⇒ ERROR 带 `COMPANY_DEFAULT_STILL_PRESENT` 与公司数 |
|
||||||
|
| `singleCompanyKeepsQuiet` | 只有一家公司时 DEFAULT 是发布期故意留的(§8.2),不许喊 |
|
||||||
|
| `droppedDefaultKeepsQuiet` | `COLUMN_DEFAULT` 为 null ⇒ 已摘除,一声不响 |
|
||||||
|
| `blankDefaultCountsAsDropped` | 空串/空白也按"已摘除"处理 |
|
||||||
|
| `noCompanyAtAllKeepsQuiet` | 0 家公司时**连列都不去查**(短路顺序也是断言对象) |
|
||||||
|
| `probeFailureIsAnnouncedNotSwallowed` | 探针抛错 ⇒ WARN 带 `COMPANY_DEFAULT_PROBE_FAILED`,不许静默读成"检查过了" |
|
||||||
|
| `probeReadsTheRightColumn` | 捕获真实 SQL,必须探 `information_schema.COLUMNS` 的 `'users'` / `'company_id'`(表名列名写错等于没探) |
|
||||||
|
| `guardRunsWhenTheApplicationIsReady` | 反射断 `checkOnStartup` 上挂着 `@EventListener(ApplicationReadyEvent.class)`——漏注解这哨兵永远不跑 |
|
||||||
|
|
||||||
|
两个标记串故意用 **ASCII**:巡检是靠 `docker logs | grep -aiE` 匹配的,中文一旦在容器里变了编码整条签名静默失效。
|
||||||
|
`scripts/_prod_watch.py` 的 `SIGNATURES` 增 `('公司DEFAULT未摘', 'COMPANY_DEFAULT_STILL_PRESENT', True)`(第 12 条,实跑 `scripts/tests` 全绿)。
|
||||||
|
`COMPANY_DEFAULT_PROBE_FAILED` 故意**不**进 ALERTS:生产 MySQL 账号本就缺 `information_schema` 读权限(见运维要点),把它做成告警只会变成常驻噪声;它出现在 WARN 里,人工核查时看得到。
|
||||||
|
|
||||||
|
### 6.4 迁移自检
|
||||||
|
|
||||||
|
`MODIFY ... NOT NULL` 本身即闸门(§3)。
|
||||||
|
文件层护栏落在 `backend-java/src/test/java/com/nanri/aiimage/config/CompanyMigrationV143Test.java`
|
||||||
|
(12 例,逐条标注它防的是哪个破坏点;断言打在**剥掉注释后的可执行 SQL** 上,避免"注释里写了这句话就算通过"):
|
||||||
|
版本号与撞号、头注释六项、`uk_company_name` 唯一、初始公司 id 钉死为 1、只允许 ALTER `users` 一张表、
|
||||||
|
回填与闸门的先后、DEFAULT 仍在、菜单幂等与 `route_path`/父级、可重跑性、回滚在扫描路径之外、
|
||||||
|
盘点文档三个数字与取号起点。变异自证 16 条(脚本注入缺陷 → 指定期望用例必须红 → 用注入前读进内存的字节还原)。
|
||||||
|
变异清单:去 `IF NOT EXISTS`、去 `IGNORE`、把 `IF(@col_exists=0)` 改成无条件执行、初始公司 id 改 7、
|
||||||
|
去掉 INSERT 的 `id` 列、删掉回填 UPDATE、把 NOT NULL 闸门提到回填之前、去掉闸门的 `DEFAULT 1`、
|
||||||
|
`uk_company_name` 降级成普通索引、去掉菜单的 `NOT EXISTS`、`route_path` 改错、父级分组改错、
|
||||||
|
给 `biz_shop_manage` 也加 `company_id`、把回滚写成 `V144__rollback_company.sql` 放进 `src/main/resources/db/`、
|
||||||
|
盘点文档取号起点不跟着改、盘点文档文件数不跟着改。
|
||||||
|
另跑 `MigrationInventoryTest` 确认版本连续、命名合规、历史校验和未变。
|
||||||
|
|
||||||
|
### 6.5 公司目录:读写收窄与出厂一致性(§2.3)
|
||||||
|
|
||||||
|
后端 4 个测试类共 26 例(`mvn -o test -Dtest="Company*Test"`):
|
||||||
|
|
||||||
|
| 测试类 | 例数 | 钉住的行为 |
|
||||||
|
|---|---|---|
|
||||||
|
| `CompanyServiceDirectoryTest` | 17 | 超管列全部(**不带任何查询条件**)、公司内 admin 只列自己公司、无角色与无公司归属一律 403、`admin_companies` 菜单闸门、写接口仅超管、名称 trim + 唯一(改名校验排除自身)+ 不超列宽、备注不超列宽、状态只能是 0/1 |
|
||||||
|
| `CompanyControllerEndpointTest` | 5 | 每个 handler 先 `requireAdminOrInternal` 再碰目录(`InOrder` 断言调用次序)、路由与后台前端逐字一致、**不暴露 DELETE**、列表返回 VO 而非实体、写接口回保存后的公司 |
|
||||||
|
| `CompanyVoTest` | 1 | 过真 `ObjectMapper` 序列化,键名恰好 `id/company_name/status/remark/created_at/updated_at`,日期 `yyyy-MM-dd HH:mm`、空日期出 `""` |
|
||||||
|
| `CompanyServiceRequireActiveTest` | 3 | `requireActive`(§2.2 那批用例):本轮只把构造器补到 3 参,断言未动 |
|
||||||
|
|
||||||
|
前端 2 个文件共 15 例:`tests/company-user-list.test.ts`(7,含一条**反向排他**——解析器读到 camelCase `companyId/companyName` 必须忽略,防止前后端各猜一套)、`tests/company-user-create.test.ts`(8)。
|
||||||
|
|
||||||
|
实跑证据(2026-10-04 04:45–05:11;日志文件属 `target/` 产物,收尾已删,下面的数字取自当轮回显):
|
||||||
|
`baseline: 26 例全绿` → 16 条变异 **16/16 KILLED**(每条都打印了它红的那一例)→
|
||||||
|
`restore check: all files byte-identical to pre-injection`(三个文件还原后 sha1 与注入前逐字节一致)→
|
||||||
|
`SURVIVORS/PROBLEMS: 0`、`PY_RC=0`。
|
||||||
|
|
||||||
|
16 条变异自证(脚本注入缺陷 → 指定的那几例必须红 → 用**注入前读进内存的字节**还原,不许 `git checkout`):
|
||||||
|
`admin-directory-loses-own-company-filter`、`super-admin-directory-also-filtered`、`admin-without-company-falls-back-to-all`、
|
||||||
|
`menu-gate-removed`、`role-gate-removed`、`super-admin-write-gate-removed`、`company-name-not-trimmed`、
|
||||||
|
`duplicate-name-check-removed`、`duplicate-check-includes-self`、`status-range-check-removed`、`name-length-check-removed`、
|
||||||
|
`remark-length-check-removed`、`vo-loses-snake-case-name`、`controller-create-skips-auth`、
|
||||||
|
`controller-gets-a-delete-endpoint`、`controller-route-typo`。
|
||||||
|
|
||||||
|
两条踩过的坑,留给后续同类用例:
|
||||||
|
|
||||||
|
- **断言要打在"有没有带值的条件"上,不是打在列名上**。`company` 表压根没有 `company_id` 列,最初写的
|
||||||
|
`getSqlSegment()).contains("company_id")` 一条恒假、配套的"超管不带条件"一条恒真,两条一起绿等于没断言。
|
||||||
|
改成 `getParamNameValuePairs()).isEmpty()`(超管)对 `containsValue(2L)`(公司内 admin)。
|
||||||
|
另两个 API 坑:`Wrapper` 不暴露 `getParamNameValuePairs()`,捕获类型必须是 `LambdaQueryWrapper`;
|
||||||
|
且要先碰一次 `getSqlSegment()` 参数才会被铺出来。MP 3.5.7 的 `insert`/`updateById` 有 `Collection` 重载,
|
||||||
|
`any()` 有歧义,必须写 `any(CompanyEntity.class)`。
|
||||||
|
- **变异脚本每轮开跑前要把所有被注入的文件写回 pristine**(实测两批都栽了)。第一版只在 `finally` 里统一还原,
|
||||||
|
于是每轮只重写"本轮那个文件":第 13 轮改 `CompanyVo` 时,第 12 轮改 `CompanyService` 的缺陷还留在盘上,
|
||||||
|
红名单里混进上一轮的用例 ⇒ 日志里"红名单共 N 例"这个数字整批失真。
|
||||||
|
16 条 KILLED 本身仍可采信,因为**每条变异期望红的那一例都只在自己那一轮出现**(已按用例名做过归因矩阵);
|
||||||
|
但要是两轮期望的用例同名,就会被静默假判 KILLED。脚本已补上"逐轮回写 pristine"。
|
||||||
|
- **变异脚本的锚点在 Windows 上要先对齐行尾**。源码是 CRLF,`decode("utf-8")` 不转换行尾,锚串里的 `\n`
|
||||||
|
会 0 命中 ⇒ 注入静默失败 ⇒ 那一轮"没红"会被误读成"变异存活"。脚本因此加了 `align()` 和
|
||||||
|
`--check-anchors` 预检(16 条锚点全部 hits=1 才开跑)。
|
||||||
|
|
||||||
|
### 6.6 第二批变异自证:登录态、移人、启动哨兵、列表公司列
|
||||||
|
|
||||||
|
覆盖 §2.4(登录/current-user 带出公司身份)、§6.2(移人不变式)、§6.3(DEFAULT 哨兵)、§2.3(列表公司列与筛选),
|
||||||
|
被注入的 7 个类共 **39 例**(首轮 37 例,补进 2 例后 39 例)。脚本 `target/mutation_company_phase2.py`,表内 29 条变异
|
||||||
|
(条目数由 AST 数出,不是手数),开跑前 `anchor pre-check: 29/29 锚点各命中 1 次`。
|
||||||
|
|
||||||
|
首轮实跑(2026-10-04 06:02–06:47,日志 `target/mutation_phase2.log`):
|
||||||
|
|
||||||
|
```
|
||||||
|
baseline: 37 例全绿(报告 7 份,rc=0)
|
||||||
|
SUMMARY: 25/28 KILLED, SURVIVED=2 ['names-by-ids-loses-dedupe', 'move-gate-for-company-admin-removed'],
|
||||||
|
INCONCLUSIVE=1 ['move-only-request-rejected-as-empty-edit'], restore_ok=True
|
||||||
|
PY_RC=1
|
||||||
|
```
|
||||||
|
|
||||||
|
三条问题全部是**用例侧/脚本侧**的洞,不是实现有缺陷(实现一行没改):
|
||||||
|
|
||||||
|
- `names-by-ids-loses-dedupe` 存活:`AdminUserListCompanyTest` 把 `CompanyService` 整个 mock 掉了,
|
||||||
|
捕获的是**调用方传出去的参数**,永远摸不到 `namesByIds` 内部的去重。全仓 grep 证明没有任何用例用**真实对象**
|
||||||
|
调过这个方法 ⇒ 这条被注释宣称的护栏从未被证明过。修法:`CompanyServiceNameLookupTest`(真实 `CompanyService`
|
||||||
|
+ mock mapper)补 2 例——重复 id 折成一次查询且 `IN` 参数每家公司只出现一遍(用 `in(col, coll)` 每元素一个
|
||||||
|
MPGENVAL 参数来钉去重)、空列表与 `null` 一条 SQL 都不发。
|
||||||
|
- `move-gate-for-company-admin-removed` 存活:断言写的是 `contains("公司")`,而"移人闸门"与"创建人同公司不变式"
|
||||||
|
两条 403 文案**都含"公司"**——删掉闸门后仍由后者抛 403,用例"因为错的原因过"。修法:两条断言各钉自己的文案
|
||||||
|
(`contains("超级管理员")` / `contains("创建人")`)。
|
||||||
|
- `move-only-request-rejected-as-empty-edit` INCONCLUSIVE:变异串本身不是合法 Java(整行替换成 `)` 丢了 `{`
|
||||||
|
⇒ 花括号失衡 ⇒ 编译失败 ⇒ 压根没有报告)。4 次尝试全 rc=1 且无 `TEST-*.xml` 即为此症。修法:替换串保留花括号。
|
||||||
|
|
||||||
|
修补后只复跑受影响的 4 条(06:53–07:00,`target/mutation_phase2b.log`,`--only` 过滤后"表内 29 条,本轮跳过 25 条"):
|
||||||
|
|
||||||
|
```
|
||||||
|
baseline: 39 例全绿(报告 7 份,rc=0)
|
||||||
|
[04] names-by-ids-loses-dedupe KILLED red=1/39 期望红=命中=batchLookupSendsEachCompanyIdOnce
|
||||||
|
[05] names-by-ids-queries-on-empty-input KILLED red=1/39 期望红=命中=batchLookupOnEmptyInputSkipsTheTable
|
||||||
|
[11] move-only-request-rejected-as-empty-edit KILLED red=5/39 期望红=命中=movingAloneIsAValidEdit
|
||||||
|
[13] move-gate-for-company-admin-removed KILLED red=1/39 期望红=命中=onlySuperAdminMayMoveAccounts
|
||||||
|
SUMMARY: 4/4 KILLED, SURVIVED=0, INCONCLUSIVE=0, restore_ok=True(表内 29 条,本轮跳过 25 条)
|
||||||
|
PY_RC=0
|
||||||
|
```
|
||||||
|
|
||||||
|
两个 7 文件的还原读数(首轮与复跑一致,sha256 前 12 位与注入前逐项相同):`CompanyService.java`
|
||||||
|
`93513896eb9a`、`AuthService.java` `d35d7715b509`、`AdminConsoleController.java` `9102c2967947`、
|
||||||
|
`AdminUserService.java` `cf1d200c49ee`、`CompanyDefaultGuard.java` `2900ed07c35c`、`AdminUserItemVo.java`
|
||||||
|
`8ee2c28e9c9f`、`AdminUserController.java` `5849f9b48b39`,全部 `byte-identical`。
|
||||||
|
复跑后 `13` 那轮的红名单恰好只有 `onlySuperAdminMayMoveAccounts` 一例——这本身就是"断言收紧后只咬它自己那条闸门"的证据。
|
||||||
|
|
||||||
|
29 条变异清单:`name-or-empty-queries-on-null-id`、`name-or-empty-throws-when-company-missing`、
|
||||||
|
`name-or-empty-hides-disabled-company`、`names-by-ids-loses-dedupe`、`names-by-ids-queries-on-empty-input`、
|
||||||
|
`login-loses-company-name`、`login-loses-company-id`、`login-gates-on-company-active`、
|
||||||
|
`current-user-company-key-snake-cased`、`current-user-drops-company-identity`、
|
||||||
|
`move-only-request-rejected-as-empty-edit`、`same-company-naming-treated-as-a-move`、
|
||||||
|
`move-gate-for-company-admin-removed`、`move-target-company-existence-unchecked`、`creator-invariant-check-removed`、
|
||||||
|
`super-admin-creator-not-exempted`、`null-creator-blocks-the-move`、`move-does-not-write-the-column`、
|
||||||
|
`admin-cross-company-filter-falls-through`、`super-admin-filter-adds-no-condition`、
|
||||||
|
`unknown-company-row-crashes-the-item`、`empty-page-still-asks-for-names`、`item-vo-company-name-loses-snake-case`、
|
||||||
|
`company-filter-param-becomes-required`、`guard-threshold-off-by-one`、`guard-treats-blank-default-as-dropped`、
|
||||||
|
`guard-probe-failure-is-swallowed`、`guard-never-runs-on-startup`、`guard-probes-the-wrong-column`。
|
||||||
|
|
||||||
|
新增一条规矩(第一条就栽过):**变异点落在被 mock 掉的依赖内部,用例必然咬不住**。判存活时先怀疑 mock 边界,
|
||||||
|
再怀疑脚本;这类护栏要用真实对象另建一组用例,注释里写"已覆盖"不作数。
|
||||||
|
|
||||||
|
### 6.7 全量回归
|
||||||
|
|
||||||
|
`mvn test`(不许 skipTests、主树禁 clean):**2026-10-04 07:09 全量实跑 `Tests run: 3589, Failures: 0, Errors: 0, Skipped: 7`,`BUILD SUCCESS`,耗时 04:52**(日志 `target/mvn_full.log`,收尾已删)。
|
||||||
|
+ `scripts/tests`(2026-10-04 06:12 实跑 **155 passed**,设计文档早前写的 137 已过期)+ `admin-frontend-vue` 的 `npm test`(06:25 复跑 **1678/1678**,RC=0)+ `frontend-vue` 的 `npm test`(06:20 复跑 **672/672**,RC=0,含本轮新增的下线清键 1 例)+ 两个前端各自的 `npm run build`(build 脚本自带 `vue-tsc --noEmit`,`frontend-vue` 06:21 RC=0,`admin-frontend-vue` 06:35 RC=0)。
|
||||||
|
**这一轮全量绿是在「本批公司改动 + 另一批未提交的 task-center 改动」的同一棵工作区树上跑出来的**,提交只含前者。
|
||||||
|
两者互不依赖已逐个取证:task-center 那 8 个改动/新增的 java 文件里 `compan` 关键词逐个文件命中 0 行(逐文件 `grep -ci`,不是全树一次过),本批改动的文件零引用 `taskcenter`;
|
||||||
|
本批唯一改签名的方法 `AdminUserService.listUsers`(加 `companyIdFilter` 形参)在 HEAD 与工作区都只有
|
||||||
|
`AdminUserController` 一个调用方,而它就在同一笔提交里;其余改动是纯增字段。
|
||||||
|
提交子集本身没有单独再跑一遍 mvn(约 5 分钟),要更硬的证据可在干净 HEAD worktree 上只叠本批重跑。
|
||||||
|
**e2e 没跑**:`admin-frontend-vue` 的 Playwright 用例(`e2e/*.spec.ts`,`npm run test:browser`)要起着前端与后端才成立,本轮未起服务,公司目录页也没有对应 spec——这一条是缺口,不是已通过项。
|
||||||
|
SFC 那一行清键(`DesktopLoginPage.vue` 的登出/切号分支)没有自动化用例覆盖:`handleKicked` 那条有,另一条靠人肉读代码确认。
|
||||||
|
既有红按差分读,不当回归:客户端批量测试有 8 例既有红、task_220 有 3 例既有红(已用干净 HEAD worktree 证实)。
|
||||||
|
门禁不要与 Nuitka 打包并行跑(计时用例会假红)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 二/三期路线(已定案的口径,防止丢失)
|
||||||
|
|
||||||
|
### 7.1 唯一索引与登录(必须同批)
|
||||||
|
|
||||||
|
`users.username` 唯一索引 → `UNIQUE (company_id, username)`。一旦允许跨公司同名:
|
||||||
|
|
||||||
|
1. `AuthService.java:94` 的 `selectOne(eq(username))` 会抛 `TooManyResultsException`,**登录全站挂** → 改为按 username 查列表,命中 1 条放行、多条要求指定公司(`LoginRequest` 加 `company`)。缺省不带公司时行为与现状完全一致。
|
||||||
|
2. `AuthService.java:50-78` 锁定 key 从裸 `username` 改为 `companyId|username`。否则新公司建个同名账号反复错密码,就能把厦门米椿花的真人锁在门外——**跨租户 DoS,不是可选优化**。
|
||||||
|
|
||||||
|
这两条与索引切换必须同一次发版,任何一条滞后都是线上事故。
|
||||||
|
|
||||||
|
### 7.2 数据隔离(方案②:中央 scope + 逐出口接入 + 护栏)
|
||||||
|
|
||||||
|
- `CompanyScopeSupport`:`currentCompanyId(user)` / `memberUserIds(companyId)` / `assertSameCompany(...)`;`role=super_admin` 豁免(**按 role 判,不按 company_id 判**)
|
||||||
|
- 需要叠公司边界的是**范围大于一人**的出口:5 套并行 scope(9 文件 37 处)、27 文件 219 处 super_admin 分支中「看全部」的部分、3 处集合式过滤、`AdminUserService.listUsers` 超管分支
|
||||||
|
- 77 处 `eq(getUserId, userId)` 由 §2.2 的 `created_by_id` 同公司不变式覆盖,**无需逐个改**
|
||||||
|
- 护栏:AST/正则扫描——对公司归属表的 `getUserId` 过滤若未走 scope 即红;变异自证(把 `in` 改回 `eq`、删掉超管豁免,必须被抓到)
|
||||||
|
- 不给业务表冗余 `company_id`:与「数据按账号归属、公司维度跟着账号走」的定案相反。若日后 `IN (成员列表)` 在热表上撑不住,再单独议是否给那两三张表冗余
|
||||||
|
|
||||||
|
### 7.3 14 个用户态前缀的越权收口
|
||||||
|
|
||||||
|
`user-tool-guard-enabled` 默认 false(§1.3)。打开前必须先逐端点审计客户端是否带令牌,漏审一个就是线上集采/跟价全线 401——这正是当初把开关默认设成 false 的原因。
|
||||||
|
且共享静态内部令牌**证明不了 user_id 是谁**,所以真正的公司隔离要等阶段B 设备令牌。建议与阶段B 绑成同一张工单。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 风险与回滚
|
||||||
|
|
||||||
|
### 8.1 迁移失败
|
||||||
|
|
||||||
|
`MODIFY ... NOT NULL` 抛错 → Flyway 标记该版本 failed,应用启动失败。恢复:补齐漏掉的行,`flyway repair` 清 failed 记录后重启。**不要**手工改 V143 文件内容(校验和会变)。
|
||||||
|
|
||||||
|
这条恢复路径成立的前提是 **V143 每条语句都可重跑**:DDL 失败时前面的语句已经落库,repair 后 Flyway 会从文件第一条重新执行。所以建表带 `IF NOT EXISTS`、种子行 `INSERT IGNORE`、`ADD COLUMN` 先查 `information_schema` 再 `PREPARE`(§3)。若写成裸语句,重启会在恢复路上撞 1050/1060/1062,只剩"手工清库"一条路——这也是 `CompanyMigrationV143Test.migrationIsRerunnableAfterPartialFailure` 存在的理由。
|
||||||
|
|
||||||
|
### 8.2 混合版本窗口(这是 DEFAULT 存在的唯一理由)
|
||||||
|
|
||||||
|
发布期间一台已上新 jar、另一台仍是旧 jar,而 `/api` 经主机 B 的 clb 打到两台。旧 jar 的 `AdminUserService.create` 不给 `company_id` 赋值:
|
||||||
|
|
||||||
|
- 列若为 `NOT NULL` 无 DEFAULT → 严格模式报 `Field 'company_id' doesn't have a default value`,**打到旧节点的建号请求全失败**(约一半)
|
||||||
|
- 列有 `DEFAULT 1` → 旧节点建号成功并落厦门米椿花。一期只有一家公司,这个结果**是正确的**,不是 bug
|
||||||
|
|
||||||
|
两台同版后,新代码永远显式写 `company_id`,DEFAULT 变成死重——但必须在第二家公司开通前摘除(§6.3 用代码盯住这件事)。
|
||||||
|
|
||||||
|
### 8.3 回滚
|
||||||
|
|
||||||
|
补丁脚本 `backend-java/docs/rollback-V143-company.sql`,**不是一条 V144 迁移**——版本化迁移放进 `src/main/resources/db/` 就会被 Flyway 在下次启动时自动执行,那等于把 V143 静默撤销掉,还会让 `MigrationInventoryTest` 的版本连续性断言跟着变。执行顺序(停两台应用 → 跑脚本 → 删 `flyway_schema_history` 的 143 行 → 回退 jar → 起应用)写在脚本头部;漏掉删历史那步,将来重装带 V143 的 jar 时 Flyway 判定"已应用"直接跳过,表和列都不会重建,而 Java 侧实体照常读写 `company_id` ⇒ 运行期 unknown column。
|
||||||
|
回滚窗口内已建的账号会连 `company_id` 一起丢,业务数据不受影响(业务表从未加列)。
|
||||||
|
这条"回滚不进 Flyway 扫描路径"的口径连同上一条"迁移必须可重跑",一并写进了 `backend-java/docs/migration-inventory.md` 的「约束」段,供后续所有迁移引用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 待确认(一期按下列默认口径已实现,若要改请在此推翻)
|
||||||
|
|
||||||
|
1. **不加 `company_code`**。一期没有任何消费点:目录页、建号下拉、顶栏显示全都用 `company_name`。
|
||||||
|
二期登录定位若真遇到跨公司同名账号,让用户在"先选公司"的下拉里挑比记短码更直观,短码只会多一处唯一索引 + 录入校验。
|
||||||
|
2. **两端都显示公司名**——后台 `AdminLayout.vue` 用户名下方一行、用户端 `AmazonTopBar.vue` 用户名左侧,均已在做(§5.1/§5.2)。
|
||||||
|
两处都是"后端没带 `companyName` 就整段不渲染",不显示 `undefined`。
|
||||||
|
3. **既显示列,也支持筛选**(§2.3 口径已实现)。筛选下拉**仅超管可见**:公司内 admin 的读接口已被后端收窄到本公司,
|
||||||
|
给它一个只能选到自己公司的筛选框是假功能。
|
||||||
|
4. **公司内 admin 一期仍只看自己名下 1 层账号**(`AdminUserService.java:92-102` 现状不变:列表的非超管分支只放行「自己」或「自己创建的 normal」)。
|
||||||
|
一期定案是"业务代码零改动",把可见范围放宽与 89 处数据出口叠公司边界放到同一批(§7.2);
|
||||||
|
因此公司目录页对 admin 只显示自己这一家,**不承诺**"看见本公司全部账号"。
|
||||||
@@ -38,7 +38,8 @@
|
|||||||
展示名回落 `device_log_file`(V127)
|
展示名回落 `device_log_file`(V127)
|
||||||
- 店铺库:`biz_shop_manage`(`shop_name` 唯一、`created_by_id` 归组,无软删列)
|
- 店铺库:`biz_shop_manage`(`shop_name` 唯一、`created_by_id` 归组,无软删列)
|
||||||
- 逐店落行的结果文件:`biz_file_result.source_filename`(仅 6 个模块按店铺建行)
|
- 逐店落行的结果文件:`biz_file_result.source_filename`(仅 6 个模块按店铺建行)
|
||||||
- 进度口径:`biz_task_progress_snapshot` 优先,文件计数兜底
|
- 进度口径:`biz_task_progress_snapshot` 优先;无快照按模块分档(采集=关键词数、上架/删除ASIN/品牌=文件数、
|
||||||
|
其余=无进度),见「进度口径」节
|
||||||
- 麦象 console:`MaixiangConsoleClient`(复用,token 查询参数鉴权)
|
- 麦象 console:`MaixiangConsoleClient`(复用,token 查询参数鉴权)
|
||||||
|
|
||||||
## 数据口径
|
## 数据口径
|
||||||
@@ -116,10 +117,15 @@ COLLECT_DATA / SIMILAR_ASIN / APPEARANCE_PATENT / BRAND 这些不落店铺,面
|
|||||||
|
|
||||||
1. `biz_task_progress_snapshot`(task_id + module_type)优先:total/success/failed/pending +
|
1. `biz_task_progress_snapshot`(task_id + module_type)优先:total/success/failed/pending +
|
||||||
`current_scope_key` + `message`;
|
`current_scope_key` + `message`;
|
||||||
2. 无快照 → `biz_file_task` 文件计数(source/success/failed_file_count);
|
2. BRAND 行 → `brand_crawl_tasks.progress_current/progress_total`;
|
||||||
3. BRAND → `brand_crawl_tasks.progress_current/progress_total`。
|
3. 无快照的采集数据(COLLECT_DATA)→ `biz_file_task.result_json` 的 `$.totalRows / $.processedRows`,
|
||||||
|
与客户端「关键词进度:第 X/N 个」同一份数、同一比值口径(SQL 侧只抽这两列,大 JSON 不出库);
|
||||||
|
4. 无快照的上架 / 删除ASIN → 行内文件计数(客户端进度条单位本就是文件);
|
||||||
|
5. 其余无快照模块(跟价、定时匹配…)→ 进度置 0,**不回退文件数**:客户端在这些模块没有进度条,
|
||||||
|
而单文件任务回退成「已完成 0 / 总 1」会被读成"一步没跑",是误导。
|
||||||
|
|
||||||
前端展示「成功 X / 总 Y(失败 Z)」+ 百分比进度条。
|
前端展示「已完成 X / 总 Y(失败 Z 徽标)」+ 百分比进度条;`progressTotal ≤ 0` 时只显示「—」,
|
||||||
|
不画 0% 空进度轨(空轨="进度 0%",与"这里没有进度可看"是两件事)。
|
||||||
|
|
||||||
### 「是否正常在跑」判定
|
### 「是否正常在跑」判定
|
||||||
|
|
||||||
@@ -162,7 +168,7 @@ SQL 用 `@Select` 注解 mapper + 手写 LIMIT/OFFSET 分页(先例 `ImageVide
|
|||||||
| `GET /api/admin/task-center/shop-options` | 店铺筛选候选:`biz_shop_manage` 去重店铺名(`LIMIT 2000`,只取 `shop_name` 一列,不带 account/password/zn_username) |
|
| `GET /api/admin/task-center/shop-options` | 店铺筛选候选:`biz_shop_manage` 去重店铺名(`LIMIT 2000`,只取 `shop_name` 一列,不带 account/password/zn_username) |
|
||||||
| `GET /api/admin/task-center/tasks` | 任务列表(分页 + 筛选:page、pageSize、username、moduleType、status、shop、startTime/endTime);字段:id、taskNo、moduleType、moduleLabel、status、userId、username、deviceId、webDevice、shopName、shopCount、createdAt、finishedAt、lastReportAt、progressTotal/progressSuccess/progressFailed、currentScope、message、stuck(`deviceName` 只在详情装配) |
|
| `GET /api/admin/task-center/tasks` | 任务列表(分页 + 筛选:page、pageSize、username、moduleType、status、shop、startTime/endTime);字段:id、taskNo、moduleType、moduleLabel、status、userId、username、deviceId、webDevice、shopName、shopCount、createdAt、finishedAt、lastReportAt、progressTotal/progressSuccess/progressFailed、currentScope、message、stuck(`deviceName` 只在详情装配) |
|
||||||
| `GET /api/admin/task-center/tasks/detail` | 任务详情(参数 `taskNo`,品牌任务为 `brand-<id>`):基础信息 + 进度快照 + 店铺/文件明细 |
|
| `GET /api/admin/task-center/tasks/detail` | 任务详情(参数 `taskNo`,品牌任务为 `brand-<id>`):基础信息 + 进度快照 + 店铺/文件明细 |
|
||||||
| `GET /api/admin/task-center/variant-tasks` | 变体采集列表(代理麦象 console):uid 集合 = 可见用户;page/pageSize + status/taskType 筛选 |
|
| `GET /api/admin/task-center/variant-tasks` | 变体采集列表(代理麦象 console):uid 集合 = 可见用户;page/pageSize + status/taskType 筛选;**不传 status = 只看在跑**(等待 0 ∪ 处理中 1 各拉一页合并,历史终态不再展示) |
|
||||||
|
|
||||||
## 前端页面
|
## 前端页面
|
||||||
|
|
||||||
@@ -178,7 +184,9 @@ SQL 用 `@Select` 注解 mapper + 手写 LIMIT/OFFSET 分页(先例 `ImageVide
|
|||||||
(店铺已删、但任务还在的情形也筛得动);
|
(店铺已删、但任务还在的情形也筛得动);
|
||||||
- 页签一「客户端任务」:表格(账号、店铺、业务、状态、任务ID、开始、最近上报、结束、进度)
|
- 页签一「客户端任务」:表格(账号、店铺、业务、状态、任务ID、开始、最近上报、结束、进度)
|
||||||
+ 详情 `el-drawer`(设备名、当前处理与分组明细只在详情出现;「操作」列已删,任务ID 单元格是详情入口);
|
+ 详情 `el-drawer`(设备名、当前处理与分组明细只在详情出现;「操作」列已删,任务ID 单元格是详情入口);
|
||||||
- 页签二「变体采集」:状态筛选 + 表格(账号、任务号、状态、开始/更新时间、进度文字 res_mes);
|
- 页签二「变体采集」:**只看在跑**——状态下拉三项(在跑=不传 status/等待执行/处理中,历史终态不提供入口),
|
||||||
|
表格(账号、任务号、状态、开始/更新时间、进度文字 res_mes);徽章是在跑条数,麦象单状态拉取上限 200,
|
||||||
|
触顶时服务层记 warn 且翻页尾部会缺行;
|
||||||
- 30s 轮询:`document.hidden` 暂停、卸载清理、手动刷新按钮。
|
- 30s 轮询:`document.hidden` 暂停、卸载清理、手动刷新按钮。
|
||||||
|
|
||||||
注册点:
|
注册点:
|
||||||
|
|||||||
@@ -31,6 +31,7 @@
|
|||||||
<div class="top-right">
|
<div class="top-right">
|
||||||
<NotificationBell />
|
<NotificationBell />
|
||||||
<BrandApiSecretSettingsButton variant="topbar" />
|
<BrandApiSecretSettingsButton variant="topbar" />
|
||||||
|
<span v-if="companyName" class="company-name" :title="`所属公司:${companyName}`">{{ companyName }}</span>
|
||||||
<span class="admin-name">{{ username }}</span>
|
<span class="admin-name">{{ username }}</span>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -45,6 +46,7 @@ import { filterGroupsByPermission, TOOL_GROUPS } from '@/pages/amazon/tool-catal
|
|||||||
import type { VisibleGroup } from '@/pages/amazon/tool-catalog'
|
import type { VisibleGroup } from '@/pages/amazon/tool-catalog'
|
||||||
import { resolvePageHref } from '@/shared/page-prefix'
|
import { resolvePageHref } from '@/shared/page-prefix'
|
||||||
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
|
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
|
||||||
|
import { readCompanyIdentity } from '@/shared/auth/company-identity'
|
||||||
|
|
||||||
const props = withDefaults(
|
const props = withDefaults(
|
||||||
defineProps<{
|
defineProps<{
|
||||||
@@ -61,6 +63,8 @@ const emit = defineEmits<{ change: [key: 'front' | 'ops' | 'logi'] }>()
|
|||||||
const activeCat = computed(() => props.activeCat)
|
const activeCat = computed(() => props.activeCat)
|
||||||
const visibleCats = ref<VisibleGroup[]>(TOOL_GROUPS.map((group) => ({ ...group, tools: [...group.tools] })))
|
const visibleCats = ref<VisibleGroup[]>(TOOL_GROUPS.map((group) => ({ ...group, tools: [...group.tools] })))
|
||||||
const username = ref('admin')
|
const username = ref('admin')
|
||||||
|
/** 所属公司名:后端未返回时为空串,该段整体不渲染(不能显示 undefined)。 */
|
||||||
|
const companyName = ref('')
|
||||||
|
|
||||||
/** 分类 tab 点击回到工具台对应分组 */
|
/** 分类 tab 点击回到工具台对应分组 */
|
||||||
const toolbarHref = resolvePageHref('/new_web_source/amazon-console.html')
|
const toolbarHref = resolvePageHref('/new_web_source/amazon-console.html')
|
||||||
@@ -84,6 +88,7 @@ function underlineStyle(cat: VisibleGroup) {
|
|||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
const localName = typeof window === 'undefined' ? '' : (window.localStorage.getItem('username') || '').trim()
|
const localName = typeof window === 'undefined' ? '' : (window.localStorage.getItem('username') || '').trim()
|
||||||
if (localName) username.value = localName
|
if (localName) username.value = localName
|
||||||
|
companyName.value = readCompanyIdentity()
|
||||||
try {
|
try {
|
||||||
const keys = await getCurrentUserAppColumnKeys()
|
const keys = await getCurrentUserAppColumnKeys()
|
||||||
visibleCats.value = filterGroupsByPermission(TOOL_GROUPS, keys)
|
visibleCats.value = filterGroupsByPermission(TOOL_GROUPS, keys)
|
||||||
@@ -253,6 +258,18 @@ onMounted(async () => {
|
|||||||
flex-shrink: 0;
|
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 {
|
.admin-name {
|
||||||
color: #c8d2e2;
|
color: #c8d2e2;
|
||||||
font-size: 13px;
|
font-size: 13px;
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ import { onMounted, ref, watch } from 'vue'
|
|||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
import { loginWithDevice } from '@/shared/api/user'
|
import { loginWithDevice } from '@/shared/api/user'
|
||||||
import { KICK_NOTICE_KEY } from '@/shared/auth/kick-handler'
|
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 { useVersionUpdate } from '@/shared/composables/useVersionUpdate'
|
||||||
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
import { clearApiSecretCache } from '@/shared/utils/api-secret-store'
|
||||||
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
|
import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue'
|
||||||
@@ -432,6 +433,8 @@ async function submitLogin() {
|
|||||||
/* 忽略 */
|
/* 忽略 */
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 公司名随后端可选返回:没有就删键,顶栏不显示该段(见 shared/auth/company-identity)
|
||||||
|
writeCompanyIdentity(data)
|
||||||
// 登录成功即持久化记住/自动登录凭据(桌面与网页均可,密码 AES 加密落 localStorage)
|
// 登录成功即持久化记住/自动登录凭据(桌面与网页均可,密码 AES 加密落 localStorage)
|
||||||
void saveCredentials(account)
|
void saveCredentials(account)
|
||||||
// 桌面端 Flask cookie 同步已随瘦身下线:登录态只存 localStorage(JWT 走 Bearer),无 cookie 依赖
|
// 桌面端 Flask cookie 同步已随瘦身下线:登录态只存 localStorage(JWT 走 Bearer),无 cookie 依赖
|
||||||
@@ -453,6 +456,7 @@ onMounted(() => {
|
|||||||
window.localStorage.removeItem(AUTH_TOKEN_KEY)
|
window.localStorage.removeItem(AUTH_TOKEN_KEY)
|
||||||
window.localStorage.removeItem('uid')
|
window.localStorage.removeItem('uid')
|
||||||
window.localStorage.removeItem('username')
|
window.localStorage.removeItem('username')
|
||||||
|
window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||||
} catch {
|
} catch {
|
||||||
/* 忽略 */
|
/* 忽略 */
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,9 @@ export interface LoginData {
|
|||||||
token?: string
|
token?: string
|
||||||
userId?: number | string
|
userId?: number | string
|
||||||
username?: string
|
username?: string
|
||||||
|
/** 所属公司(company.id,V143 新增;旧 jar 不返回该字段) */
|
||||||
|
companyId?: number | string
|
||||||
|
companyName?: string
|
||||||
[key: string]: unknown
|
[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 { get } from '@/shared/api/http'
|
||||||
|
import { writeCompanyIdentity } from './company-identity'
|
||||||
|
|
||||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||||
const UID_KEY = 'uid'
|
const UID_KEY = 'uid'
|
||||||
@@ -16,6 +17,8 @@ const UID_KEY = 'uid'
|
|||||||
interface CheckLoginData {
|
interface CheckLoginData {
|
||||||
userId?: number | string
|
userId?: number | string
|
||||||
username?: string
|
username?: string
|
||||||
|
companyId?: number | string
|
||||||
|
companyName?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 确保当前页面具备登录态;返回是否可继续进入页面 */
|
/** 确保当前页面具备登录态;返回是否可继续进入页面 */
|
||||||
@@ -38,6 +41,7 @@ export async function ensureAuth(): Promise<boolean> {
|
|||||||
if (response.data.username) {
|
if (response.data.username) {
|
||||||
window.localStorage.setItem('username', String(response.data.username))
|
window.localStorage.setItem('username', String(response.data.username))
|
||||||
}
|
}
|
||||||
|
writeCompanyIdentity(response.data)
|
||||||
return true
|
return true
|
||||||
} catch {
|
} catch {
|
||||||
// token 失效:清掉本地登录态(跳转交给路由守卫)
|
// token 失效:清掉本地登录态(跳转交给路由守卫)
|
||||||
@@ -74,6 +78,7 @@ export async function restoreLoginUser(): Promise<{ username?: string } | null>
|
|||||||
if (response.data.username) {
|
if (response.data.username) {
|
||||||
window.localStorage.setItem('username', String(response.data.username))
|
window.localStorage.setItem('username', String(response.data.username))
|
||||||
}
|
}
|
||||||
|
writeCompanyIdentity(response.data)
|
||||||
return { username: response.data.username }
|
return { username: response.data.username }
|
||||||
} catch {
|
} catch {
|
||||||
return null
|
return null
|
||||||
|
|||||||
@@ -8,6 +8,8 @@
|
|||||||
* 记住的账号密码保留,手动点一次即可重新登录(此时顶掉对方,最后登录者胜)。
|
* 记住的账号密码保留,手动点一次即可重新登录(此时顶掉对方,最后登录者胜)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { COMPANY_NAME_STORAGE_KEY } from './company-identity.ts'
|
||||||
|
|
||||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||||
const UID_KEY = 'uid'
|
const UID_KEY = 'uid'
|
||||||
const USERNAME_KEY = 'username'
|
const USERNAME_KEY = 'username'
|
||||||
@@ -69,6 +71,7 @@ export function handleKicked(): void {
|
|||||||
storage.removeItem(AUTH_TOKEN_KEY)
|
storage.removeItem(AUTH_TOKEN_KEY)
|
||||||
storage.removeItem(UID_KEY)
|
storage.removeItem(UID_KEY)
|
||||||
storage.removeItem(USERNAME_KEY)
|
storage.removeItem(USERNAME_KEY)
|
||||||
|
storage.removeItem(COMPANY_NAME_STORAGE_KEY)
|
||||||
storage.setItem(AUTO_LOGIN_KEY, '0')
|
storage.setItem(AUTO_LOGIN_KEY, '0')
|
||||||
storage.setItem(KICK_NOTICE_KEY, '1')
|
storage.setItem(KICK_NOTICE_KEY, '1')
|
||||||
} catch {
|
} 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.equal(localStorage.getItem('uid'), '1095')
|
||||||
assert.deepEqual(assigned, [])
|
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