diff --git a/admin-frontend-vue/src/api/companies-dto.ts b/admin-frontend-vue/src/api/companies-dto.ts new file mode 100644 index 000000000..b68651b2a --- /dev/null +++ b/admin-frontend-vue/src/api/companies-dto.ts @@ -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 { + const payload: Record = { companyName: text(draft.companyName).trim() } + if (typeof draft.status === 'number') payload.status = draft.status + payload.remark = trimmedOrNull(draft.remark) + return payload +} diff --git a/admin-frontend-vue/src/api/companies-model.ts b/admin-frontend-vue/src/api/companies-model.ts new file mode 100644 index 000000000..90eb4718e --- /dev/null +++ b/admin-frontend-vue/src/api/companies-model.ts @@ -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 + 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(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(payload) + if (!core || typeof core !== 'object' || Array.isArray(core)) return null + return toCompanyItem(core) +} diff --git a/admin-frontend-vue/src/api/companies.ts b/admin-frontend-vue/src/api/companies.ts new file mode 100644 index 000000000..0f22a5a9d --- /dev/null +++ b/admin-frontend-vue/src/api/companies.ts @@ -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 { + const { data } = await http.get('/api/admin/companies') + return parseCompanyList(data) +} + +export async function createCompany(draft: CompanyDraft): Promise { + const { data } = await http.post('/api/admin/companies', toCompanyPayload(draft)) + return parseCompany(data) +} + +/** 改名 / 启停;后端不做删除,停用即 status=0。 */ +export async function updateCompany(id: number, draft: CompanyDraft): Promise { + const { data } = await http.put(`/api/admin/companies/${id}`, toCompanyPayload(draft)) + return parseCompany(data) +} diff --git a/admin-frontend-vue/src/api/users-dto.ts b/admin-frontend-vue/src/api/users-dto.ts index 8e20a0512..e25b20ff7 100644 --- a/admin-frontend-vue/src/api/users-dto.ts +++ b/admin-frontend-vue/src/api/users-dto.ts @@ -15,6 +15,8 @@ export interface UserListParams { adminId?: number | null /** 角色过滤(''=全部)。 */ role?: string + /** 按所属公司过滤(V143);仅超管用得到——公司内 admin 后端本来就只返回本公司账号。 */ + companyId?: number | null } /** 序列化到 GET /api/admin/users 的查询参数(Java snake_case)。 */ @@ -26,6 +28,7 @@ export interface UserListQuery { created_by_id?: number admin_id?: number role?: string + company_id?: number } /** 用户列表项即 AdminUser(与 Java AdminUserItemVo 字段对齐)。 */ @@ -46,6 +49,12 @@ function finiteInt(value: unknown): number | null { return typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : null } +/** 公司 id 只认正整数:0/负数/NaN 一律当"没筛选",否则会下发一个必然查不到账号的过滤。 */ +function positiveId(value: unknown): number | null { + const id = finiteInt(value) + return id !== null && id > 0 ? id : null +} + /** 归一化分页/筛选参数:页码下限 1、页大小 1..上限,空关键字视为无过滤。 */ export function normalizeUserPageParams(raw: Partial): UserListParams { const page = Math.max(finiteInt(raw.page) ?? USER_PAGE_MIN_PAGE, USER_PAGE_MIN_PAGE) @@ -61,6 +70,7 @@ export function normalizeUserPageParams(raw: Partial): UserListP keyword, createdById: typeof raw.createdById === 'number' ? raw.createdById : null, adminId: typeof raw.adminId === 'number' ? raw.adminId : null, + companyId: positiveId(raw.companyId), role: typeof raw.role === 'string' ? raw.role.trim() || undefined : undefined, } } @@ -72,6 +82,8 @@ export function toUserListQuery(params: UserListParams): UserListQuery { if (params.createdById != null) query.created_by_id = params.createdById if (params.adminId != null) query.admin_id = params.adminId if (params.role) query.role = params.role + const companyId = positiveId(params.companyId) + if (companyId !== null) query.company_id = companyId return query } diff --git a/admin-frontend-vue/src/api/users-model.ts b/admin-frontend-vue/src/api/users-model.ts index b7ac86818..561696585 100644 --- a/admin-frontend-vue/src/api/users-model.ts +++ b/admin-frontend-vue/src/api/users-model.ts @@ -27,6 +27,12 @@ export function toAdminUserItem(raw: unknown): AdminUser | null { if (updatedAt) item.updatedAt = updatedAt const creator = text(r.creator_username) if (creator) item.creatorUsername = creator + // 公司维度只在后端带上时才写键:留 undefined 而不是 null,好让"这版后端没带公司" + // 与"账号确实没归属公司"在页面上是两种可读的状态。 + const companyId = numberOrNull(r.company_id) + if (companyId !== null) item.companyId = companyId + const companyName = text(r.company_name).trim() + if (companyName) item.companyName = companyName const abbr = text(r.pinyin_abbr) if (abbr) item.pinyinAbbr = abbr return item diff --git a/admin-frontend-vue/src/layout/AdminLayout.vue b/admin-frontend-vue/src/layout/AdminLayout.vue index 3e95940f0..bdf3b4fd4 100644 --- a/admin-frontend-vue/src/layout/AdminLayout.vue +++ b/admin-frontend-vue/src/layout/AdminLayout.vue @@ -104,6 +104,9 @@ async function signOut() {
{{ userVm.username }} + + {{ userVm.company }} +
{{ userVm.role }} 退出登录 diff --git a/admin-frontend-vue/src/layout/operation-guides.ts b/admin-frontend-vue/src/layout/operation-guides.ts index 9ad49e3c4..80e2aa0b1 100644 --- a/admin-frontend-vue/src/layout/operation-guides.ts +++ b/admin-frontend-vue/src/layout/operation-guides.ts @@ -29,6 +29,10 @@ export const OPERATION_GUIDES: Record = { text: '用户密钥按账号绑定,列表只展示脱敏值。可对单条立即检测连通性;清空后该用户需要重新配置密钥。', steps: ['筛选用户或状态', '立即检测连通性', '必要时清空'], }, + admin_companies: { + text: '公司决定账号归属:建号时选哪家公司,该账号名下的数据就归哪家公司。公司只做启用/停用,不提供删除——停用后不能再用于新建账号。', + steps: ['查看公司列表', '新建公司', '改名或启停'], + }, admin_dedupe_total_data: { text: '支持按关键词、用户、分组和国家筛选;导入前先确认所选分组,导出会按日期范围生成文件。', steps: ['选择分组', '筛选或导入', '核对并导出'], diff --git a/admin-frontend-vue/src/layout/topbar-model.ts b/admin-frontend-vue/src/layout/topbar-model.ts index 965498cfd..f874ee5f3 100644 --- a/admin-frontend-vue/src/layout/topbar-model.ts +++ b/admin-frontend-vue/src/layout/topbar-model.ts @@ -13,11 +13,18 @@ export function pageTitleOf(title: string | null | undefined): string { export interface TopbarUserViewModel { username: string role: string + /** 所属公司名(V143);后端没带就是空串,模板据此整段不显示,不能渲染出 undefined。 */ + company: string hasUser: boolean } /** 顶部栏用户模型:用户信息或未登录空态统一为可渲染视图模型。 */ export function topbarUserOf(user: AdminUser | null | undefined): TopbarUserViewModel { - if (!user) return { username: '当前用户', role: '', hasUser: false } - return { username: user.username || '当前用户', role: roleLabel(user.role) || user.role || '', hasUser: true } + if (!user) return { username: '当前用户', role: '', company: '', hasUser: false } + return { + username: user.username || '当前用户', + role: roleLabel(user.role) || user.role || '', + company: (user.companyName || '').trim(), + hasUser: true, + } } diff --git a/admin-frontend-vue/src/pages/account/CompaniesPage.vue b/admin-frontend-vue/src/pages/account/CompaniesPage.vue new file mode 100644 index 000000000..7ccc51b2c --- /dev/null +++ b/admin-frontend-vue/src/pages/account/CompaniesPage.vue @@ -0,0 +1,268 @@ + + + + + diff --git a/admin-frontend-vue/src/pages/account/CompanyEditorDialog.vue b/admin-frontend-vue/src/pages/account/CompanyEditorDialog.vue new file mode 100644 index 000000000..1d439bb6d --- /dev/null +++ b/admin-frontend-vue/src/pages/account/CompanyEditorDialog.vue @@ -0,0 +1,89 @@ + + + diff --git a/admin-frontend-vue/src/pages/account/CreateUserDialog.vue b/admin-frontend-vue/src/pages/account/CreateUserDialog.vue index ebbd9b43b..dc95a0df4 100644 --- a/admin-frontend-vue/src/pages/account/CreateUserDialog.vue +++ b/admin-frontend-vue/src/pages/account/CreateUserDialog.vue @@ -1,12 +1,16 @@ - 加载中... + 加载中... - {{ userListEmptyHint() }} + {{ userListEmptyHint() }} @@ -217,7 +249,14 @@ onMounted(loadUsers) - + @@ -374,7 +413,7 @@ h3 { table-layout: fixed; } .user-table-scroll > table { - min-width: 860px; + min-width: 1000px; } .table-scroll th, .table-scroll td { diff --git a/admin-frontend-vue/src/pages/account/user-create-model.ts b/admin-frontend-vue/src/pages/account/user-create-model.ts index 78c315ec6..be7baebba 100644 --- a/admin-frontend-vue/src/pages/account/user-create-model.ts +++ b/admin-frontend-vue/src/pages/account/user-create-model.ts @@ -1,11 +1,20 @@ /** 新建用户表单模型(任务 45):纯逻辑,镜像 Java AdminUserCreateRequest 字段与后端校验。 */ +// 相对路径而非 @/ 别名:本文件被 node --test 直接 import,别名只有 vite 认。 +import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '../../api/companies-dto.ts' + export const CREATE_USERNAME_MIN_LEN = 2 export const CREATE_PASSWORD_MIN_LEN = 6 /** 新建用户可选角色:super_admin 不可由表单创建(后端只收 admin|normal)。 */ export type CreatableUserRole = 'normal' | 'admin' +/** 当前操作者的公司归属(来自 /api/admin/current-user)。 */ +export interface CreateOperatorScope { + role?: string | null + companyId?: number | null +} + export interface CreateUserForm { username: string password: string @@ -14,11 +23,14 @@ export interface CreateUserForm { columnIds: number[] /** 所属管理员 id(超管创建普通账号时可指定,对齐 admin 的 created_by_id)。 */ createdBy?: number | null + /** 所属公司 id(V143)。超管必选;公司内 admin 由后端强制落自己公司。 */ + companyId?: number | null } export interface CreateUserFormErrors { username?: string password?: string + company?: string } /** 发送 POST /api/admin/user 的请求体(与 Java AdminUserCreateRequest camelCase 对齐)。 */ @@ -29,10 +41,11 @@ export interface CreateUserPayload { columnIds: number[] /** 仅 role=normal 且选了所属管理员时发送,与参考 admin.js 的 created_by_id 语义一致。 */ createdById?: number + companyId?: number } export function createEmptyCreateUserForm(): CreateUserForm { - return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null } + return { username: '', password: '', role: 'normal', columnIds: [], createdBy: null, companyId: null } } /** 未知/空白/超管角色一律归一到 normal,与后端 "admin"/"normal" 白名单一致。 */ @@ -40,8 +53,40 @@ export function normalizeCreateRole(role: string | null | undefined): CreatableU return (role || '').trim().toLowerCase() === 'admin' ? 'admin' : 'normal' } -/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填);返回逐字段错误。 */ -export function validateCreateUserForm(form: CreateUserForm): { valid: boolean; errors: CreateUserFormErrors } { +function positiveInt(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : null +} + +/** + * 建号能选哪家公司,口径与后端 AdminUserService#resolveTargetCompanyId 一致: + * 超管 = 全部启用中的公司(后端 requireActive 会拒停用公司); + * 其余角色 = 只有自己也那一家,且不看启停——后端对非超管直接落 operator.companyId、 + * 不校验状态,前端若跟着过滤就会出现「下拉没得选、提交却能建号」的自相矛盾。 + */ +export function selectableCompanies(companies: CompanyItem[], operator: CreateOperatorScope): CompanyItem[] { + const rows = Array.isArray(companies) ? companies : [] + if (operator?.role === 'super_admin') { + return rows.filter((company) => company.status === COMPANY_STATUS_ACTIVE) + } + const own = positiveInt(operator?.companyId) + if (own === null) return [] + return rows.filter((company) => company.id === own) +} + +/** + * 弹窗打开时预选哪家公司:候选只有一个(公司内 admin 的本公司)就落它; + * 多个(超管)返回 null——给超管填默认值等于替他决定账号挂在哪家,这是会写进库的判断。 + */ +export function initialCompanyId(operator: CreateOperatorScope, companies: CompanyItem[]): number | null { + const options = selectableCompanies(companies, operator) + return options.length === 1 ? options[0].id : null +} + +/** 表单校验(镜像后端:用户名≥2、密码≥6、均必填;超管必须显式选公司);返回逐字段错误。 */ +export function validateCreateUserForm( + form: CreateUserForm, + operator?: CreateOperatorScope, +): { valid: boolean; errors: CreateUserFormErrors } { const errors: CreateUserFormErrors = {} const username = (form.username || '').trim() if (!username) { @@ -55,11 +100,15 @@ export function validateCreateUserForm(form: CreateUserForm): { valid: boolean; } else if (password.length < CREATE_PASSWORD_MIN_LEN) { errors.password = `密码至少${CREATE_PASSWORD_MIN_LEN}个字符` } + if (operator?.role === 'super_admin' && positiveInt(form.companyId) === null) { + errors.company = '请选择所属公司' + } return { valid: Object.keys(errors).length === 0, errors } } /** 表单 → 创建请求体:用户名去空格、角色归一、菜单 id 拷贝不共享引用; - * createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义)。 */ + * createdById 仅在 role=normal 且选了所属管理员时携带(对齐 admin.js 的 created_by_id 语义); + * companyId 选了才带,未选时由后端落操作者自己公司。 */ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload { const payload: CreateUserPayload = { username: (form.username || '').trim(), @@ -70,5 +119,7 @@ export function toCreateUserRequest(form: CreateUserForm): CreateUserPayload { if (payload.role === 'normal' && form.createdBy != null) { payload.createdById = form.createdBy } + const companyId = positiveInt(form.companyId) + if (companyId !== null) payload.companyId = companyId return payload } diff --git a/admin-frontend-vue/src/pages/account/users-filter.ts b/admin-frontend-vue/src/pages/account/users-filter.ts index 128e8bcc6..3745bbd44 100644 --- a/admin-frontend-vue/src/pages/account/users-filter.ts +++ b/admin-frontend-vue/src/pages/account/users-filter.ts @@ -9,18 +9,27 @@ export interface UserFilterState { createdByAdminId: number | null /** 角色过滤(''=全部;super_admin/admin/normal)。 */ role: string + /** 按所属公司过滤(null=全部);只有超管能用,公司内 admin 看到的本来就是本公司。 */ + companyId: number | null page: number pageSize: number } export function createUserFilterState(): UserFilterState { - return { keyword: '', createdByAdminId: null, role: '', page: USER_PAGE_MIN_PAGE, pageSize: USER_PAGE_DEFAULT_SIZE } + return { + keyword: '', + createdByAdminId: null, + role: '', + companyId: null, + page: USER_PAGE_MIN_PAGE, + pageSize: USER_PAGE_DEFAULT_SIZE, + } } /** 修改筛选条件时重置回第一页(避免停在可能越界的旧页)。 */ export function withFilterReset( state: UserFilterState, - next: Partial>, + next: Partial>, ): UserFilterState { return { ...state, ...next, page: USER_PAGE_MIN_PAGE } } @@ -32,7 +41,11 @@ export function withPage(state: UserFilterState, page: number): UserFilterState /** 是否存在生效筛选(仅空白关键字不算)。 */ export function isFilterActive(state: UserFilterState): boolean { - return Boolean(state.keyword && state.keyword.trim()) || state.createdByAdminId != null + return ( + Boolean(state.keyword && state.keyword.trim()) || + state.createdByAdminId != null || + state.companyId != null + ) } /** 页面状态 → 查询适配层参数(空关键字不下发)。 */ @@ -43,6 +56,7 @@ export function toUserListParams(state: UserFilterState): UserListParams { pageSize: state.pageSize, keyword: keyword || undefined, createdById: state.createdByAdminId, + companyId: state.companyId, } const role = (state.role || '').trim() if (role) params.role = role diff --git a/admin-frontend-vue/src/router/routes.ts b/admin-frontend-vue/src/router/routes.ts index 8a72a42ac..4d0a9c1b0 100644 --- a/admin-frontend-vue/src/router/routes.ts +++ b/admin-frontend-vue/src/router/routes.ts @@ -19,6 +19,7 @@ export const adminPages: AdminPageDef[] = [ { path: 'account/groups', menuKey: 'admin_group_manage', title: '数据权限分组', load: () => import('@/pages/account/GroupsPage.vue') }, { path: 'account/user-secrets', menuKey: 'admin_user_secrets', title: '密钥管理', load: () => import('@/pages/account/UserSecretsPage.vue') }, { path: 'account/user-secret-usage', menuKey: 'admin_user_secret_usage', title: '密钥用量统计', load: () => import('@/pages/account/UserSecretUsagePage.vue') }, + { path: 'account/companies', menuKey: 'admin_companies', title: '公司管理', load: () => import('@/pages/account/CompaniesPage.vue') }, { path: 'shop-center/duplicate-check', menuKey: 'admin_shop_data_duplicate_check', title: '店铺撞款监控', load: () => import('@/pages/tasks/DuplicateCheckPage.vue') }, { path: 'shop-center/keys', menuKey: 'admin_shop_keys', title: '店铺密钥管理', load: () => import('@/pages/shop/ShopKeysPage.vue') }, { path: 'shop-center/shops', menuKey: 'admin_shop_manage', title: '店铺管理', load: () => import('@/pages/shop/ShopManagePage.vue') }, diff --git a/admin-frontend-vue/src/styles/main.css b/admin-frontend-vue/src/styles/main.css index 1e17f3676..dfc1ea185 100644 --- a/admin-frontend-vue/src/styles/main.css +++ b/admin-frontend-vue/src/styles/main.css @@ -106,6 +106,11 @@ button, input, textarea, select { font: inherit; } .admin-user { display: flex; align-items: center; gap: 14px; } .admin-user-meta { display: flex; align-items: flex-end; flex-direction: column; } .admin-user-meta strong { font-size: 13px; font-weight: 600; color: var(--admin-text); } +.admin-user-company { + max-width: 200px; margin-top: 3px; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; + color: #6b8096; font-size: 11.5px; +} .admin-user-role { display: inline-flex; align-items: center; padding: 2px 10px; border-radius: 999px; font-size: 12px; line-height: 1.7; diff --git a/admin-frontend-vue/src/types/admin.ts b/admin-frontend-vue/src/types/admin.ts index cd6fecb0d..40347b35b 100644 --- a/admin-frontend-vue/src/types/admin.ts +++ b/admin-frontend-vue/src/types/admin.ts @@ -11,6 +11,10 @@ export interface AdminUser { isAdmin?: boolean createdById?: number | null creatorUsername?: string + /** 所属公司(V143):列表来自 AdminUserItemVo 的 company_id/company_name, + * current-user 来自 AdminConsoleController 的 camelCase 摘要。 */ + companyId?: number | null + companyName?: string createdAt?: string updatedAt?: string pinyinAbbr?: string diff --git a/admin-frontend-vue/tests/company-directory.test.ts b/admin-frontend-vue/tests/company-directory.test.ts new file mode 100644 index 000000000..ff14f8b3d --- /dev/null +++ b/admin-frontend-vue/tests/company-directory.test.ts @@ -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, + }) +}) diff --git a/admin-frontend-vue/tests/company-menu-route.test.ts b/admin-frontend-vue/tests/company-menu-route.test.ts new file mode 100644 index 000000000..777e917f0 --- /dev/null +++ b/admin-frontend-vue/tests/company-menu-route.test.ts @@ -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, '页面标题应与菜单名一致') +}) diff --git a/admin-frontend-vue/tests/company-user-create.test.ts b/admin-frontend-vue/tests/company-user-create.test.ts new file mode 100644 index 000000000..a835d9376 --- /dev/null +++ b/admin-frontend-vue/tests/company-user-create.test.ts @@ -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 = {}) { + 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) +}) diff --git a/admin-frontend-vue/tests/company-user-list.test.ts b/admin-frontend-vue/tests/company-user-list.test.ts new file mode 100644 index 000000000..6505470d0 --- /dev/null +++ b/admin-frontend-vue/tests/company-user-list.test.ts @@ -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/, '顶栏走同一条公司名视图模型') +}) diff --git a/frontend-vue/src/pages/amazon/components/AmazonTopBar.vue b/frontend-vue/src/pages/amazon/components/AmazonTopBar.vue index ac5f4f824..05af06bf3 100644 --- a/frontend-vue/src/pages/amazon/components/AmazonTopBar.vue +++ b/frontend-vue/src/pages/amazon/components/AmazonTopBar.vue @@ -31,6 +31,7 @@
+ {{ companyName }} {{ username }}
@@ -45,6 +46,7 @@ import { filterGroupsByPermission, TOOL_GROUPS } from '@/pages/amazon/tool-catal import type { VisibleGroup } from '@/pages/amazon/tool-catalog' import { resolvePageHref } from '@/shared/page-prefix' import { getCurrentUserAppColumnKeys } from '@/shared/api/permission' +import { readCompanyIdentity } from '@/shared/auth/company-identity' const props = withDefaults( defineProps<{ @@ -61,6 +63,8 @@ const emit = defineEmits<{ change: [key: 'front' | 'ops' | 'logi'] }>() const activeCat = computed(() => props.activeCat) const visibleCats = ref(TOOL_GROUPS.map((group) => ({ ...group, tools: [...group.tools] }))) const username = ref('admin') +/** 所属公司名:后端未返回时为空串,该段整体不渲染(不能显示 undefined)。 */ +const companyName = ref('') /** 分类 tab 点击回到工具台对应分组 */ const toolbarHref = resolvePageHref('/new_web_source/amazon-console.html') @@ -84,6 +88,7 @@ function underlineStyle(cat: VisibleGroup) { onMounted(async () => { const localName = typeof window === 'undefined' ? '' : (window.localStorage.getItem('username') || '').trim() if (localName) username.value = localName + companyName.value = readCompanyIdentity() try { const keys = await getCurrentUserAppColumnKeys() visibleCats.value = filterGroupsByPermission(TOOL_GROUPS, keys) @@ -253,6 +258,18 @@ onMounted(async () => { flex-shrink: 0; } +.company-name { + max-width: 180px; + padding: 3px 10px; + border: 1px solid #3e4a62; + border-radius: 999px; + color: #9fb0c9; + font-size: 12px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + .admin-name { color: #c8d2e2; font-size: 13px; diff --git a/frontend-vue/src/pages/login/DesktopLoginPage.vue b/frontend-vue/src/pages/login/DesktopLoginPage.vue index 1db82ed52..46b22e63a 100644 --- a/frontend-vue/src/pages/login/DesktopLoginPage.vue +++ b/frontend-vue/src/pages/login/DesktopLoginPage.vue @@ -112,6 +112,7 @@ import { onMounted, ref, watch } from 'vue' import { useRouter } from 'vue-router' import { loginWithDevice } from '@/shared/api/user' import { KICK_NOTICE_KEY } from '@/shared/auth/kick-handler' +import { COMPANY_NAME_STORAGE_KEY, writeCompanyIdentity } from '@/shared/auth/company-identity' import { useVersionUpdate } from '@/shared/composables/useVersionUpdate' import { clearApiSecretCache } from '@/shared/utils/api-secret-store' import UpdateProgressBar from '@/shared/components/UpdateProgressBar.vue' @@ -432,6 +433,8 @@ async function submitLogin() { /* 忽略 */ } } + // 公司名随后端可选返回:没有就删键,顶栏不显示该段(见 shared/auth/company-identity) + writeCompanyIdentity(data) // 登录成功即持久化记住/自动登录凭据(桌面与网页均可,密码 AES 加密落 localStorage) void saveCredentials(account) // 桌面端 Flask cookie 同步已随瘦身下线:登录态只存 localStorage(JWT 走 Bearer),无 cookie 依赖 @@ -453,6 +456,7 @@ onMounted(() => { window.localStorage.removeItem(AUTH_TOKEN_KEY) window.localStorage.removeItem('uid') window.localStorage.removeItem('username') + window.localStorage.removeItem(COMPANY_NAME_STORAGE_KEY) } catch { /* 忽略 */ } diff --git a/frontend-vue/src/shared/api/user.ts b/frontend-vue/src/shared/api/user.ts index 5c5d5dc91..f6e734bd5 100644 --- a/frontend-vue/src/shared/api/user.ts +++ b/frontend-vue/src/shared/api/user.ts @@ -17,6 +17,9 @@ export interface LoginData { token?: string userId?: number | string username?: string + /** 所属公司(company.id,V143 新增;旧 jar 不返回该字段) */ + companyId?: number | string + companyName?: string [key: string]: unknown } diff --git a/frontend-vue/src/shared/auth/company-identity.ts b/frontend-vue/src/shared/auth/company-identity.ts new file mode 100644 index 000000000..26a2087ea --- /dev/null +++ b/frontend-vue/src/shared/auth/company-identity.ts @@ -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 '' + } +} diff --git a/frontend-vue/src/shared/auth/ensure-auth.ts b/frontend-vue/src/shared/auth/ensure-auth.ts index c9c94063b..ce77dd831 100644 --- a/frontend-vue/src/shared/auth/ensure-auth.ts +++ b/frontend-vue/src/shared/auth/ensure-auth.ts @@ -9,6 +9,7 @@ */ import { get } from '@/shared/api/http' +import { writeCompanyIdentity } from './company-identity' const AUTH_TOKEN_KEY = 'aiimage_auth_token' const UID_KEY = 'uid' @@ -16,6 +17,8 @@ const UID_KEY = 'uid' interface CheckLoginData { userId?: number | string username?: string + companyId?: number | string + companyName?: string } /** 确保当前页面具备登录态;返回是否可继续进入页面 */ @@ -38,6 +41,7 @@ export async function ensureAuth(): Promise { if (response.data.username) { window.localStorage.setItem('username', String(response.data.username)) } + writeCompanyIdentity(response.data) return true } catch { // token 失效:清掉本地登录态(跳转交给路由守卫) @@ -74,6 +78,7 @@ export async function restoreLoginUser(): Promise<{ username?: string } | null> if (response.data.username) { window.localStorage.setItem('username', String(response.data.username)) } + writeCompanyIdentity(response.data) return { username: response.data.username } } catch { return null diff --git a/frontend-vue/src/shared/auth/kick-handler.ts b/frontend-vue/src/shared/auth/kick-handler.ts index a1f561dcc..1695e59f7 100644 --- a/frontend-vue/src/shared/auth/kick-handler.ts +++ b/frontend-vue/src/shared/auth/kick-handler.ts @@ -8,6 +8,8 @@ * 记住的账号密码保留,手动点一次即可重新登录(此时顶掉对方,最后登录者胜)。 */ +import { COMPANY_NAME_STORAGE_KEY } from './company-identity.ts' + const AUTH_TOKEN_KEY = 'aiimage_auth_token' const UID_KEY = 'uid' const USERNAME_KEY = 'username' @@ -69,6 +71,7 @@ export function handleKicked(): void { storage.removeItem(AUTH_TOKEN_KEY) storage.removeItem(UID_KEY) storage.removeItem(USERNAME_KEY) + storage.removeItem(COMPANY_NAME_STORAGE_KEY) storage.setItem(AUTO_LOGIN_KEY, '0') storage.setItem(KICK_NOTICE_KEY, '1') } catch { diff --git a/frontend-vue/tests/company-identity.test.ts b/frontend-vue/tests/company-identity.test.ts new file mode 100644 index 000000000..27cfe6b2a --- /dev/null +++ b/frontend-vue/tests/company-identity.test.ts @@ -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 + window: { localStorage: { getItem: (k: string) => string | null; setItem: (k: string, v: string) => void; removeItem: (k: string) => void } } +} + +function stubWindow(): StorageStub { + const store = new Map() + 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).window = win + return { store, window: win } +} + +function clearWindow() { + delete (globalThis as Record).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() +}) diff --git a/frontend-vue/tests/single-device-kick.test.ts b/frontend-vue/tests/single-device-kick.test.ts index 59a2589dc..f7121bc46 100644 --- a/frontend-vue/tests/single-device-kick.test.ts +++ b/frontend-vue/tests/single-device-kick.test.ts @@ -170,3 +170,13 @@ test('普通业务错误(403 等)不触发下线', () => { assert.equal(localStorage.getItem('uid'), '1095') assert.deepEqual(assigned, []) }) + +// ---------- 公司身份(设计文档 §2.4):下线必须把公司名一起清掉 ---------- + +test('handleKicked 连公司名一起清:残留会把上一账号的归属显示给下一个账号', () => { + const { localStorage } = setupWindow({ ...loggedInStorage(), company_name: '厦门米椿花' }) + + handleKicked() + + assert.equal(localStorage.getItem('company_name'), null, '被踢后不得残留上一账号的公司名') +})