package ssw.common.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.v3.oas.annotations.Operation; import jakarta.servlet.http.HttpServletRequest; import jnpf.base.ActionResult; import jnpf.base.Pagination; import jnpf.base.entity.SuperExtendEntity; import jnpf.base.service.SuperService; import jnpf.base.vo.PaginationVO; import jnpf.util.JsonUtil; import jnpf.util.RandomUtil; import jnpf.util.UserProvider; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; /** * ssw 通用 CRUD 控制器骨架 — 业务 Controller 继承它即可省去 List/Page/Detail/Create/Update/Delete 样板。 * * 子类只声明「关键字匹配哪些列」「支持哪些过滤参数」, * 需要时覆写 {@link #beforeSave} 做业务校验。 * * 三条硬约定: * * * 审计留痕:{@link #audit} 钩子默认 noop。子类按需 override 连到自家审计服务 * (日志表 / MQ / 第三方审计平台)即可,方法签名见 {@code audit(action, bizId, target)}。 * * @param 实体类型(业务扩展位用 SuperExtendEntity) */ public abstract class BaseCrudController> { /** * 菜单权限检查钩子。基类不依赖任何权限框架 — 子类按需覆盖({@code @PreAuthorize} / * Sa-Token {@code @SaCheckPermission} / 调自家权限服务均可)。 * 默认空实现(不检查权限),适合 demo / 内部工具。 */ protected void requireMenuPermission() { } /** * 数据范围过滤钩子。基类不依赖具体的数据范围解析器 — 子类按需覆盖往 wrapper 里拼 SQL。 * 默认空实现(不过滤数据范围),适合单租户 / demo。 */ protected void applyDataScope(QueryWrapper wrapper, HttpServletRequest request) { } /** 逻辑未删除条件,所有查询都要带 */ protected static final String ALIVE = "(f_delete_mark IS NULL OR f_delete_mark = 0)"; // ------------------------------------------------------------------ 子类扩展点 protected abstract SuperService service(); /** 新建实体实例(泛型擦除拿不到构造器,交给子类) */ protected abstract T newEntity(); /** 关键字模糊匹配的列,返回空数组表示不支持关键字搜索 */ protected String[] keywordColumns() { return new String[]{"f_name"}; } /** 精确过滤:请求参数名 -> 数据库列名 */ protected Map filterColumns() { return Collections.emptyMap(); } /** * 该表的「租户」列名,返回 null 表示本表不按租户隔离 * (如实例级全局配置)。返回非 null 时,请求参数 tenantId 自动生效。 */ protected String tenantColumn() { return "f_tenant_id"; } /** 默认排序列,倒序 */ protected String defaultOrderColumn() { return "f_creator_time"; } /** * 落库前的钩子,可做业务校验/补默认值。抛异常即中断并返回 fail。 * * @param entity 待保存实体 * @param create true=新增,false=修改 */ protected void beforeSave(T entity, boolean create) { } /** 删除前的钩子,可做引用检查 */ protected void beforeDelete(T entity) { } // ------------------------------------------------------------------ 审计留痕扩展点(可选实现) /** * 本控制器对应的业务类型。默认由实体类名推导;返回 {@code null} 表示不留痕。 */ protected String auditBizType() { String name = newEntity().getClass().getSimpleName().replaceAll("Entity$", ""); return name.replaceAll("([a-z0-9])([A-Z])", "$1_$2").toUpperCase(); } /** 留痕时展示的对象描述 */ protected String auditTarget(T entity) { if (entity == null) { return null; } for (String getter : new String[]{"getCode", "getName", "getTaskNo", "getOrderCode", "getDemandCode", "getResourceName", "getProductName", "getTitle", "getFullName"}) { try { Object v = entity.getClass().getMethod(getter).invoke(entity); if (v != null && !v.toString().isBlank()) { return v.toString(); } } catch (Exception ignore) { // 该实体没有这个字段,继续试下一个 } } return entity.getId(); } /** * 写一条业务留痕。子类要启用审计时,覆盖此方法连到自家审计服务; * 不覆盖则 {@link #create} / {@link #update} / {@link #delete} 三处 audit 调用静默 noop。 * * 替换为自家实现时可参考方法签名:bizId 实体主键 / action CREATE|UPDATE|DELETE / target 业务标识。 */ protected void audit(String action, String bizId, String target) { // 默认 noop;子类按需 override } /** 写一条带结果与明细的业务留痕;默认 noop */ protected void audit(String action, String bizId, String target, String result, String failReason, String detail) { // 默认 noop;子类按需 override } // ------------------------------------------------------------------ 通用接口 @GetMapping @Operation(summary = "分页列表", description = "支持 keyword 模糊搜索、tenantId 过滤与子类声明的精确过滤参数") public ActionResult list(Pagination pagination, HttpServletRequest request) { requireMenuPermission(); QueryWrapper wrapper = buildWrapper(request); long current = pagination.getCurrentPage() <= 0 ? 1 : pagination.getCurrentPage(); long size = pagination.getPageSize() <= 0 ? 20 : Math.min(pagination.getPageSize(), 500); com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size); IPage result = service().page(page, wrapper); List records = pagination.setData(result.getRecords(), result.getTotal()); return ActionResult.page(records, JsonUtil.getJsonToBean(pagination, PaginationVO.class)); } @GetMapping("/All") @Operation(summary = "不分页全量列表", description = "用于下拉选择等场景,最多返回 1000 条") public ActionResult> all(HttpServletRequest request) { requireMenuPermission(); QueryWrapper wrapper = buildWrapper(request); wrapper.last("limit 1000"); return ActionResult.success(service().list(wrapper)); } @GetMapping("/{id}") @Operation(summary = "详情") public ActionResult detail(@PathVariable("id") String id) { requireMenuPermission(); T entity = getAlive(id); if (entity == null) { return ActionResult.fail("记录不存在或已删除"); } return ActionResult.success(entity); } @PostMapping @Operation(summary = "新增") public ActionResult create(@RequestBody T entity) { requireMenuPermission(); entity.setId(RandomUtil.uuId()); entity.setDeleteMark(null); beforeSave(entity, true); service().save(entity); audit("CREATE", entity.getId(), auditTarget(entity)); return ActionResult.success("新增成功", entity.getId()); } @PutMapping("/{id}") @Operation(summary = "修改", description = "只覆盖请求体里出现的字段,未传字段保持原值") public ActionResult update(@PathVariable("id") String id, @RequestBody T entity) { requireMenuPermission(); T exists = getAlive(id); if (exists == null) { return ActionResult.fail("记录不存在或已删除"); } entity.setId(id); // 系统列不允许从请求体覆盖 entity.setCreatorTime(null); entity.setCreatorUserId(null); entity.setDeleteMark(null); entity.setDeleteTime(null); entity.setDeleteUserId(null); beforeSave(entity, false); service().updateById(entity); // 用改前的实体取 target:改后的对象只带请求体里出现的字段,编号往往是 null audit("UPDATE", id, auditTarget(exists)); return ActionResult.success("修改成功", id); } @DeleteMapping("/{id}") @Operation(summary = "删除", description = "逻辑删除,置 f_delete_mark=1") public ActionResult delete(@PathVariable("id") String id) { requireMenuPermission(); T exists = getAlive(id); if (exists == null) { return ActionResult.fail("记录不存在或已删除"); } beforeDelete(exists); T update = newEntity(); update.setId(id); update.setDeleteMark(1); update.setDeleteTime(new Date()); update.setDeleteUserId(safeUserId()); service().updateById(update); audit("DELETE", id, auditTarget(exists)); return ActionResult.success("删除成功", id); } // ------------------------------------------------------------------ 内部工具 protected QueryWrapper buildWrapper(HttpServletRequest request) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.apply(ALIVE); String tenantColumn = tenantColumn(); if (tenantColumn != null) { String tenantId = param(request, "tenantId"); if (tenantId != null) { wrapper.eq(tenantColumn, tenantId); } } filterColumns().forEach((param, column) -> { String value = param(request, param); if (value != null) { wrapper.eq(column, value); } }); String keyword = param(request, "keyword"); String[] columns = keywordColumns(); if (keyword != null && columns.length > 0) { wrapper.and(w -> { for (int i = 0; i < columns.length; i++) { if (i == 0) { w.like(columns[i], keyword); } else { w.or().like(columns[i], keyword); } } }); } applyDataScope(wrapper, request); wrapper.orderByDesc(defaultOrderColumn()); return wrapper; } /** 取请求参数,空串统一归一成 null */ protected String param(HttpServletRequest request, String name) { if (request == null) { return null; } String value = request.getParameter(name); if (value == null) { return null; } value = value.trim(); return value.isEmpty() ? null : value; } /** 按主键取未删除的记录 */ protected T getAlive(String id) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq("f_id", id).apply(ALIVE); return service().getOne(wrapper, false); } /** 判断某列值是否已被占用(排除自身),用于编码唯一性校验 */ protected boolean existsBy(String column, String value, String excludeId) { QueryWrapper wrapper = new QueryWrapper<>(); wrapper.eq(column, value).apply(ALIVE); if (excludeId != null && !excludeId.isEmpty()) { wrapper.ne("f_id", excludeId); } return service().count(wrapper) > 0; } /** 必填校验小工具,减少 Controller 里成片的 if-blank */ protected void requireText(String value, String message) { if (value == null || value.isBlank()) { throw new IllegalArgumentException(message); } } protected String safeUserId() { try { return UserProvider.getLoginUserId(); } catch (Exception e) { return null; } } }