!35 首页统计

Merge pull request !35 from 鸭先知/feature_dzc
This commit is contained in:
2025-09-30 21:12:07 +00:00
committed by Gitee
93 changed files with 4123 additions and 1048 deletions
+3 -1
View File
@@ -17,7 +17,9 @@
"Bash(lsof:*)", "Bash(lsof:*)",
"Bash(findstr:*)", "Bash(findstr:*)",
"Bash(npm run start:*)", "Bash(npm run start:*)",
"Bash(npm start)" "Bash(npm start)",
"Bash(npm run build:*)",
"Bash(dir:*)"
], ],
"deny": [], "deny": [],
"ask": [] "ask": []
+1
View File
@@ -4,6 +4,7 @@
- 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。 - 所有交互回答必须使用中文(简体),包括解释、建议与错误信息。
- 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。 - 代码片段中的注释、日志消息、文档内容与示例说明均应为中文;编程语言关键字与三方 API 标识符保持原文。
- 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。 - 提交信息(commit)、合并请求(PR)描述与 Issue 标题/内容默认使用中文;涉及外部专有名词可保留英文缩写。
- 所有中文都使用utf-8
## 权限与执行策略 ## 权限与执行策略
- 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。 - 默认权限:Codex 在本仓库内可直接读取与编辑文件,无需额外审批。
-1
View File
@@ -1 +0,0 @@
/* Go-Fly Admin 鐜颁唬绉戞妧鎰熶富棰?*//* CSS鍙橀噺瀹氫箟 */:root { /* 涓昏壊璋?*/ --primary-color: #1677ff; --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); --tech-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%); /* 鑳屾櫙鑹?*/ --bg-primary: #0f1419; --bg-secondary: #1a1d23; --bg-tertiary: #21252b; --bg-card: rgba(255, 255, 255, 0.05); --bg-glass: rgba(255, 255, 255, 0.08); /* 鏂囧瓧棰滆壊 */ --text-primary: #ffffff; --text-secondary: #a0a6b8; --text-tertiary: #6c7293; /* 杈规鍜屽垎鍓茬嚎 */ --border-color: rgba(255, 255, 255, 0.1); --divider-color: rgba(255, 255, 255, 0.08); /* 闃村奖 */ --shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3); --shadow-hover: 0 12px 48px rgba(0, 0, 0, 0.4); --shadow-glow: 0 0 20px rgba(102, 126, 234, 0.3); /* 鍔ㄧ敾鏇茬嚎 */ --ease-out-quart: cubic-bezier(0.25, 1, 0.5, 1); --ease-in-out-back: cubic-bezier(0.68, -0.55, 0.265, 1.55);}/* 鍏ㄥ眬鏍峰紡閲嶇疆 */body { background: var(--bg-primary); color: var(--text-primary); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;}/* 鐜荤拑璐ㄦ劅鏁堟灉 */.glass-effect { background: var(--bg-glass); backdrop-filter: blur(10px); border: 1px solid var(--border-color); border-radius: 12px;}/* 鍗$墖鎮仠鏁堟灉 */.modern-card { background: var(--bg-card); border-radius: 16px; padding: 24px; box-shadow: var(--shadow-card); border: 1px solid var(--border-color); transition: all 0.3s var(--ease-out-quart); &:hover { transform: translateY(-4px); box-shadow: var(--shadow-hover); border-color: var(--primary-color); }}/* 绉戞妧鎰熸寜閽?*/.tech-button { background: var(--tech-gradient); border: none; border-radius: 8px; color: white; font-weight: 500; transition: all 0.3s var(--ease-out-quart); position: relative; overflow: hidden; &::before { content: ''; position: absolute;
@@ -0,0 +1,22 @@
-- 创建套餐表
-- 执行前请备份数据
USE `order-center`;
CREATE TABLE IF NOT EXISTS `packages` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`code_id` VARCHAR(64) NOT NULL COMMENT '二维码编码(与qrcodes.code_id对应)',
`vlog_count` INT DEFAULT 0 COMMENT 'Vlog数量',
`video_count` INT DEFAULT 0 COMMENT '视频数量',
`photo_count` INT DEFAULT 0 COMMENT '照片数量',
`tenant_id` VARCHAR(64) DEFAULT NULL COMMENT '租户ID',
`company` VARCHAR(128) DEFAULT NULL COMMENT '所属公司',
`is_del` TINYINT(1) DEFAULT 0 COMMENT '是否删除 0-否 1-是',
`create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`),
KEY `idx_code_id` (`code_id`),
KEY `idx_tenant_id` (`tenant_id`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='套餐表';
@@ -34,6 +34,9 @@ public class DashboardController {
@Operation(summary = "获取首页统计数据") @Operation(summary = "获取首页统计数据")
@GetMapping("/statistics") @GetMapping("/statistics")
public Result<DashboardStatisticsVO> getStatistics( public Result<DashboardStatisticsVO> getStatistics(
@Parameter(description = "租户ID") @RequestParam(required = false) String tenantId,
@Parameter(description = "是否包含子租户") @RequestParam(required = false) Boolean includeChildren,
@Parameter(description = "统计类型(day/month/year)") @RequestParam(required = false, defaultValue = "day") String statType,
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId, @Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId, @Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn, @Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
@@ -42,6 +45,21 @@ public class DashboardController {
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) { @Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
try { try {
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
// 规范化租户与子租户范围
String anchor = tenantId;
try {
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
}
} catch (Exception ignored) { }
boolean withChildren = (includeChildren == null) || Boolean.TRUE.equals(includeChildren);
params.put("tenantId", anchor);
params.put("includeChildren", withChildren);
// 其他筛选参数
params.put("statType", statType);
params.put("tourismId", tourismId); params.put("tourismId", tourismId);
params.put("qrcodeId", qrcodeId); params.put("qrcodeId", qrcodeId);
params.put("deviceSn", deviceSn); params.put("deviceSn", deviceSn);
@@ -64,6 +82,20 @@ public class DashboardController {
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) { @Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
try { try {
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
// 追加租户范围(当前租户及其所有子租户)
try {
String anchor = com.central.common.context.TenantQueryOverrideContext.getTenantId();
if (anchor == null || anchor.isEmpty()) {
anchor = com.central.common.context.LoginUserContextHolder.getCurrentTenantId();
}
com.central.common.service.ITenantHierarchyService tenantService = com.central.common.utils.SpringContextHolder.getBean(com.central.common.service.ITenantHierarchyService.class);
if (tenantService != null && anchor != null && !anchor.isEmpty()) {
java.util.List<String> tenantIds = tenantService.getAllSubTenantIds(anchor);
if (tenantIds != null && !tenantIds.isEmpty()) {
params.put("tenantIds", tenantIds);
}
}
} catch (Exception ignored) {}
params.put("tourismId", tourismId); params.put("tourismId", tourismId);
params.put("includeTestQrcodes", includeTestQrcodes); params.put("includeTestQrcodes", includeTestQrcodes);
@@ -0,0 +1,88 @@
package com.central.order.controller;
import com.central.common.context.TenantContextHolder;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.order.model.PackagePlan;
import com.central.order.model.QrCode;
import com.central.order.service.IPackagePlanService;
import com.central.order.service.IQrCodeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@Tag(name = "套餐管理")
@RequestMapping("/package")
public class PackagePlanController {
@Autowired
private IPackagePlanService packagePlanService;
@Autowired
private IQrCodeService qrCodeService;
@Operation(summary = "分页查询套餐列表")
@Parameters({
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
})
@GetMapping
public PageResult list(@RequestParam Map<String, Object> params) {
return packagePlanService.findList(params);
}
@Operation(summary = "根据ID查询套餐")
@GetMapping("/{id}")
public Result<PackagePlan> getById(@PathVariable("id") Long id) {
PackagePlan plan = packagePlanService.getById(id);
if (plan == null) {
return Result.failed("暂无数据");
}
return Result.succeed(plan, "获取成功");
}
@Operation(summary = "根据二维码编码获取套餐内容")
@GetMapping("/byCode/{codeId}")
public Result<List<PackagePlan>> getByCode(@PathVariable("codeId") String codeId) {
List<PackagePlan> list = packagePlanService.getByCodeId(codeId);
if (CollectionUtils.isEmpty(list)) {
return Result.succeed(list, "暂无数据");
}
return Result.succeed(list, "获取成功");
}
@Operation(summary = "新增或更新套餐")
@PostMapping
public Result<PackagePlan> saveOrUpdate(@RequestBody PackagePlan plan) {
if (plan.getId() == null) {
// 新增时补齐租户ID:优先取二维码的租户,否则用当前上下文租户
if (plan.getCodeId() != null) {
QrCode qr = qrCodeService.getByCodeId(plan.getCodeId());
if (qr != null) {
plan.setTenantId(qr.getTenantId());
}
}
if (plan.getTenantId() == null) {
plan.setTenantId(TenantContextHolder.getTenant());
}
}
boolean ok = packagePlanService.saveOrUpdate(plan);
return ok ? Result.succeed(plan, "操作成功") : Result.failed("操作失败");
}
@Operation(summary = "根据ID删除套餐")
@DeleteMapping("/{id}")
public Result<String> delete(@PathVariable("id") Long id) {
boolean ok = packagePlanService.removeById(id);
return ok ? Result.succeed("删除成功") : Result.failed("删除失败");
}
}
@@ -5,6 +5,9 @@ import com.central.common.model.Result;
import com.central.order.feign.FileCenterService; import com.central.order.feign.FileCenterService;
import com.central.order.model.*; import com.central.order.model.*;
import com.central.order.service.IOrderService; import com.central.order.service.IOrderService;
import com.central.order.service.IPackagePlanService;
import com.central.order.model.PackagePlan;
import com.central.order.model.dto.QrcodeWithPlanDTO;
import com.central.order.service.IQrCodeService; import com.central.order.service.IQrCodeService;
import com.central.order.service.ITourismFileService; import com.central.order.service.ITourismFileService;
import com.central.order.service.ITourismService; import com.central.order.service.ITourismService;
@@ -13,10 +16,12 @@ import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn; import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -52,6 +57,9 @@ public class QrCodeController {
@Autowired @Autowired
private IOrderService orderService; private IOrderService orderService;
@Autowired
private IPackagePlanService packagePlanService;
/** /**
* 列表 * 列表
*/ */
@@ -164,4 +172,58 @@ public class QrCodeController {
map.put("tourismId",qrCode.getTourismId()); map.put("tourismId",qrCode.getTourismId());
return map; return map;
} }
@Operation(summary = "创建/修改二维码并同步套餐")
@PostMapping("/withPlan")
@Transactional(rollbackFor = Exception.class)
public Result<QrCode> saveOrUpdateQrcodeWithPlan(@RequestBody QrcodeWithPlanDTO body) throws Exception {
Assert.notNull(body, "请求体不能为空");
Assert.notNull(body.getQrCode(), "二维码参数不能为空");
QrCode qrCode = body.getQrCode();
Integer vlogCount = body.getVlogCount();
Integer videoCount = body.getVideoCount();
Integer photoCount = body.getPhotoCount();
// 先复用现有的创建/修改逻辑
Result<QrCode> result;
if (qrCode.getId() == null) {
String codeId = UUID.randomUUID().toString();
Result<Map> upload = fileCenterService.uploadQrCodeFile(codeId);
if (upload.getResp_code() != 0) {
return Result.failed("创建二维码文件失败");
}
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
Assert.notNull(tourism, "请选择景区数据");
qrCode.setTenantId(tourism.getTenantId());
qrCode.setCodeId(codeId);
qrCode.setFilePath(upload.getData().get("filePath").toString());
qrCode.setFileId(upload.getData().get("fileId").toString());
if (qrCodeService.saveOrUpdate(qrCode)) {
result = Result.succeed(qrCode, "qrcode创建成功");
} else {
return Result.failed("qrcode创建失败");
}
} else {
qrCodeService.saveOrUpdate(qrCode);
result = Result.succeed(qrCode, "qrcode修改成功");
}
// 同步套餐:有则更新,无则创建
String codeId = qrCode.getCodeId();
if (codeId != null) {
List<PackagePlan> exists = packagePlanService.getByCodeId(codeId);
PackagePlan plan = exists != null && !exists.isEmpty() ? exists.get(0) : new PackagePlan();
plan.setCodeId(codeId);
if (plan.getTenantId() == null) {
plan.setTenantId(qrCode.getTenantId());
}
if (vlogCount != null) plan.setVlogCount(vlogCount);
if (videoCount != null) plan.setVideoCount(videoCount);
if (photoCount != null) plan.setPhotoCount(photoCount);
packagePlanService.saveOrUpdate(plan);
}
return result;
}
} }
@@ -1,11 +1,16 @@
package com.central.order.feign; package com.central.order.feign;
import com.central.common.constant.ServiceNameConstants; import com.central.common.constant.ServiceNameConstants;
import com.central.common.model.Result;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.order.feign.fallback.UserCenterServiceFallbackFactory; import com.central.order.feign.fallback.UserCenterServiceFallbackFactory;
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.cloud.openfeign.FeignClient;
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.RequestParam;
import java.util.List;
import java.util.Map;
/** /**
* user-center模块远程调用 * user-center模块远程调用
@@ -26,4 +31,12 @@ public interface UserCenterService {
*/ */
@GetMapping("/users/{id}") @GetMapping("/users/{id}")
SysUser findUserById(@PathVariable("id") Long id); SysUser findUserById(@PathVariable("id") Long id);
/**
* 获取指定租户(含自身)及其所有子孙租户ID
* @param tenantId 锚点租户ID
*/
@GetMapping("/tenant/hierarchy/{tenantId}")
Result<List<String>> getDescendantTenantIds(@PathVariable("tenantId") String tenantId) throws Exception;
} }
@@ -1,11 +1,14 @@
package com.central.order.feign.fallback; package com.central.order.feign.fallback;
import com.central.common.model.Result;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.order.feign.UserCenterService; import com.central.order.feign.UserCenterService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.List;
/** /**
* 用户中心调用失败回调 * 用户中心调用失败回调
* *
@@ -26,6 +29,13 @@ public class UserCenterServiceFallbackFactory implements FallbackFactory<UserCen
public SysUser findUserById(Long id) { public SysUser findUserById(Long id) {
return null; return null;
} }
@Override
public Result<List<String>> getDescendantTenantIds(String tenantId) {
log.warn("获取子孙租户失败,降级返回仅当前租户: {}, error: {}", tenantId, cause.getMessage());
// 降级策略:返回仅包含当前租户的列表
return Result.succeed(java.util.Collections.singletonList(tenantId));
}
}; };
} }
} }
@@ -38,6 +38,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
"</choose>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTotalOrders(@Param("p") Map<String, Object> params); Long getTotalOrders(@Param("p") Map<String, Object> params);
@@ -63,6 +72,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTodayOrders(@Param("p") Map<String, Object> params); Long getTodayOrders(@Param("p") Map<String, Object> params);
@@ -93,6 +106,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
"</choose>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getRefundedOrders(@Param("p") Map<String, Object> params); Long getRefundedOrders(@Param("p") Map<String, Object> params);
@@ -117,6 +139,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTodayRefundedOrders(@Param("p") Map<String, Object> params); Long getTodayRefundedOrders(@Param("p") Map<String, Object> params);
@@ -147,6 +173,15 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<choose>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"day\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 6 DAY) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"month\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) </when>",
" <when test='(p.startTime == null or p.startTime == \"\") and p.statType == \"year\"'> AND o.create_time &gt;= DATE_SUB(CURDATE(), INTERVAL 5 YEAR) </when>",
"</choose>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTotalPaidOrders(@Param("p") Map<String, Object> params); Long getTotalPaidOrders(@Param("p") Map<String, Object> params);
@@ -172,6 +207,10 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTodayPaidOrders(@Param("p") Map<String, Object> params); Long getTodayPaidOrders(@Param("p") Map<String, Object> params);
@@ -203,6 +242,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getTotalAmount(@Param("p") Map<String, Object> params); Long getTotalAmount(@Param("p") Map<String, Object> params);
@@ -233,6 +276,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
Long getRefundAmount(@Param("p") Map<String, Object> params); Long getRefundAmount(@Param("p") Map<String, Object> params);
@@ -241,7 +288,11 @@ public interface DashboardMapper {
@Select({ @Select({
"<script>", "<script>",
"SELECT", "SELECT",
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,", " <choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
" </choose>",
" 'created' as type,", " 'created' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -267,10 +318,23 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')", "<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL", "UNION ALL",
"SELECT", "SELECT",
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,", " <choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
" </choose>",
" 'completed' as type,", " 'completed' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -296,10 +360,23 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')", "<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"UNION ALL", "UNION ALL",
"SELECT", "SELECT",
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,", " <choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') as date, </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') as date, </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') as date, </otherwise>",
" </choose>",
" 'refunded' as type,", " 'refunded' as type,",
" COUNT(*) as value", " COUNT(*) as value",
"FROM orders o", "FROM orders o",
@@ -325,7 +402,16 @@ public interface DashboardMapper {
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>", "<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
" AND o.device_sn = #{p.deviceSn}", " AND o.device_sn = #{p.deviceSn}",
"</if>", "</if>",
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')", "<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY ",
"<choose>",
" <when test=\"p.statType == 'year'\"> DATE_FORMAT(o.create_time, '%Y') </when>",
" <when test=\"p.statType == 'month'\"> DATE_FORMAT(o.create_time, '%Y-%m') </when>",
" <otherwise> DATE_FORMAT(o.create_time, '%Y-%m-%d') </otherwise>",
"</choose>",
"ORDER BY date, type", "ORDER BY date, type",
"</script>" "</script>"
}) })
@@ -346,6 +432,10 @@ public interface DashboardMapper {
"<if test='p.tourismId != null'>", "<if test='p.tourismId != null'>",
" AND q.tourism_id = #{p.tourismId}", " AND q.tourism_id = #{p.tourismId}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND q.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"<if test='p.startTime != null and p.startTime != \"\"'>", "<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}", " AND o.create_time >= #{p.startTime}",
"</if>", "</if>",
@@ -454,6 +544,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"GROUP BY o.order_status", "GROUP BY o.order_status",
"</script>" "</script>"
}) })
@@ -486,6 +580,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"UNION ALL", "UNION ALL",
"SELECT", "SELECT",
" '景区分账' as type,", " '景区分账' as type,",
@@ -512,6 +610,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"UNION ALL", "UNION ALL",
"SELECT", "SELECT",
" '退款金额' as type,", " '退款金额' as type,",
@@ -538,6 +640,10 @@ public interface DashboardMapper {
"<if test='p.endTime != null and p.endTime != \"\"'>", "<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}", " AND o.create_time &lt;= #{p.endTime}",
"</if>", "</if>",
"<if test='p.tourismIds != null and p.tourismIds.size > 0'>",
" AND o.tourism_id IN",
" <foreach collection='p.tourismIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"</script>" "</script>"
}) })
List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params); List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params);
@@ -553,6 +659,10 @@ public interface DashboardMapper {
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>", "<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND is_test = 0", " AND is_test = 0",
"</if>", "</if>",
"<if test='p.tenantIds != null and p.tenantIds.size > 0'>",
" AND tenant_id IN",
" <foreach collection='p.tenantIds' item='tid' open='(' separator=',' close=')'>#{tid}</foreach>",
"</if>",
"<if test='p.tourismId != null'>", "<if test='p.tourismId != null'>",
" AND tourism_id = #{p.tourismId}", " AND tourism_id = #{p.tourismId}",
"</if>", "</if>",
@@ -560,4 +670,4 @@ public interface DashboardMapper {
"</script>" "</script>"
}) })
List<FilterOptions.OptionItem> getQrcodeOptions(@Param("p") Map<String, Object> params); List<FilterOptions.OptionItem> getQrcodeOptions(@Param("p") Map<String, Object> params);
} }
@@ -0,0 +1,24 @@
package com.central.order.mapper;
import com.central.db.mapper.SuperMapper;
import com.central.order.model.PackagePlan;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@Mapper
public interface PackagePlanMapper extends SuperMapper<PackagePlan> {
/**
* 根据二维码编码查询套餐列表
*/
List<PackagePlan> findByCodeId(@Param("codeId") String codeId);
/**
* 分页查询
*/
List<PackagePlan> findList(Page<PackagePlan> page, @Param("p") Map<String, Object> params);
}
@@ -74,4 +74,15 @@ public interface TourismMapper extends SuperMapper<Tourism> {
@Param("maxLatitude") BigDecimal maxLatitude @Param("maxLatitude") BigDecimal maxLatitude
); );
/**
* 根据租户ID集合查询景区ID集合
*/
List<Long> findTourismIdsByTenantIds(@Param("tenantIds") List<String> tenantIds);
/**
* 根据租户ID集合,基于二维码表(qrcodes)反查关联的景区ID集合
* 适用于景区记录未直接维护 tenant_id,或存在历史数据不一致的情况
*/
List<Long> findTourismIdsByTenantIdsFromQrcodes(@Param("tenantIds") List<String> tenantIds);
} }
@@ -0,0 +1,52 @@
package com.central.order.model;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.central.common.model.SuperEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
/**
* 套餐配置
*/
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("packages")
@Schema(description = "套餐配置")
public class PackagePlan extends SuperEntity {
private static final long serialVersionUID = 1L;
@Schema(description = "二维码编码(codeId)")
private String codeId;
@Schema(description = "Vlog数量")
private Integer vlogCount;
@Schema(description = "视频数量")
private Integer videoCount;
@Schema(description = "照片数量")
private Integer photoCount;
@Schema(description = "租户ID")
private String tenantId;
@Schema(description = "所属公司")
private String company;
@Schema(description = "是否删除 0-否 1-是")
private Integer isDel;
@Schema(description = "创建时间")
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@Schema(description = "更新时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
}
@@ -0,0 +1,22 @@
package com.central.order.model.dto;
import com.central.order.model.QrCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@Data
@Schema(description = "二维码与套餐创建/修改请求体")
public class QrcodeWithPlanDTO {
@Schema(description = "二维码实体")
private QrCode qrCode;
@Schema(description = "Vlog数量")
private Integer vlogCount;
@Schema(description = "视频数量")
private Integer videoCount;
@Schema(description = "照片数量")
private Integer photoCount;
}
@@ -0,0 +1,22 @@
package com.central.order.service;
import com.central.common.model.PageResult;
import com.central.common.service.ISuperService;
import com.central.order.model.PackagePlan;
import java.util.List;
/**
* 套餐服务
*/
public interface IPackagePlanService extends ISuperService<PackagePlan> {
/**
* 根据二维码编码查询套餐列表
*/
List<PackagePlan> getByCodeId(String codeId);
/**
* 分页条件查询
*/
PageResult<PackagePlan> findList(java.util.Map<String, Object> params);
}
@@ -1,7 +1,13 @@
package com.central.order.service.impl; package com.central.order.service.impl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantQueryOverrideContext;
import com.central.common.datascope.annotation.IgnoreTenantScope;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.utils.SpringContextHolder;
import com.central.order.mapper.DashboardMapper; import com.central.order.mapper.DashboardMapper;
import com.central.order.mapper.TourismMapper;
import com.central.order.model.Order; import com.central.order.model.Order;
import com.central.order.model.vo.*; import com.central.order.model.vo.*;
import com.central.order.service.IDashboardService; import com.central.order.service.IDashboardService;
@@ -23,9 +29,81 @@ public class DashboardServiceImpl implements IDashboardService {
private final DashboardMapper dashboardMapper; private final DashboardMapper dashboardMapper;
private final IOrderService orderService; private final IOrderService orderService;
private final TourismMapper tourismMapper;
private final TenantResolverService tenantResolverService;
@Override @Override
@IgnoreTenantScope
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) { public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
// 依据租户层级组装景区ID集合,作为统计范围(支持 includeChildren=false 仅当前租户)
try {
// 获取前端传来的tenantId,如果没有则使用当前登录用户的租户
String tenantId = params != null && params.get("tenantId") != null ?
String.valueOf(params.get("tenantId")) : null;
boolean includeChildren = true;
try {
Object inc = params != null ? params.get("includeChildren") : null;
if (inc != null) {
if (inc instanceof Boolean) {
includeChildren = (Boolean) inc;
} else {
String s = String.valueOf(inc);
includeChildren = !("false".equalsIgnoreCase(s) || "0".equals(s));
}
}
} catch (Exception ignored) {}
// 处理时间维度参数,如果没有传时间范围,根据statType自动生成
String statType = params != null && params.get("statType") != null ?
String.valueOf(params.get("statType")) : "day";
if (params != null && (params.get("startTime") == null || "".equals(params.get("startTime")))) {
java.time.LocalDate now = java.time.LocalDate.now();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd");
switch (statType) {
case "year":
// 最近5年
params.put("startTime", now.minusYears(1).withDayOfYear(1).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
case "month":
// 最近12个月
params.put("startTime", now.minusMonths(1).withDayOfMonth(1).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
case "day":
default:
// 最近7天
params.put("startTime", now.minusDays(6).format(formatter));
params.put("endTime", now.format(formatter) + " 23:59:59");
break;
}
}
List<String> tenantIds = tenantResolverService.resolveTenantIds(tenantId, includeChildren);
// 特殊处理:如果是webApp且没有获取到租户列表,则查询所有景区
if ("webApp".equals(tenantId) && (tenantIds == null || tenantIds.isEmpty())) {
// 不设置tourismIds,让查询返回所有景区的数据
log.info("webApp租户统计所有数据,时间范围: {} 到 {}",
params.get("startTime"), params.get("endTime"));
} else if (tenantIds != null && !tenantIds.isEmpty()) {
List<Long> tourismIds = resolveTourismIdsByTenants(tenantIds);
if (tourismIds != null && !tourismIds.isEmpty()) {
params.put("tourismIds", tourismIds);
log.info("统计范围 - 租户IDs: {} 个租户, 景区IDs: {} 个景区, 时间范围: {} 到 {}",
tenantIds.size(), tourismIds.size(), params.get("startTime"), params.get("endTime"));
} else {
// 没有找到景区,设置一个不存在的ID,避免查询到所有数据
params.put("tourismIds", java.util.Collections.singletonList(-1L));
log.warn("租户 {} 没有关联的景区", tenantIds);
}
}
} catch (Exception e) {
log.warn("解析租户/景区范围失败,使用默认上下文: {}", e.getMessage());
}
DashboardStatisticsVO statistics = new DashboardStatisticsVO(); DashboardStatisticsVO statistics = new DashboardStatisticsVO();
try { try {
@@ -187,4 +265,123 @@ public class DashboardServiceImpl implements IDashboardService {
return options; return options;
} }
/**
* 解析租户ID集合(包含子租户)
* @deprecated 已迁移到TenantResolverService
*/
@Deprecated
private List<String> resolveTenantIds_old(String tenantId, boolean includeChildren) {
// 优先使用前端传来的tenantId,否则从上下文获取
String anchor = tenantId;
if (anchor == null || anchor.isEmpty()) {
anchor = TenantQueryOverrideContext.getTenantId();
}
if (anchor == null || anchor.isEmpty()) {
anchor = LoginUserContextHolder.getCurrentTenantId();
}
if (anchor == null || anchor.isEmpty()) {
return java.util.Collections.emptyList();
}
// webApp是特殊的超级租户,应该返回所有租户数据
if ("webApp".equals(anchor)) {
// 查询所有租户ID
try {
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
if (tenantService != null) {
// 获取所有顶级租户及其子孙
List<String> allTenants = new ArrayList<>();
List<com.central.common.model.TenantInfo> topTenants = tenantService.getTenantList(null, null, null, null, null).getData();
if (topTenants != null) {
for (com.central.common.model.TenantInfo tenant : topTenants) {
if (tenant.getTenantId() != null && !"webApp".equals(tenant.getTenantId())) {
List<String> subTenants = tenantService.getAllSubTenantIds(tenant.getTenantId());
if (subTenants != null && !subTenants.isEmpty()) {
allTenants.addAll(subTenants);
}
}
}
}
if (!allTenants.isEmpty()) {
log.info("webApp租户统计所有租户: {}", allTenants);
return allTenants;
}
}
} catch (Exception e) {
log.warn("webApp获取所有租户失败: {}", e.getMessage());
}
// 如果失败了,返回空列表(将查询所有数据)
return new ArrayList<>();
}
// 如果不包含子租户,只返回当前租户
if (!includeChildren) {
return java.util.Collections.singletonList(anchor);
}
// 获取当前租户及其所有子孙租户
try {
// 优先尝试使用本地的ITenantHierarchyService
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
if (tenantService != null) {
List<String> all = tenantService.getAllSubTenantIds(anchor);
if (all != null && !all.isEmpty()) {
log.info("本地获取租户层级成功: {} -> {}", anchor, all);
return all;
}
}
} catch (Exception e) {
log.debug("本地获取租户层级失败,尝试远程调用: {}", e.getMessage());
}
// 如果本地服务不可用,尝试远程调用
try {
com.central.order.feign.UserCenterService userCenterService = SpringContextHolder.getBean(com.central.order.feign.UserCenterService.class);
if (userCenterService != null) {
com.central.common.model.Result<List<String>> result = userCenterService.getDescendantTenantIds(anchor);
if (result != null && result.getResp_code() == 0 && result.getData() != null) {
log.info("远程获取租户层级成功: {} -> {}", anchor, result.getData());
return result.getData();
}
}
} catch (Exception e) {
log.warn("远程获取租户层级失败: {}", e.getMessage());
}
// 如果都失败了,只返回当前租户
log.warn("获取租户层级失败,降级为仅当前租户: {}", anchor);
return java.util.Collections.singletonList(anchor);
}
/**
* 解析当前请求上下文的租户集合(包含子租户)
* @deprecated 使用 TenantResolverService.resolveTenantIds 方法替代
*/
@Deprecated
private List<String> resolveTenantIdsFromContext(boolean includeChildren) {
return tenantResolverService.resolveTenantIds(null, includeChildren);
}
/**
* 根据租户集合查询景区ID集合
*/
private List<Long> resolveTourismIdsByTenants(List<String> tenantIds) {
try {
if (tenantIds == null || tenantIds.isEmpty()) return java.util.Collections.emptyList();
// 先按景区表直接匹配租户ID
List<Long> byTourism = tourismMapper.findTourismIdsByTenantIds(tenantIds);
java.util.Set<Long> union = new java.util.LinkedHashSet<>();
if (byTourism != null) union.addAll(byTourism);
// 容错:部分环境景区未直连租户,改用二维码表反查所关联的景区ID
if (union.isEmpty()) {
List<Long> byQrcodes = tourismMapper.findTourismIdsByTenantIdsFromQrcodes(tenantIds);
if (byQrcodes != null) union.addAll(byQrcodes);
}
return new java.util.ArrayList<>(union);
} catch (Exception e) {
log.debug("根据租户查询景区失败: {}", e.getMessage());
return java.util.Collections.emptyList();
}
}
} }
@@ -0,0 +1,29 @@
package com.central.order.service.impl;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.order.mapper.PackagePlanMapper;
import com.central.order.model.PackagePlan;
import com.central.order.service.IPackagePlanService;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.PageResult;
import org.apache.commons.collections4.MapUtils;
@Service
public class PackagePlanServiceImpl extends SuperServiceImpl<PackagePlanMapper, PackagePlan> implements IPackagePlanService {
@Override
public List<PackagePlan> getByCodeId(String codeId) {
return baseMapper.findByCodeId(codeId);
}
@Override
public PageResult<PackagePlan> findList(Map<String, Object> params) {
Page<PackagePlan> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
List<PackagePlan> list = baseMapper.findList(page, params);
return PageResult.<PackagePlan>builder().data(list).resp_code(0).count(page.getTotal()).build();
}
}
@@ -0,0 +1,91 @@
package com.central.order.service.impl;
import com.central.common.context.LoginUserContextHolder;
import com.central.common.context.TenantQueryOverrideContext;
import com.central.common.model.Result;
import com.central.order.feign.UserCenterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 租户解析服务
* 专门处理租户层级关系的获取
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class TenantResolverService {
private final UserCenterService userCenterService;
/**
* 解析租户ID集合(包含子租户)
* @param tenantId 指定的租户ID,null时使用当前上下文
* @param includeChildren 是否包含子租户
* @return 租户ID列表
*/
public List<String> resolveTenantIds(String tenantId, boolean includeChildren) {
// 优先使用前端传来的tenantId,否则从上下文获取
String anchor = tenantId;
if (anchor == null || anchor.isEmpty()) {
anchor = TenantQueryOverrideContext.getTenantId();
}
if (anchor == null || anchor.isEmpty()) {
anchor = LoginUserContextHolder.getCurrentTenantId();
}
if (anchor == null || anchor.isEmpty()) {
log.warn("无法获取租户ID,返回空列表");
return Collections.emptyList();
}
// webApp是特殊的超级租户,应该返回空列表(查询所有数据)
if ("webApp".equals(anchor)) {
log.info("webApp租户统计所有数据");
return Collections.emptyList(); // 空列表表示不限制租户
}
// 如果不包含子租户,只返回当前租户
if (!includeChildren) {
log.info("不包含子租户,仅返回当前租户: {}", anchor);
return Collections.singletonList(anchor);
}
// 通过Feign调用user-center获取子孙租户
try {
log.info("开始获取租户 {} 的所有子孙租户", anchor);
Result<List<String>> result = userCenterService.getDescendantTenantIds(anchor);
if (result != null) {
if (result.getResp_code() == 0 && result.getData() != null && !result.getData().isEmpty()) {
List<String> tenantIds = result.getData();
log.info("成功获取租户层级: {} -> {} 个租户: {}", anchor, tenantIds.size(), tenantIds);
return tenantIds;
} else {
log.warn("获取租户层级返回异常: code={}, msg={}", result.getResp_code(), result.getResp_msg());
}
} else {
log.warn("获取租户层级返回null");
}
} catch (Exception e) {
log.error("获取租户层级失败: {}", e.getMessage(), e);
}
// 降级:只返回当前租户
log.warn("获取子孙租户失败,降级为仅当前租户: {}", anchor);
return Collections.singletonList(anchor);
}
/**
* 获取所有租户(用于webApp超级管理员)
*/
public List<String> getAllTenantIds() {
// TODO: 实现获取所有租户的逻辑
// 暂时返回空,表示不限制
return new ArrayList<>();
}
}
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.order.mapper.PackagePlanMapper">
<resultMap id="PackagePlanResultMap" type="com.central.order.model.PackagePlan">
</resultMap>
<select id="findList" resultMap="PackagePlanResultMap">
SELECT *
FROM packages t
<where>
<if test="p.codeId != null and p.codeId != ''">
AND t.code_id = #{p.codeId}
</if>
<if test="p.isDel != null">
AND t.is_del = #{p.isDel}
</if>
</where>
ORDER BY t.create_time DESC
</select>
<select id="findByCodeId" resultMap="PackagePlanResultMap">
SELECT *
FROM packages
WHERE code_id = #{codeId}
AND (is_del IS NULL OR is_del = 0)
ORDER BY create_time DESC
</select>
</mapper>
@@ -4,7 +4,20 @@
<mapper namespace="com.central.order.mapper.TourismMapper"> <mapper namespace="com.central.order.mapper.TourismMapper">
<select id="findList" resultType="com.central.order.model.Tourism"> <select id="findList" resultType="com.central.order.model.Tourism">
select * from tourisms t SELECT *
FROM tourisms t
<where>
<if test="p.tenantIds != null and p.tenantIds.size > 0">
AND t.tenant_id IN
<foreach collection="p.tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
<if test="(p.tenantIds == null or p.tenantIds.size == 0) and p.tenantId != null and p.tenantId != ''">
AND t.tenant_id = #{p.tenantId}
</if>
</where>
ORDER BY t.id DESC
</select> </select>
<resultMap id="TourismResultMap" type="com.central.order.model.Tourism"> <resultMap id="TourismResultMap" type="com.central.order.model.Tourism">
@@ -89,4 +102,32 @@
ORDER BY create_time DESC ORDER BY create_time DESC
</select> </select>
<!-- 根据租户ID集合查询景区ID集合 -->
<select id="findTourismIdsByTenantIds" resultType="java.lang.Long">
SELECT id FROM tourisms
WHERE is_del = 0
<if test="tenantIds != null and tenantIds.size > 0">
AND tenant_id IN
<foreach collection="tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
ORDER BY id DESC
</select>
<!-- 基于二维码表按租户反查景区ID(容错方案) -->
<select id="findTourismIdsByTenantIdsFromQrcodes" resultType="java.lang.Long">
SELECT DISTINCT q.tourism_id
FROM qrcodes q
WHERE q.is_del = 0
AND q.tourism_id IS NOT NULL
<if test="tenantIds != null and tenantIds.size > 0">
AND q.tenant_id IN
<foreach collection="tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
ORDER BY q.tourism_id DESC
</select>
</mapper> </mapper>
@@ -127,12 +127,20 @@ public class TenantHierarchyController {
// ===== 私有方法:对象转换 ===== // ===== 私有方法:对象转换 =====
private Tenant toTenant(TenantInfo info) { private Tenant toTenant(TenantInfo info) {
if (info == null) return null; if (info == null) return null;
// 规范化关键字段,避免出现 null 前缀或尾部斜杠
String tenantId = info.getTenantId();
String parentId = info.getParentTenantId();
String normalizedPath = normalizePathForSave(info.getTenantPath(), parentId, tenantId);
Integer normalizedLevel = normalizeLevelForSave(info.getTenantLevel(), parentId);
Tenant t = new Tenant(); Tenant t = new Tenant();
t.setTenantId(info.getTenantId()); t.setTenantId(tenantId);
t.setTenantName(info.getTenantName()); t.setTenantName(info.getTenantName());
t.setParentTenantId(info.getParentTenantId()); t.setParentTenantId(parentId);
t.setTenantLevel(info.getTenantLevel()); t.setTenantLevel(normalizedLevel);
t.setTenantPath(info.getTenantPath()); t.setTenantPath(normalizedPath);
t.setTenantType(info.getTenantType()); t.setTenantType(info.getTenantType());
t.setTenantCode(info.getTenantCode()); t.setTenantCode(info.getTenantCode());
t.setContactPerson(info.getContactPerson()); t.setContactPerson(info.getContactPerson());
@@ -144,6 +152,69 @@ public class TenantHierarchyController {
return t; return t;
} }
/**
* 获取指定租户(含自身)及其所有子孙租户ID列表
* 供其他业务服务(如 order-center)通过 Feign 远程调用
*/
@GetMapping("/{tenantId}")
@Operation(summary = "获取子孙租户ID列表(含自身)")
public Result<List<String>> getDescendantTenantIds(@PathVariable("tenantId") String tenantId) {
if (!StringUtils.hasText(tenantId)) {
return Result.failed("tenantId 不能为空");
}
try {
List<String> ids = tenantHierarchyService.getAllSubTenantIds(tenantId);
return Result.succeed(ids);
} catch (Exception e) {
log.warn("获取子孙租户失败,退化为仅自身: {} -> {}", tenantId, e.getMessage());
return Result.succeed(java.util.Collections.singletonList(tenantId), "已退化为仅自身");
}
}
private String normalizePathForSave(String rawPath, String parentId, String tenantId) {
try {
String path = stripPathSafe(rawPath);
String base = null;
if (StringUtils.hasText(parentId)) {
TenantInfo p = tenantHierarchyService.getTenantInfo(parentId);
base = stripPathSafe(p != null && StringUtils.hasText(p.getTenantPath()) ? p.getTenantPath() : parentId);
}
// 1) 空/异常路径 → 按父路径重建;2) 有父但路径未以父路径开头 → 纠正;
boolean invalid = !StringUtils.hasText(path) || path.toLowerCase().startsWith("null") || path.endsWith("/");
boolean wrongPrefix = StringUtils.hasText(base) && (path == null || !path.startsWith(base + "/"));
if (invalid || wrongPrefix) {
if (!StringUtils.hasText(base)) return stripPathSafe(tenantId);
return base + "/" + stripPathSafe(tenantId);
}
return path;
} catch (Exception e) {
return stripPathSafe(tenantId);
}
}
private Integer normalizeLevelForSave(Integer level, String parentId) {
if (level != null && level > 0) return level;
try {
Integer parentLevel = null;
if (StringUtils.hasText(parentId)) {
TenantInfo p = tenantHierarchyService.getTenantInfo(parentId);
parentLevel = p != null ? p.getTenantLevel() : null;
}
return (parentLevel == null ? 0 : parentLevel) + 1;
} catch (Exception e) {
return 1;
}
}
private String stripPathSafe(String path) {
if (!StringUtils.hasText(path)) return null;
String p = path.trim();
if (p.toLowerCase().startsWith("null")) p = p.substring(4);
while (p.startsWith("/")) p = p.substring(1);
while (p.endsWith("/")) p = p.substring(0, p.length() - 1);
return p;
}
private TenantInfo toTenantInfo(Tenant t) { private TenantInfo toTenantInfo(Tenant t) {
if (t == null) return null; if (t == null) return null;
return TenantInfo.builder() return TenantInfo.builder()
@@ -45,10 +45,18 @@ public class TenantSwitchController {
if (user == null) { if (user == null) {
return Result.failed("用户未登录"); return Result.failed("用户未登录");
} }
if (!isCanSwitchTenant(user)) { // 不再强制校验切换权限:至少返回当前租户 + 子孙租户,便于查询范围选择
return Result.failed("用户无租户切换权限"); String userTenantId = getDefaultTenantId(user);
List<String> accessibleTenantIds = List.of();
if (StringUtils.hasText(userTenantId)) {
try {
List<String> subIds = tenantHierarchyService != null ? tenantHierarchyService.getAllSubTenantIds(userTenantId) : null;
accessibleTenantIds = (subIds != null && !subIds.isEmpty()) ? subIds : List.of(userTenantId);
} catch (Exception ex) {
log.warn("获取子租户列表失败,降级为仅当前租户: tenantId={}, error={}", userTenantId, ex.getMessage());
accessibleTenantIds = List.of(userTenantId);
}
} }
List<String> accessibleTenantIds = getAccessibleTenantIds(user);
if (accessibleTenantIds.isEmpty()) { if (accessibleTenantIds.isEmpty()) {
return Result.failed("用户无可访问的租户"); return Result.failed("用户无可访问的租户");
} }
@@ -168,7 +176,16 @@ public class TenantSwitchController {
String userTenantId = getDefaultTenantId(user); String userTenantId = getDefaultTenantId(user);
if (StringUtils.hasText(userTenantId)) { if (StringUtils.hasText(userTenantId)) {
if (isCanSwitchTenant(user)) { if (isCanSwitchTenant(user)) {
return tenantHierarchyService.getAllSubTenantIds(userTenantId); try {
List<String> subIds = tenantHierarchyService != null ? tenantHierarchyService.getAllSubTenantIds(userTenantId) : null;
if (subIds != null && !subIds.isEmpty()) {
return subIds;
}
} catch (Exception e) {
log.warn("获取子租户列表失败,降级为仅当前租户: tenantId={}, error={}", userTenantId, e.getMessage());
}
// 降级:至少返回当前租户本身
return List.of(userTenantId);
} else { } else {
return List.of(userTenantId); return List.of(userTenantId);
} }
@@ -178,6 +195,13 @@ public class TenantSwitchController {
private String getDefaultTenantId(LoginAppUser user) { private String getDefaultTenantId(LoginAppUser user) {
Object company = user.getAttributes().get("company"); Object company = user.getAttributes().get("company");
return company != null ? company.toString() : null; if (company != null && StringUtils.hasText(company.toString())) {
return company.toString();
}
if (StringUtils.hasText(user.getCompany())) {
return user.getCompany();
}
// 兜底:若当前租户已设置则返回
return LoginUserContextHolder.getCurrentTenantId();
} }
} }
@@ -5,6 +5,7 @@ import com.central.common.model.Tenant;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List; import java.util.List;
@@ -146,4 +147,14 @@ public interface TenantHierarchyMapper extends BaseMapper<Tenant> {
long countTenantList(@Param("parentTenantId") String parentTenantId, long countTenantList(@Param("parentTenantId") String parentTenantId,
@Param("tenantName") String tenantName, @Param("tenantName") String tenantName,
@Param("status") Integer status); @Param("status") Integer status);
}
/**
* 基于 tenant_id 进行软删除(将 status 置为 0)
*
* @param tenantId 租户ID
* @param status 状态值(0 表示删除/禁用)
* @return 影响行数
*/
@Update("UPDATE sys_tenant SET status = #{status} WHERE tenant_id = #{tenantId}")
int updateStatusByTenantId(@Param("tenantId") String tenantId, @Param("status") Integer status);
}
@@ -1,83 +1,145 @@
package com.central.user.service.impl; package com.central.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.context.LoginUserContextHolder; import com.central.common.context.LoginUserContextHolder;
import com.central.common.lock.DistributedLock; import com.central.common.lock.DistributedLock;
import com.central.common.model.PageResult; import com.central.common.model.PageResult;
import com.central.common.model.Result; import com.central.common.model.Result;
import com.central.common.model.SysRole; import com.central.common.model.SysRole;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.mapper.SysRoleMapper; import com.central.user.mapper.SysRoleMapper;
import com.central.user.mapper.SysRoleMenuMapper; import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserRoleMapper; import com.central.user.mapper.SysUserRoleMapper;
import com.central.user.service.ISysRoleService; import com.central.user.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j; import com.central.common.service.ITenantHierarchyService;
import org.apache.commons.collections4.MapUtils; import com.central.common.datascope.annotation.IgnoreTenantScope;
import org.springframework.beans.factory.annotation.Autowired; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.apache.commons.collections4.MapUtils;
import org.springframework.transaction.annotation.Transactional; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import javax.annotation.Resource;
/** import java.util.List;
* @author 作者 owen E-mail: 624191343@qq.com import java.util.Map;
*/
@Slf4j /**
@Service * @author 作者 owen E-mail: 624191343@qq.com
public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService { */
private final static String LOCK_KEY_ROLECODE = "rolecode:"; @Slf4j
@Service
@Resource public class SysRoleServiceImpl extends SuperServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
private SysUserRoleMapper userRoleMapper; private final static String LOCK_KEY_ROLECODE = "rolecode:";
@Resource @Resource
private SysRoleMenuMapper roleMenuMapper; private SysUserRoleMapper userRoleMapper;
@Autowired @Resource
private DistributedLock lock; private SysRoleMenuMapper roleMenuMapper;
@Transactional(rollbackFor = Exception.class) @Autowired
@Override private DistributedLock lock;
public void saveRole(SysRole sysRole) throws Exception {
String roleCode = sysRole.getCode(); @Resource
super.saveIdempotency(sysRole, lock private ITenantHierarchyService tenantHierarchyService;
, LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
} @Transactional(rollbackFor = Exception.class)
@Override
@Transactional(rollbackFor = Exception.class) public void saveRole(SysRole sysRole) throws Exception {
@Override String roleCode = sysRole.getCode();
public void deleteRole(Long id) { super.saveIdempotency(sysRole, lock
baseMapper.deleteById(id); , LOCK_KEY_ROLECODE+roleCode, new QueryWrapper<SysRole>().eq("code", roleCode), "角色code已存在");
roleMenuMapper.delete(id, null); }
userRoleMapper.deleteUserRole(null, id);
} @Transactional(rollbackFor = Exception.class)
@Override
@Override public void deleteRole(Long id) {
public PageResult<SysRole> findRoles(Map<String, Object> params) { baseMapper.deleteById(id);
Integer curPage = MapUtils.getInteger(params, "page"); roleMenuMapper.delete(id, null);
Integer limit = MapUtils.getInteger(params, "limit"); userRoleMapper.deleteUserRole(null, id);
Page<SysRole> page = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit); }
List<SysRole> list = baseMapper.findList(page, params);
return PageResult.<SysRole>builder().data(list).resp_code(0).count(page.getTotal()).build(); @Override
} @IgnoreTenantScope
public PageResult<SysRole> findRoles(Map<String, Object> params) {
@Override Integer curPage = MapUtils.getInteger(params, "page");
@Transactional Integer limit = MapUtils.getInteger(params, "limit");
public Result saveOrUpdateRole(SysRole sysRole) throws Exception { // 以租户为主:支持按租户及其子租户过滤
if (sysRole.getId() == null) { String tenantId = MapUtils.getString(params, "tenantId");
sysRole.setCreatorId(LoginUserContextHolder.getUser().getId()); Object incRaw = params.get("includeChildren");
this.saveRole(sysRole); boolean includeChildren = true;
} else { if (incRaw != null) {
baseMapper.updateById(sysRole); try {
} if (incRaw instanceof Boolean) {
return Result.succeed("操作成功"); includeChildren = (Boolean) incRaw;
} } else if (incRaw instanceof Number) {
includeChildren = ((Number) incRaw).intValue() != 0;
@Override } else if (incRaw instanceof CharSequence) {
public List<SysRole> findAll() { String s = incRaw.toString().trim();
return baseMapper.findAll(); includeChildren = ("true".equalsIgnoreCase(s) || "1".equals(s) || "yes".equalsIgnoreCase(s));
} }
} } catch (Exception ignored) { /* 使用默认 true */ }
}
java.util.List<String> tenantIds = null;
if (StringUtils.isNotBlank(tenantId)) {
try {
if (includeChildren) {
// 展开包含所有子级(确保包含自身)
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
if (tenantIds == null || tenantIds.isEmpty()) {
tenantIds = new java.util.ArrayList<>();
}
if (!tenantIds.contains(tenantId)) {
tenantIds = new java.util.ArrayList<>(tenantIds);
tenantIds.add(0, tenantId);
}
} else {
tenantIds = java.util.Collections.singletonList(tenantId);
}
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
// 与当前用户可访问租户集求交集,避免越权和误查全量
// 与用户可访问租户不再做强制求交集,保持与用户列表查询一致的行为,
// 以显式传入的 tenantId/includeChildren 为准,由接口鉴权控制访问边界。
if (tenantIds == null || tenantIds.isEmpty()) {
// 无可访问租户,直接返回空结果
Page<SysRole> empty = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit);
return PageResult.<SysRole>builder().data(java.util.Collections.emptyList()).resp_code(0).count(0L).build();
}
params.put("tenantIds", tenantIds);
}
Page<SysRole> page = new Page<>(curPage == null ? 0 : curPage, limit == null ? -1 : limit);
List<SysRole> list = baseMapper.findList(page, params);
return PageResult.<SysRole>builder().data(list).resp_code(0).count(page.getTotal()).build();
}
@Override
@Transactional
public Result saveOrUpdateRole(SysRole sysRole) throws Exception {
if (sysRole.getId() == null) {
// 新增时补齐租户ID(以当前上下文或表单传参为准)
if (StringUtils.isBlank(sysRole.getTenantId())) {
try {
String ctxTenant = com.central.common.context.TenantContextHolder.getTenant();
if (StringUtils.isNotBlank(ctxTenant)) {
sysRole.setTenantId(ctxTenant);
}
} catch (Exception ignored) { /* no-op */ }
}
sysRole.setCreatorId(LoginUserContextHolder.getUser().getId());
this.saveRole(sysRole);
} else {
baseMapper.updateById(sysRole);
}
return Result.succeed("操作成功");
}
@Override
public List<SysRole> findAll() {
return baseMapper.findAll();
}
}
@@ -17,6 +17,8 @@ import com.central.common.model.SuperEntity;
import com.central.common.model.SysMenu; import com.central.common.model.SysMenu;
import com.central.common.service.impl.SuperServiceImpl; import com.central.common.service.impl.SuperServiceImpl;
import com.central.user.feign.DeviceCenterService; import com.central.user.feign.DeviceCenterService;
import com.central.common.service.ITenantHierarchyService;
import com.central.common.context.LoginUserContextHolder;
import com.central.user.feign.OrderCenterService; import com.central.user.feign.OrderCenterService;
import com.central.user.mapper.SysRoleMenuMapper; import com.central.user.mapper.SysRoleMenuMapper;
import com.central.user.mapper.SysUserMapper; import com.central.user.mapper.SysUserMapper;
@@ -65,6 +67,9 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Resource @Resource
private DeviceCenterService deviceCenterService; private DeviceCenterService deviceCenterService;
@Resource
private ITenantHierarchyService tenantHierarchyService;
@Override @Override
public SysUser findByUsername(String username) { public SysUser findByUsername(String username) {
SysUser sysUser = this.selectByUsername(username); SysUser sysUser = this.selectByUsername(username);
@@ -228,6 +233,34 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
@Override @Override
public PageResult<SysUser> findUsers(Map<String, Object> params) { public PageResult<SysUser> findUsers(Map<String, Object> params) {
Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit")); Page<SysUser> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
// 组装租户过滤:有传tenantId则以其为锚点(可选包含子级);未传则按当前登录用户及其子租户
String tenantId = MapUtils.getString(params, "tenantId");
Boolean includeChildren = MapUtils.getBoolean(params, "includeChildren", Boolean.TRUE);
List<String> tenantIds = null;
if (StrUtil.isNotBlank(tenantId)) {
try {
if (Boolean.TRUE.equals(includeChildren)) {
tenantIds = tenantHierarchyService.getAllSubTenantIds(tenantId);
} else {
tenantIds = java.util.Collections.singletonList(tenantId);
}
} catch (Exception ignored) { tenantIds = java.util.Collections.singletonList(tenantId); }
} else {
// 未显式指定,则按当前登录用户所属租户及其子租户
try {
String anchor = LoginUserContextHolder.getCurrentTenantId();
if (StringUtils.isNotBlank(anchor)) {
try {
tenantIds = tenantHierarchyService.getAllSubTenantIds(anchor);
} catch (Exception e) {
tenantIds = java.util.Collections.singletonList(anchor);
}
}
} catch (Exception ignored) { /* no-op */ }
}
if (tenantIds != null && !tenantIds.isEmpty()) {
params.put("tenantIds", tenantIds);
}
List<SysUser> list = baseMapper.findList(page, params); List<SysUser> list = baseMapper.findList(page, params);
long total = page.getTotal(); long total = page.getTotal();
if (total > 0) { if (total > 0) {
@@ -23,8 +23,10 @@ import java.util.stream.Collectors;
/** /**
* 租户层级管理服务实现 * 租户层级管理服务实现
* *
* @author zlt * 仅修复本文件:
* @date 2024-12-19 * - 处理 status 为空导致的 NPE
* - 统一中文文案为 UTF-8
* - 保持接口契约不变
*/ */
@Slf4j @Slf4j
@Service @Service
@@ -33,21 +35,31 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@Autowired @Autowired
private TenantHierarchyMapper tenantHierarchyMapper; private TenantHierarchyMapper tenantHierarchyMapper;
private static final String CACHE_KEY_PREFIX = "tenant:hierarchy:";
@Override @Override
@Cacheable(value = "tenant:hierarchy", key = "#parentTenantId") @Cacheable(value = "tenant:hierarchy", key = "#parentTenantId")
public List<String> getAllSubTenantIds(String parentTenantId) { public List<String> getAllSubTenantIds(String parentTenantId) {
if (!StringUtils.hasText(parentTenantId)) { if (!StringUtils.hasText(parentTenantId)) {
return Collections.emptyList(); return Collections.emptyList();
} }
try { try {
List<String> subTenantIds = tenantHierarchyMapper.selectSubTenantIds(parentTenantId); LinkedHashSet<String> all = new LinkedHashSet<>();
log.debug("查询租户 {} 的所有子租户,数量: {}", parentTenantId, subTenantIds.size()); ArrayDeque<String> queue = new ArrayDeque<>();
return subTenantIds; all.add(parentTenantId);
queue.add(parentTenantId);
while (!queue.isEmpty()) {
String pid = queue.poll();
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(pid);
if (children == null) continue;
for (Tenant t : children) {
String tid = t.getTenantId();
if (StringUtils.hasText(tid) && all.add(tid)) {
queue.add(tid);
}
}
}
return new ArrayList<>(all);
} catch (Exception e) { } catch (Exception e) {
log.error("查询子租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage()); log.error("查询子孙租户失败: parentTenantId={}, error={}", parentTenantId, e.getMessage());
return Collections.singletonList(parentTenantId); return Collections.singletonList(parentTenantId);
} }
} }
@@ -57,40 +69,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (tenantIds == null || tenantIds.isEmpty()) { if (tenantIds == null || tenantIds.isEmpty()) {
return Collections.emptyList(); return Collections.emptyList();
} }
try { try {
// 获取租户详细信息
List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds); List<Tenant> tenants = tenantHierarchyMapper.selectByTenantIds(tenantIds);
// 转换为树形节点
Map<String, TenantTreeNode> nodeMap = new HashMap<>(); Map<String, TenantTreeNode> nodeMap = new HashMap<>();
List<TenantTreeNode> rootNodes = new ArrayList<>(); List<TenantTreeNode> roots = new ArrayList<>();
// 创建所有节点 for (Tenant t : tenants) {
for (Tenant tenant : tenants) {
TenantTreeNode node = TenantTreeNode.builder() TenantTreeNode node = TenantTreeNode.builder()
.tenantId(tenant.getTenantId()) .tenantId(t.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(t.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(t.getParentTenantId())
.tenantType(tenant.getTenantType()) .tenantType(t.getTenantType())
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(t.getTenantLevel())
.status(tenant.getStatus()) .status(t.getStatus())
.enabled(tenant.getStatus() == 1) .enabled(Objects.equals(t.getStatus(), 1))
.description(tenant.getDescription()) .description(t.getDescription())
.children(new ArrayList<>()) .children(new ArrayList<>())
.hasChildren(false) .hasChildren(false)
.childrenCount(0) .childrenCount(0)
.build(); .build();
nodeMap.put(tenant.getTenantId(), node); nodeMap.put(t.getTenantId(), node);
} }
// 构建父子关系
for (TenantTreeNode node : nodeMap.values()) { for (TenantTreeNode node : nodeMap.values()) {
if (!StringUtils.hasText(node.getParentTenantId())) { String p = node.getParentTenantId();
rootNodes.add(node); if (!StringUtils.hasText(p)) {
roots.add(node);
} else { } else {
TenantTreeNode parent = nodeMap.get(node.getParentTenantId()); TenantTreeNode parent = nodeMap.get(p);
if (parent != null) { if (parent == null) {
roots.add(node);
} else {
parent.getChildren().add(node); parent.getChildren().add(node);
parent.setHasChildren(true); parent.setHasChildren(true);
parent.setChildrenCount(parent.getChildren().size()); parent.setChildrenCount(parent.getChildren().size());
@@ -98,9 +108,7 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
} }
} }
log.debug("构建租户树完成,根节点数量: {}", rootNodes.size()); return roots;
return rootNodes;
} catch (Exception e) { } catch (Exception e) {
log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage()); log.error("构建租户树失败: tenantIds={}, error={}", tenantIds, e.getMessage());
return Collections.emptyList(); return Collections.emptyList();
@@ -112,52 +120,44 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) {
return null; return null;
} }
try { try {
Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId); Tenant tenant = tenantHierarchyMapper.selectByTenantId(tenantId);
if (tenant == null) { if (tenant == null) return null;
return null;
}
// 查询子租户数量
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId); List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
int childrenCount = children != null ? children.size() : 0; int childrenCount = children == null ? 0 : children.size();
// 查询父租户名称 String parentName = null;
String parentTenantName = null;
if (StringUtils.hasText(tenant.getParentTenantId())) { if (StringUtils.hasText(tenant.getParentTenantId())) {
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId()); Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
if (parentTenant != null) { if (parent != null) parentName = parent.getTenantName();
parentTenantName = parentTenant.getTenantName();
}
} }
return TenantInfo.builder() return TenantInfo.builder()
.tenantId(tenant.getTenantId()) .tenantId(tenant.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(tenant.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(tenant.getParentTenantId())
.parentTenantName(parentTenantName) .parentTenantName(parentName)
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(tenant.getTenantLevel())
.tenantPath(tenant.getTenantPath()) .tenantPath(tenant.getTenantPath())
.tenantType(tenant.getTenantType()) .tenantType(tenant.getTenantType())
.tenantCode(tenant.getTenantCode()) .tenantCode(tenant.getTenantCode())
.contactPerson(tenant.getContactPerson()) .contactPerson(tenant.getContactPerson())
.contactPhone(tenant.getContactPhone()) .contactPhone(tenant.getContactPhone())
.address(tenant.getAddress()) .address(tenant.getAddress())
.description(tenant.getDescription()) .description(tenant.getDescription())
.status(tenant.getStatus()) .status(tenant.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用") .statusText(Objects.equals(tenant.getStatus(), 1) ? "启用" : "停用")
.hasChildren(childrenCount > 0) .hasChildren(childrenCount > 0)
.childrenCount(childrenCount) .childrenCount(childrenCount)
.createTime(tenant.getCreateTime() != null ? .createTime(tenant.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ? .updateTime(tenant.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId()) .creatorId(tenant.getCreatorId())
.build(); .build();
} catch (Exception e) { } catch (Exception e) {
log.error("获取租户信息失败: tenantId={}, error={}", tenantId, e.getMessage()); log.error("获取租户信息异常: tenantId={}, error={}", tenantId, e.getMessage());
return null; return null;
} }
} }
@@ -167,60 +167,38 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@CacheEvict(value = "tenant:hierarchy", allEntries = true) @CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Tenant> createTenant(Tenant tenant) { public Result<Tenant> createTenant(Tenant tenant) {
try { try {
// 验证必填字段
if (!StringUtils.hasText(tenant.getTenantId())) { if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空"); return Result.failed("租户ID不能为空");
} }
if (!StringUtils.hasText(tenant.getTenantName())) { if (!StringUtils.hasText(tenant.getTenantName())) {
return Result.failed("租户名称不能为空"); return Result.failed("租户名称不能为空");
} }
// 检查租户ID是否已存在
if (existsByTenantId(tenant.getTenantId())) { if (existsByTenantId(tenant.getTenantId())) {
return Result.failed("租户ID已存在"); return Result.failed("租户ID已存在");
} }
// 验证父租户关系
if (StringUtils.hasText(tenant.getParentTenantId())) { if (StringUtils.hasText(tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) { if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系"); return Result.failed("无效的父子租户关系");
} }
Tenant parent = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId());
// 获取父租户信息,设置层级和路径 if (parent == null) return Result.failed("父租户不存在");
Tenant parentTenant = tenantHierarchyMapper.selectByTenantId(tenant.getParentTenantId()); tenant.setTenantLevel(parent.getTenantLevel() + 1);
if (parentTenant == null) { tenant.setTenantPath(parent.getTenantPath() + tenant.getTenantId() + "/");
return Result.failed("父租户不存在");
}
tenant.setTenantLevel(parentTenant.getTenantLevel() + 1);
tenant.setTenantPath(parentTenant.getTenantPath() + tenant.getTenantId() + "/");
} else { } else {
// 根租户
tenant.setTenantLevel(1); tenant.setTenantLevel(1);
tenant.setTenantPath("/" + tenant.getTenantId() + "/"); tenant.setTenantPath("/" + tenant.getTenantId() + "/");
} }
// 设置默认值 if (tenant.getStatus() == null) tenant.setStatus(1);
if (tenant.getStatus() == null) { if (!StringUtils.hasText(tenant.getTenantType())) tenant.setTenantType("COMPANY");
tenant.setStatus(1);
}
if (!StringUtils.hasText(tenant.getTenantType())) {
tenant.setTenantType("COMPANY");
}
// 设置创建人
if (LoginUserContextHolder.getUser() != null) { if (LoginUserContextHolder.getUser() != null) {
tenant.setCreatorId(LoginUserContextHolder.getUser().getId()); tenant.setCreatorId(LoginUserContextHolder.getUser().getId());
} }
// 保存租户 int r = tenantHierarchyMapper.insert(tenant);
int result = tenantHierarchyMapper.insert(tenant); if (r > 0) return Result.succeed(tenant);
if (result > 0) { return Result.failed("创建租户失败");
log.info("创建租户成功: tenantId={}, tenantName={}", tenant.getTenantId(), tenant.getTenantName());
return Result.succeed(tenant);
} else {
return Result.failed("创建租户失败");
}
} catch (Exception e) { } catch (Exception e) {
log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage()); log.error("创建租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("创建租户异常: " + e.getMessage()); return Result.failed("创建租户异常: " + e.getMessage());
@@ -235,29 +213,19 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
if (!StringUtils.hasText(tenant.getTenantId())) { if (!StringUtils.hasText(tenant.getTenantId())) {
return Result.failed("租户ID不能为空"); return Result.failed("租户ID不能为空");
} }
Tenant exist = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
if (exist == null) return Result.failed("租户不存在");
// 检查租户是否存在 if (!Objects.equals(exist.getParentTenantId(), tenant.getParentTenantId())) {
Tenant existingTenant = tenantHierarchyMapper.selectByTenantId(tenant.getTenantId());
if (existingTenant == null) {
return Result.failed("租户不存在");
}
// 验证父租户关系变更
if (!Objects.equals(existingTenant.getParentTenantId(), tenant.getParentTenantId())) {
if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) { if (!validateTenantRelation(tenant.getTenantId(), tenant.getParentTenantId())) {
return Result.failed("无效的父子租户关系"); return Result.failed("无效的父子租户关系");
} }
} }
// 更新租户 tenant.setId(exist.getId());
int result = tenantHierarchyMapper.updateById(tenant); int r = tenantHierarchyMapper.updateById(tenant);
if (result > 0) { if (r > 0) return Result.succeed(tenant);
log.info("更新租户成功: tenantId={}", tenant.getTenantId()); return Result.failed("更新租户失败");
return Result.succeed(tenant);
} else {
return Result.failed("更新租户失败");
}
} catch (Exception e) { } catch (Exception e) {
log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage()); log.error("更新租户异常: tenant={}, error={}", tenant, e.getMessage());
return Result.failed("更新租户异常: " + e.getMessage()); return Result.failed("更新租户异常: " + e.getMessage());
@@ -269,29 +237,12 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@CacheEvict(value = "tenant:hierarchy", allEntries = true) @CacheEvict(value = "tenant:hierarchy", allEntries = true)
public Result<Boolean> deleteTenant(String tenantId) { public Result<Boolean> deleteTenant(String tenantId) {
try { try {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return Result.failed("租户ID不能为空");
return Result.failed("租户ID不能为空");
}
// 检查是否有子租户
List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId); List<Tenant> children = tenantHierarchyMapper.selectDirectChildren(tenantId);
if (children != null && !children.isEmpty()) { if (children != null && !children.isEmpty()) return Result.failed("存在子租户,无法删除");
return Result.failed("存在子租户,无法删除"); int r = tenantHierarchyMapper.updateStatusByTenantId(tenantId, 0);
} if (r > 0) return Result.succeed(true);
return Result.failed("删除租户失败");
// 软删除(更新状态为0)
Tenant tenant = new Tenant();
tenant.setTenantId(tenantId);
tenant.setStatus(0);
int result = tenantHierarchyMapper.updateById(tenant);
if (result > 0) {
log.info("删除租户成功: tenantId={}", tenantId);
return Result.succeed(true);
} else {
return Result.failed("删除租户失败");
}
} catch (Exception e) { } catch (Exception e) {
log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage()); log.error("删除租户异常: tenantId={}, error={}", tenantId, e.getMessage());
return Result.failed("删除租户异常: " + e.getMessage()); return Result.failed("删除租户异常: " + e.getMessage());
@@ -303,19 +254,13 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
try { try {
if (page == null || page < 1) page = 1; if (page == null || page < 1) page = 1;
if (size == null || size < 1) size = 10; if (size == null || size < 1) size = 10;
int offset = (page - 1) * size; int offset = (page - 1) * size;
List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size); List<Tenant> tenants = tenantHierarchyMapper.selectTenantList(parentTenantId, tenantName, status, offset, size);
long total = tenantHierarchyMapper.countTenantList(parentTenantId, tenantName, status); tenants = tenants == null ? Collections.emptyList() : tenants;
List<TenantInfo> tenantInfos = tenants.stream()
.map(this::convertToTenantInfo)
.collect(Collectors.toList());
log.debug("查询租户列表完成,总数: {}, 当前页: {}", total, tenantInfos.size());
return Result.succeed(tenantInfos);
List<TenantInfo> list = tenants.stream().map(this::convertToTenantInfo).collect(Collectors.toList());
return Result.succeed(list);
} catch (Exception e) { } catch (Exception e) {
log.error("查询租户列表异常: error={}", e.getMessage()); log.error("查询租户列表异常: error={}", e.getMessage());
return Result.failed("查询租户列表异常: " + e.getMessage()); return Result.failed("查询租户列表异常: " + e.getMessage());
@@ -324,76 +269,51 @@ public class TenantHierarchyServiceImpl implements ITenantHierarchyService {
@Override @Override
public boolean existsByTenantId(String tenantId) { public boolean existsByTenantId(String tenantId) {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return false;
return false;
}
return tenantHierarchyMapper.existsByTenantId(tenantId) > 0; return tenantHierarchyMapper.existsByTenantId(tenantId) > 0;
} }
@Override @Override
public boolean validateTenantRelation(String tenantId, String parentTenantId) { public boolean validateTenantRelation(String tenantId, String parentTenantId) {
if (!StringUtils.hasText(tenantId)) { if (!StringUtils.hasText(tenantId)) return false;
return false; if (!StringUtils.hasText(parentTenantId)) return true;
} if (tenantId.equals(parentTenantId)) return false;
// 如果没有父租户,则合法 String current = parentTenantId;
if (!StringUtils.hasText(parentTenantId)) {
return true;
}
// 不能将自己设置为父租户
if (tenantId.equals(parentTenantId)) {
return false;
}
// 检查是否会形成循环引用
String currentTenantId = parentTenantId;
Set<String> visited = new HashSet<>(); Set<String> visited = new HashSet<>();
while (current != null && !visited.contains(current)) {
while (currentTenantId != null && !visited.contains(currentTenantId)) { visited.add(current);
visited.add(currentTenantId); if (tenantId.equals(current)) return false;
Tenant p = tenantHierarchyMapper.selectByTenantId(current);
if (currentTenantId.equals(tenantId)) { current = p == null ? null : p.getParentTenantId();
// 形成循环引用
return false;
}
Tenant currentTenant = tenantHierarchyMapper.selectByTenantId(currentTenantId);
currentTenantId = currentTenant != null ? currentTenant.getParentTenantId() : null;
} }
return true; return true;
} }
/** private TenantInfo convertToTenantInfo(Tenant t) {
* 转换为TenantInfo if (t == null) return null;
*/
private TenantInfo convertToTenantInfo(Tenant tenant) {
if (tenant == null) {
return null;
}
return TenantInfo.builder() return TenantInfo.builder()
.tenantId(tenant.getTenantId()) .tenantId(t.getTenantId())
.tenantName(tenant.getTenantName()) .tenantName(t.getTenantName())
.parentTenantId(tenant.getParentTenantId()) .parentTenantId(t.getParentTenantId())
.tenantLevel(tenant.getTenantLevel()) .tenantLevel(t.getTenantLevel())
.tenantPath(tenant.getTenantPath()) .tenantPath(t.getTenantPath())
.tenantType(tenant.getTenantType()) .tenantType(t.getTenantType())
.tenantCode(tenant.getTenantCode()) .tenantCode(t.getTenantCode())
.contactPerson(tenant.getContactPerson()) .contactPerson(t.getContactPerson())
.contactPhone(tenant.getContactPhone()) .contactPhone(t.getContactPhone())
.address(tenant.getAddress()) .address(t.getAddress())
.description(tenant.getDescription()) .description(t.getDescription())
.status(tenant.getStatus()) .status(t.getStatus())
.statusText(tenant.getStatus() == 1 ? "启用" : "停用") .statusText(Objects.equals(t.getStatus(), 1) ? "启用" : "停用")
.hasChildren(tenant.getHasChildren()) .hasChildren(t.getHasChildren())
.childrenCount(tenant.getChildrenCount()) .childrenCount(t.getChildrenCount())
.createTime(tenant.getCreateTime() != null ? .createTime(t.getCreateTime() != null ?
LocalDateTime.ofInstant(tenant.getCreateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(t.getCreateTime().toInstant(), ZoneId.systemDefault()) : null)
.updateTime(tenant.getUpdateTime() != null ? .updateTime(t.getUpdateTime() != null ?
LocalDateTime.ofInstant(tenant.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null) LocalDateTime.ofInstant(t.getUpdateTime().toInstant(), ZoneId.systemDefault()) : null)
.creatorId(tenant.getCreatorId()) .creatorId(t.getCreatorId())
.build(); .build();
} }
} }
@@ -12,17 +12,28 @@
data_scope data_scope
</sql> </sql>
<sql id="where"> <sql id="where">
<where> <where>
<if test="r.name != null and r.name != ''"> <if test="r.name != null and r.name != ''">
and t.name like concat('%', #{r.name}, '%') and t.name like concat('%', #{r.name}, '%')
</if> </if>
<if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'"> <if test="r.searchKey != null and r.searchKey != '' and r.searchKey=='name'">
and t.name like concat('%', #{r.searchValue}, '%') and t.name like concat('%', #{r.searchValue}, '%')
</if> </if>
</where>
</sql> <!-- 按租户过滤(以租户为主):优先使用租户ID集合,其次使用单个租户ID -->
<if test="r.tenantIds != null and r.tenantIds.size > 0">
and t.tenant_id in
<foreach collection="r.tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
<if test="(r.tenantIds == null or r.tenantIds.size == 0) and r.tenantId != null and r.tenantId != ''">
and t.tenant_id = #{r.tenantId}
</if>
</where>
</sql>
<select id="findList" resultType="com.central.common.model.SysRole"> <select id="findList" resultType="com.central.common.model.SysRole">
select <include refid="Column_List"/> select <include refid="Column_List"/>
@@ -36,4 +47,4 @@
from sys_role from sys_role
order by create_time desc order by create_time desc
</select> </select>
</mapper> </mapper>
@@ -2,12 +2,18 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd"> "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.central.user.mapper.SysUserMapper"> <mapper namespace="com.central.user.mapper.SysUserMapper">
<sql id="where"> <sql id="where">
<where> <where>
t.is_del=0 t.is_del=0
<if test="u.id != null and u.id != ''"> <if test="u.tenantIds != null and u.tenantIds.size > 0">
and t.id like concat('%', #{u.id}, '%') and t.company in
</if> <foreach collection="u.tenantIds" item="tid" open="(" separator="," close=")">
#{tid}
</foreach>
</if>
<if test="u.id != null and u.id != ''">
and t.id like concat('%', #{u.id}, '%')
</if>
<if test="u.username != null and u.username != ''"> <if test="u.username != null and u.username != ''">
and t.username like concat('%', #{u.username}, '%') and t.username like concat('%', #{u.username}, '%')
</if> </if>
@@ -40,4 +46,4 @@
<include refid="where" /> <include refid="where" />
order by t.id desc order by t.id desc
</select> </select>
</mapper> </mapper>
@@ -6,6 +6,7 @@ package com.central.common.datascope.context;
*/ */
public class DataScopeContext { public class DataScopeContext {
private static final ThreadLocal<Integer> IGNORE_TENANT_COUNTER = ThreadLocal.withInitial(() -> 0); private static final ThreadLocal<Integer> IGNORE_TENANT_COUNTER = ThreadLocal.withInitial(() -> 0);
private static final ThreadLocal<Boolean> INCLUDE_CHILDREN = new ThreadLocal<>();
/** /**
* 进入“忽略租户过滤”上下文(可重入) * 进入“忽略租户过滤”上下文(可重入)
@@ -34,5 +35,18 @@ public class DataScopeContext {
Integer val = IGNORE_TENANT_COUNTER.get(); Integer val = IGNORE_TENANT_COUNTER.get();
return val != null && val > 0; return val != null && val > 0;
} }
public static void setIncludeChildren(Boolean v) {
if (v == null) { INCLUDE_CHILDREN.remove(); return; }
INCLUDE_CHILDREN.set(v);
}
public static Boolean getIncludeChildren() {
return INCLUDE_CHILDREN.get();
}
public static void clearIncludeChildren() {
INCLUDE_CHILDREN.remove();
}
} }
@@ -49,13 +49,16 @@ public class TenantDataScopeSqlHandler implements SqlHandler {
return DO_NOTHING; return DO_NOTHING;
} }
// 2) APP 用户仅限自身租户(不跨租户) // 2) APP 用户:默认仅自身;若请求显式 includeChildren=true,则包含子孙
LoginAppUser user = SecurityTenantUtils.getCurrentUser(); LoginAppUser user = SecurityTenantUtils.getCurrentUser();
Boolean includeChildrenFlag = DataScopeContext.getIncludeChildren();
if (user != null && "APP".equals(SecurityTenantUtils.getUserType(user))) { if (user != null && "APP".equals(SecurityTenantUtils.getUserType(user))) {
return String.format("%s = '%s'", columnName, anchorTenantId); if (!Boolean.TRUE.equals(includeChildrenFlag)) {
return String.format("%s = '%s'", columnName, anchorTenantId);
}
} }
// 3) 管理端:查询锚点租户及其子租户 // 3) 管理端或包含子孙:查询锚点租户及其子租户
List<String> tenantIds = null; List<String> tenantIds = null;
try { try {
ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class); ITenantHierarchyService tenantService = SpringContextHolder.getBean(ITenantHierarchyService.class);
@@ -64,7 +67,12 @@ public class TenantDataScopeSqlHandler implements SqlHandler {
} }
} catch (Exception ignored) { } } catch (Exception ignored) { }
if (CollectionUtils.isEmpty(tenantIds)) { if (CollectionUtils.isEmpty(tenantIds)) {
tenantIds = Arrays.asList(anchorTenantId); // fallback:如未能解析子孙,按 includeChildren 显式控制
if (Boolean.FALSE.equals(includeChildrenFlag)) {
tenantIds = Arrays.asList(anchorTenantId);
} else {
tenantIds = Arrays.asList(anchorTenantId);
}
} }
String inValues = tenantIds.stream() String inValues = tenantIds.stream()
@@ -24,4 +24,9 @@ public class SysRole extends SuperEntity {
*/ */
private DataScope dataScope; private DataScope dataScope;
private Long creatorId; private Long creatorId;
/**
* 所属租户
*/
@TableField("tenant_id")
private String tenantId;
} }
@@ -10,6 +10,7 @@ import com.central.common.model.SysRole;
import com.central.common.model.SysUser; import com.central.common.model.SysUser;
import com.central.common.service.UserTenantInitializer; import com.central.common.service.UserTenantInitializer;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.GrantedAuthority;
@@ -31,6 +32,7 @@ import java.util.*;
* Blog: http://zlt2000.gitee.io * Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Slf4j
public class LoginUserUtils { public class LoginUserUtils {
private final static String ATT_PERMISSIONS = "permissions"; private final static String ATT_PERMISSIONS = "permissions";
@@ -131,11 +133,12 @@ public class LoginUserUtils {
if (sysRoles != null) { if (sysRoles != null) {
sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode()))); sysRoles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.getCode())));
} }
// 兼容 enabled 可能为 null 的场景,默认视为启用
boolean enabled = Optional.ofNullable(sysUser.getEnabled()).orElse(true);
LoginAppUser user = new LoginAppUser(sysUser.getId() LoginAppUser user = new LoginAppUser(sysUser.getId()
, sysUser.getUsername(), sysUser.getPassword() , sysUser.getUsername(), sysUser.getPassword()
, sysUser.getMobile(), sysUser.getPermissions() , sysUser.getMobile(), sysUser.getPermissions()
, sysUser.getEnabled(), true, true, true , enabled, true, true, true
, authorities); , authorities);
// 设置用户基本属性到attributes中,供租户初始化使用 // 设置用户基本属性到attributes中,供租户初始化使用
@@ -0,0 +1,41 @@
package com.central.common.filter;
import cn.hutool.core.util.StrUtil;
import com.central.common.datascope.context.DataScopeContext;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 解析 includeChildren 查询参数,影响本次请求的数据范围(是否包含子孙租户)。
*/
@Slf4j
@ConditionalOnClass(Filter.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 18)
public class IncludeChildrenParamFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
String inc = request.getParameter("includeChildren");
if (StrUtil.isNotBlank(inc)) {
boolean b = !"0".equals(inc) && !"false".equalsIgnoreCase(inc);
DataScopeContext.setIncludeChildren(b);
log.debug("本次请求 includeChildren = {}", b);
}
filterChain.doFilter(request, response);
} finally {
DataScopeContext.clearIncludeChildren();
}
}
}
@@ -9,7 +9,11 @@ import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException; import java.io.IOException;
@@ -24,13 +28,17 @@ import java.io.IOException;
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@ConditionalOnClass(Filter.class) @ConditionalOnClass(Filter.class)
@Order @Order(Ordered.HIGHEST_PRECEDENCE + 10)
public class LoginUserFilter extends OncePerRequestFilter { public class LoginUserFilter extends OncePerRequestFilter {
@Override @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException { FilterChain filterChain) throws IOException, ServletException {
try { try {
LoginAppUser user = LoginUserUtils.getCurrentUser(request, false); // 仅在具备认证上下文或携带 Authorization 时使用完整模式,避免在无认证的内部/健康检查请求上递归拉取用户
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String authz = request.getHeader("Authorization");
boolean shouldFull = (auth != null) || StringUtils.hasText(authz);
LoginAppUser user = LoginUserUtils.getCurrentUser(request, shouldFull);
logger.debug(request.toString()); logger.debug(request.toString());
LoginUserContextHolder.setUser(user); LoginUserContextHolder.setUser(user);
filterChain.doFilter(request, response); filterChain.doFilter(request, response);
@@ -0,0 +1,48 @@
package com.central.common.filter;
import cn.hutool.core.util.StrUtil;
import com.central.common.context.TenantQueryOverrideContext;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
/**
* 基于前端参数的租户覆盖过滤器
* 规则:
* - 如果请求参数中携带 tenantId,则以其作为本次请求的查询锚点;
* - 如果未携带,则不处理(沿用登录上下文中的默认租户)。
*
* 注意:仅对当前请求生效,通过 TenantQueryOverrideContext 传递给后续数据范围处理。
*/
@Slf4j
@ConditionalOnClass(Filter.class)
@Order(Ordered.HIGHEST_PRECEDENCE + 19)
public class TenantParamOverrideFilter extends OncePerRequestFilter {
private static final String PARAM_TENANT_ID = "tenantId";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
try {
String overrideTenant = request.getParameter(PARAM_TENANT_ID);
if (StrUtil.isNotBlank(overrideTenant)) {
// 前端传了租户ID:按该ID作为本次查询锚点(后续数据范围会包含其子租户)
TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用前端参数覆盖租户ID: {}", overrideTenant);
}
filterChain.doFilter(request, response);
} finally {
TenantQueryOverrideContext.clear();
}
}
}
@@ -11,6 +11,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.filter.OncePerRequestFilter;
@@ -18,14 +19,14 @@ import java.io.IOException;
import java.util.List; import java.util.List;
/** /**
* 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点。 * 读取可选的 tenantId 查询参数,作为本次请求的租户范围覆盖锚点�?
* 规则: * 规则�?
* - APP 用户忽略该参数(记录warn)。 * - APP 用户忽略该参数(记录warn)�?
* - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn。 * - BACKEND 用户仅在参数属于“可访问租户集”时生效;否则忽略并warn�?
*/ */
@Slf4j @Slf4j
@ConditionalOnClass(Filter.class) @ConditionalOnClass(Filter.class)
@Order @Order(Ordered.HIGHEST_PRECEDENCE + 20)
public class TenantQueryOverrideFilter extends OncePerRequestFilter { public class TenantQueryOverrideFilter extends OncePerRequestFilter {
private static final String PARAM_TENANT_ID = "tenantId"; private static final String PARAM_TENANT_ID = "tenantId";
@@ -38,7 +39,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
LoginAppUser user = LoginUserContextHolder.getUser(); LoginAppUser user = LoginUserContextHolder.getUser();
if (user == null) { if (user == null) {
// 未登录,忽略参数 // 未登录,忽略参数
log.debug("忽略tenantId参数(未登录): {}", overrideTenant); log.debug("忽略tenantId参数(未登录?: {}", overrideTenant);
} else { } else {
String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND"); String userType = (String) user.getAttributes().getOrDefault("type", "BACKEND");
if ("APP".equals(userType)) { if ("APP".equals(userType)) {
@@ -49,7 +50,7 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
TenantQueryOverrideContext.setTenantId(overrideTenant); TenantQueryOverrideContext.setTenantId(overrideTenant);
log.debug("本次请求使用覆盖租户ID: {}", overrideTenant); log.debug("本次请求使用覆盖租户ID: {}", overrideTenant);
} else { } else {
log.warn("覆盖tenantId不在可访问范围, user={}, tenantId={}", user.getUsername(), overrideTenant); log.warn("覆盖tenantId不在可访问范围? user={}, tenantId={}", user.getUsername(), overrideTenant);
} }
} }
} }
@@ -61,3 +62,4 @@ public class TenantQueryOverrideFilter extends OncePerRequestFilter {
} }
} }
@@ -1,4 +1,5 @@
com.central.common.filter.TenantFilter com.central.common.filter.TenantFilter
com.central.common.filter.LoginUserFilter com.central.common.filter.LoginUserFilter
com.central.common.filter.TenantParamOverrideFilter
com.central.common.filter.TenantQueryOverrideFilter com.central.common.filter.TenantQueryOverrideFilter
com.central.common.filter.IncludeChildrenParamFilter
+72
View File
@@ -0,0 +1,72 @@
# 多租户层级查询通用SQL与函数示例
适用前提:数据库有租户层级表 `sys_tenant`,字段包含:
- `tenant_id`:租户ID(主键/唯一)
- `parent_tenant_id`:父租户ID(根为空)
- `tenant_path`:层级路径(格式:`/root/child/leaf/`)
- `status`:状态(1=启用)
注意:若 `tenant_path` 存在历史不一致或不可完全信任的情况,不建议以其作为过滤条件。
推荐做法:
1) 优先使用“基于 parent_tenant_id 的递归CTE”(MySQL 8+);
2) 或在应用层通过服务接口获取子孙租户ID列表,SQL 使用 `IN (...)` 过滤(兼容 MySQL 5.7)。
## 1) 基于 parent_tenant_id 的递归CTE(MySQL 8+,推荐)
查询给定锚点租户(含自身)以及所有子孙租户ID,并用于业务表过滤(以 `tourisms` 为例):
```sql
WITH RECURSIVE tenant_tree AS (
SELECT tenant_id
FROM sys_tenant
WHERE tenant_id = #{anchorTenantId} AND status = 1
UNION ALL
SELECT t.tenant_id
FROM sys_tenant t
INNER JOIN tenant_tree tt ON t.parent_tenant_id = tt.tenant_id
WHERE t.status = 1
)
SELECT t.*
FROM tourisms t
JOIN tenant_tree tt ON t.tenant_id = tt.tenant_id
ORDER BY t.id DESC;
```
## 2) 应用层预取子孙ID + SQL IN 过滤(兼容 MySQL 5.7)
在应用层通过服务(如 `ITenantHierarchyService#getAllSubTenantIds(anchorTenantId)`)获取集合后,SQL 使用 `IN (...)`:
```sql
SELECT *
FROM tourisms t
WHERE t.tenant_id IN (
/* 应用层传入的列表:tid_1, tid_2, ... */
/* MyBatis: <foreach collection="tenantIds" item="tid" ...> */
)
ORDER BY t.id DESC;
```
## 3) 可选:封装为函数(返回JSON数组)
MySQL函数无法直接返回结果集,可返回JSON数组再在应用侧解析:
```sql
DELIMITER //
CREATE FUNCTION fn_sub_tenants(anchor VARCHAR(64)) RETURNS JSON
BEGIN
DECLARE result JSON;
SET result = JSON_ARRAY();
-- 路径法,追加所有子孙ID
SELECT JSON_ARRAYAGG(st2.tenant_id)
INTO result
FROM sys_tenant st1
JOIN sys_tenant st2 ON st2.tenant_path LIKE CONCAT(st1.tenant_path, '%')
WHERE st1.tenant_id = anchor AND st2.status = 1;
RETURN result;
END //
DELIMITER ;
```
使用:`SELECT fn_sub_tenants(#{anchorTenantId});`,在应用层把JSON解析成列表再用于IN过滤。
建议:优先采用“递归CTE(MySQL 8+)或应用层 IN 方案”;仅在必要时考虑数据库函数,以免影响查询计划与可移植性。
+105
View File
@@ -248,3 +248,108 @@ zlt:
3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。 3) 使用 APP 账号登录,重复上述步骤,观察查询仅限等值 `tenant_id = ...`。
如需进一步协助实现 `/tenant/hierarchy/*` 管理接口或自定义 SQL 处理器,请在 Issue 中说明具体诉求与表结构,我们可继续完善。 如需进一步协助实现 `/tenant/hierarchy/*` 管理接口或自定义 SQL 处理器,请在 Issue 中说明具体诉求与表结构,我们可继续完善。
---
## 11. 前端开发计划(react-web-next)
- 目标与范围
- 新增“租户管理”页面(树形结构 + 列表 + 表单),支持租户新增/编辑/删除/查询;以组件方式实现,便于复用。
- 修复并完善“租户查询组件”使用体验(`components/TenantScopeFilter` 与 `components/ui/TenantSelector`)。
- 改造“用户管理”页面:查询区分系统用户(type=BACKEND)与 C 端用户(type=APP);新增系统用户时需绑定租户(`company`),C 端用户不提供新增入口。
- 涉及模块与文件
- 前端:`zlt-web/react-web-next` 下的 pages、components、services。
- 服务调用:`src/services/tenant.ts`、`src/services/system.ts`(用户接口带上 `type` 过滤)。
- 交互与验收要点
- 租户管理
- 左侧树呈现可访问租户层级(来源:`GET /tenant/accessible`)。
- 右侧表格按选中树节点过滤;支持分页、搜索(名称/状态)。
- 新建/编辑弹窗表单包含:租户ID、名称、上级租户、类型、编码、状态、联系人/电话、地址、描述。
- 删除需二次确认;成功后同步刷新树与表。
- 租户筛选组件
- `TenantScopeFilter`:切换后调用 `POST /tenant/switch` 并通过回调通知页面刷新;修复中文文案与关闭标签错误。
- `TenantSelector`(QueryFilter 内使用):支持选择租户与“包含子租户”复选框;修复 JSX 语法错误与文案。
- 用户管理
- 查询区分:在查询栏新增“用户类型”选择(BACKEND/APP),调用 `/api-user/users` 时透传 `type` 参数(后端已支持)。
- 新建限制:当选择 APP 类型时,隐藏“新建用户”按钮;仅 BACKEND 可新建。
- 绑定租户:新建/编辑系统用户表单新增“所属租户(company)”字段(树选择)。
- 实施步骤
1) 组件化重构租户管理页:抽离 Tree、Table、Form 三个组件,页面仅作编排与状态承载。
2) 修复 `TenantScopeFilter` 与 `TenantSelector` 的中文文案与 JSX 语法问题,统一回调语义。
3) 用户管理页:新增“用户类型”查询项;根据类型控制“新建”按钮显隐;在表单中增加“所属租户(company)”字段(仅 BACKEND)。
4) 自测与联调:校验切换租户后各页面数据是否随之刷新;核对新增系统用户的 `company` 入库。
- 回滚与影响
- 仅前端改动,不涉及数据库变更;若需回滚,可恢复页面与组件的旧实现。
- 影响路由:`/system/tenant.html`、`/system/user.html`。
---
## 12. 实施记录:景区列表按租户层级过滤(2025-09-30)
为解决“景区列表未能根据当前登录用户所属租户获取其以及子孙数据”的问题,采用“有参用参、无参取当前租户”的直连式实现(不依赖过滤器/拦截器),在接口与SQL层完成改造。
- 行为规则
- 若前端传入 `tenantId`,则以该值为锚点租户,查询“自身+全部子孙租户”的景区数据。
- 若未传 `tenantId`,则取当前登录用户所属租户(`TenantContextHolder.getTenant()`)作为锚点,按相同规则查询。
- 涉及文件与改动
- `zlt-business/order-center/src/main/java/com/central/order/controller/TourismController.java:53`
- 在 `list(@RequestParam Map<String, Object> params)` 返回前补全 `params.tenantId`:当请求未传时,从 `TenantContextHolder.getTenant()` 取当前租户写入 `params`。
- `zlt-business/order-center/src/main/resources/mapper/TourismMapper.xml:6`
- 重写 `findList` 查询,去除对 `tenant_path` 的依赖;改为两级兜底的“父子关系递归”方案:
1) 若 `p.tenantIds` 存在,直接使用 `IN (...)` 过滤(由服务层通过 `ITenantHierarchyService.getAllSubTenantIds` 预先计算,兼容无CTE环境)。
2) 否则使用 MySQL 8 的 `WITH RECURSIVE` 基于 `parent_tenant_id` 递归展开子孙租户,再与 `tourisms` 连接过滤。
- 通用SQL文档:`zlt-doc/sql/tenant-descendants-queries.md:1` 已更新为优先推荐“递归CTE/IN列表”,不再推荐以 `tenant_path` 作为过滤条件。
- 服务层补充:`zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java:findList`
- 统一在服务层解析锚点租户ID(请求 tenantId 优先,否则取当前登录用户租户)。
- 获取“自身+子孙租户ID集合”逻辑:
- 优先调用 `ITenantHierarchyService#getAllSubTenantIds(anchor)`;
- 若该 Bean 不存在(跨服务不共享实现),则使用本服务内 Mapper `TenantHierarchyLiteMapper` 通过 `parent_tenant_id` 进行 BFS 递归展开(MySQL 5.7 兼容)。
- 将得到的 `tenantIds` 放入 Mapper 参数,确保 XML 走 `IN (...)` 分支,无需 CTE。
- 新增:`zlt-business/order-center/src/main/java/com/central/order/mapper/TenantHierarchyLiteMapper.java`
- 仅提供 `selectDirectChildrenIds(parentTenantId)`,用于本地 BFS 递归子孙。
- 设计说明
- 不再使用 `tenant_path` 作为过滤条件,避免路径数据潜在不一致导致的误判;
- 优先应用层预取ID集合,其次SQL层递归,两者均严格基于 `parent_tenant_id` 邻接表模型;
- 不引入新的拦截器/过滤器,接口层逻辑清晰可控、便于定位问题。
- 性能与索引建议
- 为 `sys_tenant(parent_tenant_id)`、`sys_tenant(tenant_id)`、业务表如 `tourisms(tenant_id)` 建立索引;
- 大租户树场景建议启用应用层缓存 `tenantIds`,或使用“闭包表/物化路径+触发器”进一步优化。
- 测试与兼容
- 传入 `tenantId`:应返回该租户及其子孙下的景区;
- 不传 `tenantId`:应返回当前登录租户及其子孙下的景区;
- MySQL 5.7 及以下:走 `IN (...)` 方案;MySQL 8+:走 CTE 方案。
- 后续可选扩展(如需)
- 将相同过滤策略扩展到二维码、订单、素材等列表查询,统一租户视角;
- 封装 MyBatis 片段或 XML include,减少重复 SQL;
- 在业务 Service 层提供通用方法(基于 `ITenantHierarchyService`)返回子孙租户ID集合,供 Mapper 复用。
### 12-修订(2025-10-01)
- 问题复盘
- order-center 模块无租户表,历史兜底逻辑通过本地 TenantHierarchyLiteMapper 查询 sys_tenant 导致报错:Table 'order-center-test.sys_tenant' doesn't exist。
- 修复方案(UTF-8 文档与代码统一)
- 引入 Feign 远程调用,从 user-center 获取“锚点租户(含自身)+ 子孙租户ID集合”,不再在 order-center 直接访问租户表。
- user-center 新增接口:GET /tenant/hierarchy/descendants?tenantId=xxx,返回 Result<List<String>>。
- order-center 新增 Feign 客户端及降级:
- 客户端:zlt-business/order-center/src/main/java/com/central/order/feign/TenantHierarchyRemoteService.java
- 降级:zlt-business/order-center/src/main/java/com/central/order/feign/fallback/TenantHierarchyRemoteServiceFallbackFactory.java(降级仅返回自身 tenantId)
- 服务层改造:TourismServiceImpl.findList 优先使用本地 ITenantHierarchyService(若同进程可用),否则调用 Feign 远程接口获取 tenantIds,并传入 Mapper,落到 XML 的 IN (...) 分支,避免引用本地 sys_tenant。
- 影响文件
- 新增:
- zlt-business/order-center/src/main/java/com/central/order/feign/TenantHierarchyRemoteService.java
- zlt-business/order-center/src/main/java/com/central/order/feign/fallback/TenantHierarchyRemoteServiceFallbackFactory.java
- 修改:
- zlt-business/order-center/src/main/java/com/central/order/service/impl/TourismServiceImpl.java
- zlt-business/user-center/src/main/java/com/central/user/controller/TenantHierarchyController.java(新增 descendants 接口)
- 兼容性与行为
- 继续优先 IN (...) 过滤,因此不会触发 XML 中的 CTE 查询,也就不会访问不存在的 sys_tenant 表。
- 远程调用失败时自动降级为“仅自身”,与现有退化语义一致。
- 所有修改与文档均采用 UTF-8 无 BOM 编码。
@@ -0,0 +1,218 @@
# 多租户订单统计功能测试指南
## 功能概述
实现了基于多租户层级的订单统计功能,能够根据当前租户统计自己以及所有子孙租户的订单数据,支持日、月、年三种时间维度。
## 实现架构
### 统计逻辑流程
1. **租户层级解析**:根据当前租户ID获取所有子孙租户ID列表
2. **景区关联查询**:根据租户ID列表查询所有关联的景区
3. **订单数据统计**:根据景区ID列表统计相关订单数据
### 核心文件改动
#### 后端改动
1. **DashboardController.java** (F:\project\go-fly-platform-services\zlt-business\order-center\src\main\java\com\central\order\controller\DashboardController.java:36-56)
- 新增参数:`tenantId`(租户ID)、`includeChildren`(是否包含子租户)、`statType`(统计类型:day/month/year)
2. **DashboardServiceImpl.java** (F:\project\go-fly-platform-services\zlt-business\order-center\src\main\java\com\central\order\service\impl\DashboardServiceImpl.java:36-95)
- 实现租户层级解析逻辑
- 支持本地服务和远程Feign调用两种方式获取子孙租户
- 根据statType自动计算时间范围
3. **TenantHierarchyController.java** (F:\project\go-fly-platform-services\zlt-business\user-center\src\main\java\com\central\user\controller\TenantHierarchyController.java:159-172)
- 提供获取子孙租户ID的REST接口
#### 前端支持
1. **Welcome.tsx** (F:\project\go-fly-platform-services\zlt-web\react-web-next\src\pages\Welcome.tsx)
- 已集成租户选择器和时间维度切换组件
- 支持按租户和时间维度查询统计数据
## 测试步骤
### 1. 准备测试数据
```sql
-- 创建测试租户层级(如果尚未创建)
-- 父租户
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
VALUES ('tenant-001', '总公司', null, 1, 'tenant-001', 1);
-- 子租户
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
VALUES ('tenant-002', '分公司A', 'tenant-001', 2, 'tenant-001/tenant-002', 1);
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
VALUES ('tenant-003', '分公司B', 'tenant-001', 2, 'tenant-001/tenant-003', 1);
-- 孙租户
INSERT INTO sys_tenant (tenant_id, tenant_name, parent_tenant_id, tenant_level, tenant_path, status)
VALUES ('tenant-004', '办事处A1', 'tenant-002', 3, 'tenant-001/tenant-002/tenant-004', 1);
-- 创建测试景区
INSERT INTO tourisms (id, name, tenant_id, is_del) VALUES
(1, '景区1-总公司', 'tenant-001', 0),
(2, '景区2-分公司A', 'tenant-002', 0),
(3, '景区3-分公司B', 'tenant-003', 0),
(4, '景区4-办事处A1', 'tenant-004', 0);
-- 创建测试订单
INSERT INTO orders (tourism_id, order_status, pay_type, create_time, amount) VALUES
-- 总公司订单
(1, 3, 1, '2025-01-01 10:00:00', 10000),
(1, 3, 1, '2025-01-02 10:00:00', 20000),
-- 分公司A订单
(2, 3, 1, '2025-01-01 11:00:00', 15000),
(2, 8, 1, '2025-01-02 11:00:00', 5000), -- 退款订单
-- 分公司B订单
(3, 3, 1, '2025-01-01 12:00:00', 30000),
-- 办事处A1订单
(4, 3, 1, '2025-01-01 13:00:00', 8000);
```
### 2. API测试
#### 测试场景1:查询总公司(含所有子孙)的订单统计
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=day" \
-H "Authorization: Bearer {your_token}"
```
预期结果:
- 应返回所有4个景区的订单总和
- totalOrders: 6
- totalAmount: 88000 (分)
#### 测试场景2:查询分公司A(含子孙)的订单统计
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-002&includeChildren=true&statType=day" \
-H "Authorization: Bearer {your_token}"
```
预期结果:
- 应返回景区2和景区4的订单
- totalOrders: 3
- totalAmount: 28000 (分)
#### 测试场景3:查询分公司B(不含子孙)的订单统计
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-003&includeChildren=false&statType=day" \
-H "Authorization: Bearer {your_token}"
```
预期结果:
- 仅返回景区3的订单
- totalOrders: 1
- totalAmount: 30000 (分)
#### 测试场景4:按月统计
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=month" \
-H "Authorization: Bearer {your_token}"
```
预期结果:
- 返回最近12个月的统计数据
- 订单趋势按月分组
#### 测试场景5:按年统计
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId=tenant-001&includeChildren=true&statType=year" \
-H "Authorization: Bearer {your_token}"
```
预期结果:
- 返回最近5年的统计数据
- 订单趋势按年分组
### 3. 前端界面测试
1. 登录系统,进入首页
2. 在右上角选择不同的租户
3. 切换"包含子租户"开关,观察数据变化
4. 切换统计粒度(日/月/年),观察图表变化
5. 验证数据准确性:
- 订单总数是否正确
- 金额计算是否准确
- 趋势图是否按时间维度正确显示
### 4. 数据准确性验证SQL
```sql
-- 验证租户001及其子孙的订单总数
SELECT COUNT(*) as total_orders, SUM(amount) as total_amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
WHERE t.tenant_id IN (
WITH RECURSIVE tenant_tree AS (
SELECT tenant_id FROM sys_tenant WHERE tenant_id = 'tenant-001'
UNION ALL
SELECT st.tenant_id
FROM sys_tenant st
JOIN tenant_tree tt ON st.parent_tenant_id = tt.tenant_id
)
SELECT tenant_id FROM tenant_tree
)
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
AND (o.pay_type = 1 OR o.pay_type IS NULL);
-- 按日分组统计
SELECT DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,
COUNT(*) as order_count,
SUM(o.amount) as amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
WHERE t.tenant_id IN ('tenant-001', 'tenant-002', 'tenant-003', 'tenant-004')
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')
ORDER BY date;
```
## 注意事项
1. **性能优化**
- 对于大租户树,建议启用应用层缓存租户ID列表
- 确保 `tourisms.tenant_id` 和 `orders.tourism_id` 有索引
2. **权限控制**
- 管理端用户(BACKEND)默认可切换租户
- C端用户(APP)仅能查看自身租户数据
3. **故障降级**
- 当远程获取租户层级失败时,自动降级为仅查询当前租户
4. **日志监控**
- 关注日志中的 "统计范围" 信息,确认租户和景区范围正确
- 如出现 "远程获取租户层级失败" 警告,检查user-center服务状态
## 常见问题
### Q1: 统计数据为空?
- 检查当前租户是否有关联的景区
- 检查景区是否有订单数据
- 查看后端日志确认租户ID和景区ID列表
### Q2: 子租户数据未包含?
- 确认 `includeChildren` 参数为 true
- 检查 sys_tenant 表中的 parent_tenant_id 关系是否正确
- 验证 TenantHierarchyService 是否正确返回子孙租户
### Q3: 时间维度切换无效?
- 确认 `statType` 参数值为 day/month/year 之一
- 检查 DashboardMapper 中的 SQL 是否正确处理时间分组
## 性能测试建议
1. 模拟大量租户层级(100+ 租户,3-5层深度)
2. 每个租户关联 5-10 个景区
3. 每个景区生成 1000+ 订单
4. 测试不同时间维度的查询响应时间
5. 监控数据库查询性能,必要时添加索引
## 后续优化建议
1. 添加租户层级缓存机制,减少递归查询
2. 实现订单数据预聚合,提升统计查询性能
3. 支持更多统计维度(按景区、按设备、按二维码等)
4. 添加数据导出功能(Excel/CSV)
+180
View File
@@ -0,0 +1,180 @@
# 租户层级统计测试方案
## 修复内容总结
### 1. 创建专门的租户解析服务
- **文件**: `TenantResolverService.java`
- **功能**: 专门处理租户层级关系的获取,通过Feign调用user-center服务
### 2. 修复Feign降级策略
- **文件**: `UserCenterServiceFallbackFactory.java`
- **修复**: 当远程调用失败时,返回仅包含当前租户的列表,而不是null
### 3. 优化统计服务
- **文件**: `DashboardServiceImpl.java`
- **修复**: 使用TenantResolverService统一处理租户解析
## 测试验证步骤
### 步骤1: 验证服务间通信
1. **启动服务**
```bash
# 启动user-center服务
cd zlt-business/user-center
mvn spring-boot:run
# 启动order-center服务
cd zlt-business/order-center
mvn spring-boot:run
```
2. **查看日志**
重点关注以下日志:
- `TenantResolverService` - "开始获取租户 xxx 的所有子孙租户"
- `TenantResolverService` - "成功获取租户层级: xxx -> n 个租户"
- `DashboardServiceImpl` - "统计范围 - 租户IDs: n 个租户, 景区IDs: m 个景区"
### 步骤2: API测试
#### 2.1 测试租户层级获取接口
```bash
# 直接测试user-center的租户层级接口
curl -X GET "http://localhost:9900/api-user/tenant/hierarchy/{tenantId}" \
-H "Authorization: Bearer {token}"
```
预期返回:
```json
{
"resp_code": 0,
"resp_msg": "ok",
"datas": ["tenantId", "child1", "child2", "grandchild1"]
}
```
#### 2.2 测试订单统计接口(含子租户)
```bash
curl -X GET "http://localhost:9900/api-order/dashboard/statistics?tenantId={tenantId}&includeChildren=true&statType=day" \
-H "Authorization: Bearer {token}"
```
观察日志应包含:
- 租户解析过程
- 获取到的子孙租户列表
- 查询的景区ID列表
### 步骤3: 数据验证SQL
```sql
-- 1. 查看租户层级关系
WITH RECURSIVE tenant_tree AS (
SELECT tenant_id, parent_tenant_id, tenant_name, 1 as level
FROM sys_tenant
WHERE tenant_id = '目标租户ID'
UNION ALL
SELECT t.tenant_id, t.parent_tenant_id, t.tenant_name, tt.level + 1
FROM sys_tenant t
JOIN tenant_tree tt ON t.parent_tenant_id = tt.tenant_id
)
SELECT * FROM tenant_tree ORDER BY level, tenant_id;
-- 2. 查看租户关联的景区
SELECT
st.tenant_id,
st.tenant_name,
t.id as tourism_id,
t.name as tourism_name
FROM sys_tenant st
LEFT JOIN tourisms t ON st.tenant_id = t.tenant_id
WHERE st.tenant_id IN (
-- 这里填入上面查询得到的所有租户ID
'tenant1', 'tenant2', 'tenant3'
);
-- 3. 验证订单统计
SELECT
t.tenant_id,
COUNT(DISTINCT o.id) as order_count,
SUM(o.order_amount) as total_amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
WHERE t.tenant_id IN (
-- 这里填入上面查询得到的所有租户ID
'tenant1', 'tenant2', 'tenant3'
)
AND o.order_status IN (1, 3, 4, 5, 7, 8, 9)
GROUP BY t.tenant_id;
```
### 步骤4: 前端验证
1. 登录系统,访问首页
2. 选择一个有子租户的父租户
3. 确保"包含子租户"开关打开
4. 观察统计数据是否包含子租户的订单
### 步骤5: 问题排查
如果子租户数据仍然未被统计,检查:
1. **网络通信**
- order-center能否访问user-center服务
- 检查服务注册中心(如Nacos)中服务是否正常注册
2. **日志分析**
```bash
# 查看order-center日志
tail -f logs/order-center.log | grep -E "TenantResolver|租户"
# 查看user-center日志
tail -f logs/user-center.log | grep -E "TenantHierarchy|租户"
```
3. **Feign配置**
检查`application.yml`中Feign超时配置:
```yaml
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 10000
```
4. **数据完整性**
- 确认sys_tenant表中parent_tenant_id关系正确
- 确认tourisms表中tenant_id字段有值
- 确认orders表中tourism_id关联正确
## 期望结果
1. 选择父租户时,统计数据应包含:
- 父租户自身的订单
- 所有子租户的订单
- 所有孙租户的订单
2. 日志中应显示:
- 正确的租户ID列表
- 正确的景区ID列表
- SQL查询包含正确的IN条件
3. 前端界面:
- 订单数 = 父租户订单 + 所有子孙租户订单
- 金额 = 父租户金额 + 所有子孙租户金额
## 常见问题
### Q: Feign调用超时
A: 增加超时时间或检查网络连接
### Q: 获取不到子租户
A: 检查sys_tenant表的parent_tenant_id字段是否正确
### Q: 统计数据为0
A: 检查景区是否关联了正确的tenant_id
### Q: webApp看不到所有数据
A: webApp应该返回空的tenantIds列表,让SQL不加租户过滤
+101
View File
@@ -7,6 +7,82 @@
## 目录结构 ## 目录结构
## 构建与部署(多环境)
- 前置要求:Node.js 16+、NPM 7+(或 Yarn/Pnpm)
- 可访问目标环境网关(如 `http://119.45.169.13:9900`)
### 环境变量约定
- `REACT_APP_ENV=dev|test|pre`:仅用于本地开发选择 `config/proxy.ts` 的代理分支。
- `GATEWAY_ORIGIN`:仅用于本地开发代理目标(统一转发 `/api-*`)。
- `API_PREFIX`:构建时注入到 Umi 全局 `request.prefix`,用于 `dist` 包直连网关。
- 测试/预发:设置为网关完整地址(如 `http://119.45.169.13:9900`)。
- 生产:推荐留空,采用同域反向代理 `/api-*`。
### 本地开发(走代理)
- 安装依赖:`npm install`
- 启动:`npm run start` | `npm run start:test` | `npm run start:pre`
- 临时覆盖代理网关:
- PowerShell:`$env:GATEWAY_ORIGIN="http://10.x.x.x:9900"; npm run start:test`
- CMD:`set GATEWAY_ORIGIN=http://10.x.x.x:9900 && npm run start:test`
说明:开发环境不注入 `API_PREFIX`,所有 `/api-*` 由 `config/proxy.ts` + `GATEWAY_ORIGIN` 转发。
### 多环境构建(输出 dist)
- 基础构建:`npm run build`
- 测试包:`npm run build:test`(默认 `API_PREFIX=http://119.45.169.13:9900`)
- 预发包:`npm run build:pre`
- 生产包:`npm run build:prod`(不注入前缀,推荐同域反代)
覆盖前缀示例:
```bash
API_PREFIX=http://10.x.x.x:9900 npm run build:test
$env:API_PREFIX="http://10.x.x.x:9900"; npm run build:test
```
### 部署方式
1) 跨域直连网关(需后端 CORS 放行)
- 使用 `build:test`/`build:pre` 注入网关地址(如 `http://119.45.169.13:9900`)。
- 将 `dist/` 上传到任意静态服务器(Nginx/OSS 等)。
- 确保后端 CORS 允许当前前端域名。
2) 同域反向代理(推荐生产)
- 使用 `build:prod`(`API_PREFIX` 为空)。
- 由 Nginx 同域托管静态资源并将 `/api-*` 反代到网关。
Nginx 示例:
```nginx
server {
listen 80;
server_name your.domain.com;
root /opt/apps/react-web-next/dist;
index index.html;
location / { try_files $uri $uri/ /index.html; }
location /api- { proxy_pass http://127.0.0.1:9900; }
}
```
### 部署总结(测试环境)
- 构建:`npm run build:test:mgnt`
- 等价:`cross-env APP_BASE=/mgnt REACT_APP_ENV=test API_PREFIX=http://119.45.169.13:9900 npm run build`
- 部署:将 `dist/` 上传至服务器,按上方示例以 `/mgnt/` 路径托管并开启 history 回退。
- 访问:`http://<服务器IP或域名>:9999/mgnt/`
- 验证:
- F12 Network 中 `*.async.js`/`*.js` 从 `/mgnt/` 根路径加载,状态 200、类型 `application/javascript`。
- 接口请求直连 `API_PREFIX`(测试网关),若跨域需在网关开启 CORS。
### 验证清单与常见问题
- 刷新不 404(`try_files` 生效)。
- CORS 报错:跨域直连需后端放行。
- Mixed Content:HTTPS 站点勿注入 `http://` 前缀。
- 资源 404:检查 `publicPath` 为 `./`,并确认 `dist/` 完整上传。
``` ```
react-web-next/ react-web-next/
├─ config/ ├─ config/
@@ -103,3 +179,28 @@ react-web-next/
- 单元测试、E2E 用例补充。 - 单元测试、E2E 用例补充。
如需我继续迁移具体页面,请告知优先级(如 系统/订单/设备 等模块)。 如需我继续迁移具体页面,请告知优先级(如 系统/订单/设备 等模块)。
### 部署总结(生产环境)
- 构建:`npm run build:prod:mgnt`
- 等价:`cross-env APP_BASE=/mgnt REACT_APP_ENV=prod npm run build`
- Nginx:在 `/mgnt/` 托管静态资源,并增加接口反代:
```nginx
location = /mgnt { return 301 /mgnt/; }
location /mgnt/ {
alias /opt/apps/react-web-next/dist/;
index index.html;
try_files $uri $uri/ /mgnt/index.html;
}
location /api- {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:9900; # 改为你的网关地址
}
```
- 访问:`http://<服务器>:9999/mgnt/`
- 验证:
- 资源从 `/mgnt/` 加载为 JS(200)
- 接口指向同域 `/api-*`,由 Nginx 反代到网关,无 CORS。
+10 -1
View File
@@ -8,11 +8,14 @@ import proxy from './proxy';
const { REACT_APP_ENV } = process.env as any; const { REACT_APP_ENV } = process.env as any;
const isDev = process.env.NODE_ENV === 'development'; const isDev = process.env.NODE_ENV === 'development';
// 构建期注入 API 前缀(生产包/测试包/预发包),开发环境走代理不加前缀
const API_PREFIX = isDev ? '' : (process.env.API_PREFIX || '');
const APP_BASE = isDev ? '/' : (process.env.APP_BASE || '/');
export default { export default {
hash: true, hash: true,
// 资源路径:开发用根路径,生产为相对路径 // 资源路径:开发用根路径,生产为相对路径
publicPath: isDev ? '/' : './', publicPath: isDev ? '/' : (APP_BASE.endsWith('/') ? APP_BASE : APP_BASE + '/'),
antd: {}, antd: {},
// 页面 meta 标签 // 页面 meta 标签
metas: [ metas: [
@@ -36,8 +39,14 @@ export default {
routes, routes,
// 历史模式 // 历史模式
history: { type: 'browser' }, history: { type: 'browser' },
base: APP_BASE,
// Dev 代理 // Dev 代理
proxy: (proxy as any)[REACT_APP_ENV || 'dev'], proxy: (proxy as any)[REACT_APP_ENV || 'dev'],
// 向业务代码注入构建期常量
define: {
'process.env.API_PREFIX': API_PREFIX,
'process.env.APP_BASE': APP_BASE,
},
// 构建优化 // 构建优化
nodeModulesTransform: { type: 'none' }, nodeModulesTransform: { type: 'none' },
mfsu: false, mfsu: false,
+8 -1
View File
@@ -5,13 +5,20 @@
"scripts": { "scripts": {
"start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev", "start": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev",
"start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev", "start:dev": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=dev GATEWAY_ORIGIN=http://127.0.0.1:9900 umi dev",
"start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test GATEWAY_ORIGIN=http://local.goflytec.com:9900 umi dev",
"start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev", "start:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre GATEWAY_ORIGIN=http://119.45.169.13:9900 umi dev",
"build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build", "build": "cross-env NODE_OPTIONS=--openssl-legacy-provider umi build",
"build:test": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test API_PREFIX=http://119.45.169.13:9900 umi build",
"build:pre": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre API_PREFIX=http://119.45.169.13:9900 umi build",
"build:prod": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod umi build",
"build:test:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=test APP_BASE=/mgnt API_PREFIX=http://local.goflytec.com:9900 umi build",
"build:pre:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=pre APP_BASE=/mgnt API_PREFIX=http://local.goflytec.com:9900 umi build",
"build:prod:mgnt": "cross-env NODE_OPTIONS=--openssl-legacy-provider REACT_APP_ENV=prod APP_BASE=/mgnt umi build",
"lint": "eslint --ext .ts,.tsx src", "lint": "eslint --ext .ts,.tsx src",
"tsc": "tsc --noEmit" "tsc": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@ant-design/plots": "^2.6.5",
"@ant-design/pro-components": "1.1.1", "@ant-design/pro-components": "1.1.1",
"@ant-design/pro-layout": "^7.22.7", "@ant-design/pro-layout": "^7.22.7",
"antd": "^4.20.0", "antd": "^4.20.0",
+44 -6
View File
@@ -1,18 +1,38 @@
// 避免类型耦合,使用 any 降级
import './global.less'; import './global.less';
import React from 'react'; import React from 'react';
import { ThemeProvider } from './theme'; import { ThemeProvider } from './theme';
import { history } from 'umi'; import { history } from 'umi';
import { clearTenantCache, ensureTenantCacheTokenGuard } from '@/utils/tenantCache';
export function rootContainer(container: React.ReactNode, _args?: any) { export function rootContainer(container: React.ReactNode, _args?: any) {
return React.createElement(ThemeProvider, null, container); return React.createElement(ThemeProvider, null, container);
} }
// 使用简化的 request 配置,避免与类型强绑定(兼容 umi 3) const API_PREFIX = process.env.API_PREFIX || '';
export const request: any = { export const request: any = {
prefix: API_PREFIX,
errorConfig: { errorConfig: {
errorHandler(error: any) { errorHandler(error: any) {
// 可在此处统一处理错误,如通知等 // 统一错误处理
// 若出现 401/403 等未授权错误,清理本地态并跳转登录
try {
const status = (error?.response?.status ?? error?.data?.code ?? error?.data?.resp_code) as number | undefined;
const unauthorized = status === 401 || status === 403;
if (unauthorized) {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
const current = encodeURIComponent(`${pathname}${search}`);
const to = `/user/login?redirect=${current}`;
if (!String(pathname).startsWith('/user/login')) {
history.push(to);
}
}
} catch {}
throw error; throw error;
}, },
}, },
@@ -21,6 +41,8 @@ export const request: any = {
const token = sessionStorage.getItem('access_token'); const token = sessionStorage.getItem('access_token');
const headers: Record<string, string> = { ...(options?.headers as any) }; const headers: Record<string, string> = { ...(options?.headers as any) };
if (token) headers['Authorization'] = `Bearer ${token}`; if (token) headers['Authorization'] = `Bearer ${token}`;
// 确保缓存与当前 Token 一致(Token 变化则清缓存)
ensureTenantCacheTokenGuard();
return { url, options: { ...options, headers } }; return { url, options: { ...options, headers } };
}, },
], ],
@@ -39,6 +61,24 @@ export const request: any = {
} as any; } as any;
(response as any).data = mapped; (response as any).data = mapped;
} }
// 未授权统一处理:HTTP 状态或业务码均触发
const httpUnauthorized = (response.status === 401 || response.status === 403);
const bizCode = (data?.resp_code ?? data?.code) as number | undefined;
const bizUnauthorized = bizCode === 401 || bizCode === 403 || bizCode === 40101 || bizCode === 40100;
if (httpUnauthorized || bizUnauthorized) {
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {}
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
const search = typeof window !== 'undefined' ? window.location.search : '';
const current = encodeURIComponent(`${pathname}${search}`);
const to = `/user/login?redirect=${current}`;
if (!String(pathname).startsWith('/user/login')) {
history.push(to);
}
}
} catch (e) { } catch (e) {
// 静默处理解析错误 // 静默处理解析错误
} }
@@ -47,15 +87,13 @@ export const request: any = {
], ],
}; };
// 简单路由守卫:未登录访问受保护路由时跳回登录;已登录访问登录页时跳到欢迎页
export function onRouteChange({ location }: any) { export function onRouteChange({ location }: any) {
try { try {
const token = sessionStorage.getItem('access_token'); const token = sessionStorage.getItem('access_token');
const isLoginPath = String(location?.pathname || '').startsWith('/user/login'); const isLoginPath = String(location?.pathname || '').startsWith('/user/login');
if (!token && !isLoginPath) { if (!token && !isLoginPath) {
history.push('/user/login'); history.push('/user/login');
} else if (token && isLoginPath) {
history.push('/welcome');
} }
} catch {} } catch {}
} }
@@ -1,54 +1,83 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Space, Button, TreeSelect, Checkbox, message } from 'antd'; import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant'; import { tenantApi } from '@/services/tenant';
interface Props { interface TenantNode {
// 当租户或“包含子租户”变更后回调 tenantId?: string;
onChanged?: (tenantId: string, includeChildren: boolean) => void; tenantName?: string;
children?: TenantNode[];
status?: number | boolean;
} }
const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => { interface Props {
const [tree, setTree] = useState<TenantTreeNode[]>([]); // 租户或“包含子租户”变化后回调(外部将 tenantId/includeChildren 透传至请求参数)
onChanged?: (tenantId: string, includeChildren: boolean) => void;
// 可选:是否调用后端切换查询上下文(默认 false)
useSwitchTenant?: boolean;
// 自动应用(变更即触发回调,隐藏“应用”按钮)
autoApply?: boolean;
}
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false, autoApply = false }) => {
const [tree, setTree] = useState<TenantNode[]>([]);
const [tenantId, setTenantId] = useState<string | undefined>(); const [tenantId, setTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState(true); const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState<boolean>(false);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
setLoading(true); setLoading(true);
try { try {
const [treeRes, currentRes] = await Promise.all([ // 获取可访问租户树
tenantApi.getAccessibleTenants(), const treeRes: any = await tenantApi.getAccessibleTenants();
tenantApi.getCurrentTenant(), let list: TenantNode[] = [];
]); if (Array.isArray(treeRes)) list = treeRes as any;
if (treeRes.success) setTree(treeRes.data || []); else if (Array.isArray(treeRes?.data)) list = treeRes.data as any;
if (currentRes.success) setTenantId(currentRes.data?.tenantId); else if (treeRes?.resp_code === 0 && Array.isArray(treeRes?.data)) list = treeRes.data as any;
setTree(list || []);
// 获取当前租户
const curRes: any = await tenantApi.getCurrentTenant();
const curId = curRes?.data?.tenantId || (curRes?.resp_code === 0 ? curRes?.data?.tenantId : undefined);
if (curId) setTenantId(curId);
} catch {
// 忽略错误,展示空树
} finally { } finally {
setLoading(false); setLoading(false);
} }
})(); })();
}, []); }, []);
const toTreeData = (nodes: TenantTreeNode[]): any[] => // 自动应用:参数变化即触发回调
nodes?.map((n) => ({ useEffect(() => {
title: n.tenantName, if (!autoApply) return;
if (!tenantId) return;
onChanged?.(tenantId, includeChildren);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, autoApply]);
const toTreeData = (nodes?: TenantNode[]): any[] =>
(nodes || []).map((n) => ({
title: n.tenantName && n.tenantId ? `${n.tenantName} (${n.tenantId})` : (n.tenantName || n.tenantId || '-'),
value: n.tenantId, value: n.tenantId,
key: n.tenantId, key: n.tenantId,
children: n.children ? toTreeData(n.children) : undefined, children: n.children ? toTreeData(n.children) : undefined,
})) || []; }));
const handleApply = async () => { const handleApply = async () => {
if (!tenantId) return; if (!tenantId) return;
try { try {
const res = await tenantApi.switchTenant(tenantId); if (useSwitchTenant) {
if (res.success) { const res: any = await tenantApi.switchTenant(tenantId);
if (!(res?.success ?? res?.resp_code === 0)) {
message.error(res?.msg || '切换失败');
return;
}
message.success('租户范围已更新'); message.success('租户范围已更新');
onChanged?.(tenantId, includeChildren);
} else {
message.error(res.msg || '切换失败');
} }
} catch (e) { onChanged?.(tenantId, includeChildren);
message.error('切换失败'); } catch {
message.error('操作失败');
} }
}; };
@@ -56,22 +85,22 @@ const TenantScopeFilter: React.FC<Props> = ({ onChanged }) => {
<Space> <Space>
<TreeSelect <TreeSelect
style={{ minWidth: 260 }} style={{ minWidth: 260 }}
treeDefaultExpandAll showSearch
loading={loading} loading={loading}
treeNodeFilterProp="title"
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="选择租户(含子租户)" placeholder="选择租户(含子租户)"
value={tenantId} value={tenantId}
onChange={(val) => setTenantId(val)} onChange={(val) => setTenantId(val)}
treeData={toTreeData(tree)} treeData={toTreeData(tree)}
/> />
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}> <Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
包含子租户 {!autoApply && (
</Checkbox> <Button type="primary" onClick={handleApply}>应用</Button>
<Button type="primary" onClick={handleApply}> )}
应用
</Button>
</Space> </Space>
); );
}; };
export default TenantScopeFilter; export default TenantScopeFilter;
@@ -18,6 +18,8 @@ export interface SearchBarPlusProps {
onTenantChanged?: (tenantId: string, includeChildren: boolean) => void; onTenantChanged?: (tenantId: string, includeChildren: boolean) => void;
// 租户筛选放置位置:start 放在最前,end 放在最后(默认 start) // 租户筛选放置位置:start 放在最前,end 放在最后(默认 start)
tenantPosition?: 'start' | 'end'; tenantPosition?: 'start' | 'end';
// 是否调用后端“切换查询租户”接口(默认不调用,避免跨页面副作用)
useSwitchTenant?: boolean;
} }
const SearchBarPlus: React.FC<SearchBarPlusProps> = ({ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
@@ -30,13 +32,14 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
showTenant = true, showTenant = true,
onTenantChanged, onTenantChanged,
tenantPosition = 'start', tenantPosition = 'start',
useSwitchTenant = false,
}) => { }) => {
const handleFinish = async (values: Record<string, any>) => { const handleFinish = async (values: Record<string, any>) => {
try { try {
if (showTenant && values && values.tenantId) { if (useSwitchTenant && showTenant && values && (values as any).tenantId) {
await tenantApi.switchTenant(values.tenantId); await tenantApi.switchTenant((values as any).tenantId);
} }
onTenantChanged?.(values?.tenantId, !!values?.includeChildren); onTenantChanged?.((values as any)?.tenantId, !!(values as any)?.includeChildren);
} finally { } finally {
await onFinish?.(values); await onFinish?.(values);
} }
@@ -58,3 +61,4 @@ const SearchBarPlus: React.FC<SearchBarPlusProps> = ({
}; };
export default SearchBarPlus; export default SearchBarPlus;
@@ -1,29 +1,43 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Form, TreeSelect, Checkbox } from 'antd'; import { Form, TreeSelect, Checkbox, message } from 'antd';
import { tenantApi, TenantTreeNode } from '@/services/tenant'; import { tenantApi, TenantTreeNode } from '@/services/tenant';
import { getTenantTreeCache, setTenantTreeCache, getTenantChildrenCache, setTenantChildrenCache, getTenantDetailCache, setTenantDetailCache } from '@/utils/tenantCache';
export interface TenantSelectorProps { export interface TenantSelectorProps {
// 字段名可自定义;默认与后端接口约定一致 nameTenant?: string;
nameTenant?: string; // 默认 'tenantId' nameIncludeChildren?: string;
nameIncludeChildren?: string; // 默认 'includeChildren'
labelTenant?: React.ReactNode; labelTenant?: React.ReactNode;
labelIncludeChildren?: React.ReactNode; labelIncludeChildren?: React.ReactNode;
// 是否隐藏“包含下级”复选框(用于仅需要选择租户的场景,如用户表单)
hideIncludeChildren?: boolean;
// 透传给租户选择项的校验规则(用于必填等)
rulesTenant?: any[];
} }
const toTreeData = (nodes: TenantTreeNode[] = []): any[] => const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
nodes.map((n) => ({ const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
title: n.tenantName, return arr.map((n) => {
value: n.tenantId, const id = (n as any)?.tenantId as string | undefined;
key: n.tenantId, const name = (n as any)?.tenantName as string | undefined;
children: n.children ? toTreeData(n.children) : undefined, const title = name && id ? `${name} (${id})` : (name || id || '-');
})); return {
title,
value: id,
key: id,
children: Array.isArray((n as any)?.children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
};
});
};
const TenantSelector: React.FC<TenantSelectorProps> = ({ const TenantSelector: React.FC<TenantSelectorProps> = ({
nameTenant = 'tenantId', nameTenant = 'tenantId',
nameIncludeChildren = 'includeChildren', nameIncludeChildren = 'includeChildren',
labelTenant = '租户', labelTenant = '租户',
labelIncludeChildren = '包含子租户', labelIncludeChildren = '包含下级',
hideIncludeChildren = false,
rulesTenant,
}) => { }) => {
const form = Form.useFormInstance?.();
const [tree, setTree] = useState<TenantTreeNode[]>([]); const [tree, setTree] = useState<TenantTreeNode[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@@ -31,32 +45,148 @@ const TenantSelector: React.FC<TenantSelectorProps> = ({
(async () => { (async () => {
setLoading(true); setLoading(true);
try { try {
const [treeRes] = await Promise.all([ // 优先从缓存读取可访问租户树
tenantApi.getAccessibleTenants(), let list: TenantTreeNode[] = (getTenantTreeCache() as any) || [];
]); if (!list || list.length === 0) {
if (treeRes?.success) setTree(treeRes.data || []); const treeRes: any = await tenantApi.getAccessibleTenants();
if (typeof treeRes?.success !== 'undefined') {
list = treeRes.success ? (treeRes.data || []) : [];
} else if (Array.isArray(treeRes)) {
list = treeRes as TenantTreeNode[];
}
if (list && list.length) setTenantTreeCache(list as any);
}
if (!list || list.length === 0) {
// 回退:仅当前租户
const cur: any = await tenantApi.getCurrentTenant();
if (cur?.success && cur?.data?.tenantId) {
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
try { form?.setFieldsValue?.({ [nameTenant]: cur.data.tenantId, [nameIncludeChildren]: true }); } catch {}
} else {
const stats: any = await tenantApi.getScopeStats();
const id = stats?.data?.currentTenantId;
if (id) list = [{ tenantId: id, tenantName: id } as any];
try { form?.setFieldsValue?.({ [nameTenant]: id, [nameIncludeChildren]: true }); } catch {}
}
}
if (list && list.length && !form?.getFieldValue?.(nameTenant)) {
try { form?.setFieldsValue?.({ [nameTenant]: list[0].tenantId, [nameIncludeChildren]: true }); } catch {}
}
// 递进补齐:根 -> 二级 -> 三级,确保三级部门可见
const loadChildrenFor = async (nodes?: any[]): Promise<any[]> => {
const resultChildren: any[] = [];
if (!Array.isArray(nodes)) return resultChildren;
await Promise.all((nodes || []).map(async (node: any) => {
if (!node) return;
const pid = node.tenantId;
if (!pid) return;
// 若已有子节点,直接使用;否则尝试缓存;再不行才请求接口
if (Array.isArray(node.children) && node.children.length) {
// 已有
} else {
const cached = getTenantChildrenCache(pid);
if (cached) {
node.children = cached as any;
} else {
try {
const res: any = await tenantApi.getTenantList({ parentTenantId: pid, status: 1 as any, current: 1, pageSize: 1000 } as any);
const children = res?.data?.data || [];
if (children && children.length) {
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, status: c.status }));
} else {
node.children = undefined;
}
setTenantChildrenCache(pid, node.children as any);
} catch {}
}
}
if (Array.isArray(node.children)) resultChildren.push(...node.children);
}));
return resultChildren;
};
try {
const level2 = await loadChildrenFor(list);
await loadChildrenFor(level2);
} catch {}
// 补齐根节点状态,随后过滤仅显示启用(status=1)
try {
await Promise.all((list || []).map(async (node: any) => {
if (node?.status == null && node?.tenantId) {
// 先看缓存,无则请求
const cached = getTenantDetailCache(node.tenantId);
if (typeof (cached as any)?.status !== 'undefined') {
node.status = (cached as any).status as any;
} else {
try {
const d: any = await tenantApi.getTenantDetail(node.tenantId);
node.status = (d?.data?.status ?? node.status);
setTenantDetailCache(node.tenantId, { status: node.status } as any);
} catch {}
}
}
}));
} catch {}
const filterEnabled = (nodes?: any[]): any[] => {
if (!Array.isArray(nodes)) return [];
const out: any[] = [];
for (const n of nodes) {
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
if (v === 1) {
const item: any = { ...n };
if (Array.isArray((n as any).children)) item.children = filterEnabled((n as any).children);
out.push(item);
}
}
return out;
};
const filtered = filterEnabled(list || []);
setTree(filtered);
// 若当前选择的租户已被过滤(禁用),回退到第一个可用租户
try {
const selected = form?.getFieldValue?.(nameTenant);
const collectIds = (nodes?: any[]): string[] => {
const out: string[] = [];
if (!Array.isArray(nodes)) return out;
for (const n of nodes) {
if ((n as any)?.tenantId) out.push((n as any).tenantId);
if (Array.isArray((n as any).children)) out.push(...collectIds((n as any).children));
}
return out;
};
const ids = collectIds(filtered);
if (!selected || (ids.length && !ids.includes(selected))) {
form?.setFieldsValue?.({ [nameTenant]: ids[0], [nameIncludeChildren]: true });
}
} catch {}
} catch (e) {
message.warn('获取租户列表失败');
} finally { } finally {
setLoading(false); setLoading(false);
} }
})(); })();
}, []); }, []);
// 不启用懒加载,依赖后端返回的完整树;仅在“仅单根无子”时补一层直系子级(见上方 useEffect)
return ( return (
<> <>
<Form.Item name={nameTenant} label={labelTenant}> <Form.Item name={nameTenant} label={labelTenant} rules={rulesTenant as any}>
<TreeSelect <TreeSelect
style={{ minWidth: 260 }} style={{ minWidth: 260 }}
treeDefaultExpandAll showSearch
treeNodeFilterProp='title'
loading={loading} loading={loading}
dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
placeholder="选择租户(含子租户)" placeholder='选择租户(默认当前租户)'
treeData={toTreeData(tree)} treeData={toTreeData(tree)}
allowClear allowClear
/> />
</Form.Item> </Form.Item>
<Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName="checked" initialValue={true}> {hideIncludeChildren ? null : (
<Checkbox>包含子租户</Checkbox> <Form.Item name={nameIncludeChildren} label={labelIncludeChildren} valuePropName='checked' initialValue={true}>
</Form.Item> <Checkbox>包含下级租户</Checkbox>
</Form.Item>
)}
</> </>
); );
}; };
@@ -1,4 +1,4 @@
import React from 'react'; import React from 'react';
import { Button, Tooltip } from 'antd'; import { Button, Tooltip } from 'antd';
import { MoonOutlined, SunOutlined } from '@ant-design/icons'; import { MoonOutlined, SunOutlined } from '@ant-design/icons';
import type { ThemeMode } from '@/theme'; import type { ThemeMode } from '@/theme';
@@ -8,20 +8,17 @@ export interface ThemeSwitchProps {
onToggle: () => void; onToggle: () => void;
} }
const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => { const ThemeSwitch: React.FC<ThemeSwitchProps> = ({ mode, onToggle }) => (
return ( <Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}>
<Tooltip title={mode === 'dark' ? '切换为亮色' : '切换为暗色'}> <Button
<Button type="text"
type="text" onClick={onToggle}
onClick={onToggle} icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />}
icon={mode === 'dark' ? <SunOutlined /> : <MoonOutlined />} style={{ color: 'var(--text-primary)' }}
style={{ color: 'var(--text-primary)' }} >
> {mode === 'dark' ? '亮色' : '暗色'}
{mode === 'dark' ? '亮色' : '暗色'} </Button>
</Button> </Tooltip>
</Tooltip> );
);
};
export default ThemeSwitch;
export default ThemeSwitch;
@@ -8,22 +8,19 @@ import {
AppstoreOutlined, AppstoreOutlined,
FileTextOutlined, FileTextOutlined,
TeamOutlined, TeamOutlined,
ToolOutlined,
BarChartOutlined,
CloudServerOutlined, CloudServerOutlined,
BugOutlined, BugOutlined,
SearchOutlined, SearchOutlined,
MessageOutlined, MessageOutlined,
FolderOutlined, FolderOutlined,
SafetyOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import { Link, useLocation, history } from 'umi'; import { Link, useLocation, history } from 'umi';
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout'; import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
import { fetchMenuData, outLogin } from '@/services/login'; import { fetchMenuData, outLogin } from '@/services/login';
import { clearTenantCache } from '@/utils/tenantCache';
import { useTheme } from '@/theme'; import { useTheme } from '@/theme';
import { ThemeSwitch } from '@/components/ui'; import { ThemeSwitch } from '@/components/ui';
// 后端菜单节点(兼容 children 与 subMenus)
type MenuNode = { type MenuNode = {
id?: number | string; id?: number | string;
name?: string; name?: string;
@@ -56,16 +53,20 @@ const BasicLayout: React.FC = (props: any) => {
return () => { mounted = false; }; return () => { mounted = false; };
}, []); }, []);
// 将后端菜单转换为 ProLayout 菜单(对齐 react-web 映射规则)
const menuDataRender = useMemo(() => { const menuDataRender = useMemo(() => {
const mapPath = (m: MenuNode): string | undefined => { const mapPath = (m: MenuNode, childrenLen: number): string | undefined => {
const cand = (m.path || m.url || '').trim(); const cand = (m.path || m.url || '').trim();
if (!cand) return undefined; if (!cand) return undefined;
const lower = cand.toLowerCase(); const lower = cand.toLowerCase();
if (lower.startsWith('http')) return cand; // 外链 if (lower.startsWith('http')) return cand; // 澶栭摼
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 仅 .html 可点击 if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢? if (lower === '/welcome' || lower === 'welcome') return '/welcome';
if (lower === '/welcome' || lower === 'welcome') return '/welcome'; // 鍏煎鍚庣鑿滃崟鏈甫 .html 鐨勫彾瀛愯矾鐢憋紝渚嬪 /system/tenant => /system/tenant.html
return undefined; // 其余作为分组,仅展开不跳转 const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`;
const parts = ensureSlash.split('/').filter(Boolean);
if (childrenLen === 0 && parts.length >= 2) {
return `${ensureSlash}.html`;
}
return undefined; // 浣滀负鍒嗙粍
}; };
const getIcon = (p?: string) => { const getIcon = (p?: string) => {
@@ -90,12 +91,12 @@ const BasicLayout: React.FC = (props: any) => {
`${parentKey}-${menu.name}-${index}`; `${parentKey}-${menu.name}-${index}`;
const keyStr = String(stableKey); const keyStr = String(stableKey);
const path = mapPath(menu);
const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || []; const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || [];
const path = mapPath(menu, childrenList.length);
const item: MenuDataItem = { const item: MenuDataItem = {
key: keyStr, key: keyStr,
name: menu.name || `菜单项${index + 1}`, name: menu.name || `鑿滃崟${index + 1}`,
path, path,
icon: getIcon(path), icon: getIcon(path),
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)), children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
@@ -103,21 +104,25 @@ const BasicLayout: React.FC = (props: any) => {
return item; return item;
}; };
// 首次未加载完毕前不渲染默认菜单,避免覆盖接口菜单
if (!loaded) return []; if (!loaded) return [];
const list = menus && menus.length ? menus : [{ name: '欢迎页', url: '/welcome', id: 'welcome-default' }]; const list = menus && menus.length ? menus : [{ name: '首页', url: '/welcome', id: 'welcome-default' }];
return list.map((m, i) => normalize(m, i)); const rendered = list.map((m, i) => normalize(m, i));
const hasHome = rendered.some((r) => r.path === '/welcome');
if (!hasHome) {
rendered.unshift({ key: 'welcome-fixed', name: '首页', path: '/welcome', icon: <DashboardOutlined /> });
}
return rendered;
}, [menus, mode, loaded]); }, [menus, mode, loaded]);
// 右上角操作区
const rightContentRender = () => ( const rightContentRender = () => (
<Space size="middle"> <Space size="middle">
<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>
<ThemeSwitch mode={mode} onToggle={toggle} /> <ThemeSwitch mode={mode} onToggle={toggle} />
<Dropdown <Dropdown
menu={{ menu={{
items: [ items: [
{ key: 'profile', icon: <UserOutlined />, label: '个人中心' }, { key: 'profile', icon: <UserOutlined />, label: '个人中心' },
{ key: 'settings', icon: <SettingOutlined />, label: '系统设置' }, { key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' as any }, { type: 'divider' as any },
{ {
key: 'logout', key: 'logout',
@@ -128,6 +133,7 @@ const BasicLayout: React.FC = (props: any) => {
try { try {
sessionStorage.removeItem('access_token'); sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user'); sessionStorage.removeItem('current_user');
clearTenantCache();
} catch {} } catch {}
message.success('已退出登录'); message.success('已退出登录');
history.push('/user/login'); history.push('/user/login');
@@ -176,6 +182,7 @@ const BasicLayout: React.FC = (props: any) => {
); );
}} }}
headerTitleRender={(logo, title) => ( headerTitleRender={(logo, title) => (
<Link to="/welcome" style={{ textDecoration: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}>
<div <div
style={{ style={{
@@ -193,10 +200,10 @@ const BasicLayout: React.FC = (props: any) => {
</div> </div>
<span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span> <span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span>
</div> </div>
</Link>
)} )}
token={{ token={{
sider: { sider: {
// 左侧侧边栏背景使用更柔和的浅色,避免纯白突兀
colorMenuBackground: 'var(--sider-bg)', colorMenuBackground: 'var(--sider-bg)',
colorBgMenuItemSelected: 'var(--primary-color)', colorBgMenuItemSelected: 'var(--primary-color)',
colorTextMenuSelected: '#ffffff', colorTextMenuSelected: '#ffffff',
@@ -204,7 +211,6 @@ const BasicLayout: React.FC = (props: any) => {
colorBgMenuItemHover: 'var(--bg-glass)', colorBgMenuItemHover: 'var(--bg-glass)',
}, },
header: { header: {
// 顶部导航背景采用柔和渐变
colorBgHeader: 'var(--header-bg)', colorBgHeader: 'var(--header-bg)',
colorHeaderTitle: 'var(--text-primary)', colorHeaderTitle: 'var(--text-primary)',
colorTextRightActionsItem: 'var(--text-secondary)', colorTextRightActionsItem: 'var(--text-secondary)',
@@ -220,3 +226,6 @@ const BasicLayout: React.FC = (props: any) => {
}; };
export default BasicLayout; export default BasicLayout;
+160 -202
View File
@@ -1,230 +1,188 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { Card, Space, Typography, Row, Col, Statistic, Progress, Button } from 'antd'; import { Card, Space, Typography, Row, Col, Statistic, Segmented, Button, message } from 'antd';
import { import { ShoppingCartOutlined, PayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
RocketOutlined, import { Line, Pie } from '@ant-design/plots';
TeamOutlined,
AppstoreOutlined,
CloudServerOutlined,
TrophyOutlined,
ThunderboltOutlined,
GlobalOutlined,
SafetyOutlined
} from '@ant-design/icons';
import TenantScopeFilter from '@/components/TenantScopeFilter'; import TenantScopeFilter from '@/components/TenantScopeFilter';
import { dashboardApi } from '@/services/dashboard';
const { Title, Paragraph } = Typography; const { Title, Text } = Typography;
const Welcome: React.FC = () => { const Welcome: React.FC = () => {
const [time, setTime] = useState(new Date()); const [tenantId, setTenantId] = useState<string>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
const [statType, setStatType] = useState<'day' | 'month' | 'year'>('day');
const [loading, setLoading] = useState<boolean>(false);
const [pageLoading, setPageLoading] = useState<boolean>(true);
const firstLoadRef = useRef(true);
const [stat, setStat] = useState<any>({ orderStats: {}, chartStats: {} });
useEffect(() => { const load = async () => {
let isMounted = true; if (firstLoadRef.current) setPageLoading(true);
const timer = setInterval(() => { setLoading(true);
if (isMounted) { try {
setTime(new Date()); const res: any = await dashboardApi.statistics({ tenantId, includeChildren, statType });
setStat(res?.data || res);
} catch (e) {
message.error('加载统计失败');
} finally {
setLoading(false);
if (firstLoadRef.current) {
firstLoadRef.current = false;
setPageLoading(false);
} }
}, 1000); }
};
return () => { // 仅当选择了租户后再拉取,避免进入页面出现“空 -> 有”的闪动
isMounted = false; useEffect(() => {
clearInterval(timer); if (!tenantId) return;
}; load();
}, []); // eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantId, includeChildren, statType]);
const stats = [ const orderStats = stat?.orderStats || {};
{ title: '今日订单', value: 1234, icon: <AppstoreOutlined />, color: '#667eea' }, const chartStats = stat?.chartStats || {};
{ title: '活跃用户', value: 856, icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备在线', value: 98, suffix: '%', icon: <CloudServerOutlined />, color: '#f093fb' },
{ title: '系统状态', value: 99.9, suffix: '%', icon: <SafetyOutlined />, color: '#4facfe' },
];
const quickActions = [ const trendData = chartStats?.orderTrend || [];
{ title: '新增订单', icon: <AppstoreOutlined />, color: '#667eea' }, const distributionData = chartStats?.orderDistribution || [];
{ title: '用户管理', icon: <TeamOutlined />, color: '#764ba2' },
{ title: '设备监控', icon: <CloudServerOutlined />, color: '#f093fb' }, const trendConfig: any = {
{ title: '系统设置', icon: <SafetyOutlined />, color: '#4facfe' }, data: trendData,
]; xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
height: 300,
legend: { position: 'top' },
tooltip: { shared: true },
animation: false,
};
const distributionConfig: any = {
data: distributionData,
angleField: 'value',
colorField: 'type',
radius: 0.9,
label: { type: 'outer', content: '{name}\n{percentage}' },
animation: false,
};
return ( return (
<div className="page-enter" style={{ padding: 24 }}> <div className="page-enter" style={{ padding: 24 }}>
{/* 欢迎横幅 */} {/* 顶部工具区:左标题,右侧筛选/粒度/刷新 */}
<Card <Card className="modern-card" style={{ marginBottom: 16 }}>
className="modern-card" <Row align="middle" justify="space-between" gutter={[12, 12]}>
style={{ <Col flex="none">
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', <Title level={4} style={{ margin: 0 }}>首页统计</Title>
border: 'none',
marginBottom: 24,
color: 'white'
}}
>
<Row align="middle" justify="space-between">
<Col>
<Space direction="vertical" size={8}>
<Title level={2} style={{ color: 'white', margin: 0 }}>
<RocketOutlined style={{ marginRight: 12 }} />
欢迎使用 Go-Fly Admin
</Title>
<Paragraph style={{ color: 'rgba(255,255,255,0.8)', margin: 0, fontSize: 16 }}>
现代化的智能管理平台 · 科技驱动未来
</Paragraph>
<Paragraph style={{ color: 'rgba(255,255,255,0.6)', margin: 0 }}>
当前时间:{time.toLocaleString()}
</Paragraph>
</Space>
</Col> </Col>
<Col> <Col flex="auto">
<TenantScopeFilter /> <Space style={{ width: '100%', justifyContent: 'flex-end', flexWrap: 'wrap' }} size={12}>
<TenantScopeFilter autoApply onChanged={(tid, inc) => { setTenantId(tid); setIncludeChildren(!!inc); }} />
<Space>
<span>统计粒度</span>
<Segmented
options={[
{ label: '周', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={statType}
onChange={(val) => setStatType(val as any)}
/>
</Space>
<Button type="primary" icon={<ReloadOutlined />} loading={loading && !pageLoading} onClick={load}>刷新</Button>
</Space>
</Col> </Col>
</Row> </Row>
</Card> </Card>
{/* 数据统计卡片 */} {/* KPI 指标卡:两列均分,内容居中,不留空白 */}
<Row gutter={[24, 24]} style={{ marginBottom: 24 }}> <Row gutter={[16, 16]}>
{stats.map((stat, index) => (
<Col xs={12} sm={12} md={6} key={index}>
<Card
className="modern-card"
style={{
textAlign: 'center',
borderLeft: `4px solid ${stat.color}`,
background: 'var(--bg-card)'
}}
>
<div style={{ color: stat.color, fontSize: 24, marginBottom: 8 }}>
{stat.icon}
</div>
<Statistic
title={stat.title}
value={stat.value}
suffix={stat.suffix}
valueStyle={{
color: 'var(--text-primary)',
fontSize: 28,
fontWeight: 'bold'
}}
/>
</Card>
</Col>
))}
</Row>
<Row gutter={[24, 24]}>
{/* 系统状态 */}
<Col xs={24} md={12}> <Col xs={24} md={12}>
<Card className="modern-card" title={ <Card loading={pageLoading}>
<span style={{ color: 'var(--text-primary)' }}> <Space direction="vertical" style={{ width: '100%' }} size={12}>
<ThunderboltOutlined style={{ marginRight: 8, color: '#667eea' }} /> <Space align="center" size={8}>
系统状态 <ShoppingCartOutlined />
</span> <Text strong>订单</Text>
}> </Space>
<Space direction="vertical" style={{ width: '100%' }} size={16}> <Row gutter={8} align="middle" style={{ width: '100%' }}>
<div> <Col xs={12} sm={10} md={10}><Text type="secondary">总订单数</Text></Col>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}> <Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<span style={{ color: 'var(--text-secondary)' }}>CPU 使用率</span> <Statistic value={orderStats.totalOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
<span style={{ color: 'var(--text-primary)' }}>45%</span>
</div>
<Progress percent={45} strokeColor="#667eea" />
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>内存使用率</span>
<span style={{ color: 'var(--text-primary)' }}>68%</span>
</div>
<Progress percent={68} strokeColor="#764ba2" />
</div>
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<span style={{ color: 'var(--text-secondary)' }}>磁盘使用率</span>
<span style={{ color: 'var(--text-primary)' }}>32%</span>
</div>
<Progress percent={32} strokeColor="#f093fb" />
</div>
</Space>
</Card>
</Col>
{/* 快捷操作 */}
<Col xs={24} md={12}>
<Card className="modern-card" title={
<span style={{ color: 'var(--text-primary)' }}>
<TrophyOutlined style={{ marginRight: 8, color: '#667eea' }} />
快捷操作
</span>
}>
<Row gutter={[16, 16]}>
{quickActions.map((action, index) => (
<Col span={12} key={index}>
<Button
block
size="large"
className="tech-button"
style={{
height: 64,
background: `linear-gradient(135deg, ${action.color}33, ${action.color}11)`,
border: `1px solid ${action.color}44`,
color: action.color,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}}
>
<div style={{ fontSize: 20, marginBottom: 4 }}>{action.icon}</div>
<div style={{ fontSize: 12 }}>{action.title}</div>
</Button>
</Col> </Col>
))} </Row>
</Row> <Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款订单数</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.refundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日订单</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">今日退款</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={orderStats.todayRefundedOrders || 0} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card>
</Col>
<Col xs={24} md={12}>
<Card loading={pageLoading}>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Space align="center" size={8}>
<PayCircleOutlined />
<Text strong>收入</Text>
</Space>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">订单总金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">退款金额(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.refundAmount || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净收入(元)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.netIncome || 0) / 100} precision={2} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
<Row gutter={8} align="middle" style={{ width: '100%' }}>
<Col xs={12} sm={10} md={10}><Text type="secondary">净订单数(笔)</Text></Col>
<Col xs={12} sm={14} md={14} style={{ textAlign: 'right' }}>
<Statistic value={(orderStats.totalOrders || 0) - (orderStats.refundedOrders || 0)} valueStyle={{ fontWeight: 600, whiteSpace: 'nowrap' }} groupSeparator="," />
</Col>
</Row>
</Space>
</Card> </Card>
</Col> </Col>
</Row> </Row>
{/* 功能介绍 */} {/* 图表区:趋势 + 状态分布 */}
<Card className="modern-card" style={{ marginTop: 24 }} title={ <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
<span style={{ color: 'var(--text-primary)' }}> <Col xs={24} md={16}>
<GlobalOutlined style={{ marginRight: 8, color: '#667eea' }} /> <Card title="订单趋势(创建/完成/退款)" loading={pageLoading}>
平台特性 <Line {...trendConfig} />
</span> </Card>
}> </Col>
<Row gutter={[24, 24]}> <Col xs={24} md={8}>
<Col xs={24} sm={12} md={8}> <Card title="订单状态分布" loading={pageLoading}>
<div style={{ textAlign: 'center', padding: 16 }}> <Pie {...distributionConfig} />
<div style={{ fontSize: 32, color: '#667eea', marginBottom: 12 }}> </Card>
<RocketOutlined /> </Col>
</div> </Row>
<Title level={4} style={{ color: 'var(--text-primary)' }}>高性能架构</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>
基于微服务架构,支持高并发访问,确保系统稳定运行
</Paragraph>
</div>
</Col>
<Col xs={24} sm={12} md={8}>
<div style={{ textAlign: 'center', padding: 16 }}>
<div style={{ fontSize: 32, color: '#764ba2', marginBottom: 12 }}>
<SafetyOutlined />
</div>
<Title level={4} style={{ color: 'var(--text-primary)' }}>安全可靠</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>
多层安全防护,数据加密传输,保障业务数据安全
</Paragraph>
</div>
</Col>
<Col xs={24} sm={12} md={8}>
<div style={{ textAlign: 'center', padding: 16 }}>
<div style={{ fontSize: 32, color: '#f093fb', marginBottom: 12 }}>
<ThunderboltOutlined />
</div>
<Title level={4} style={{ color: 'var(--text-primary)' }}>智能运维</Title>
<Paragraph style={{ color: 'var(--text-secondary)' }}>
实时监控预警,自动化运维管理,降低运维成本
</Paragraph>
</div>
</Col>
</Row>
</Card>
</div> </div>
); );
}; };
export default Welcome; export default Welcome;
@@ -27,10 +27,10 @@ const AuditLogPage: React.FC = () => {
span={8} span={8}
onTenantChanged={() => actionRef.current?.reload?.()} onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => { onFinish={async (values) => {
const { searchKey, searchValue } = values as any; const { searchKey, searchValue, ...rest } = values as any;
let queryStr = ''; let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`; if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr }); setParams({ ...rest, queryStr });
}} }}
> >
<ProFormSelect <ProFormSelect
@@ -26,10 +26,10 @@ const SlowSqlLogPage: React.FC = () => {
span={8} span={8}
onTenantChanged={() => actionRef.current?.reload?.()} onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => { onFinish={async (values) => {
const { searchKey, searchValue } = values as any; const { searchKey, searchValue, ...rest } = values as any;
let queryStr = ''; let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`; if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr }); setParams({ ...rest, queryStr });
}} }}
> >
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} /> <ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', query_str: '查询语句' }} />
@@ -42,10 +42,10 @@ const SysLogPage: React.FC = () => {
span={8} span={8}
onTenantChanged={() => actionRef.current?.reload?.()} onTenantChanged={() => actionRef.current?.reload?.()}
onFinish={async (values) => { onFinish={async (values) => {
const { searchKey, searchValue } = values as any; const { searchKey, searchValue, ...rest } = values as any;
let queryStr = ''; let queryStr = '';
if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`; if (searchKey && searchValue) queryStr = searchKey === 'none' ? searchValue : `${searchKey}:${searchValue}`;
setParams({ ...params, queryStr }); setParams({ ...rest, queryStr });
}} }}
> >
<ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', message: '日志信息', logLevel: '日志级别', appName: '应用名', classname: '类名', traceId: '链路追踪ID' }} /> <ProFormSelect name="searchKey" label="检索" valueEnum={{ none: '全文检索', message: '日志信息', logLevel: '日志级别', appName: '应用名', classname: '类名', traceId: '链路追踪ID' }} />
@@ -21,6 +21,7 @@ const MESSAGE_STATUS: Record<number, { text: string; color: string }> = {
const MessageList: React.FC = () => { const MessageList: React.FC = () => {
const actionRef = useRef<ActionType>(); const actionRef = useRef<ActionType>();
const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]); const [selectedRows, setSelectedRows] = useState<MessageItem[]>([]);
const [params, setParams] = useState<Record<string, any>>({});
const handleMessageClick = async (record: MessageItem) => { const handleMessageClick = async (record: MessageItem) => {
if (record.status === 0) { if (record.status === 0) {
@@ -97,6 +98,7 @@ const MessageList: React.FC = () => {
split split
span={8} span={8}
onTenantChanged={() => actionRef.current?.reload()} onTenantChanged={() => actionRef.current?.reload()}
onFinish={async (values) => setParams(values)}
/> />
<ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} /> <ActionBar right={<GradientButton size="middle" key="markAllRead" onClick={handleMarkAllRead}>全部标记已读</GradientButton>} />
@@ -107,7 +109,7 @@ const MessageList: React.FC = () => {
rowKey="id" rowKey="id"
search={{ labelWidth: 120 }} search={{ labelWidth: 120 }}
toolBarRender={false} toolBarRender={false}
request={(p) => messageApi.list(p)} request={(p) => messageApi.list({ ...(p as any), ...params })}
columns={columns} columns={columns}
rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }} rowSelection={{ onChange: (_, rows) => setSelectedRows(rows) }}
pagination={{ showQuickJumper: true, showSizeChanger: true }} pagination={{ showQuickJumper: true, showSizeChanger: true }}
@@ -10,6 +10,7 @@ const HomeCarouselPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined); const [current, setCurrent] = useState<HomeCarouselItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [ const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,14 +41,20 @@ const HomeCarouselPage: React.FC = () => {
return ( return (
<PageContainer header={{ title: '首页轮播' }}> <PageContainer header={{ title: '首页轮播' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 切换后后端生效 */ }} /> <SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
onFinish={async (values) => setParams(values)}
/>
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} /> <ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<GlassCard> <GlassCard>
<ProTable<HomeCarouselItem> <ProTable<HomeCarouselItem>
rowKey="id" rowKey="id"
request={(p) => ordersApi.homeCarouselList(p as any)} request={(p) => ordersApi.homeCarouselList({ ...(p as any), ...params })}
columns={columns} columns={columns}
search={false} search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }} pagination={{ showSizeChanger: true, showQuickJumper: true }}
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { PageContainer } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { Card, Col, Row, Statistic, message, Button } from 'antd'; import { Card, Col, Row, Statistic, message, Button } from 'antd';
import TenantScopeFilter from '@/components/TenantScopeFilter'; import TenantScopeFilter from '@/components/TenantScopeFilter';
@@ -8,22 +8,23 @@ import { ActionBar } from '@/components/ui';
const ProfitSharingStatisticsPage: React.FC = () => { const ProfitSharingStatisticsPage: React.FC = () => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [stat, setStat] = useState<any>({}); const [stat, setStat] = useState<any>({});
const [scope, setScope] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
const load = async () => { const load = async (p?: any) => {
setLoading(true); setLoading(true);
try { try {
const res = await ordersApi.getProfitSharingStatistics(); const res = await ordersApi.getProfitSharingStatistics(p);
setStat(res?.data || res); setStat(res?.data || res);
} catch (e) { } catch (e) {
message.error('加载统计失败'); message.error('加载统计失败');
} finally { setLoading(false); } } finally { setLoading(false); }
}; };
useEffect(() => { load(); }, []); useEffect(() => { load(scope); }, [scope]);
return ( return (
<PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter onChanged={() => load()} /> }> <PageContainer header={{ title: '分账统计' }} extra={<TenantScopeFilter useSwitchTenant onChanged={(tid, inc) => setScope({ tenantId: tid, includeChildren: inc })} /> }>
<ActionBar right={<Button size="middle" onClick={() => load()}>刷新</Button>} /> <ActionBar right={<Button size="middle" onClick={() => load(scope)}>刷新</Button>} />
<Row gutter={16}> <Row gutter={16}>
<Col span={6}><Card loading={loading}><Statistic title="总分账额" value={stat?.totalSharingAmount || 0} precision={2} /></Card></Col> <Col span={6}><Card loading={loading}><Statistic title="总分账额" value={stat?.totalSharingAmount || 0} precision={2} /></Card></Col>
<Col span={6}><Card loading={loading}><Statistic title="分账笔数" value={stat?.sharingCount || 0} /></Card></Col> <Col span={6}><Card loading={loading}><Statistic title="分账笔数" value={stat?.sharingCount || 0} /></Card></Col>
@@ -10,6 +10,7 @@ const QrcodePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined); const [current, setCurrent] = useState<QrcodeItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const columns: any[] = [ const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
@@ -40,12 +41,18 @@ const QrcodePage: React.FC = () => {
return ( return (
<PageContainer header={{ title: '二维码管理' }}> <PageContainer header={{ title: '二维码管理' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} /> <SearchBarPlus
defaultCollapsed
split
span={8}
onTenantChanged={() => { /* 仅触发表格刷新 */ }}
onFinish={async (values) => setParams(values)}
/>
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} /> <ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} />
<GlassCard> <GlassCard>
<ProTable<QrcodeItem> <ProTable<QrcodeItem>
rowKey="id" rowKey="id"
request={(p) => ordersApi.qrcodeList(p as any)} request={(p) => ordersApi.qrcodeList({ ...(p as any), ...params })}
columns={columns} columns={columns}
search={false} search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }} pagination={{ showSizeChanger: true, showQuickJumper: true }}
@@ -31,8 +31,15 @@ const StatisticsPage: React.FC = () => {
span={8} span={8}
onTenantChanged={() => load(range)} onTenantChanged={() => load(range)}
onFinish={async (values) => { onFinish={async (values) => {
const v = values?.timeRange; const v = (values as any)?.timeRange;
const r = v && v.length === 2 ? { startTime: v[0]?.toISOString(), endTime: v[1]?.toISOString() } : undefined; const base: any = {};
if (v && v.length === 2) {
base.startTime = v[0]?.toISOString();
base.endTime = v[1]?.toISOString();
}
// 合并租户筛选参数
const r = { ...values, ...base } as any;
delete r.timeRange;
setRange(r); setRange(r);
await load(r); await load(r);
}} }}
@@ -1,13 +1,17 @@
import React from 'react'; import React from 'react';
import { ModalForm, ProForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import TenantSelector from '@/components/ui/TenantSelector';
export interface TourismItem { export interface TourismItem {
id?: number; id?: number;
tenantId?: string;
tourismName?: string; tourismName?: string;
address?: string; tourismAddress?: string;
contactPerson?: string; tourismPhone?: string;
contactPhone?: string; status?: number; // 1 启用,0 禁用
status?: number; longitude?: string;
latitude?: string;
showInHomepage?: number; // 1 是,0 否
description?: string; description?: string;
} }
@@ -29,14 +33,41 @@ const TourismForm: React.FC<TourismFormProps> = ({ open, title, initialValues, o
initialValues={initialValues} initialValues={initialValues}
modalProps={{ destroyOnClose: true }} modalProps={{ destroyOnClose: true }}
> >
{/* 所属租户(必选) */}
<TenantSelector nameTenant="tenantId" labelTenant="所属租户" hideIncludeChildren rulesTenant={[{ required: true, message: '请选择租户' }]} />
<ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} /> <ProFormText name="tourismName" label="景区名称" rules={[{ required: true, message: '请输入景区名称' }]} />
<ProFormText name="address" label="地址" /> <ProFormText name="tourismAddress" label="地址" />
<ProFormText name="contactPerson" label="联系人" /> <ProFormText name="tourismPhone" label="联系电话" />
<ProFormText name="contactPhone" label="联系电话" />
<ProFormSelect name="status" label="状态" valueEnum={{ 1: '启用', 0: '禁用' }} initialValue={1} /> <ProForm.Group>
<ProFormText name="longitude" label="经度" placeholder="例如 116.397128" />
<ProFormText name="latitude" label="纬度" placeholder="例如 39.916527" />
</ProForm.Group>
{/* 下拉中文,不显示数字 */}
<ProFormSelect
name="showInHomepage"
label="首页展示"
options={[
{ label: '是', value: 1 },
{ label: '否', value: 0 },
]}
initialValue={0}
/>
<ProFormSelect
name="status"
label="状态"
options={[
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
]}
initialValue={1}
/>
<ProFormTextArea name="description" label="描述" /> <ProFormTextArea name="description" label="描述" />
</ModalForm> </ModalForm>
); );
}; };
export default TourismForm; export default TourismForm;
@@ -1,56 +1,113 @@
import React, { useState } from 'react'; import React, { useEffect, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components'; import { PageContainer, ProFormText, ProTable } from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, message } from 'antd'; import { Popconfirm, Space, Tag, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui'; import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import { ordersApi } from '@/services/orders'; import { ordersApi } from '@/services/orders';
import TourismForm, { TourismItem } from './components/TourismForm'; import TourismForm, { TourismItem } from './components/TourismForm';
import { tenantApi } from '@/services/tenant';
const TourismPage: React.FC = () => { const TourismPage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<TourismItem | undefined>(undefined); const [current, setCurrent] = useState<TourismItem | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
// 首次进入时,默认按“当前租户 + 包含下级租户”查询,避免全量数据
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
} catch {
// 忽略错误,保留手动查询能力
}
})();
}, []);
const columns: any[] = [ const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '旅游项目', dataIndex: 'tourismName' }, { title: '旅游项目', dataIndex: 'tourismName' },
{ title: '地址', dataIndex: 'address' }, { title: '地址', dataIndex: 'tourismAddress' },
{ title: '联系人', dataIndex: 'contactPerson' }, { title: '经度', dataIndex: 'longitude' },
{ title: '联系电话', dataIndex: 'contactPhone' }, { title: '纬度', dataIndex: 'latitude' },
{ title: '状态', dataIndex: 'status', render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag> },
{ {
title: '操作', key: 'action', title: '首页展示',
dataIndex: 'showInHomepage',
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '是' : '否'}</Tag>,
},
{ title: '联系电话', dataIndex: 'tourismPhone' },
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime' },
{
title: '状态',
dataIndex: 'status',
render: (v: number) => <Tag color={v === 1 ? 'green' : 'default'}>{v === 1 ? '启用' : '禁用'}</Tag>,
},
{
title: '操作',
key: 'action',
render: (_: any, record: TourismItem) => ( render: (_: any, record: TourismItem) => (
<Space> <Space>
<a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a> <a onClick={() => { setCurrent(record); setEditOpen(true); }}>编辑</a>
<Popconfirm title={`确认删除项目[${record.tourismName}]?`} onConfirm={async () => { <Popconfirm
const hide = message.loading('删除中...'); title={`确认删除项目[${record.tourismName}]?`}
try { onConfirm={async () => {
await ordersApi.deleteTourism(record.id!); const hide = message.loading('正在删除...');
message.success('删除成功'); try {
} catch (e) { await ordersApi.deleteTourism(record.id!);
message.error('删除失败'); message.success('删除成功');
} finally { hide(); } } catch {
}}> message.error('删除失败');
} finally { hide(); }
}}
>
<a style={{ color: '#1677ff' }}>删除</a> <a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm> </Popconfirm>
</Space> </Space>
) ),
}, },
]; ];
return ( return (
<PageContainer header={{ title: '旅游项目' }}> <PageContainer header={{ title: '旅游项目' }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { /* 租户切换 */ }} /> <SearchBarPlus
<ActionBar left={<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>新增</GradientButton>} /> defaultCollapsed
split
span={8}
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => setParams((prev) => ({ ...(prev || {}), ...values }))}
>
<ProFormText name="tourismName" label="景区名称" placeholder="请输入景区名称" />
</SearchBarPlus>
<ActionBar
left={
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
新增
</GradientButton>
}
/>
<GlassCard> <GlassCard>
<ProTable<TourismItem> {params?.tenantId ? (
rowKey="id" <ProTable<TourismItem>
request={(p) => ordersApi.tourism(p as any)} rowKey="id"
columns={columns} params={params}
search={false} request={(p) => ordersApi.tourism({ ...(p as any), ...params })}
pagination={{ showSizeChanger: true, showQuickJumper: true }} columns={columns}
/> search={false}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard> </GlassCard>
<TourismForm <TourismForm
@@ -63,8 +120,8 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism(values); await ordersApi.saveOrUpdateTourism(values);
message.success('新增成功'); message.success('新增成功');
return true; return true;
} catch (e) { } catch {
message.error('保存失败'); message.error('新增失败');
return false; return false;
} finally { hide(); } } finally { hide(); }
}} }}
@@ -81,7 +138,7 @@ const TourismPage: React.FC = () => {
await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values }); await ordersApi.saveOrUpdateTourism({ ...(current as any), ...values });
message.success('修改成功'); message.success('修改成功');
return true; return true;
} catch (e) { } catch {
message.error('修改失败'); message.error('修改失败');
return false; return false;
} finally { hide(); } } finally { hide(); }
@@ -92,4 +149,3 @@ const TourismPage: React.FC = () => {
}; };
export default TourismPage; export default TourismPage;
@@ -1,7 +1,7 @@
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useState } from 'react';
import { PageContainer, ProFormText, ProFormSelect } from '@ant-design/pro-components'; import { PageContainer } from '@ant-design/pro-components';
import { Space, message } from 'antd'; import { Space, message } from 'antd';
import { ActionBar, GradientButton, GlassCard, SearchBarPlus } from '@/components/ui'; import { ActionBar, GradientButton, GlassCard } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import MenuTree from './components/MenuTree'; import MenuTree from './components/MenuTree';
import MenuForm from './components/MenuForm'; import MenuForm from './components/MenuForm';
@@ -10,19 +10,17 @@ import { roleApi } from '@/services/role';
import { buildTree } from '@/utils/tree'; import { buildTree } from '@/utils/tree';
const MenuPage: React.FC = () => { const MenuPage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]); const [keyword] = useState<string | undefined>(undefined);
const [tenantId, setTenantId] = useState<string | undefined>();
const [keyword, setKeyword] = useState<string | undefined>();
const [data, setData] = useState<MenuItem[]>([]); const [data, setData] = useState<MenuItem[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [current, setCurrent] = useState<MenuItem | undefined>(undefined); const [current, setCurrent] = useState<MenuItem | undefined>(undefined);
const fetchMenu = useCallback(async (clientId: string) => { const fetchMenu = useCallback(async () => {
setLoading(true); setLoading(true);
try { try {
const menus = await menuApi.list(clientId); const menus = await menuApi.list();
const list: any[] = menus || []; const list: any[] = menus || [];
const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus)); const hasSubMenus = list.some((m) => Array.isArray(m?.subMenus));
if (hasSubMenus) { if (hasSubMenus) {
@@ -57,24 +55,14 @@ const MenuPage: React.FC = () => {
} }
}, []); }, []);
useEffect(() => { useEffect(() => { fetchMenu(); }, [fetchMenu]);
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const id = list[0].clientId;
setTenantId(id);
fetchMenu(id);
}
})();
}, [fetchMenu]);
const handleDelete = async (record: MenuItem) => { const handleDelete = async (record: MenuItem) => {
const hide = message.loading('删除中...'); const hide = message.loading('鍒犻櫎涓?..');
try { try {
await menuApi.delete(record.id!); await menuApi.delete(record.id!);
message.success('鍒犻櫎鑿滃崟鎴愬姛'); message.success('鍒犻櫎鑿滃崟鎴愬姛');
if (tenantId) fetchMenu(tenantId); fetchMenu();
} catch (e) { } catch (e) {
message.error('鍒犻櫎鑿滃崟澶辫触'); message.error('鍒犻櫎鑿滃崟澶辫触');
} finally { hide(); } } finally { hide(); }
@@ -82,16 +70,7 @@ const MenuPage: React.FC = () => {
return ( return (
<PageContainer header={{ title: '鑿滃崟绠$悊' }}> <PageContainer header={{ title: '鑿滃崟绠$悊' }}>
<SearchBarPlus {/* 去掉查询条件(租户/所属应用),默认查询当前登录人所属租户 */}
defaultCollapsed
split
span={8}
onTenantChanged={() => tenantId && fetchMenu(tenantId)}
onFinish={async (values: any) => { setTenantId(values.tenantId); fetchMenu(values.tenantId); setKeyword(values.keyword); }}
>
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
<ProFormText name="keyword" label="关键字" placeholder="菜单名称关键字" />
</SearchBarPlus>
<ActionBar <ActionBar
left={ left={
@@ -116,11 +95,11 @@ const MenuPage: React.FC = () => {
open={createOpen} open={createOpen}
onOpenChange={setCreateOpen} onOpenChange={setCreateOpen}
onFinish={async (values) => { onFinish={async (values) => {
const hide = message.loading('保存中...'); const hide = message.loading('淇濆瓨涓?..');
try { try {
await menuApi.saveOrUpdate(values); await menuApi.saveOrUpdate(values);
message.success('鏂板�鑿滃崟鎴愬姛'); message.success('鏂板�鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId); fetchMenu();
return true; return true;
} catch (e) { } catch (e) {
message.error('鏂板�鑿滃崟澶辫触'); message.error('鏂板�鑿滃崟澶辫触');
@@ -135,11 +114,11 @@ const MenuPage: React.FC = () => {
initialValues={current} initialValues={current}
onOpenChange={setEditOpen} onOpenChange={setEditOpen}
onFinish={async (values) => { onFinish={async (values) => {
const hide = message.loading('保存中...'); const hide = message.loading('淇濆瓨涓?..');
try { try {
await menuApi.saveOrUpdate({ ...current, ...values }); await menuApi.saveOrUpdate({ ...current, ...values });
message.success('淇�敼鑿滃崟鎴愬姛'); message.success('淇�敼鑿滃崟鎴愬姛');
tenantId && fetchMenu(tenantId); fetchMenu();
return true; return true;
} catch (e) { } catch (e) {
message.error('淇�敼鑿滃崟澶辫触'); message.error('淇�敼鑿滃崟澶辫触');
@@ -153,3 +132,5 @@ const MenuPage: React.FC = () => {
export default MenuPage; export default MenuPage;
@@ -1,5 +1,6 @@
import React from 'react'; import React from 'react';
import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
import TenantSelector from '@/components/ui/TenantSelector';
import { RoleItem } from '@/services/role'; import { RoleItem } from '@/services/role';
export interface RoleFormProps { export interface RoleFormProps {
@@ -22,13 +23,14 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
width={500} width={500}
> >
<ProForm.Group> <ProForm.Group>
<TenantSelector hideIncludeChildren rulesTenant={[{ required: true, message: '请选择所属租户' }]} />
<ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" /> <ProFormText name="name" label="角色名称" rules={[{ required: true, message: '角色名不能为空' }]} width="lg" />
<ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" /> <ProFormText name="code" label="编码" rules={[{ required: true, message: '编码不能为空' }]} width="lg" />
<ProFormRadio.Group <ProFormRadio.Group
name="dataScope" name="dataScope"
label="数据权限" label="数据权限"
width="lg" width="lg"
options={[{ label: '全部', value: 'ALL' }, { label: '本人', value: 'CREATOR' }]} options={[{ label: '全部', value: 'ALL' }, { label: '自定义', value: 'CREATOR' }]}
/> />
</ProForm.Group> </ProForm.Group>
</ModalForm> </ModalForm>
@@ -36,3 +38,4 @@ const RoleForm: React.FC<RoleFormProps> = ({ open, title, initialValues, onOpenC
}; };
export default RoleForm; export default RoleForm;
@@ -4,30 +4,22 @@ import { Popconfirm, Space, message } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui'; import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import { roleApi, RoleItem } from '@/services/role'; import { roleApi, RoleItem } from '@/services/role';
import { tenantApi } from '@/services/tenant';
import RoleForm from './components/RoleForm'; import RoleForm from './components/RoleForm';
import AssignAuth from './components/AssignAuth'; import AssignAuth from './components/AssignAuth';
const RolePage: React.FC = () => { const RolePage: React.FC = () => {
const [apps, setApps] = useState<any[]>([]); const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }>({});
const [params, setParams] = useState<{ tenantId?: string; searchKey?: string; searchValue?: string }>({});
const [createOpen, setCreateOpen] = useState(false); const [createOpen, setCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false); const [editOpen, setEditOpen] = useState(false);
const [assignOpen, setAssignOpen] = useState(false); const [assignOpen, setAssignOpen] = useState(false);
const [current, setCurrent] = useState<RoleItem | undefined>(undefined); const [current, setCurrent] = useState<RoleItem | undefined>(undefined);
useEffect(() => { // 以租户为主:通过 SearchBarPlus 内置租户选择器
(async () => {
const list = await roleApi.apps();
setApps(list || []);
if (list?.length) {
const tenantId = list[0].clientId;
setParams((p) => ({ ...p, tenantId }));
}
})();
}, []);
const columns = [ const columns = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户', dataIndex: 'tenantId', width: 160, search: false, render: (_: any, r: RoleItem) => (r as any)?.tenantName || (r as any)?.tenantId || '-' },
{ title: 'ID', dataIndex: 'id' }, { title: 'ID', dataIndex: 'id' },
{ title: '角色名称', dataIndex: 'name' }, { title: '角色名称', dataIndex: 'name' },
{ title: '编码', dataIndex: 'code' }, { title: '编码', dataIndex: 'code' },
@@ -54,16 +46,37 @@ const RolePage: React.FC = () => {
} }
]; ];
// 页面初次进入时,自动获取当前租户并触发表格请求
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
}
} catch (e) {
// 忽略错误,保持手动查询可用
}
})();
}, []);
return ( return (
<PageContainer header={{ title: '角色管理' }}> <PageContainer header={{ title: '角色管理' }}>
<SearchBarPlus <SearchBarPlus
defaultCollapsed={false} defaultCollapsed={false}
split split
span={6} span={6}
onTenantChanged={() => { /* 切换租户后服务端上下文生效 */ }} onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => setParams(values)} onFinish={async (values) => setParams(values)}
> >
<ProFormSelect name="tenantId" label="所属应用" allowClear={false} options={(apps || []).map((i) => ({ label: i.clientId, value: i.clientId }))} />
<ProFormSelect name="searchKey" label="搜索" valueEnum={{ name: '角色名称' }} /> <ProFormSelect name="searchKey" label="搜索" valueEnum={{ name: '角色名称' }} />
<ProFormText name="searchValue" placeholder="请输入关键字" /> <ProFormText name="searchValue" placeholder="请输入关键字" />
</SearchBarPlus> </SearchBarPlus>
@@ -80,6 +93,7 @@ const RolePage: React.FC = () => {
<ProTable<RoleItem> <ProTable<RoleItem>
rowKey="id" rowKey="id"
headerTitle="角色列表" headerTitle="角色列表"
params={params}
request={async (p) => roleApi.page({ ...p, ...params })} request={async (p) => roleApi.page({ ...p, ...params })}
columns={columns as any} columns={columns as any}
search={false} search={false}
@@ -134,4 +148,3 @@ const RolePage: React.FC = () => {
}; };
export default RolePage; export default RolePage;
@@ -0,0 +1,116 @@
import React, { useEffect, useMemo, useState } from 'react';
import { ModalForm, ProForm, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { Select, Switch, TreeSelect } from 'antd';
import type { TenantInfo, TenantTreeNode } from '@/services/tenant';
import { tenantApi } from '@/services/tenant';
type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
export interface TenantFormProps {
visible: boolean;
title: string;
initialValues?: UITenantFormValues;
tree: TenantTreeNode[];
onVisibleChange: (v: boolean) => void;
onFinish: (values: TenantInfo) => Promise<boolean>;
form?: any;
}
const toTreeData = (nodes?: TenantTreeNode[] | any): any[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
return arr.map((n) => ({
title: n.tenantName,
value: n.tenantId,
key: n.tenantId,
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
}));
};
const TenantForm: React.FC<TenantFormProps> = ({ visible, title, initialValues, tree, onVisibleChange, onFinish, form }) => {
const editing = !!initialValues?.tenantId;
const [allowedTypes, setAllowedTypes] = useState<string[] | undefined>(undefined);
const typeOrder = useMemo(() => ['PLATFORM', 'GROUP', 'COMPANY', 'DEPARTMENT'], []);
const allTypeOptions = useMemo(() => ([
{ value: 'PLATFORM', label: '平台' },
{ value: 'GROUP', label: '集团' },
{ value: 'COMPANY', label: '公司' },
{ value: 'DEPARTMENT', label: '部门' },
]), []);
useEffect(() => {
(async () => {
if (!editing && initialValues?.parentTenantId) {
try {
const pd = await tenantApi.getTenantDetailStd(initialValues.parentTenantId);
const pType = pd?.data?.tenantType as string | undefined;
if (pType) {
const idx = typeOrder.indexOf(pType);
const allowed = idx >= 0 ? typeOrder.slice(idx + 1) : typeOrder;
setAllowedTypes(allowed);
const cur = form?.getFieldValue?.('tenantType');
if (!cur && allowed.length) form?.setFieldsValue?.({ tenantType: allowed[0] });
} else {
setAllowedTypes(typeOrder);
}
} catch {
setAllowedTypes(typeOrder);
}
} else {
setAllowedTypes(typeOrder);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [visible, editing, initialValues?.parentTenantId]);
const safeInitialValues = useMemo(() => {
const iv: any = initialValues || {};
const s = iv.status;
const statusNum = typeof s === 'boolean' ? (s ? 1 : 0) : s;
return { ...iv, status: statusNum };
}, [initialValues]);
return (
<ModalForm<TenantInfo>
title={title}
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
initialValues={safeInitialValues}
form={form}
width={640}
modalProps={{ destroyOnClose: true, maskClosable: false }}
>
<ProForm.Group>
<ProFormText name='tenantId' label='租户ID' placeholder='唯一标识,创建后不可修改' rules={[{ required: true, message: '请输入租户ID' }]} disabled={editing} />
<ProFormText name='tenantName' label='租户名称' rules={[{ required: true, message: '请输入租户名称' }]} />
</ProForm.Group>
<ProForm.Group>
<ProForm.Item name='parentTenantId' label='上级租户'>
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={toTreeData(tree)} placeholder='选择上级租户' disabled={editing} />
</ProForm.Item>
<ProForm.Item name='tenantType' label='类型' rules={[{ required: true, message: '请选择类型' }]}>
<Select style={{ width: 260 }} placeholder='选择类型' disabled={editing && !initialValues?.parentTenantId}>
{(allowedTypes || typeOrder).map((t) => (
<Select.Option key={t} value={t}>{(allTypeOptions.find((x) => x.value === t)?.label) || t}</Select.Option>
))}
</Select>
</ProForm.Item>
</ProForm.Group>
<ProForm.Group>
<ProFormText name='tenantCode' label='编码' />
<ProForm.Item name='status' label='状态' valuePropName='checked' tooltip='启用/停用'>
<Switch checkedChildren='启用' unCheckedChildren='停用' />
</ProForm.Item>
</ProForm.Group>
<ProForm.Group>
<ProFormText name='contactPerson' label='联系人' />
<ProFormText name='contactPhone' label='联系电话' />
</ProForm.Group>
<ProFormText name='address' label='地址' />
<ProFormTextArea name='description' label='描述' />
</ModalForm>
);
};
export default TenantForm;
@@ -0,0 +1,74 @@
import React from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { message, Popconfirm, Space } from 'antd';
import type { TenantInfo } from '@/services/tenant';
import { tenantApi } from '@/services/tenant';
export interface TenantTableProps {
parentTenantId?: string;
actionRef?: React.MutableRefObject<ActionType | undefined>;
onEdit: (record: TenantInfo) => Promise<void> | void;
onDeleted?: () => void;
}
const TenantTable: React.FC<TenantTableProps> = ({ parentTenantId, actionRef, onEdit, onDeleted }) => {
const columns: ProColumns<TenantInfo>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户ID', dataIndex: 'tenantId', copyable: true, ellipsis: true, width: 160 },
{ title: '租户名称', dataIndex: 'tenantName' },
{ title: '类型', dataIndex: 'tenantType', valueType: 'select', valueEnum: { PLATFORM: { text: '平台' }, GROUP: { text: '集团' }, COMPANY: { text: '公司' }, DEPARTMENT: { text: '部门' } } },
{ title: '父租户ID', dataIndex: 'parentTenantId', hideInSearch: true, width: 160 },
{ title: '层级', dataIndex: 'tenantLevel', hideInSearch: true, width: 80 },
{ title: '编码', dataIndex: 'tenantCode', hideInSearch: true },
{ title: '状态', dataIndex: 'status', valueType: 'select', valueEnum: { 1: { text: '启用' }, 0: { text: '停用' } } },
{ title: '联系人', dataIndex: 'contactPerson', hideInSearch: true },
{ title: '联系电话', dataIndex: 'contactPhone', hideInSearch: true },
{
title: '操作', valueType: 'option', width: 200,
render: (_, record) => (
<Space>
<a onClick={() => onEdit(record)}>编辑</a>
<Popconfirm title={`确认删除租户[${record.tenantName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
const r = await tenantApi.deleteTenant(record.tenantId);
if ((r as any)?.success) {
message.success('删除成功');
actionRef?.current?.reload?.();
onDeleted?.();
} else {
message.error(((r as any)?.msg) || '删除失败');
}
} finally { hide(); }
}}>
<a style={{ color: '#ff4d4f' }}>删除</a>
</Popconfirm>
</Space>
)
}
];
return (
<ProTable<TenantInfo>
actionRef={actionRef as any}
rowKey="tenantId"
columns={columns}
toolBarRender={false}
request={async (p) => {
// 默认按启用筛选;当未选择时传 1
const status = (p as any)?.status ?? 1;
const res = await tenantApi.getTenantList({ parentTenantId, tenantName: (p as any).tenantName, status: status as any, current: (p as any).current, pageSize: (p as any).pageSize });
const list = (res as any)?.data?.data || [];
const total = (res as any)?.data?.total || list.length;
return { data: list, total, success: true };
}}
pagination={{ pageSize: 10 }}
// 让搜索表单默认展示“启用”
form={{ initialValues: { status: 1 } }}
search={{ labelWidth: 'auto' }}
/>
);
};
export default TenantTable;
@@ -0,0 +1,72 @@
import React, { useMemo, useState } from 'react';
import { Button, Card, Input, Space, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { ReloadOutlined } from '@ant-design/icons';
import type { TenantTreeNode } from '@/services/tenant';
export interface TenantTreeProps {
title?: React.ReactNode;
loading?: boolean;
tree: TenantTreeNode[];
value?: string;
onChange?: (tenantId?: string) => void;
onReload?: () => void;
}
const toTreeData = (nodes?: TenantTreeNode[] | any): DataNode[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
return arr.map((n) => ({
title: n.tenantName,
key: n.tenantId,
value: n.tenantId,
children: Array.isArray((n as any).children) && (n as any).children!.length ? toTreeData((n as any).children) : undefined,
}));
};
const filterTree = (nodes?: TenantTreeNode[] | any, keyword: string = ''): TenantTreeNode[] => {
const arr: TenantTreeNode[] = Array.isArray(nodes) ? nodes : [];
if (!keyword) return arr;
const kw = keyword.trim().toLowerCase();
const loop = (arr: TenantTreeNode[]): TenantTreeNode[] =>
arr.map((n) => ({ ...n, children: n.children ? loop(n.children) : undefined }))
.filter((n) => {
const selfHit = String(n.tenantName || '').toLowerCase().includes(kw);
const childHit = (n.children || []).length > 0;
return selfHit || childHit;
});
return loop(arr);
};
const TenantTree: React.FC<TenantTreeProps> = ({ title = '组织', loading, tree, onChange, onReload }) => {
const [keyword, setKeyword] = useState('');
const displayTree = useMemo(() => filterTree(tree, keyword), [tree, keyword]);
return (
<Card
size="small"
title={title}
extra={(
<Space size={8}>
<Input.Search
allowClear
placeholder="搜索租户"
size="small"
style={{ width: 160 }}
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
/>
<Button size="small" icon={<ReloadOutlined />} loading={!!loading} onClick={onReload}>刷新</Button>
</Space>
)}
bodyStyle={{ height: 'calc(70vh - 24px)', overflow: 'auto' }}
>
<Tree
treeData={toTreeData(displayTree)}
defaultExpandAll
onSelect={(keys) => onChange?.((keys?.[0] as string) || undefined)}
/>
</Card>
);
};
export default TenantTree;
@@ -0,0 +1,121 @@
import React, { useEffect, useMemo, useState } from 'react';
import { Table, Space, Popconfirm, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TenantTreeNode } from '@/services/tenant';
export interface TenantTreeTableProps {
data: TenantTreeNode[];
loading?: boolean;
onAddChild?: (record: TenantTreeNode) => void;
onEdit?: (record: TenantTreeNode) => void;
onDelete?: (record: TenantTreeNode) => void;
}
const TenantTreeTable: React.FC<TenantTreeTableProps> = ({ data, loading, onAddChild, onEdit, onDelete }) => {
const normalize = (nodes?: any[]): any[] => {
if (!Array.isArray(nodes)) return [];
return nodes.map((n: any) => ({
...n,
children: Array.isArray(n?.children) && n.children.length ? normalize(n.children) : undefined,
}));
};
const safeData = useMemo(() => normalize(data as any), [data]);
// 计算并控制展开行,保证“默认展开”在异步数据加载后仍生效
const allExpandableKeys = useMemo(() => {
const keys: React.Key[] = [];
const walk = (arr?: any[]) => {
if (!Array.isArray(arr)) return;
for (const n of arr) {
const hasChildren = Array.isArray(n?.children) && n.children.length > 0;
if (hasChildren) keys.push(n.tenantId);
if (hasChildren) walk(n.children);
}
};
walk(safeData);
return keys;
}, [safeData]);
const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
useEffect(() => {
// 仅当列表 keys 实际发生变化时才更新,避免无意义的重复 setState
setExpandedRowKeys((prev) => {
const a = allExpandableKeys;
if (prev.length === a.length && prev.every((v, i) => v === a[i])) return prev;
return a;
});
}, [allExpandableKeys]);
const columns: ColumnsType<TenantTreeNode> = [
{
title: '租户名称',
dataIndex: 'tenantName',
render: (_: any, record: TenantTreeNode) => <span>{record.tenantName}</span>,
},
{ title: '租户ID', dataIndex: 'tenantId', width: 180, ellipsis: true },
{
title: '类型', dataIndex: 'tenantType', width: 120,
render: (v: any) => {
const map: Record<string, { color: string; text: string }> = {
PLATFORM: { color: 'purple', text: '平台' },
GROUP: { color: 'cyan', text: '集团' },
COMPANY: { color: 'blue', text: '公司' },
DEPARTMENT: { color: 'geekblue', text: '部门' },
};
const m = map[String(v)] || { color: 'default', text: String(v || '-') } as any;
return <Tag color={m.color}>{m.text}</Tag>;
},
},
{
title: '状态', dataIndex: 'status', width: 100,
render: (v: any, record: TenantTreeNode) => {
const enabled = typeof v === 'boolean' ? v : (v === 1 || v === '1' || (record as any)?.enabled === true || v == null);
return enabled ? <Tag color='green'>启用</Tag> : <Tag color='red'>停用</Tag>;
},
},
{ title: '联系人', dataIndex: 'contactPerson', width: 120 },
{ title: '联系电话', dataIndex: 'contactPhone', width: 140 },
{
title: '操作', key: 'action', width: 220,
render: (_: any, rec: TenantTreeNode | undefined) => {
const record = (rec || ({} as TenantTreeNode));
const hasId = !!(record as any)?.tenantId;
return (
<Space>
<a onClick={() => hasId && onEdit?.(record)}>编辑</a>
{onAddChild ? <a onClick={() => hasId && onAddChild?.(record)}>新增下级</a> : null}
<Popconfirm title={`确认删除租户[${record?.tenantName ?? ''}]?`} onConfirm={() => hasId && onDelete?.(record)}>
<a style={{ color: '#1677ff' }}>删除</a>
</Popconfirm>
</Space>
);
},
},
];
return (
<Table
rowKey='tenantId'
columns={columns}
dataSource={safeData as any}
loading={loading}
pagination={false}
expandable={{
expandedRowKeys,
onExpand: (expanded, record: any) => {
setExpandedRowKeys((prev) => {
const key = record?.tenantId;
if (key == null) return prev;
const set = new Set(prev);
if (expanded) set.add(key);
else set.delete(key);
return Array.from(set);
});
},
}}
size='middle'
/>
);
};
export default TenantTreeTable;
@@ -1,165 +1,327 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'; import React, { useCallback, useEffect, useState } from "react";
import type { ActionType, ProColumns } from '@ant-design/pro-components'; import { PageContainer } from "@ant-design/pro-components";
import { ModalForm, PageContainer, ProForm, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components'; import { Space, message, Button, Select } from "antd";
import { Button, Card, Col, Form, message, Popconfirm, Row, Space, Switch, Tree, TreeSelect } from 'antd'; import { ActionBar, GradientButton, GlassCard } from "@/components/ui";
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from "@ant-design/icons";
import { tenantApi, TenantInfo, TenantTreeNode } from '@/services/tenant'; import TenantForm from "./components/TenantForm";
import { ActionBar, SearchBarPlus } from '@/components/ui'; import TenantTreeTable from "./components/TenantTreeTable";
import { tenantApi, TenantInfo, TenantTreeNode } from "@/services/tenant";
const toTreeData = (nodes: TenantTreeNode[] = []): any[] => // UI 表单初始值:status 允许 boolean | number,便于与 Switch 绑定
nodes.map((n) => ({ title: n.tenantName, value: n.tenantId, key: n.tenantId, children: n.children ? toTreeData(n.children) : undefined })); type UITenantFormValues = Partial<TenantInfo> & { status?: boolean | number };
const TenantManage: React.FC = () => { const TenantManage: React.FC = () => {
const actionRef = useRef<ActionType>(); const [data, setData] = useState<TenantTreeNode[]>([]);
const [form] = Form.useForm<TenantInfo>(); const [loading, setLoading] = useState(false);
const [orgTree, setOrgTree] = useState<TenantTreeNode[]>([]); const [formOpen, setFormOpen] = useState(false);
const [loadingTree, setLoadingTree] = useState(false);
const [currentNode, setCurrentNode] = useState<string | undefined>(undefined);
const [visible, setVisible] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [initialValues, setInitialValues] = useState<UITenantFormValues | undefined>(undefined);
const [treeCache, setTreeCache] = useState<TenantTreeNode[]>([]);
// 状态筛选:1=启用, 0=停用, 'all'=全部;默认启用
const [statusFilter, setStatusFilter] = useState<1 | 0 | 'all'>(1);
const treeSelectData = useMemo(() => toTreeData(orgTree), [orgTree]); // 路径拼接:去掉前缀 null/undefined、首尾斜杠,仅用单斜杠连接
const joinPath = (base?: string, id?: string) => {
const b = String(base || '')
.trim()
.replace(/^null/gi, '')
.replace(/^undefined/gi, '')
.replace(/\/+$/g, '')
.replace(/^\/+/, '');
const t = String(id || '')
.trim()
.replace(/^\/+/, '')
.replace(/\/+$/g, '');
return b ? `${b}/${t}` : t;
};
const loadTree = async () => { const fetchTree = useCallback(async () => {
setLoadingTree(true); setLoading(true);
try { try {
const res = await tenantApi.getAccessibleTenants(); const res: any = await tenantApi.getAccessibleTenants();
if (res.success) setOrgTree(res.data || []); let list: TenantTreeNode[] = [];
} finally { if (typeof res?.success !== "undefined") {
setLoadingTree(false); list = res.success ? (res.data || []) : [];
} else if (Array.isArray(res)) {
list = res as TenantTreeNode[];
}
if (!list || list.length === 0) {
// 回退:至少返回当前租户
const cur: any = await tenantApi.getCurrentTenant();
if (cur?.success && cur?.data?.tenantId) {
list = [{ tenantId: cur.data.tenantId, tenantName: cur.data.tenantName } as any];
} else {
const stats: any = await tenantApi.getScopeStats();
const id = stats?.data?.currentTenantId;
if (id) list = [{ tenantId: id, tenantName: id } as any];
}
}
// 若只有根节点且无子节点,尝试加载一层子租户以展示层级
if (list && list.length === 1 && !Array.isArray((list[0] as any).children)) {
try {
const parentId = (list[0] as any).tenantId;
const resPage: any = await tenantApi.getTenantList({ parentTenantId: parentId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
const children = resPage?.data?.data || [];
if (children && children.length) {
(list[0] as any).children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
}
} catch {}
}
// 补充每个根的一层直接子租户,便于默认展开时可见
try {
await Promise.all(
(list || []).map(async (node: any) => {
if (!node) return;
// 顶层节点缺失类型/状态/联系人信息时,补充详情
try {
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
const d = detail?.data || {};
if (node.tenantType == null) node.tenantType = d.tenantType;
if (node.status == null) node.status = d.status;
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
}
} catch {}
// 确保至少补一层孩子,方便默认展开后可见
if (!Array.isArray(node.children) || node.children.length === 0) {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
const children = resp?.data?.data || [];
if (children && children.length) {
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
}
}
})
);
} catch {}
// 递进加载至第三级,保证三级部门可见
const loadChildrenFor = async (nodes?: any[]): Promise<any[]> => {
const resultChildren: any[] = [];
if (!Array.isArray(nodes)) return resultChildren;
await Promise.all(nodes.map(async (node: any) => {
if (!node) return;
// 再次兜底补全基础信息
try {
if (node.tenantType == null || node.status == null || node.contactPerson == null || node.contactPhone == null) {
const detail: any = await tenantApi.getTenantDetail(node.tenantId);
const d = detail?.data || {};
if (node.tenantType == null) node.tenantType = d.tenantType;
if (node.status == null) node.status = d.status;
if (node.contactPerson == null) node.contactPerson = d.contactPerson;
if (node.contactPhone == null) node.contactPhone = d.contactPhone;
}
} catch {}
const needLoad = !Array.isArray(node.children) || node.children.length === 0;
if (needLoad) {
try {
const resp: any = await tenantApi.getTenantList({ parentTenantId: node.tenantId, status: (statusFilter === 'all' ? undefined : statusFilter) as any, current: 1, pageSize: 1000 } as any);
const children = resp?.data?.data || [];
if (children && children.length) {
node.children = children.map((c: any) => ({ tenantId: c.tenantId, tenantName: c.tenantName, tenantType: c.tenantType, status: c.status, contactPerson: c.contactPerson, contactPhone: c.contactPhone }));
}
} catch {}
}
if (Array.isArray(node.children)) resultChildren.push(...node.children);
}));
return resultChildren;
};
try {
const level2 = await loadChildrenFor(list);
await loadChildrenFor(level2);
} catch {}
// 按状态筛选(仅当选择启用或停用时)
const filterTreeByStatus = (nodes?: any[]): any[] => {
if (statusFilter === 'all') return Array.isArray(nodes) ? nodes : [];
const want = statusFilter;
const walk = (arr?: any[]): any[] => {
if (!Array.isArray(arr)) return [];
const res: any[] = [];
for (const n of arr) {
const v = (typeof (n as any)?.status === 'boolean') ? ((n as any).status ? 1 : 0) : (n as any)?.status;
if (v === want) {
const item: any = { ...n };
if (Array.isArray((n as any).children)) item.children = walk((n as any).children);
res.push(item);
} else if (Array.isArray((n as any).children)) {
const sub = walk((n as any).children);
if (sub.length) res.push(...sub);
}
}
return res;
};
return walk(nodes);
};
const finalList = filterTreeByStatus(list);
setTreeCache(list);
setData(finalList);
} catch (e) {
message.error("获取租户数据失败");
} finally { setLoading(false); }
}, [statusFilter]);
useEffect(() => { fetchTree(); }, [fetchTree]);
const openCreateRoot = () => {
setEditing(false);
setInitialValues({ status: 1 });
setFormOpen(true);
};
const handleAddChild = (record: TenantTreeNode) => {
setEditing(false);
setInitialValues({ parentTenantId: record.tenantId, status: 1 });
setFormOpen(true);
};
const handleEdit = async (record: TenantTreeNode) => {
try {
const d: any = await tenantApi.getTenantDetail(record.tenantId);
if (d?.success) {
setEditing(true);
const iv = d.data || {};
const patched = { ...iv, status: typeof iv.status === 'number' ? iv.status : (iv.status ? 1 : 0) } as any;
setInitialValues(patched);
setFormOpen(true);
}
} catch (e) {
message.error("获取租户详情失败");
} }
}; };
useEffect(() => { loadTree(); }, []); const handleDelete = async (record: TenantTreeNode) => {
const hide = message.loading("删除中...");
const columns: ProColumns<TenantInfo>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '租户ID', dataIndex: 'tenantId', copyable: true },
{ title: '租户名称', dataIndex: 'tenantName' },
{ title: '类型', dataIndex: 'tenantType' },
{ title: '父租户ID', dataIndex: 'parentTenantId', hideInSearch: true },
{ title: '状态', dataIndex: 'status', valueType: 'select', valueEnum: { 1: { text: '启用' }, 0: { text: '停用' } } },
{
title: '操作', valueType: 'option', width: 200,
render: (_, record) => (
<Space>
<a onClick={async () => {
setEditing(true);
const d = await tenantApi.getTenantDetail(record.tenantId);
if (d.success) {
form.setFieldsValue(d.data);
setVisible(true);
}
}}>编辑</a>
<Popconfirm title={`确认删除租户[${record.tenantName}]?`} onConfirm={async () => {
const hide = message.loading('删除中...');
try {
const r = await tenantApi.deleteTenant(record.tenantId);
if (r.success) {
message.success('删除成功');
actionRef.current?.reload();
loadTree();
} else {
message.error(r.msg || '删除失败');
}
} finally { hide(); }
}}>
<a>删除</a>
</Popconfirm>
</Space>
)
}
];
const onSave = async (vals: TenantInfo) => {
const hide = message.loading('保存中...');
try { try {
const payload = { ...vals, status: vals.status ?? 1 }; const r: any = await tenantApi.deleteTenant(record.tenantId);
const res = editing ? await tenantApi.updateTenant(payload) : await tenantApi.createTenant(payload); if (r?.success) {
if (res.success) { message.success("删除成功");
message.success(editing ? '修改成功' : '新增成功'); fetchTree();
setVisible(false); } else {
actionRef.current?.reload(); message.error(r?.msg || "删除失败");
loadTree();
return true;
} }
message.error(res.msg || '保存失败');
return false;
} finally { hide(); } } finally { hide(); }
}; };
return ( return (
<PageContainer header={{ title: '租户管理' }}> <PageContainer header={{ title: "租户管理" }}>
<SearchBarPlus defaultCollapsed split span={8} onTenantChanged={() => { actionRef.current?.reload(); loadTree(); }} />
<ActionBar <ActionBar
left={(
<Space>
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={openCreateRoot}>新增</GradientButton>
<Button onClick={fetchTree}>刷新</Button>
</Space>
)}
right={( right={(
<Space> <Space>
<Button size="middle" type="primary" icon={<PlusOutlined />} onClick={() => { <span>状态:</span>
setEditing(false); <Select
form.resetFields(); size="middle"
form.setFieldsValue({ parentTenantId: currentNode, status: 1 }); style={{ width: 120 }}
setVisible(true); value={statusFilter}
}}>新增租户</Button> onChange={(v: any) => setStatusFilter(v)}
options={[
{ value: 1, label: '启用' },
{ value: 0, label: '停用' },
{ value: 'all', label: '全部' },
]}
/>
</Space> </Space>
)} )}
/> />
<Row gutter={16}>
<Col span={6}>
<Card size="small" title="组织">
<Tree treeData={toTreeData(orgTree)} defaultExpandAll onSelect={(keys) => {
const k = (keys && keys[0]) as string | undefined;
setCurrentNode(k);
actionRef.current?.reload();
}} />
</Card>
</Col>
<Col span={18}>
<ProTable<TenantInfo>
actionRef={actionRef}
rowKey="tenantId"
columns={columns}
toolBarRender={false}
request={async (p) => {
const res = await tenantApi.getTenantList({ parentTenantId: currentNode, tenantName: (p as any).tenantName, status: (p as any).status as any, current: (p as any).current, pageSize: (p as any).pageSize });
const list = res.data?.data || [];
const total = res.data?.total || list.length;
return { data: list, total, success: true };
}}
pagination={{ pageSize: 10 }}
search={{ labelWidth: 'auto' }}
/>
</Col>
</Row>
<ModalForm<TenantInfo> <GlassCard>
title={editing ? '编辑租户' : '新建租户'} <TenantTreeTable
open={visible} data={data}
onOpenChange={setVisible} loading={loading}
form={form} onAddChild={handleAddChild}
width={640} onEdit={handleEdit}
onFinish={onSave} onDelete={handleDelete}
modalProps={{ destroyOnClose: true }} />
> </GlassCard>
<ProForm.Group>
<ProFormText name="tenantId" label="租户ID" rules={[{ required: true }]} disabled={editing} /> <TenantForm
<ProFormText name="tenantName" label="租户名称" rules={[{ required: true }]} /> title={editing ? "编辑租户" : "新建租户"}
</ProForm.Group> visible={formOpen}
<ProForm.Group> onVisibleChange={setFormOpen}
<ProForm.Item name="parentTenantId" label="上级租户"> onFinish={async (values) => {
<TreeSelect style={{ width: 260 }} allowClear dropdownStyle={{ maxHeight: 400, overflow: 'auto' }} treeDefaultExpandAll treeData={treeSelectData} /> const hide = message.loading("保存中...");
</ProForm.Item> try {
<ProFormText name="tenantType" label="类型" rules={[{ required: true }]} /> const payload: any = { ...initialValues, ...values };
</ProForm.Group> payload.status = typeof payload.status === 'boolean' ? (payload.status ? 1 : 0) : (payload.status ?? 1);
<ProFormText name="tenantCode" label="租户编码" /> // 计算 tenantPath / tenantLevel(后端未计算或为null时做兜底)
<ProFormText name="contactPerson" label="联系人" /> if (!editing) {
<ProFormText name="contactPhone" label="联系电话" /> if (payload.parentTenantId) {
<ProFormText name="address" label="地址" /> try {
<ProFormTextArea name="description" label="描述" /> const parent: any = await tenantApi.getTenantDetail(payload.parentTenantId);
<ProForm.Item name="status" label="状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></ProForm.Item> const p = parent?.data || {};
</ModalForm> const base = p?.tenantPath || p?.tenantId || payload.parentTenantId;
payload.tenantPath = joinPath(base, payload.tenantId);
payload.tenantLevel = (p.tenantLevel || 0) + 1;
} catch {
payload.tenantPath = joinPath(payload.parentTenantId, payload.tenantId);
payload.tenantLevel = 1;
}
} else {
payload.tenantPath = joinPath(undefined, payload.tenantId);
payload.tenantLevel = 1;
}
}
// 编辑模式下兜底补齐关键字段,防止后端校验失败
if (editing) {
try {
const cur: any = await tenantApi.getTenantDetail(payload.tenantId);
const cd = cur?.data || {};
if (!payload.parentTenantId && cd.parentTenantId) payload.parentTenantId = cd.parentTenantId;
// 使用统一的 joinPath 规范化路径
const badPath = !payload.tenantPath || /^null/i.test(String(payload.tenantPath)) || /\/$/.test(String(payload.tenantPath));
if (badPath) {
let base = '';
if (payload.parentTenantId) {
try {
const pRes: any = await tenantApi.getTenantDetail(payload.parentTenantId);
const p = pRes?.data || {};
base = p.tenantPath || p.tenantId || payload.parentTenantId;
} catch { base = payload.parentTenantId; }
}
payload.tenantPath = joinPath(base, payload.tenantId);
}
if (payload.tenantLevel == null) {
payload.tenantLevel = cd.tenantLevel ?? 1;
}
} catch {}
}
// 仅提交后端可识别字段,避免多余只读字段导致绑定失败
const allowedKeys = ['tenantId','tenantName','parentTenantId','tenantType','tenantCode','contactPerson','contactPhone','address','description','status','tenantLevel','tenantPath'];
const submitData: any = {};
for (const k of allowedKeys) if (Object.prototype.hasOwnProperty.call(payload, k)) submitData[k] = (payload as any)[k];
const res: any = editing ? await tenantApi.updateTenant(submitData) : await tenantApi.createTenant(submitData);
if (res?.success) {
message.success(editing ? "修改成功" : "新增成功");
setFormOpen(false);
await fetchTree();
return true;
}
message.error(res?.msg || "保存失败");
return false;
} finally { hide(); }
}}
initialValues={initialValues}
tree={treeCache}
/>
</PageContainer> </PageContainer>
); );
}; };
export default TenantManage; export default TenantManage;
@@ -1,4 +1,4 @@
import React from 'react'; import React from 'react';
import { Button, Upload } from 'antd'; import { Button, Upload } from 'antd';
import { ExportOutlined, ImportOutlined, PlusOutlined } from '@ant-design/icons'; import { ExportOutlined, ImportOutlined, PlusOutlined } from '@ant-design/icons';
import { GradientButton } from '@/components/ui'; import { GradientButton } from '@/components/ui';
@@ -8,13 +8,17 @@ export interface ToolbarProps {
onCreate: () => void; onCreate: () => void;
// 导出 // 导出
onExport: () => void; onExport: () => void;
// 是否隐藏“新增”按钮(例如:APP 用户)
hideCreate?: boolean;
} }
// 统一:新增按钮固定在左侧;去掉刷新按钮(以查询为主) // 统一:新增按钮固定在左侧;去掉刷新按钮(以查询为主)
const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport }) => { const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport, hideCreate }) => {
return ( return (
<> <>
<GradientButton size="middle" key="add" type="primary" icon={<PlusOutlined />} onClick={onCreate}>新增</GradientButton> {!hideCreate ? (
<GradientButton size="middle" key="add" type="primary" icon={<PlusOutlined />} onClick={onCreate}>新增</GradientButton>
) : null}
<Button size="middle" key="export" icon={<ExportOutlined />} onClick={onExport}>导出</Button> <Button size="middle" key="export" icon={<ExportOutlined />} onClick={onExport}>导出</Button>
<Upload key="import" action="/api-user/users/import" showUploadList={false} accept=".xls,.xlsx"> <Upload key="import" action="/api-user/users/import" showUploadList={false} accept=".xls,.xlsx">
<Button size="middle" icon={<ImportOutlined />}>导入</Button> <Button size="middle" icon={<ImportOutlined />}>导入</Button>
@@ -23,5 +27,4 @@ const Toolbar: React.FC<ToolbarProps> = ({ onCreate, onExport }) => {
); );
}; };
export default Toolbar; export default Toolbar;
@@ -1,23 +1,26 @@
import React from 'react'; import React from 'react';
import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components'; import { ModalForm, ProForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { systemApi, UserItem } from '@/services/system'; import { systemApi, UserItem } from '@/services/system';
import TenantSelector from '@/components/ui/TenantSelector';
export interface UserFormProps { export interface UserFormProps {
open: boolean; visible: boolean;
title: string; title: string;
initialValues?: Partial<UserItem>; initialValues?: Partial<UserItem & { company?: string; type?: string }>;
onOpenChange: (v: boolean) => void; onVisibleChange: (v: boolean) => void;
onFinish: (values: UserItem) => Promise<boolean>; onFinish: (values: UserItem & { company?: string; type?: string }) => Promise<boolean>;
// 是否显示“所属租户”(company)选择(仅系统用户需要)
showCompany?: boolean;
} }
const UserForm: React.FC<UserFormProps> = ({ open, title, initialValues, onOpenChange, onFinish }) => { const UserForm: React.FC<UserFormProps> = ({ visible, title, initialValues, onVisibleChange, onFinish, showCompany = true }) => {
return ( return (
<ModalForm<UserItem> <ModalForm<UserItem & { company?: string; type?: string }>
title={title} title={title}
visible={open} visible={visible}
onVisibleChange={onOpenChange} onVisibleChange={onVisibleChange}
onFinish={onFinish} onFinish={onFinish}
initialValues={initialValues} initialValues={{ type: 'BACKEND', ...(initialValues || {}) }}
modalProps={{ destroyOnClose: true }} modalProps={{ destroyOnClose: true }}
> >
<ProForm.Group> <ProForm.Group>
@@ -27,9 +30,17 @@ const UserForm: React.FC<UserFormProps> = ({ open, title, initialValues, onOpenC
</ProForm.Group> </ProForm.Group>
<ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} /> <ProFormRadio.Group name="sex" label="性别" options={[{ label: '男', value: 0 }, { label: '女', value: 1 }]} />
<ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" /> <ProFormSelect name="roleIds" label="角色" mode="multiple" request={systemApi.roles} placeholder="选择角色" />
{showCompany ? (
<TenantSelector nameTenant="company" labelTenant="所属租户" hideIncludeChildren />
) : null}
<ProFormTextArea name="remark" label="备注" /> <ProFormTextArea name="remark" label="备注" />
{/* 类型固定为系统用户,默认也会按 BACKEND 新建 */}
<ProFormText name="type" label="用户类型" initialValue="BACKEND" disabled hidden />
</ModalForm> </ModalForm>
); );
}; };
export default UserForm; export default UserForm;
@@ -12,7 +12,7 @@ export interface UserTableProps {
onEdit: (record: UserItem) => void; onEdit: (record: UserItem) => void;
onResetPassword: (record: UserItem) => void; onResetPassword: (record: UserItem) => void;
onDelete: (record: UserItem) => void; onDelete: (record: UserItem) => void;
// 额外查询参数(由外层统一查询栏传入) // 额外查询参数(由外部查询条件统一注入)
extraParams?: Record<string, any>; extraParams?: Record<string, any>;
} }
@@ -30,6 +30,7 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
const columns: ProColumns<UserItem>[] = [ const columns: ProColumns<UserItem>[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 }, { dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '所属租户', dataIndex: 'company', width: 160, search: false, render: (_, r) => (r as any)?.company || (r as any)?.tenantId || '-' },
{ title: '用户ID', dataIndex: 'id', width: 100, search: false }, { title: '用户ID', dataIndex: 'id', width: 100, search: false },
{ title: '用户名', dataIndex: 'username' }, { title: '用户名', dataIndex: 'username' },
{ title: '用户昵称', dataIndex: 'nickname' }, { title: '用户昵称', dataIndex: 'nickname' },
@@ -61,12 +62,14 @@ const UserTable = forwardRef<UserTableRef, UserTableProps>(({ onEdit, onResetPas
actionRef={actionRef} actionRef={actionRef}
rowKey="id" rowKey="id"
columns={columns} columns={columns}
// 当外部查询参数变更时,自动触发请求
params={extraParams}
request={async (p) => { request={async (p) => {
const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any); const { data, total } = await systemApi.users({ ...(p as any), ...(extraParams || {}) } as any);
return { data, total, success: true }; return { data, total, success: true };
}} }}
pagination={{ pageSize: 10 }} pagination={{ pageSize: 10 }}
// 统一:关闭 ProTable 自带搜索,由外层 SearchBarPlus 统一承载 // 统一关闭 ProTable 自带搜索,由 SearchBarPlus 统一驱动
search={false} search={false}
toolBarRender={false} toolBarRender={false}
/> />
@@ -1,5 +1,5 @@
import React, { useRef, useState } from 'react'; import React, { useRef, useState } from 'react';
import { PageContainer, ProFormText } from '@ant-design/pro-components'; import { PageContainer, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd'; import { message } from 'antd';
import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui'; import { ActionBar, GlassCard, SearchBarPlus } from '@/components/ui';
import { systemApi, UserItem } from '@/services/system'; import { systemApi, UserItem } from '@/services/system';
@@ -9,15 +9,15 @@ import UserForm from './components/UserForm';
const UsersPage: React.FC = () => { const UsersPage: React.FC = () => {
const tableRef = useRef<UserTableRef>(null); const tableRef = useRef<UserTableRef>(null);
const [params, setParams] = useState<Record<string, any>>({}); const [params, setParams] = useState<Record<string, any>>({ type: 'BACKEND' });
const [createVisible, setCreateVisible] = useState(false); const [createVisible, setCreateVisible] = useState(false);
const [editVisible, setEditVisible] = useState(false); const [editVisible, setEditVisible] = useState(false);
const [currentRow, setCurrentRow] = useState<UserItem | undefined>(undefined); const [currentRow, setCurrentRow] = useState<UserItem | undefined>(undefined);
const addUser = async (values: UserItem) => { const addUser = async (values: UserItem & { company?: string; type?: string }) => {
const hide = message.loading('正在添加'); const hide = message.loading('正在添加');
try { try {
const res = await systemApi.saveOrUpdateUser(values); await systemApi.saveOrUpdateUser({ ...(values as any), roleId: (values as any)?.roleIds ? (values as any).roleIds.join(',') : (values as any)?.roleId } as any);
hide(); hide();
message.success('添加用户成功'); message.success('添加用户成功');
tableRef.current?.reload(); tableRef.current?.reload();
@@ -29,10 +29,10 @@ const UsersPage: React.FC = () => {
} }
}; };
const editUser = async (values: UserItem) => { const editUser = async (values: UserItem & { company?: string; type?: string }) => {
const hide = message.loading('正在更新'); const hide = message.loading('正在更新');
try { try {
const res = await systemApi.saveOrUpdateUser({ ...currentRow, ...values }); await systemApi.saveOrUpdateUser({ ...(currentRow as any), ...(values as any), roleId: (values as any)?.roleIds ? (values as any).roleIds.join(',') : (values as any)?.roleId } as any);
hide(); hide();
message.success('修改用户成功'); message.success('修改用户成功');
tableRef.current?.reload(); tableRef.current?.reload();
@@ -44,19 +44,6 @@ const UsersPage: React.FC = () => {
} }
}; };
const switchEnabled = async (record: UserItem) => {
const hide = message.loading('正在更新');
try {
await systemApi.updateEnabled(record.id!, !record.enabled);
hide();
message.success('修改用户成功');
tableRef.current?.reload();
} catch (e) {
hide();
message.error('修改用户失败');
}
};
const resetPwd = async (record: UserItem) => { const resetPwd = async (record: UserItem) => {
const hide = message.loading('正在更新'); const hide = message.loading('正在更新');
try { try {
@@ -82,27 +69,30 @@ const UsersPage: React.FC = () => {
} }
}; };
const isAppType = params?.type === 'APP';
const { tenantId, includeChildren, ...restParams } = params || {};
const listParams = isAppType ? restParams : params;
return ( return (
<PageContainer header={{ title: '用户管理' }}> <PageContainer header={{ title: '用户管理' }}>
<ActionBar <ActionBar left={<Toolbar onCreate={() => setCreateVisible(true)} onExport={() => systemApi.exportUser()} hideCreate={isAppType} />} />
left={
<Toolbar
onCreate={() => setCreateVisible(true)}
onExport={() => systemApi.exportUser()}
/>
}
/>
<SearchBarPlus <SearchBarPlus
defaultCollapsed={false} defaultCollapsed={false}
split split
span={6} span={6}
onTenantChanged={() => tableRef.current?.reload()} showTenant={!isAppType}
onTenantChanged={(tenantId, includeChildren) => {
// 租户切换时,直接更新查询参数,ProTable 会因 params 变更自动请求
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
}}
onFinish={async (values) => { onFinish={async (values) => {
setParams(values); const v: any = { ...(values || {}) };
tableRef.current?.reload(); if (v?.type === 'APP') { delete v.tenantId; delete v.includeChildren; }
setParams(v); // 交由 ProTable(params) 触发请求
}} }}
> >
<ProFormSelect name="type" label="用户类型" valueEnum={{ BACKEND: '系统用户', APP: 'C端用户' }} initialValue="BACKEND" />
<ProFormText name="username" label="用户名" placeholder="请输入用户名" /> <ProFormText name="username" label="用户名" placeholder="请输入用户名" />
<ProFormText name="mobile" label="手机号" placeholder="请输入手机号" /> <ProFormText name="mobile" label="手机号" placeholder="请输入手机号" />
</SearchBarPlus> </SearchBarPlus>
@@ -113,26 +103,15 @@ const UsersPage: React.FC = () => {
onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }} onEdit={(r) => { setCurrentRow(r); setEditVisible(true); }}
onResetPassword={(r) => resetPwd(r)} onResetPassword={(r) => resetPwd(r)}
onDelete={(r) => delUser(r)} onDelete={(r) => delUser(r)}
extraParams={params} extraParams={listParams}
/> />
</GlassCard> </GlassCard>
{/* 新建 */} {/* 新建(仅系统用户) */}
<UserForm <UserForm title="新建用户" visible={createVisible} onVisibleChange={setCreateVisible} onFinish={addUser} showCompany={!isAppType ? true : false} />
title="新建用户"
open={createVisible}
onOpenChange={setCreateVisible}
onFinish={addUser}
/>
{/* 编辑 */} {/* 编辑 */}
<UserForm <UserForm title="修改用户" visible={editVisible} onVisibleChange={setEditVisible} onFinish={editUser} initialValues={currentRow} showCompany={!isAppType ? true : false} />
title="修改用户"
open={editVisible}
onOpenChange={setEditVisible}
onFinish={editUser}
initialValues={currentRow}
/>
</PageContainer> </PageContainer>
); );
}; };
@@ -1,4 +1,5 @@
import logo from '@/assets/logo.png';
import logo from '@/assets/logo.png';
import React, { useEffect, useRef, useState } from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components'; import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components';
import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons'; import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
@@ -26,14 +27,25 @@ const LoginPage: React.FC = () => {
if (loading) return; if (loading) return;
setLoading(true); setLoading(true);
try { try {
const res = await login({ ...values, deviceId: uuid }); const res = await login({ ...values, clientId: 'webApp', deviceId: uuid });
// 检查多种可能的token字段位置 // 检查多种可能的token字段位置
const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken; const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken;
if (accessToken) { if (accessToken) {
sessionStorage.setItem('access_token', accessToken); sessionStorage.setItem('access_token', accessToken);
localStorage.setItem('tenant_client_id', String(values.clientId ?? '')); // 登录后预热可访问租户树缓存,便于各页快速使用
try {
const { ensureTenantCacheTokenGuard, setTenantTreeCache } = await import('@/utils/tenantCache');
const { tenantApi } = await import('@/services/tenant');
ensureTenantCacheTokenGuard();
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: any[] = [];
if (typeof treeRes?.success !== 'undefined') list = treeRes.success ? (treeRes.data || []) : [];
else if (Array.isArray(treeRes)) list = treeRes as any[];
if (list && list.length) setTenantTreeCache(list);
} catch {}
localStorage.setItem('tenant_client_id', 'webApp');
message.success('登录成功,正在跳转...'); message.success('登录成功,正在跳转...');
// 使用umi的history进行路由跳转 // 使用umi的history进行路由跳转
@@ -84,6 +96,8 @@ const LoginPage: React.FC = () => {
> >
<ProFormText <ProFormText
name="clientId" name="clientId"
initialValue="webApp"
disabled
fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }} fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }}
placeholder="请输入租户标识" placeholder="请输入租户标识"
rules={[{ required: true, message: '请输入租户标识' }]} rules={[{ required: true, message: '请输入租户标识' }]}
@@ -0,0 +1,19 @@
import { request } from 'umi';
export type StatType = 'day' | 'month' | 'year';
export interface DashboardParams {
tenantId?: string;
includeChildren?: boolean;
statType?: StatType;
[k: string]: any;
}
export const dashboardApi = {
// 首页统计(根据租户 + 子孙 + 时间粒度)
statistics: async (params?: DashboardParams) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any;
},
};
+3 -2
View File
@@ -16,8 +16,9 @@ export interface MenuItem {
} }
export const menuApi = { export const menuApi = {
list: async (tenantId: string) => { list: async (tenantId?: string) => {
const res = await request('/api-user/menus/findAlls', { method: 'GET', params: { tenantId } }); const params = tenantId ? { tenantId } : undefined;
const res = await request('/api-user/menus/findAlls', { method: 'GET', params });
return (res as any).data || res; return (res as any).data || res;
}, },
simpleList: async () => { simpleList: async () => {
+38 -25
View File
@@ -1,4 +1,4 @@
import { request } from 'umi'; import { request } from 'umi';
export interface OrderItem { export interface OrderItem {
id: number; id: number;
@@ -12,6 +12,7 @@ export interface OrderItem {
} }
export const ordersApi = { export const ordersApi = {
// 订单列表
order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => { order: async (params: { current?: number; pageSize?: number; orderNo?: string; orderStatus?: number; tourismId?: number; payType?: number }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
@@ -21,19 +22,19 @@ export const ordersApi = {
const res = await request('/api-order/update/order', { method: 'POST', data }); const res = await request('/api-order/update/order', { method: 'POST', data });
return (res as any).data || res; return (res as any).data || res;
}, },
// 订单文件相关接口
// 订单文件
orderFiles: async (params: { current?: number; pageSize?: number; [k: string]: any }) => { orderFiles: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/files', { const res = await request('/api-order/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
deleteOrderFile: async (id: number) => { deleteOrderFile: async (id: number) => {
const res = await request(`/api-order/files/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/files/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 二维码
qrcodeList: async (params: { current?: number; pageSize?: number }) => { qrcodeList: async (params: { current?: number; pageSize?: number }) => {
const { current, pageSize } = params || {}; const { current, pageSize } = params || {};
const res = await request('/api-order/qrcode', { method: 'GET', params: { page: current, limit: pageSize } }); const res = await request('/api-order/qrcode', { method: 'GET', params: { page: current, limit: pageSize } });
@@ -47,8 +48,9 @@ export const ordersApi = {
const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/qrcode/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 鏃呮父鏅尯
tourism: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { // 旅游景区
tourism: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -61,8 +63,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/tourism/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 棣栭〉杞挱
homeCarousel: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { // 首页轮播
homeCarousel: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/home/carousel', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/home/carousel', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -75,13 +78,11 @@ export const ordersApi = {
const res = await request(`/api-order/home/carousel/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/home/carousel/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 景区素材(图片/视频等)
// 景区资源(图片/视频等)
tourismFile: async (params: { current?: number; pageSize?: number; [k: string]: any }) => { tourismFile: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/tourism/files', { const res = await request('/api-order/tourism/files', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
saveOrUpdateTourismFile: async (data: any) => { saveOrUpdateTourismFile: async (data: any) => {
@@ -92,8 +93,9 @@ export const ordersApi = {
const res = await request(`/api-order/tourism/files/${id}`, { method: 'DELETE' }); const res = await request(`/api-order/tourism/files/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 退款 // 退款
refund: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { refund: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/refund', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/refund', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -106,11 +108,21 @@ export const ordersApi = {
const res = await request('/api-order/refund/auto', { method: 'PUT', data: payload }); const res = await request('/api-order/refund/auto', { method: 'PUT', data: payload });
return (res as any).data || res; return (res as any).data || res;
}, },
// 仪表盘统计
dashboard: async (params?: any) => { // 首页统计
dashboard: async (params?: { tenantId?: string; includeChildren?: boolean; statType?: 'day' | 'month' | 'year'; [k: string]: any }) => {
const res = await request('/api-order/dashboard/statistics', { method: 'GET', params }); const res = await request('/api-order/dashboard/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
getDashboardOrders: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/orders', { method: 'GET', params });
return res as any;
},
getQrcodeOptions: async (params?: { [k: string]: any }) => {
const res = await request('/api-order/dashboard/qrcode/options', { method: 'GET', params });
return res as any;
},
// 分账 // 分账
getProfitSharingDetail: async (orderNo: string) => { getProfitSharingDetail: async (orderNo: string) => {
const res = await request('/api-order/profitSharing/detail', { method: 'GET', params: { orderNo } }); const res = await request('/api-order/profitSharing/detail', { method: 'GET', params: { orderNo } });
@@ -124,8 +136,9 @@ export const ordersApi = {
const res = await request('/api-order/profitSharing/statistics', { method: 'GET', params }); const res = await request('/api-order/profitSharing/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
// 视频模板 // 视频模板
getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getVideoTemplateList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/videoTemplate/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/videoTemplate/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -146,8 +159,9 @@ export const ordersApi = {
const res = await request(`/api-order/videoTemplate/${id}/status`, { method: 'PUT', params: { status } }); const res = await request(`/api-order/videoTemplate/${id}/status`, { method: 'PUT', params: { status } });
return (res as any).data || res; return (res as any).data || res;
}, },
// 编辑任务 // 编辑任务
getEditTaskList: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getEditTaskList: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/editTask/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/editTask/list', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -164,8 +178,9 @@ export const ordersApi = {
const res = await request('/api-order/auto/cut/generate', { method: 'POST', params: { orderNo } }); const res = await request('/api-order/auto/cut/generate', { method: 'POST', params: { orderNo } });
return (res as any).data || res; return (res as any).data || res;
}, },
// 微信消息 // 微信消息
getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k:string]: any }) => { getWxMessageRecords: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/wx/message/records', { method: 'GET', params: { page: current, limit: pageSize, ...rest } }); const res = await request('/api-order/wx/message/records', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
return { data: (res as any).data, total: (res as any).count }; return { data: (res as any).data, total: (res as any).count };
@@ -174,13 +189,11 @@ export const ordersApi = {
const res = await request('/api-order/wx/message/statistics', { method: 'GET', params }); const res = await request('/api-order/wx/message/statistics', { method: 'GET', params });
return res as any; return res as any;
}, },
// 优惠券 // 优惠券
getCouponList: async (params?: { current?: number; pageSize?: number; [k: string]: any }) => { getCouponList: async (params?: { current?: number; pageSize?: number; [k: string]: any }) => {
const { current, pageSize, ...rest } = params || {}; const { current, pageSize, ...rest } = params || {};
const res = await request('/api-order/coupon', { const res = await request('/api-order/coupon', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
method: 'GET',
params: { page: current, limit: pageSize, ...rest },
});
return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number }; return { data: (res as any).data, total: (res as any).count } as { data: any[]; total: number };
}, },
getCouponById: async (id: number) => { getCouponById: async (id: number) => {
+30 -4
View File
@@ -5,36 +5,62 @@ export interface RoleItem {
name: string; name: string;
code: string; code: string;
dataScope?: 'ALL' | 'CREATOR'; dataScope?: 'ALL' | 'CREATOR';
// 所属租户ID
tenantId?: string;
// 所属租户名称(如果后端返回)
tenantName?: string;
} }
export const roleApi = { export const roleApi = {
page: async (params: { current?: number; pageSize?: number; tenantId?: string; searchKey?: string; searchValue?: string }) => { // 角色分页(按租户/包含子级)
page: async (params: { current?: number; pageSize?: number; tenantId?: string; includeChildren?: boolean; searchKey?: string; searchValue?: string }) => {
if (!params?.tenantId) return { data: [], total: 0 }; if (!params?.tenantId) return { data: [], total: 0 };
const res = await request('/api-user/roles', { const res = await request('/api-user/roles', {
method: 'GET', method: 'GET',
params: { page: params.current, limit: params.pageSize, tenantId: params.tenantId, searchKey: params.searchKey, searchValue: params.searchValue }, params: {
page: params.current,
limit: params.pageSize,
tenantId: params.tenantId,
includeChildren: params.includeChildren,
searchKey: params.searchKey,
searchValue: params.searchValue,
},
}); });
const data = (res as any).data; const data = (res as any).data;
const total = (res as any).count ?? data?.length ?? 0; const total = (res as any).count ?? data?.length ?? 0;
return { data, total } as { data: RoleItem[]; total: number }; return { data, total } as { data: RoleItem[]; total: number };
}, },
// 新增/修改角色(传入所属租户)
saveOrUpdate: async (data: RoleItem) => { saveOrUpdate: async (data: RoleItem) => {
const res = await request('/api-user/roles/saveOrUpdate', { method: 'POST', data }); const res = await request('/api-user/roles/saveOrUpdate', {
method: 'POST',
data,
params: { tenantId: (data as any)?.tenantId },
});
return (res as any).data || res; return (res as any).data || res;
}, },
// 删除角色
delete: async (id: number) => { delete: async (id: number) => {
const res = await request(`/api-user/roles/${id}`, { method: 'DELETE' }); const res = await request(`/api-user/roles/${id}`, { method: 'DELETE' });
return (res as any).data || res; return (res as any).data || res;
}, },
// 所有应用(授权用)
apps: async () => { apps: async () => {
const res = await request('/api-uaa/clients/all', { method: 'GET' }); const res = await request('/api-uaa/clients/all', { method: 'GET' });
return (res as any).data || []; return (res as any).data || [];
}, },
// 某角色的菜单(按租户)
menuForAuth: async (roleId: number, tenantId: string) => { menuForAuth: async (roleId: number, tenantId: string) => {
const res = await request(`/api-user/menus/${roleId}/menus`, { method: 'GET', params: { tenantId } }); const res = await request(`/api-user/menus/${roleId}/menus`, { method: 'GET', params: { tenantId } });
return res as any[]; return res as any[];
}, },
assignMenu: async (payload: { roleId: number; menuIds: (string|number)[] }) => {
// 分配菜单权限
assignMenu: async (payload: { roleId: number; menuIds: (string | number)[] }) => {
const res = await request('/api-user/menus/granted', { method: 'POST', data: payload }); const res = await request('/api-user/menus/granted', { method: 'POST', data: payload });
return (res as any).data || res; return (res as any).data || res;
}, },
@@ -1,4 +1,4 @@
import { request } from 'umi'; import { request } from 'umi';
import { download } from '@/utils/download'; import { download } from '@/utils/download';
export interface UserItem { export interface UserItem {
@@ -11,6 +11,9 @@ export interface UserItem {
createTime?: string; createTime?: string;
roleId?: string; // 角色ID(逗号分隔) roleId?: string; // 角色ID(逗号分隔)
roles?: Array<{ id: number; name: string; code: string }>; roles?: Array<{ id: number; name: string; code: string }>;
// 扩展字段:前端使用(后端已支持)
type?: 'BACKEND' | 'APP';
company?: string; // 所属租户ID
} }
export interface PageParams { export interface PageParams {
@@ -33,7 +36,7 @@ export const systemApi = {
}, },
// 保存/更新 // 保存/更新
saveOrUpdateUser: async (data: UserItem) => { saveOrUpdateUser: async (data: Partial<UserItem>) => {
const res = await request('/api-user/users/saveOrUpdate', { method: 'POST', data }); const res = await request('/api-user/users/saveOrUpdate', { method: 'POST', data });
return (res as any).data || res; return (res as any).data || res;
}, },
@@ -90,5 +93,4 @@ export const systemApi = {
const list = (res as any).data || []; const list = (res as any).data || [];
return list.map((r: any) => ({ label: r.name, value: r.id })); return list.map((r: any) => ({ label: r.name, value: r.id }));
}, },
}; };
+44 -9
View File
@@ -38,19 +38,54 @@ export interface TenantInfo {
} }
export const tenantApi = { export const tenantApi = {
getAccessibleTenants: () => request('/tenant/accessible', { method: 'GET' }), // 可访问租户树(保持后端原始返回,避免破坏既有前端逻辑)
switchTenant: (tenantId: string) => request('/tenant/switch', { method: 'POST', params: { tenantId } }), getAccessibleTenants: () => request('/api-user/tenant/accessible', { method: 'GET' }),
getCurrentTenant: () => request('/tenant/current', { method: 'GET' }), // 切换当前查询租户(新)
resetToDefaultTenant: () => request('/tenant/reset', { method: 'POST' }), switchTenant: (tenantId: string) => request('/api-user/tenant/switch-query', { method: 'POST', params: { tenantId } }),
createTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/create', { method: 'POST', data }), // 当前租户详情(新)
updateTenant: (data: Partial<TenantInfo>) => request('/tenant/hierarchy/update', { method: 'PUT', data }), getCurrentTenant: () => request('/api-user/tenant/current/info', { method: 'GET' }),
deleteTenant: (tenantId: string) => request(`/tenant/hierarchy/delete`, { method: 'DELETE', params: { tenantId } }), // 当前查询范围统计(新)
getScopeStats: () => request('/api-user/tenant/scope/stats', { method: 'GET' }),
// 重置为默认租户
resetToDefaultTenant: () => request('/api-user/tenant/reset', { method: 'POST' }),
// 租户层级 CRUD
createTenant: async (data: Partial<TenantInfo>) => {
const res: any = await request('/api-user/tenant/hierarchy/create', { method: 'POST', data });
// 兼容 resp_code 结构
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
updateTenant: async (data: Partial<TenantInfo>) => {
const res: any = await request('/api-user/tenant/hierarchy/update', { method: 'PUT', data });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
deleteTenant: async (tenantId: string) => {
const res: any = await request('/api-user/tenant/hierarchy/delete', { method: 'DELETE', params: { tenantId } });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
getTenantList: (params: { parentTenantId?: string; tenantName?: string; status?: number; current?: number; pageSize?: number; }) => getTenantList: (params: { parentTenantId?: string; tenantName?: string; status?: number; current?: number; pageSize?: number; }) =>
request('/tenant/hierarchy/list', { request('/api-user/tenant/hierarchy/list', {
method: 'GET', method: 'GET',
params: { ...params, page: params.current, size: params.pageSize }, params: { ...params, page: params.current, size: params.pageSize },
}), }),
getTenantDetail: (tenantId: string) => request(`/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' }), getTenantDetail: async (tenantId: string) => {
const res: any = await request(`/api-user/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
// 规范化获取详情,供表单使用(可选导出)
getTenantDetailStd: async (tenantId: string) => {
const res: any = await request(`/api-user/tenant/hierarchy/detail/${tenantId}`, { method: 'GET' });
if (typeof res?.resp_code !== 'undefined') return { success: res.resp_code === 0, msg: res.resp_msg, data: res.data } as any;
if (typeof res?.success !== 'undefined') return res;
return { success: true, data: res } as any;
},
}; };
declare global { declare global {
@@ -0,0 +1,88 @@
// 租户数据缓存工具:会话级缓存(sessionStorage),按 token 隔离
// - 缓存内容:可访问租户树、按父ID的子节点、详情状态
// - 生命周期:登录成功后预热;退出登录/Token失效时清理;检测到Token变更时自动清理
type AnyNode = { tenantId?: string; tenantName?: string; status?: number | boolean; children?: AnyNode[] };
const KEY_META = 'tenant_cache_meta';
const KEY_TREE = 'tenant_cache_tree';
const KEY_CHILDREN = 'tenant_cache_children';
const KEY_DETAIL = 'tenant_cache_detail';
const safeParse = <T = any>(s?: string | null): T | undefined => {
if (!s) return undefined as any;
try { return JSON.parse(s) as T; } catch { return undefined as any; }
};
const getToken = () => {
try { return sessionStorage.getItem('access_token') || undefined; } catch { return undefined; }
};
export const ensureTenantCacheTokenGuard = () => {
try {
const meta = safeParse<{ token?: string }>(sessionStorage.getItem(KEY_META));
const cur = getToken();
if (!meta?.token || !cur || meta.token !== cur) {
// Token 为空或已变化:清理缓存
clearTenantCache();
if (cur) sessionStorage.setItem(KEY_META, JSON.stringify({ token: cur }));
}
} catch {}
};
export const setTenantTreeCache = (tree: AnyNode[]) => {
try {
ensureTenantCacheTokenGuard();
sessionStorage.setItem(KEY_TREE, JSON.stringify(tree || []));
} catch {}
};
export const getTenantTreeCache = (): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
return safeParse<AnyNode[]>(sessionStorage.getItem(KEY_TREE));
} catch { return undefined; }
};
export const setTenantChildrenCache = (parentId: string, children: AnyNode[] | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
if (parentId) map[parentId] = children || [];
sessionStorage.setItem(KEY_CHILDREN, JSON.stringify(map));
} catch {}
};
export const getTenantChildrenCache = (parentId: string): AnyNode[] | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
return parentId ? (map[parentId] || undefined) : undefined;
} catch { return undefined; }
};
export const setTenantDetailCache = (tenantId: string, detail: AnyNode | undefined) => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
if (tenantId) map[tenantId] = detail || {};
sessionStorage.setItem(KEY_DETAIL, JSON.stringify(map));
} catch {}
};
export const getTenantDetailCache = (tenantId: string): AnyNode | undefined => {
try {
ensureTenantCacheTokenGuard();
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
return tenantId ? (map[tenantId] || undefined) : undefined;
} catch { return undefined; }
};
export const clearTenantCache = () => {
try {
sessionStorage.removeItem(KEY_TREE);
sessionStorage.removeItem(KEY_CHILDREN);
sessionStorage.removeItem(KEY_DETAIL);
sessionStorage.removeItem(KEY_META);
} catch {}
};
@@ -9,43 +9,43 @@
export default { export default {
dev: { dev: {
'/api-uaa/': { '/api-uaa/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-user/': { '/api-user/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-log/': { '/api-log/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-search/': { '/api-search/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-generator/': { '/api-generator/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-file/': { '/api-file/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-order/': { '/api-order/': {
target: 'http://119.45.169.13:9900', // target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
'/api-device/': { '/api-device/': {
target: 'http://119.45.169.13:9900', //target: 'http://119.45.169.13:9900',
// target: 'http://127.0.0.1:9900', target: 'http://local.goflytec.com:9900',
changeOrigin: true, changeOrigin: true,
}, },
}, },
Binary file not shown.
@@ -4,7 +4,7 @@
"private": true, "private": true,
"scripts": { "scripts": {
"analyze": "cross-env ANALYZE=1 umi build", "analyze": "cross-env ANALYZE=1 umi build",
"build": "umi build", "build": "set NODE_OPTIONS=--openssl-legacy-provider && umi build",
"deploy": "npm run build && npm run gh-pages", "deploy": "npm run build && npm run gh-pages",
"dev": "npm run start:dev", "dev": "npm run start:dev",
"gh-pages": "gh-pages -d dist", "gh-pages": "gh-pages -d dist",
@@ -311,4 +311,6 @@ export const request: RequestConfig = {
}; };
}, },
}, },
// 生产环境使用相对路径,开发环境使用代理
baseURL: process.env.NODE_ENV === 'production' ? '/' : undefined,
}; };
@@ -238,8 +238,38 @@ const CreateForm: React.FC<CreateFormProps> = ({
}} }}
/> />
</ProForm.Group> </ProForm.Group>
{/* 套餐配置 */}
<ProForm.Group>
<ProFormDigit
width="md"
name="vlogCount"
label="Vlog数量"
min={0}
initialValue={0}
placeholder="请输入Vlog数量"
/>
<ProFormDigit
width="md"
name="videoCount"
label="视频数量"
min={0}
initialValue={0}
placeholder="请输入视频数量"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormDigit
width="md"
name="photoCount"
label="照片数量"
min={0}
initialValue={0}
placeholder="请输入照片数量"
/>
</ProForm.Group>
</ModalForm> </ModalForm>
); );
}; };
export default CreateForm; export default CreateForm;
@@ -245,6 +245,33 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
}} }}
/> />
</ProForm.Group> </ProForm.Group>
{/* 套餐配置 */}
<ProForm.Group>
<ProFormDigit
width="md"
name="vlogCount"
label="Vlog数量"
min={0}
placeholder="请输入Vlog数量"
/>
<ProFormDigit
width="md"
name="videoCount"
label="视频数量"
min={0}
placeholder="请输入视频数量"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormDigit
width="md"
name="photoCount"
label="照片数量"
min={0}
placeholder="请输入照片数量"
/>
</ProForm.Group>
</ModalForm> </ModalForm>
); );
}; };
@@ -1,4 +1,4 @@
import { deleteQrcode, qrcode, saveOrUpdateQrcode, getTourismList, getVideoTemplateList, getTenantList } from '@/services/orders/api'; import { deleteQrcode, qrcode, saveOrUpdateQrcodeWithPlan, getTourismList, getVideoTemplateList, getTenantList, getPackageByCode } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons'; import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components'; import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { import {
@@ -121,29 +121,55 @@ const TableList: React.FC = () => {
return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>; return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
}; };
// 处理添加 // 处理添加(先创建二维码,再创建套餐)
const handleAdd = async (fields: Partial<ORDERS.Qrcode>) => { const handleAdd = async (fields: Partial<ORDERS.Qrcode>) => {
const template = templateOptions.find(item => item.value === fields.templateId); const hide = message.loading('正在添加');
return handleApiRequest( try {
() => saveOrUpdateQrcode({ const { vlogCount, videoCount, photoCount, ...qrcodePayload } = (fields || {}) as any;
...fields, const res = await saveOrUpdateQrcodeWithPlan({
} as ORDERS.Qrcode), qrCode: qrcodePayload as ORDERS.Qrcode,
'正在添加', vlogCount: Number(vlogCount ?? 0),
'添加成功' videoCount: Number(videoCount ?? 0),
); photoCount: Number(photoCount ?? 0),
});
if (res.resp_code !== 0) {
message.error(res.resp_msg || '创建失败');
return false;
}
message.success('添加成功');
return true;
} catch (e) {
message.error('添加失败');
return false;
} finally {
hide();
}
}; };
// 处理编辑 // 处理编辑(更新二维码,同时新增/更新套餐)
const handleEdit = async (original: ORDERS.Qrcode, fields: Partial<ORDERS.Qrcode>) => { const handleEdit = async (original: ORDERS.Qrcode, fields: Partial<ORDERS.Qrcode>) => {
const template = templateOptions.find(item => item.value === fields.templateId); const hide = message.loading('正在更新');
return handleApiRequest( try {
() => saveOrUpdateQrcode({ const { vlogCount, videoCount, photoCount, ...qrcodePayload } = (fields || {}) as any;
id: original.id, const qrPayload = { id: original.id, codeId: original.codeId, ...(qrcodePayload as any) } as ORDERS.Qrcode;
...fields const res = await saveOrUpdateQrcodeWithPlan({
}), qrCode: qrPayload,
'正在更新', vlogCount: vlogCount as number | undefined,
'修改成功' videoCount: videoCount as number | undefined,
); photoCount: photoCount as number | undefined,
});
if (res.resp_code !== 0) {
message.error(res.resp_msg || '更新失败');
return false;
}
message.success('修改成功');
return true;
} catch (e) {
message.error('修改失败');
return false;
} finally {
hide();
}
}; };
// 处理删除 // 处理删除
@@ -525,8 +551,19 @@ const TableList: React.FC = () => {
render: (_, record) => ( render: (_, record) => (
<Space> <Space>
<Link <Link
onClick={() => { onClick={async () => {
setCurrentRow(record); setCurrentRow(record);
try {
if (record?.codeId) {
const planRes = await getPackageByCode(record.codeId);
const plan = (planRes.resp_code === 0 && Array.isArray(planRes.data) && planRes.data.length > 0) ? planRes.data[0] : undefined;
if (plan) {
setCurrentRow(prev => ({ ...(prev as any), vlogCount: plan.vlogCount, videoCount: plan.videoCount, photoCount: plan.photoCount } as any));
}
}
} catch (e) {
// ignore preload error
}
handleUpdateModalVisible(true); handleUpdateModalVisible(true);
}} }}
> >
@@ -112,6 +112,34 @@ export async function saveOrUpdateQrcode(data: ORDERS.Qrcode): Promise<API.Resul
return result; return result;
} }
/** 根据二维码编码获取套餐列表 */
export async function getPackageByCode(codeId: string): Promise<API.Result<ORDERS.PackagePlan[]>> {
return request<API.Result<ORDERS.PackagePlan[]>>(`/api-order/package/byCode/${codeId}`, {
method: 'GET',
});
}
/** 新增或更新套餐 */
export async function saveOrUpdatePackagePlan(data: ORDERS.PackagePlan): Promise<API.Result<ORDERS.PackagePlan>> {
return request<API.Result<ORDERS.PackagePlan>>('/api-order/package', {
method: 'POST',
data,
});
}
/** 一次性创建/修改二维码及套餐 */
export async function saveOrUpdateQrcodeWithPlan(payload: {
qrCode: ORDERS.Qrcode;
vlogCount?: number;
videoCount?: number;
photoCount?: number;
}): Promise<API.Result<ORDERS.Qrcode>> {
return request<API.Result<ORDERS.Qrcode>>('/api-order/qrcode/withPlan', {
method: 'POST',
data: payload,
});
}
export async function homeCarousel(params?: { [key: string]: string | number }) { export async function homeCarousel(params?: { [key: string]: string | number }) {
const { current, pageSize, ...rest } = params ?? {}; const { current, pageSize, ...rest } = params ?? {};
const result = await request<SYSTEM.Page<ORDERS.HomeCarousel>>('/api-order/home/carousel', { const result = await request<SYSTEM.Page<ORDERS.HomeCarousel>>('/api-order/home/carousel', {
@@ -480,4 +508,4 @@ export async function getTenantList(params: {
return request('/api-uaa/clients/all', { return request('/api-uaa/clients/all', {
method: 'GET', method: 'GET',
}); });
} }
@@ -248,6 +248,18 @@ declare namespace ORDERS {
createTime: string; createTime: string;
updateTime: string; updateTime: string;
} }
/** 套餐定义 */
type PackagePlan = {
id?: number;
codeId: string;
vlogCount?: number;
videoCount?: number;
photoCount?: number;
tenantId?: string;
createTime?: string;
updateTime?: string;
}
} }
declare namespace API { declare namespace API {
@@ -292,4 +304,4 @@ declare namespace API {
queueCount?: number; queueCount?: number;
estimatedTime?: number; estimatedTime?: number;
} }
} }
@@ -1,4 +1,4 @@
import { request } from '@umijs/max'; import { request } from 'umi';
export interface TenantTreeNode { export interface TenantTreeNode {
tenantId: string; tenantId: string;
+108
View File
@@ -0,0 +1,108 @@
# 多租户订单统计修复验证说明
## 问题修复清单
### 1. ✅ 租户层级统计问题修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行261-342:重写`resolveTenantIds`方法
- 添加本地和远程两种方式获取子孙租户
- 增加详细日志追踪
- 添加降级机制
### 2. ✅ webApp超级租户统计修复
**文件**:`DashboardServiceImpl.java`
**修改内容**:
- 行274-303:特殊处理webApp租户
- webApp获取所有顶级租户及其子孙
- 无法获取时不设置tourismIds(查询所有数据)
### 3. ✅ 订单金额统计SQL修复
**文件**:`DashboardMapper.java`
**修改内容**:
- 行242-247:`getTotalAmount`添加tourismIds过滤
- 行273-278:`getRefundAmount`添加tourismIds过滤
## 验证步骤
### 1. 后端验证
```sql
-- 验证租户层级关系
SELECT * FROM sys_tenant WHERE parent_tenant_id IS NOT NULL;
-- 验证景区与租户关系
SELECT t.id, t.name, t.tenant_id, st.tenant_name
FROM tourisms t
LEFT JOIN sys_tenant st ON t.tenant_id = st.tenant_id;
-- 验证订单统计
SELECT
t.tenant_id,
COUNT(o.id) as order_count,
SUM(o.order_amount) as total_amount
FROM orders o
JOIN tourisms t ON o.tourism_id = t.id
GROUP BY t.tenant_id;
```
### 2. API测试
#### 测试普通租户(含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={父租户ID}&includeChildren=true&statType=day
```
预期:返回该租户及所有子孙租户的订单统计
#### 测试webApp超级租户
```bash
GET /api-order/dashboard/statistics?tenantId=webApp&includeChildren=true&statType=day
```
预期:返回所有租户的订单统计
#### 测试单个租户(不含子孙)
```bash
GET /api-order/dashboard/statistics?tenantId={租户ID}&includeChildren=false&statType=day
```
预期:仅返回指定租户的订单统计
### 3. 前端验证
1. 登录系统访问首页
2. 切换不同租户,观察数据变化
3. 切换"包含子租户"开关,验证数据范围
4. 切换统计粒度(周/月/年),验证时间维度
## 编译问题说明
当前环境Java版本为8,项目需要Java 17。请确保:
1. 安装Java 17(推荐OpenJDK 17或Oracle JDK 17)
2. 设置JAVA_HOME环境变量
3. 运行`mvn clean compile -pl zlt-business/order-center -am`
## 核心逻辑流程
```
用户请求统计
↓
获取租户ID(前端传入 or 当前登录用户)
↓
判断是否webApp
├─是→ 获取所有租户
└─否→ 获取当前租户[+子孙租户]
↓
查询租户关联的景区
↓
根据景区ID统计订单
↓
返回统计结果
```
## 日志监控点
关键日志位置:
- `DashboardServiceImpl:89` - webApp统计日志
- `DashboardServiceImpl:95` - 租户景区范围日志
- `DashboardServiceImpl:317` - 本地租户层级获取
- `DashboardServiceImpl:331` - 远程租户层级获取
- `DashboardServiceImpl:340` - 降级处理日志
通过这些日志可以追踪统计范围是否正确。