feat(admin): 批量删除并入筛选行省一整行+公司管理加删除/批量删除(2026-11-23 用户口径)

- BatchDeleteActions margin-left:auto 右对齐、不再独占一行,14 页迁入各自筛选/工具行(Users/Groups/Menus/UserSecrets/QueryAsin/AsinInvalid/SkipPrice/DedupeRegistry/ProductCategory/DeviceLogs/DigitalHuman/ShopManage/ShopKeys/BrandGating);主按钮沿用全局 34px 同高,align-batch-toolbar-inline.test.ts 钉形状防回归
- 公司删除:DELETE /api/admin/companies/{id}(仅超管,名下有账号拒并带数量),只收公司行+columns 菜单树(PermissionMenuService.deleteTreeByCompany 与 copyTreeFromTemplate 对称),业务数据不级联;列表 VO 带 user_count 供前端置灰勾选/删除按钮;批量删除按用户管理同形走前端逐条循环
- CompaniesPage 加勾选列+行删除按钮(ops-cell 补 flex-wrap 过 ops-cell-must-wrap),删除后 refreshCompanyDirectory 同步 tab 条
- 测试:CompanyServiceDeleteTest 6+PermissionMenuServiceDeleteTreeTest 2+CompanyVoTest user_count 契约+CompanyControllerEndpointTest 翻转 exposesNoDeleteEndpoint→点名 DELETE 端点+CompanyReadPathMenuGateTest ensureSuperAdmin 3→4(delete 入册)+company-directory/row-buttons 补例;source-pin 基线重生成(265 文件/1859 例)
- 验证:admin-vue vue-tsc rc=0、node --test 1976 全绿、vitest mount 247 全绿;backend test-compile rc=0、Company*/PermissionMenu*/跨切守卫点名全绿(CatchSilenceRatchet 红因=另一路在飞件 JdPublishFillAiService 3 个 catch,归属京东窗不代抬)
This commit is contained in:
2026-11-23 01:41:37 +08:00
parent 87fe7ed383
commit 898e8a5ea9
35 changed files with 597 additions and 46 deletions
@@ -17,6 +17,12 @@ export interface CompanyItem {
updatedAt: string | null updatedAt: string | null
/** 所属平台(V206):'amazon'|'jd';后端恒带值(列 NOT NULL DEFAULT 'amazon'),旧负载缺省不渲染。 */ /** 所属平台(V206):'amazon'|'jd';后端恒带值(列 NOT NULL DEFAULT 'amazon'),旧负载缺省不渲染。 */
platform?: string platform?: string
/**
* 在册账号数(2026-11-23):仅列表回包带(create/update 不带)。
* 非零 ⇒ 该公司不能删(用户拍板「有账号不能删」),勾选框与删除按钮据此置灰。
* 缺省(旧负载/测试桩)按 0 读——那是"看起来可删",后端删除时仍有权威校验兜底。
*/
userCount?: number
} }
/** 新建/改名的表单草稿。 */ /** 新建/改名的表单草稿。 */
@@ -30,6 +30,9 @@ export function toCompanyItem(raw: unknown): CompanyItem | null {
// platform 后端恒带(列 NOT NULL);旧负载/测试桩缺省就不渲染该键,字段形状与 users-model 一致。 // platform 后端恒带(列 NOT NULL);旧负载/测试桩缺省就不渲染该键,字段形状与 users-model 一致。
const platform = text(r.platform) const platform = text(r.platform)
if (platform) item.platform = platform if (platform) item.platform = platform
// user_count 仅公司目录列表下发(create/update 不带);非负整数才认,缺省不渲染(按 0 读)。
const userCount = numberOrNull(r.user_count)
if (userCount !== null && userCount >= 0) item.userCount = userCount
return item return item
} }
+6 -1
View File
@@ -16,8 +16,13 @@ export async function createCompany(draft: CompanyDraft): Promise<CompanyItem |
return parseCompany(data) return parseCompany(data)
} }
/** 改名 / 启停;后端不做删除,停用即 status=0。 */ /** 改名 / 启停(删除走独立出口 deleteCompany,与用户管理同形)。 */
export async function updateCompany(id: number, draft: CompanyDraft): Promise<CompanyItem | null> { export async function updateCompany(id: number, draft: CompanyDraft): Promise<CompanyItem | null> {
const { data } = await http.put(`/api/admin/companies/${id}`, toCompanyPayload(draft)) const { data } = await http.put(`/api/admin/companies/${id}`, toCompanyPayload(draft))
return parseCompany(data) return parseCompany(data)
} }
/** 删除公司:DELETE /api/admin/companies/{id},success=false 由 unwrap 抛后端 message。 */
export async function deleteCompany(id: number): Promise<void> {
await http.delete<unknown>(`/api/admin/companies/${id}`)
}
@@ -28,7 +28,9 @@ defineProps<{
</template> </template>
<style scoped> <style scoped>
.batch-delete-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; } /* 2026-11-23 用户口径「批量删除放上去,最大化利用空间」:不再独占一行,由各页放进筛选/工具行,
margin-left:auto 在 flex 行内右对齐(落点=查询按钮右侧留白)。 */
.batch-delete-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-left: auto; }
.batch-delete-actions button { .batch-delete-actions button {
min-height: 34px; min-height: 34px;
padding: 5px 12px; padding: 5px 12px;
@@ -39,6 +41,7 @@ defineProps<{
font: inherit; font: inherit;
cursor: pointer; cursor: pointer;
} }
/* 主按钮沿用 34px:全局 main.css 已把 panel 内 .btn(查询)压到 34px,同高才不会一高一矮。 */
.batch-delete-actions .batch-delete-button { color: #fff; background: #b35f6a; border-color: #b35f6a; } .batch-delete-actions .batch-delete-button { color: #fff; background: #b35f6a; border-color: #b35f6a; }
.batch-delete-button:hover:not(:disabled) { background: #a34f5b; } .batch-delete-button:hover:not(:disabled) { background: #a34f5b; }
.batch-clear-button:hover:not(:disabled) { background: #edf5fb; } .batch-clear-button:hover:not(:disabled) { background: #edf5fb; }
@@ -1,15 +1,20 @@
<script setup lang="ts"> <script setup lang="ts">
/** 公司管理(设计文档 §2.3):列表 + 新建 + 改名/启停。 /** 公司管理(设计文档 §2.3):列表 + 新建 + 改名/启停 + 删除/批量删除(2026-11-23,名下有账号不能删)。
* 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合, * 可见范围由后端收窄(超管全部、公司内 admin 只自己公司);写操作仅超管,这里隐藏入口只是配合,
* 真正的把关在 CompanyController,页面不得当作权限边界。 */ * 真正的把关在 CompanyController,页面不得当作权限边界。 */
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { formatDateTime } from '@/utils/datetime' import { formatDateTime } from '@/utils/datetime'
import { fetchCompanies } from '@/api/companies' import { useRowSelection } from '@/utils/use-row-selection'
import { deleteCompany, fetchCompanies } from '@/api/companies'
import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto' import { COMPANY_STATUS_ACTIVE, type CompanyItem } from '@/api/companies-dto'
import { useAdminSessionStore } from '@/stores/admin-session' import { useAdminSessionStore } from '@/stores/admin-session'
import { refreshCompanyDirectory } from '@/stores/company-tab' import { refreshCompanyDirectory } from '@/stores/company-tab'
import { usePlatformTabStore } from '@/stores/platform-tab' import { usePlatformTabStore } from '@/stores/platform-tab'
import BatchDeleteActions from '@/components/BatchDeleteActions.vue'
import BatchDeleteCheckbox from '@/components/BatchDeleteCheckbox.vue'
import { openAdminConfirm } from '@/components/admin-confirm'
import OldPagination from '@/components/OldPagination.vue' import OldPagination from '@/components/OldPagination.vue'
import CompanyEditorDialog from './CompanyEditorDialog.vue' import CompanyEditorDialog from './CompanyEditorDialog.vue'
import { showAdminFeedback } from '@/components/admin-feedback-ui' import { showAdminFeedback } from '@/components/admin-feedback-ui'
@@ -61,16 +66,58 @@ function openEdit(company: CompanyItem) {
editorVisible.value = true editorVisible.value = true
} }
/** 删除前置闸(勾选框置灰与删除按钮共用同一份理由;后端删除时还有权威校验兜底)。 */
function deleteBlockReasonOf(company: CompanyItem): string | undefined {
if (!canManage.value) return '只有超级管理员可以删除公司'
const userCount = company.userCount ?? 0
if (userCount > 0) return `该公司名下还有 ${userCount} 个账号,请先删除或转移后再删除公司`
return undefined
}
async function reloadCompaniesAndDirectory() {
await loadCompanies()
refreshCompanyDirectory().catch((error: unknown) => {
console.warn('[company-tab] 公司变动后目录重拉失败', error)
})
}
const batch = useRowSelection({
pageRows: () => pagedRows.value,
rowId: (row) => row.id,
rowLabel: (row) => row.companyName || `公司 ${row.id}`,
deleteOne: (id) => deleteCompany(id),
refresh: reloadCompaniesAndDirectory,
blocked: () => loading.value || !!loadFailure.value,
scope: () => [platformTab.active],
precheck: (row) => deleteBlockReasonOf(row),
})
async function removeCompany(company: CompanyItem) {
if (batch.busy) return
const reason = deleteBlockReasonOf(company)
if (reason) {
showAdminFeedback(reason, 'error')
return
}
// 对齐分组管理:统一确认出口,删除不做级联(账号与业务数据留在各自页面处理)。
if (!(await openAdminConfirm({ message: `确定删除公司“${company.companyName || company.id}”吗?删除后不可恢复。`, danger: true }))) return
try {
await deleteCompany(company.id)
batch.removeFromSelection(company.id)
ElMessage.success('删除成功')
await reloadCompaniesAndDirectory()
} catch (error) {
showAdminFeedback(error instanceof Error ? error.message : '删除失败', 'error')
}
}
// 保存成功后:本页列表照常重拉,共享公司目录(tab 条)强制重拉一份。 // 保存成功后:本页列表照常重拉,共享公司目录(tab 条)强制重拉一份。
// 本页不参与公司隔离(控制方 2026-10-06「公司管理不要有 tab」)⇒ 走 store 的具名出口 // 本页不参与公司隔离(控制方 2026-10-06「公司管理不要有 tab」)⇒ 走 store 的具名出口
// refreshCompanyDirectory,而不是自己持一份 company-tab store(后者形状与「给这页上了 tab」 // refreshCompanyDirectory,而不是自己持一份 company-tab store(后者形状与「给这页上了 tab」
// 分不开,company-config-entry-super-only 的 pageFiles 分母会当场红)。 // 分不开,company-config-entry-super-only 的 pageFiles 分母会当场红)。
// 重拉失败不弹新提示(§12 第 5 条未批的界面暴露):tab 条保留旧名单,下一次切平台 tab / 重进页面会再试。 // 重拉失败不弹新提示(§12 第 5 条未批的界面暴露):tab 条保留旧名单,下一次切平台 tab / 重进页面会再试。
async function onCompaniesSaved() { async function onCompaniesSaved() {
await loadCompanies() await reloadCompaniesAndDirectory()
refreshCompanyDirectory().catch((error: unknown) => {
console.warn('[company-tab] 公司保存后目录重拉失败', error)
})
} }
// 切平台 tab(V206)= 重新取数:公司归属按平台分列,两 tab 各看各的公司。 // 切平台 tab(V206)= 重新取数:公司归属按平台分列,两 tab 各看各的公司。
@@ -95,6 +142,7 @@ onMounted(loadCompanies)
<label>公司名称</label> <label>公司名称</label>
<input v-model="filterKeyword" type="text" placeholder="输入公司名称" /> <input v-model="filterKeyword" type="text" placeholder="输入公司名称" />
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadCompanies" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadCompanies" />
@@ -102,18 +150,26 @@ onMounted(loadCompanies)
<table> <table>
<thead> <thead>
<tr> <tr>
<th class="batch-delete-cell" scope="col">
<BatchDeleteCheckbox label="全选当前页可删除公司" :checked="batch.pageAll" :partial="batch.pageSome"
:disabled="batch.disabled || batch.pageEmpty" @change="batch.togglePage" />
</th>
<th style="width: 58px">序号</th> <th style="width: 58px">序号</th>
<th>公司名称</th> <th>公司名称</th>
<th style="width: 90px">状态</th> <th style="width: 90px">状态</th>
<th style="width: 24%">备注</th> <th style="width: 24%">备注</th>
<th style="width: 160px">创建时间</th> <th style="width: 160px">创建时间</th>
<th style="width: 160px">修改时间</th> <th style="width: 160px">修改时间</th>
<th style="width: 90px">操作</th> <th style="width: 140px">操作</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
<template v-if="filteredRows.length"> <template v-if="filteredRows.length">
<tr v-for="(company, index) in pagedRows" :key="company.id"> <tr v-for="(company, index) in pagedRows" :key="company.id" :class="{ 'batch-selected': batch.isSelected(company) }">
<td class="batch-delete-cell">
<BatchDeleteCheckbox :label="batch.reason(company) || `选择 ${batch.label(company)}`" :checked="batch.isSelected(company)"
:disabled="batch.disabled || !!batch.reason(company)" @change="batch.toggle(company)" />
</td>
<td>{{ index + 1 }}</td> <td>{{ index + 1 }}</td>
<td>{{ company.companyName || '-' }}</td> <td>{{ company.companyName || '-' }}</td>
<td> <td>
@@ -125,16 +181,20 @@ onMounted(loadCompanies)
<td>{{ formatDateTime(company.createdAt) }}</td> <td>{{ formatDateTime(company.createdAt) }}</td>
<td>{{ formatDateTime(company.updatedAt || company.createdAt) }}</td> <td>{{ formatDateTime(company.updatedAt || company.createdAt) }}</td>
<td class="ops-cell"> <td class="ops-cell">
<button v-if="canManage" class="btn btn-sm" type="button" @click="openEdit(company)">编辑</button> <template v-if="canManage">
<button class="btn btn-sm" type="button" @click="openEdit(company)">编辑</button>
<button class="btn btn-sm btn-danger" type="button" :disabled="batch.busy || !!deleteBlockReasonOf(company)"
:title="deleteBlockReasonOf(company) || undefined" @click="removeCompany(company)">删除</button>
</template>
<span v-else class="cell-none">-</span> <span v-else class="cell-none">-</span>
</td> </td>
</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">{{ filterKeyword.trim() ? '暂无匹配公司' : '暂无公司' }}</td> <td colspan="8" class="empty-tip">{{ filterKeyword.trim() ? '暂无匹配公司' : '暂无公司' }}</td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
@@ -283,6 +343,7 @@ h3 {
align-items: center; align-items: center;
gap: 8px; gap: 8px;
white-space: nowrap; white-space: nowrap;
flex-wrap: wrap;
} }
.cell-none { .cell-none {
color: #8293a5; color: #8293a5;
@@ -139,10 +139,10 @@ onMounted(loadGroups)
<label>组长</label> <label>组长</label>
<input v-model="filterLeader" type="text" placeholder="输入组长用户名" /> <input v-model="filterLeader" type="text" placeholder="输入组长用户名" />
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadGroups" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll"> <div class="table-scroll">
<table> <table>
<thead> <thead>
@@ -283,10 +283,10 @@ onMounted(loadMenus)
<el-option label="软件" value="app" /> <el-option label="软件" value="app" />
</el-select> </el-select>
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadMenus" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadMenus" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll columns-table-scroll"> <div class="table-scroll columns-table-scroll">
<table> <table>
<thead> <thead>
@@ -393,10 +393,10 @@ onMounted(load)
</button> </button>
</div> </div>
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="secrets-table-scroll"> <div class="secrets-table-scroll">
<table> <table>
<thead> <thead>
@@ -257,6 +257,8 @@ onMounted(() => {
</el-select> </el-select>
</div> </div>
<button class="btn" type="button" @click="search">查询</button> <button class="btn" type="button" @click="search">查询</button>
<!-- 批量删除并入筛选行(2026-11-23 用户口径),margin-left:auto 右对齐,不再独占一行。 -->
<BatchDeleteActions :batch="batch" />
</div> </div>
<div v-if="statePhase === 'error' && loadError" class="msg err"> <div v-if="statePhase === 'error' && loadError" class="msg err">
@@ -264,7 +266,6 @@ onMounted(() => {
<button class="btn btn-sm btn-secondary" type="button" @click="retry">重试</button> <button class="btn btn-sm btn-secondary" type="button" @click="retry">重试</button>
</div> </div>
<BatchDeleteActions :batch="batch" />
<div class="table-scroll user-table-scroll"> <div class="table-scroll user-table-scroll">
<table> <table>
<thead> <thead>
@@ -186,10 +186,10 @@ onMounted(() => {
</el-select> </el-select>
</div> </div>
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll invalid-asin-table-scroll"> <div class="table-scroll invalid-asin-table-scroll">
<table> <table>
<thead> <thead>
@@ -410,6 +410,7 @@ onUnmounted(() => {
<div class="dedupe-filter-actions"> <div class="dedupe-filter-actions">
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<div class="dedupe-filter-date-row"> <div class="dedupe-filter-date-row">
@@ -429,7 +430,6 @@ onUnmounted(() => {
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll dedupe-table-scroll"> <div class="table-scroll dedupe-table-scroll">
<table> <table>
<thead> <thead>
@@ -343,11 +343,11 @@ onMounted(loadTree)
<button class="btn btn-sm btn-secondary" type="button" @click="exportCategories">导出</button> <button class="btn btn-sm btn-secondary" type="button" @click="exportCategories">导出</button>
<button v-if="selected && !searching" class="btn btn-sm" type="button" @click="openCreate(selected)">新增子类目</button> <button v-if="selected && !searching" class="btn btn-sm" type="button" @click="openCreate(selected)">新增子类目</button>
<button class="btn" type="button" @click="openCreate(null)">新增类目</button> <button class="btn" type="button" @click="openCreate(null)">新增类目</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadTree" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="loadTree" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll category-table-scroll"> <div class="table-scroll category-table-scroll">
<table> <table>
<thead> <thead>
@@ -435,10 +435,10 @@ onMounted(() => {
</div> </div>
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
<button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button> <button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll query-asin-table-scroll"> <div class="table-scroll query-asin-table-scroll">
<table> <table>
<thead> <thead>
@@ -477,10 +477,10 @@ onMounted(() => {
</div> </div>
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
<button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button> <button class="btn btn-secondary" type="button" @click="doExport">导出 XLSX</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll skip-price-asin-table-scroll"> <div class="table-scroll skip-price-asin-table-scroll">
<table> <table>
<thead> <thead>
@@ -352,10 +352,10 @@ onMounted(() => {
<button class="btn btn-ghost" type="button" @click="reset">重置</button> <button class="btn btn-ghost" type="button" @click="reset">重置</button>
</div> </div>
</div> </div>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="logs-table-scroll"> <div class="logs-table-scroll">
<table> <table>
<thead> <thead>
@@ -232,11 +232,11 @@ onMounted(load)
<div class="dh-head-tools admin-header-controls"> <div class="dh-head-tools admin-header-controls">
<input v-model="versionKeyword" type="text" placeholder="搜索版本号" class="dh-keyword" /> <input v-model="versionKeyword" type="text" placeholder="搜索版本号" class="dh-keyword" />
<button class="btn" type="button" @click="uploadVisible = true">上传新版本</button> <button class="btn" type="button" @click="uploadVisible = true">上传新版本</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll digital-human-version-table-scroll"> <div class="table-scroll digital-human-version-table-scroll">
<table> <table>
<thead> <thead>
@@ -244,10 +244,10 @@ onMounted(load)
</el-select> </el-select>
</div> </div>
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="shop-key-table-scroll"> <div class="shop-key-table-scroll">
<table> <table>
<thead> <thead>
@@ -267,10 +267,10 @@ onMounted(() => {
<input v-model="filter.shopName" type="text" placeholder="请输入店铺名" @keyup.enter="apply" /> <input v-model="filter.shopName" type="text" placeholder="请输入店铺名" @keyup.enter="apply" />
</div> </div>
<button class="btn" type="button" @click="apply">查询</button> <button class="btn" type="button" @click="apply">查询</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" /> <LoadFailureBar v-if="loadFailure" :message="loadFailure" @retry="load" />
<BatchDeleteActions :batch="batch" />
<div class="table-scroll shop-manage-table-scroll"> <div class="table-scroll shop-manage-table-scroll">
<table> <table>
<thead> <thead>
@@ -339,11 +339,11 @@ onMounted(() => {
</el-select> </el-select>
<button class="g-btn g-btn-primary" type="button" @click="query">查询</button> <button class="g-btn g-btn-primary" type="button" @click="query">查询</button>
<button class="g-btn g-btn-ghost" type="button" @click="resetFilter">重置</button> <button class="g-btn g-btn-ghost" type="button" @click="resetFilter">重置</button>
<BatchDeleteActions :batch="batch" />
</div> </div>
<LoadFailureBar v-if="loadError" :message="loadError" @retry="loadPage()" /> <LoadFailureBar v-if="loadError" :message="loadError" @retry="loadPage()" />
<BatchDeleteActions :batch="batch" />
<div class="g-table-wrap" v-loading="pageLoading"> <div class="g-table-wrap" v-loading="pageLoading">
<table v-if="rows.length" class="g-table"> <table v-if="rows.length" class="g-table">
<thead> <thead>
@@ -32,3 +32,14 @@ test('align_menus_row_buttons_old_btn', () => {
assert.doesNotMatch(s, /el-button[^>]*@click="openEdit/, '行内不再用 EP 按钮') assert.doesNotMatch(s, /el-button[^>]*@click="openEdit/, '行内不再用 EP 按钮')
assert.match(s, /openAdminConfirm\(\{ message: `确定删除菜单/, '删除确认走统一确认出口,文案对齐旧版') assert.match(s, /openAdminConfirm\(\{ message: `确定删除菜单/, '删除确认走统一确认出口,文案对齐旧版')
}) })
test('align_companies_row_buttons_old_btn', () => {
const s = readSource('src/pages/account/CompaniesPage.vue')
assert.match(s, /class="btn btn-sm"[^>]*@click="openEdit\(company\)"/, '编辑用旧版 btn-sm 实心小按钮')
assert.match(s, /class="btn btn-sm btn-danger"[^>]*@click="removeCompany\(company\)"/, '删除用旧版 btn-sm btn-danger(2026-11-23 用户口径:公司管理加删除)')
assert.doesNotMatch(s, /el-button[^>]*@click="openEdit/, '行内不再用 EP 按钮')
assert.match(s, /openAdminConfirm\(\{ message: `确定删除公司/, '删除确认走统一确认出口')
// 名下有账号的公司删不得:勾选框与删除按钮共用同一份理由(deleteBlockReasonOf)
assert.match(s, /deleteBlockReasonOf\(company\)/, '删除按钮按理由置灰,悬停可见原因')
assert.match(s, /该公司名下还有 \$\{userCount\} 个账号/, '置灰文案带账号数')
})
@@ -0,0 +1,38 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { readSource } from './helpers.ts'
/**
* 2026-11-23 用户口径「批量删除放上去,最大化利用空间」:BatchDeleteActions 不再独占一行,
* 由各页并入筛选/工具行(组件 margin-left:auto 右对齐)。本钉防回归——有人把它挪回
* 「LoadFailureBar 之后独占一行」的旧形状即红。
*
* 正向锚点 = 该页筛选行里紧挨着它的前一个控件;负向 = 旧形状「LoadFailureBar 后跟独立批量行」。
*/
const MOVED_PAGES: Array<{ file: string; rowMate: RegExp; note: string }> = [
{ file: 'src/pages/account/UsersPage.vue', rowMate: /@click="search">查询<\/button>[\s\S]{0,300}?<BatchDeleteActions/, note: '查询按钮右侧' },
{ file: 'src/pages/account/GroupsPage.vue', rowMate: /placeholder="输入组长用户名" \/>\s*<\/div>\s*<BatchDeleteActions/, note: '组长输入框右侧' },
{ file: 'src/pages/account/MenusPage.vue', rowMate: /value="app" \/>\s*<\/el-select>\s*<\/div>\s*<BatchDeleteActions/, note: '菜单类型下拉右侧' },
{ file: 'src/pages/account/UserSecretsPage.vue', rowMate: /<\/button>\s*<\/div>\s*<\/div>\s*<BatchDeleteActions/, note: '刷新余额那组按钮右侧' },
{ file: 'src/pages/asin/QueryAsinPage.vue', rowMate: /导出 XLSX<\/button>\s*<BatchDeleteActions/, note: '导出按钮右侧' },
{ file: 'src/pages/asin/AsinInvalidPage.vue', rowMate: /@click="apply">查询<\/button>\s*<BatchDeleteActions/, note: '查询按钮右侧' },
{ file: 'src/pages/asin/SkipPricePage.vue', rowMate: /导出 XLSX<\/button>\s*<BatchDeleteActions/, note: '导出按钮右侧' },
{ file: 'src/pages/asin/DedupeRegistryPage.vue', rowMate: /@click="apply">查询<\/button>\s*<\/div>\s*<BatchDeleteActions/, note: '查询按钮组右侧' },
{ file: 'src/pages/asin/ProductCategoryPage.vue', rowMate: /@click="openCreate\(null\)">新增类目<\/button>\s*<BatchDeleteActions/, note: '新增类目按钮右侧' },
{ file: 'src/pages/records/DeviceLogsPage.vue', rowMate: /<\/button>\s*<\/div>\s*<\/div>\s*<BatchDeleteActions/, note: '重置按钮组右侧' },
{ file: 'src/pages/records/RecordsDigitalHumanVersionPage.vue', rowMate: /@click="uploadVisible = true">上传新版本<\/button>\s*<BatchDeleteActions/, note: '上传按钮右侧' },
{ file: 'src/pages/shop/ShopManagePage.vue', rowMate: /@click="apply">查询<\/button>\s*<BatchDeleteActions/, note: '查询按钮右侧' },
{ file: 'src/pages/shop/ShopKeysPage.vue', rowMate: /@click="apply">查询<\/button>\s*<BatchDeleteActions/, note: '查询按钮右侧' },
{ file: 'src/pages/tasks/BrandGatingPanel.vue', rowMate: /@click="resetFilter">重置<\/button>\s*<BatchDeleteActions/, note: '重置按钮右侧' },
]
for (const { file, rowMate, note } of MOVED_PAGES) {
test(`align_batch_inline_${file.split('/').pop()}`, () => {
const s = readSource(file)
assert.doesNotMatch(s, /<LoadFailureBar[^>]*\/>\s*<BatchDeleteActions/, `旧形状(LoadFailureBar 后独占一行)不许回来`)
assert.match(s, rowMate, `批量删除应并入筛选/工具行(${note}),紧跟行内前一个控件`)
// 行内形状收口:组件是该行容器的最后一个孩子,紧跟该行的闭合 </div>
assert.match(s, /<BatchDeleteActions :batch="batch" \/>\s*\n\s*<\/div>/, '组件应紧跟行容器闭合,而不是自己占一行再接表格')
assert.equal((s.match(/<BatchDeleteActions/g) || []).length, 1, '每页只许一份批量删除入口')
})
}
@@ -1,10 +1,10 @@
{ {
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。", "note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": { "totals": {
"files": 264, "files": 265,
"cases": 1857, "cases": 1859,
"pins": 462, "pins": 463,
"reads": 663 "reads": 664
}, },
"files": { "files": {
"admin-scaffold.test.ts": { "admin-scaffold.test.ts": {
@@ -22,6 +22,11 @@
"pins": 7, "pins": 7,
"reads": 7 "reads": 7
}, },
"align-batch-toolbar-inline.test.ts": {
"cases": 1,
"pins": 1,
"reads": 1
},
"align-category-tree.test.ts": { "align-category-tree.test.ts": {
"cases": 6, "cases": 6,
"pins": 5, "pins": 5,
@@ -208,7 +213,7 @@
"reads": 3 "reads": 3
}, },
"company-directory.test.ts": { "company-directory.test.ts": {
"cases": 8, "cases": 9,
"pins": 0, "pins": 0,
"reads": 0 "reads": 0
}, },
@@ -55,6 +55,24 @@ test('parseCompany 解析单条(新建/改名回包)', () => {
assert.equal(parseCompany({ success: true, data: { company_name: '无 id' } }), null) assert.equal(parseCompany({ success: true, data: { company_name: '无 id' } }), null)
}) })
test('user_count 仅列表解析进 userCount:非零即「名下有账号、删不得」(2026-11-23)', () => {
const rows = parseCompanyList({ success: true, data: [
{ id: 1, company_name: '厦门米椿花', status: 1, user_count: 3 },
{ id: 2, company_name: '福州数富', status: 1, user_count: 0 },
{ id: 3, company_name: '旧负载', status: 1 },
{ id: 4, company_name: '脏值', status: 1, user_count: -1 },
{ id: 5, company_name: '脏值2', status: 1, user_count: 'x' },
] })
assert.equal(rows[0].userCount, 3)
assert.equal(rows[1].userCount, 0, '零账号=可删,字段照带')
assert.ok(!('userCount' in rows[2]), '旧负载不带该键(按 0 读是消费方的事)')
assert.ok(!('userCount' in rows[3]), '负数不是合法计数,丢弃')
assert.ok(!('userCount' in rows[4]), '非数字丢弃')
// 新建/改名回包不带 user_count:单条解析同样不凭空造键
const saved = parseCompany({ success: true, data: { id: 6, company_name: '厦门米椿花', status: 1 } })
assert.ok(saved && !('userCount' in saved))
})
test('公司名必填、去空格后不得为空,且不超过列宽', () => { test('公司名必填、去空格后不得为空,且不超过列宽', () => {
assert.equal(validateCompanyDraft({ companyName: ' ' }), '公司名称不能为空') assert.equal(validateCompanyDraft({ companyName: ' ' }), '公司名称不能为空')
assert.equal(validateCompanyDraft({ companyName: ' 厦门米椿花 ' }), '') assert.equal(validateCompanyDraft({ companyName: ' 厦门米椿花 ' }), '')
@@ -11,6 +11,7 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
@@ -21,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* 公司目录(设计文档 §2.3)。可见范围与写入边界都在 CompanyService 里判, * 公司目录(设计文档 §2.3)。可见范围与写入边界都在 CompanyService 里判,
@@ -29,7 +31,7 @@ import java.util.List;
@RestController @RestController
@RequiredArgsConstructor @RequiredArgsConstructor
@RequestMapping("/api/admin") @RequestMapping("/api/admin")
@Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名与启停") @Tag(name = "管理后台-公司", description = "公司目录查询、新增、改名、启停与删除")
public class CompanyController { public class CompanyController {
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
@@ -42,7 +44,11 @@ public class CompanyController {
@Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤") @Parameter(description = "所属平台(V206):amazon|jd,缺省不过滤")
@RequestParam(name = "platform", required = false) String platform) { @RequestParam(name = "platform", required = false) String platform) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
List<CompanyVo> items = companyService.listVisible(operator, platform).stream().map(CompanyVo::from).toList(); // 一次分组查询带出各公司在册账号数:前端据此把「名下还有账号」的公司勾选框置灰(2026-11-23)。
Map<Long, Long> userCounts = companyService.userCountByCompany();
List<CompanyVo> items = companyService.listVisible(operator, platform).stream()
.map(company -> CompanyVo.from(company, userCounts.getOrDefault(company.getId(), 0L)))
.toList();
return ApiResponse.success(items); return ApiResponse.success(items);
} }
@@ -53,7 +59,6 @@ public class CompanyController {
return ApiResponse.success("公司创建成功", CompanyVo.from(companyService.create(operator, body))); return ApiResponse.success("公司创建成功", CompanyVo.from(companyService.create(operator, body)));
} }
/** 没有 DELETE:账号挂着的公司删不掉,停用(status=0)就是终态。 */
@PutMapping("/companies/{id}") @PutMapping("/companies/{id}")
@Operation(summary = "改名与启停(仅超级管理员)") @Operation(summary = "改名与启停(仅超级管理员)")
public ApiResponse<CompanyVo> updateCompany(HttpServletRequest request, public ApiResponse<CompanyVo> updateCompany(HttpServletRequest request,
@@ -62,4 +67,13 @@ public class CompanyController {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request); AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
return ApiResponse.success("更新成功", CompanyVo.from(companyService.update(operator, id, body))); return ApiResponse.success("更新成功", CompanyVo.from(companyService.update(operator, id, body)));
} }
/** 删除(2026-11-23):只收公司行+该公司菜单树,名下有账号的公司删不得(CompanyService 兜底校验)。 */
@DeleteMapping("/companies/{id}")
@Operation(summary = "删除公司(仅超级管理员,名下有账号则拒绝)")
public ApiResponse<Void> deleteCompany(HttpServletRequest request, @PathVariable Long id) {
AdminUserEntity operator = adminAuthSupport.requireAdminOrInternal(request);
companyService.delete(operator, id);
return ApiResponse.success("删除成功", null);
}
} }
@@ -1,9 +1,26 @@
package com.nanri.aiimage.modules.company.mapper; package com.nanri.aiimage.modules.company.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.nanri.aiimage.modules.company.model.dto.CompanyUserCountRow;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper @Mapper
public interface CompanyMapper extends BaseMapper<CompanyEntity> { public interface CompanyMapper extends BaseMapper<CompanyEntity> {
/**
* 每家公司在册账号数(users.company_id 分组计数,SQL 收口在 Mapper 层)。
* 停用账号也算在册——它们仍挂在公司上,删了公司一样把人挂在查不到的租户名下。
* 公司行是硬删(无软删位),users 侧同样硬删,所以这里不用再过滤删除标记。
*/
@Select("SELECT company_id AS companyId, COUNT(*) AS userCount FROM users GROUP BY company_id")
List<CompanyUserCountRow> selectUserCountByCompany();
/** 单家公司在册账号数:CompanyService.delete 的「有账号不能删」闸门用(权威校验,前端那份只是展示提示)。 */
@Select("SELECT COUNT(*) FROM users WHERE company_id = #{companyId}")
Long selectUserCountByCompanyId(@Param("companyId") Long companyId);
} }
@@ -0,0 +1,14 @@
package com.nanri.aiimage.modules.company.model.dto;
import lombok.Data;
/**
* 每家公司在册账号数(CompanyMapper.selectUserCountByCompany 的行形状)。
* 公司管理列表用它标出"名下还有账号、删不得"的公司(2026-11-23 用户拍板:有账号不能删)。
*/
@Data
public class CompanyUserCountRow {
private Long companyId;
private Long userCount;
}
@@ -19,7 +19,7 @@ public class CompanyEntity {
private Long id; private Long id;
@TableField("company_name") @TableField("company_name")
private String companyName; private String companyName;
/** 1=启用 0=停用。停用不删行:有账号挂着的公司删不掉。 */ /** 1=启用 0=停用。停用≠删除:删除是独立显式入口(DELETE /api/admin/companies/{id}),名下有账号的公司删不得。 */
private Integer status; private Integer status;
private String remark; private String remark;
/** /**
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.company.model.vo; package com.nanri.aiimage.modules.company.model.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import lombok.Data; import lombok.Data;
@@ -27,8 +28,19 @@ public class CompanyVo {
private String createdAt; private String createdAt;
@JsonProperty("updated_at") @JsonProperty("updated_at")
private String updatedAt; private String updatedAt;
/**
* 在册账号数(2026-11-23):仅公司目录列表下发,供前端标出「名下还有账号、删不得」的公司;
* create/update 回包不带(null 不序列化,旧键集形状不变)。
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty("user_count")
private Long userCount;
public static CompanyVo from(CompanyEntity entity) { public static CompanyVo from(CompanyEntity entity) {
return from(entity, null);
}
public static CompanyVo from(CompanyEntity entity, Long userCount) {
CompanyVo vo = new CompanyVo(); CompanyVo vo = new CompanyVo();
vo.setId(entity.getId()); vo.setId(entity.getId());
vo.setCompanyName(entity.getCompanyName()); vo.setCompanyName(entity.getCompanyName());
@@ -37,6 +49,7 @@ public class CompanyVo {
vo.setPlatform(entity.getPlatform()); vo.setPlatform(entity.getPlatform());
vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME)); vo.setCreatedAt(entity.getCreatedAt() == null ? "" : entity.getCreatedAt().format(TIME));
vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME)); vo.setUpdatedAt(entity.getUpdatedAt() == null ? "" : entity.getUpdatedAt().format(TIME));
vo.setUserCount(userCount);
return vo; return vo;
} }
} }
@@ -8,9 +8,11 @@ import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminPlatformScope; import com.nanri.aiimage.common.service.AdminPlatformScope;
import com.nanri.aiimage.modules.company.mapper.CompanyMapper; import com.nanri.aiimage.modules.company.mapper.CompanyMapper;
import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest; import com.nanri.aiimage.modules.company.model.dto.CompanySaveRequest;
import com.nanri.aiimage.modules.company.model.dto.CompanyUserCountRow;
import com.nanri.aiimage.modules.company.model.entity.CompanyEntity; import com.nanri.aiimage.modules.company.model.entity.CompanyEntity;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService; import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -20,7 +22,9 @@ import java.util.HashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
public class CompanyService { public class CompanyService {
@@ -84,6 +88,18 @@ public class CompanyService {
return companyMapper.selectList(query); return companyMapper.selectList(query);
} }
/**
* 各公司在册账号数(id → count,一次分组查询,别逐行 COUNT 凑 N+1)。
* 公司管理列表据此标出「名下还有账号、删不得」的公司;没有账号的公司不在 Map 里,
* 调用方用 {@code getOrDefault(id, 0L)} 归零。
*/
public Map<Long, Long> userCountByCompany() {
return companyMapper.selectUserCountByCompany().stream()
.filter(row -> row.getCompanyId() != null)
.collect(Collectors.toMap(CompanyUserCountRow::getCompanyId,
row -> row.getUserCount() == null ? 0L : row.getUserCount()));
}
/** /**
* 按 id 批量补公司名(§2.3 账号列表、§2.4 登录态都用它,别写成逐行查的 N+1)。 * 按 id 批量补公司名(§2.3 账号列表、§2.4 登录态都用它,别写成逐行查的 N+1)。
* *
@@ -147,7 +163,7 @@ public class CompanyService {
return entity; return entity;
} }
/** 改名 + 启停一起改;不提供删除,账号挂着的公司删不掉。 */ /** 改名 + 启停一起改;删除是独立入口 {@link #delete}(名下有账号的公司删不得)。 */
public CompanyEntity update(AdminUserEntity operator, Long id, CompanySaveRequest request) { public CompanyEntity update(AdminUserEntity operator, Long id, CompanySaveRequest request) {
ensureSuperAdmin(operator); ensureSuperAdmin(operator);
CompanyEntity company = companyMapper.selectById(id); CompanyEntity company = companyMapper.selectById(id);
@@ -172,6 +188,32 @@ public class CompanyService {
return company; return company;
} }
/**
* 删除公司(2026-11-23 用户拍板「有账号不能删」):只收公司行 + 该公司的菜单权限树
* (columns,与建号时 {@code copyTreeFromTemplate} 种下的对称),业务数据一律不级联。
*
* <p>店铺分组/店铺密钥/去重数据/京东与外观专利等表里的 {@code company_id} 行是历史数据,
* 留着无害:company id 自增不复用,唯一键都带 company_id,不存在新公司撞旧数据;
* 这与京东删除任务不级联清数据库表是同一条铁律(删除只收显式说的那部分)。</p>
*
* <p>事务包住两件事:删菜单树 + 删公司行,任一失败一起回滚,不留「行没了树还在」的半成品。</p>
*/
@Transactional
public void delete(AdminUserEntity operator, Long id) {
ensureSuperAdmin(operator);
CompanyEntity company = companyMapper.selectById(id);
if (company == null) {
throw new BusinessException("公司不存在");
}
Long userCount = companyMapper.selectUserCountByCompanyId(id);
if (userCount != null && userCount > 0) {
throw new BusinessException("该公司名下还有 " + userCount + " 个账号,请先删除或转移后再删除公司");
}
permissionMenuService.deleteTreeByCompany(id);
companyMapper.deleteById(id);
log.info("[company] 公司已删除 companyId={} name={}", id, company.getCompanyName());
}
/** uk_company_name 只能兜底并发,不能当校验用:撞索引抛的是"用户名已存在"这类看不懂的文案。 */ /** uk_company_name 只能兜底并发,不能当校验用:撞索引抛的是"用户名已存在"这类看不懂的文案。 */
private void ensureNameAvailable(String companyName, Long excludeId) { private void ensureNameAvailable(String companyName, Long excludeId) {
LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<CompanyEntity>() LambdaQueryWrapper<CompanyEntity> query = new LambdaQueryWrapper<CompanyEntity>()
@@ -467,6 +467,28 @@ public class PermissionMenuService {
return inserted; return inserted;
} }
/**
* 删除某公司的整棵菜单树(columns 表按 company_id 清行),与 {@link #copyTreeFromTemplate}
* 对称:建号时种下的树,删号时收走,不留孤儿行。
*
* <p>调用方(CompanyService.delete)必须先确认该公司名下已无账号——树是公司私有配置,
* 没有账号引用它才允许整棵删;这里不再重复判账号数(判了就要反向依赖 admin 模块,
* 事务边界由调用方的 @Transactional 兜住,删树失败连公司行一起回滚)。</p>
*
* @return 本次删除的菜单行数(写日志与测试断言用)
*/
@Transactional
public int deleteTreeByCompany(Long companyId) {
if (companyId == null || companyId <= 0) {
throw new BusinessException("公司 id 不能为空");
}
int deleted = permissionMenuMapper.delete(new LambdaQueryWrapper<PermissionMenuEntity>()
.eq(PermissionMenuEntity::getCompanyId, companyId));
log.info("[menu-tree-delete] 公司菜单树已删 companyId={} rows={}", companyId, deleted);
invalidateMenuTreeCache();
return deleted;
}
/** Returns only persisted direct grant IDs (never recursively expanded). */ /** Returns only persisted direct grant IDs (never recursively expanded). */
public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) { public UserColumnIdsVo getUserColumnIds(Long userId, String menuType) {
return getUserColumnIds(null, userId, menuType); return getUserColumnIds(null, userId, menuType);
@@ -20,6 +20,7 @@ import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
@@ -30,8 +31,9 @@ import static org.mockito.Mockito.when;
/** /**
* 公司目录端点的对外契约(设计文档 §2.3)。 * 公司目录端点的对外契约(设计文档 §2.3)。
* *
* <p>钉的是 admin-frontend-vue/src/api/companies.ts 实际会打的三个地址,以及"先鉴权、 * <p>钉的是 admin-frontend-vue/src/api/companies.ts 实际会打的地址(含 2026-11-23 新增的
* 再碰目录"的顺序。路径写错时前端只会拿到空列表、不报错,所以只能由用例盯着。</p> * 删除口),以及"先鉴权、再碰目录"的顺序。路径写错时前端只会拿到空列表、不报错,
* 所以只能由用例盯着。</p>
*/ */
class CompanyControllerEndpointTest { class CompanyControllerEndpointTest {
@@ -58,6 +60,7 @@ class CompanyControllerEndpointTest {
when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator); when(adminAuthSupport.requireAdminOrInternal(request)).thenReturn(operator);
when(companyService.listVisible(operator, null)).thenReturn(List.of(company(1L, "厦门米椿花"))); when(companyService.listVisible(operator, null)).thenReturn(List.of(company(1L, "厦门米椿花")));
when(companyService.userCountByCompany()).thenReturn(Map.of(1L, 3L));
when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富")); when(companyService.create(any(), any())).thenReturn(company(2L, "福州数富"));
when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技")); when(companyService.update(any(), any(), any())).thenReturn(company(2L, "福州数富科技"));
} }
@@ -76,6 +79,7 @@ class CompanyControllerEndpointTest {
controller.listCompanies(request, null); controller.listCompanies(request, null);
controller.createCompany(request, body); controller.createCompany(request, body);
controller.updateCompany(request, 2L, body); controller.updateCompany(request, 2L, body);
controller.deleteCompany(request, 2L);
InOrder order = inOrder(adminAuthSupport, companyService); InOrder order = inOrder(adminAuthSupport, companyService);
order.verify(adminAuthSupport).requireAdminOrInternal(request); order.verify(adminAuthSupport).requireAdminOrInternal(request);
@@ -84,6 +88,8 @@ class CompanyControllerEndpointTest {
order.verify(companyService).create(operator, body); order.verify(companyService).create(operator, body);
order.verify(adminAuthSupport).requireAdminOrInternal(request); order.verify(adminAuthSupport).requireAdminOrInternal(request);
order.verify(companyService).update(operator, 2L, body); order.verify(companyService).update(operator, 2L, body);
order.verify(adminAuthSupport).requireAdminOrInternal(request);
order.verify(companyService).delete(operator, 2L);
} }
@Test @Test
@@ -93,16 +99,22 @@ class CompanyControllerEndpointTest {
assertThat(pathsOf("listCompanies")).contains("/companies"); assertThat(pathsOf("listCompanies")).contains("/companies");
assertThat(pathsOf("createCompany")).contains("/companies"); assertThat(pathsOf("createCompany")).contains("/companies");
assertThat(pathsOf("updateCompany")).contains("/companies/{id}"); assertThat(pathsOf("updateCompany")).contains("/companies/{id}");
assertThat(pathsOf("deleteCompany")).contains("/companies/{id}");
} }
@Test @Test
@DisplayName("不提供删除公司的端点:账号挂着的公司删不掉,只能停用") @DisplayName("删除端点在册(2026-11-23 起):只许挂在 /companies/{id} 上")
void exposesNoDeleteEndpoint() { void exposesDeleteEndpointForCompanyRemoval() {
Method deleteMethod = null;
for (Method method : CompanyController.class.getDeclaredMethods()) { for (Method method : CompanyController.class.getDeclaredMethods()) {
assertThat(AnnotatedElementUtils.findMergedAnnotation(method, DeleteMapping.class)) if (method.getName().equals("deleteCompany")) {
.as("方法 %s 不该是 DELETE", method.getName()) deleteMethod = method;
.isNull(); }
} }
assertThat(deleteMethod).as("CompanyController 必须有 deleteCompany 端点").isNotNull();
DeleteMapping mapping = AnnotatedElementUtils.findMergedAnnotation(deleteMethod, DeleteMapping.class);
assertThat(mapping).as("deleteCompany 必须是 @DeleteMapping").isNotNull();
assertThat(mapping.path()).contains("/companies/{id}");
} }
@Test @Test
@@ -114,6 +126,14 @@ class CompanyControllerEndpointTest {
assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花"); assertThat(response.getData().get(0).getCompanyName()).isEqualTo("厦门米椿花");
} }
@Test
@DisplayName("列表带出在册账号数:Map 缺了这家就归 0,前端把非零的公司勾选框置灰")
void listCarriesUserCountForTheDeleteGuard() {
ApiResponse<List<CompanyVo>> response = controller.listCompanies(request, null);
assertThat(response.getData().get(0).getUserCount()).isEqualTo(3L);
}
@Test @Test
@DisplayName("新建/改名把落库后的那一条回给前端,省一次重新拉列表") @DisplayName("新建/改名把落库后的那一条回给前端,省一次重新拉列表")
void writeEndpointsReturnTheSavedCompany() { void writeEndpointsReturnTheSavedCompany() {
@@ -42,4 +42,28 @@ class CompanyVoTest {
// 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined // 库里没读到的时间给空串:前端 formatDateTime 才有占位,不会渲染出 undefined
assertThat(json.get("updated_at")).isEqualTo(""); assertThat(json.get("updated_at")).isEqualTo("");
} }
@Test
@DisplayName("在册账号数只在列表回包带(from(entity, count)),create/update 回包不带该键")
void carriesUserCountOnlyWhenGiven() throws Exception {
CompanyEntity entity = new CompanyEntity();
entity.setId(2L);
entity.setCompanyName("福州数富");
entity.setStatus(1);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> listed = mapper.readValue(
mapper.writeValueAsString(CompanyVo.from(entity, 5L)),
new TypeReference<Map<String, Object>>() {
});
Map<String, Object> saved = mapper.readValue(
mapper.writeValueAsString(CompanyVo.from(entity)),
new TypeReference<Map<String, Object>>() {
});
// 列表带 user_count:前端 CompaniesPage 据此把「名下还有账号」的公司勾选框置灰(2026-11-23)
assertThat(listed.get("user_count")).isEqualTo(5);
// create/update 回包键集保持旧形状(NON_NULL:null 不序列化),前端解析器不吃惊
assertThat(saved.keySet()).doesNotContain("user_count");
}
} }
@@ -48,9 +48,10 @@ class CompanyReadPathMenuGateTest {
List<String> guards = executableLines(text).stream() List<String> guards = executableLines(text).stream()
.filter(line -> line.contains("ensureSuperAdmin(operator);")) .filter(line -> line.contains("ensureSuperAdmin(operator);"))
.collect(Collectors.toList()); .collect(Collectors.toList());
// 2026-11-23 追加 delete(删公司):写路径从三处变四处,每一处都必须还挂着同一道超管闸
assertThat(guards) assertThat(guards)
.as("create / update / listVisible 三处的超管闸门 must 保留") .as("create / update / listVisible / delete 四处的超管闸门 must 保留")
.hasSize(3); .hasSize(4);
} }
/** 取样集非空自检:扫描一旦 0 命中,上面几条就恒绿,等于没护栏。 */ /** 取样集非空自检:扫描一旦 0 命中,上面几条就恒绿,等于没护栏。 */
@@ -0,0 +1,148 @@
package com.nanri.aiimage.modules.company.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.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.CompanyUserCountRow;
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.InOrder;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
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.anyLong;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 删除公司的守卫链(2026-11-23 用户拍板「名下有账号不能删」)。
*
* <p>删除只收两样:公司行 + 该公司的菜单权限树(与建号时 copyTreeFromTemplate 对称);
* 业务数据(店铺分组/密钥/去重/京东/外观专利等 company_id 行)一律不级联——
* 与京东删除任务不级联清数据库是同一条铁律。有账号的公司必须先删/转账号,这里再兜一道权威校验,
* 前端那份 user_count 置灰只是展示提示,不能当权限边界。</p>
*/
class CompanyServiceDeleteTest {
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);
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;
}
@Test
@DisplayName("删除公司仅超管:公司内管理员也删不得")
void companyAdminCannotDelete() {
assertThatThrownBy(() -> companyService.delete(operator("admin", 2L), 1L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("超级管理员");
verify(companyMapper, never()).deleteById(anyLong());
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
}
@Test
@DisplayName("删一家不存在的公司按失败处理,不许静默通过")
void deleteRejectsUnknownCompany() {
when(companyMapper.selectById(9L)).thenReturn(null);
assertThatThrownBy(() -> companyService.delete(operator("super_admin", 1L), 9L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("不存在");
verify(companyMapper, never()).deleteById(anyLong());
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
}
@Test
@DisplayName("名下还有账号的公司删不得:文案带账号数,树和行都不许动")
void deleteRejectsCompanyThatStillHasUsers() {
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
when(companyMapper.selectUserCountByCompanyId(2L)).thenReturn(5L);
assertThatThrownBy(() -> companyService.delete(operator("super_admin", 1L), 2L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("5 个账号");
verify(permissionMenuService, never()).deleteTreeByCompany(anyLong());
verify(companyMapper, never()).deleteById(anyLong());
}
@Test
@DisplayName("零账号的公司才可删:先删该公司菜单树、再删公司行,同一事务两步走")
void deleteRemovesMenuTreeThenCompanyRow() {
when(companyMapper.selectById(2L)).thenReturn(company(2, "福州数富", 1));
when(companyMapper.selectUserCountByCompanyId(2L)).thenReturn(0L);
when(permissionMenuService.deleteTreeByCompany(2L)).thenReturn(21);
companyService.delete(operator("super_admin", 1L), 2L);
InOrder order = inOrder(permissionMenuService, companyMapper);
order.verify(permissionMenuService).deleteTreeByCompany(2L);
order.verify(companyMapper).deleteById(2L);
}
@Test
@DisplayName("删除入口必须是 @Transactional:删树失败要连公司行一起回滚,不留半成品")
void deleteIsTransactionalSoTreeAndRowRollBackTogether() throws Exception {
assertThat(CompanyService.class
.getMethod("delete", AdminUserEntity.class, Long.class)
.isAnnotationPresent(Transactional.class)).isTrue();
}
@Test
@DisplayName("userCountByCompany 一次分组查询出全量,行缺 companyId 时安全跳过")
void userCountByCompanyAggregatesInOneQuery() {
CompanyUserCountRow row = new CompanyUserCountRow();
row.setCompanyId(3L);
row.setUserCount(7L);
CompanyUserCountRow broken = new CompanyUserCountRow();
broken.setCompanyId(null);
when(companyMapper.selectUserCountByCompany()).thenReturn(List.of(row, broken));
Map<Long, Long> counts = companyService.userCountByCompany();
assertThat(counts).containsOnlyKeys(3L);
assertThat(counts.get(3L)).isEqualTo(7L);
}
}
@@ -0,0 +1,85 @@
package com.nanri.aiimage.modules.permission.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.mapper.AdminUserMapper;
import com.nanri.aiimage.modules.permission.mapper.PermissionMenuMapper;
import com.nanri.aiimage.modules.permission.mapper.UserColumnPermissionMapper;
import com.nanri.aiimage.modules.permission.model.entity.PermissionMenuEntity;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
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.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* {@link PermissionMenuService#deleteTreeByCompany(Long)} 的单测:删号公司时按 company_id
* 整棵收走菜单树(与 copyTreeFromTemplate 对称)。账号数守卫在 CompanyService.delete 那一层,
* 这里只钉「按公司收行」这件事本身。
*/
class PermissionMenuServiceDeleteTreeTest {
private PermissionMenuMapper menuMapper;
private UserColumnPermissionMapper permissionMapper;
private AdminUserMapper userMapper;
private PermissionMenuService service;
@BeforeAll
static void initMybatisPlusTableInfo() {
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
TableInfoHelper.initTableInfo(assistant, PermissionMenuEntity.class);
}
@BeforeEach
void setUp() {
menuMapper = mock(PermissionMenuMapper.class);
permissionMapper = mock(UserColumnPermissionMapper.class);
userMapper = mock(AdminUserMapper.class);
service = new PermissionMenuService(menuMapper, permissionMapper, userMapper);
}
@SuppressWarnings("unchecked")
private LambdaQueryWrapper<PermissionMenuEntity> capturedDelete() {
ArgumentCaptor<LambdaQueryWrapper<PermissionMenuEntity>> captor =
ArgumentCaptor.forClass((Class) LambdaQueryWrapper.class);
verify(menuMapper).delete(captor.capture());
// MP 的参数要渲染一次 sqlSegment 才落进 paramNameValuePairs
assertThat(captor.getValue().getSqlSegment()).isNotNull();
return captor.getValue();
}
@Test
@DisplayName("按 company_id 整棵删:条件带目标公司的 id,回删掉的行数")
void deletesEveryMenuRowOfTheTargetCompany() {
when(menuMapper.delete(any())).thenReturn(21);
int deleted = service.deleteTreeByCompany(7L);
assertThat(deleted).isEqualTo(21);
LambdaQueryWrapper<PermissionMenuEntity> query = capturedDelete();
assertThat(query.getParamNameValuePairs()).containsValue(7L);
// 只按归属收行,不按类型/父级再切:每家公司一棵树,一次清干净
assertThat(query.getSqlSegment()).doesNotContain("menu_type");
}
@Test
@DisplayName("公司 id 空或非法直接拒,不许退化成清全表")
void rejectsBlankOrInvalidCompanyId() {
assertThatThrownBy(() -> service.deleteTreeByCompany(null))
.isInstanceOf(BusinessException.class);
assertThatThrownBy(() -> service.deleteTreeByCompany(0L))
.isInstanceOf(BusinessException.class);
verify(menuMapper, never()).delete(any());
}
}