feat: 新增MCP密钥管理功能及商机金额校验

- 新增用户MCP密钥管理相关的后端实体、DTO、Mapper、Service、Controller
- 新增前端MCP密钥接口及类型定义
- 新增商机金额低于阈值时的确认弹窗
- 优化商机日期格式支持,兼容多种常见日期写法
- 完善MCP认证逻辑,支持原有Bot凭证和新MCP密钥统一认证
main
kangwenjing 2026-12-03 16:02:13 +08:00
parent e8faab8e20
commit 254bc46aeb
23 changed files with 2048 additions and 16 deletions

View File

@ -0,0 +1,155 @@
package com.unis.crm.common;
import java.time.DateTimeException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.util.Locale;
import java.util.Optional;
public final class LenientDateTimeParser {
private static final ZoneId DEFAULT_ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("uuuu-M-d")
.toFormatter(Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
private static final DateTimeFormatter DATE_TIME_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("uuuu-M-d")
.optionalStart()
.appendPattern(" H:m")
.optionalStart()
.appendPattern(":s")
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND, 1, 9, true)
.optionalEnd()
.optionalEnd()
.optionalStart()
.appendOffset("+HH:mm", "Z")
.optionalEnd()
.optionalEnd()
.toFormatter(Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
private static final DateTimeFormatter COMPACT_DATE_FORMATTER = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
private static final DateTimeFormatter COMPACT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("uuuuMMddHHmmss", Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
private LenientDateTimeParser() {
}
public static Optional<OffsetDateTime> parseOffsetDateTime(String rawValue) {
String normalized = normalize(rawValue);
if (normalized == null) {
return Optional.empty();
}
Optional<Long> epoch = parseEpochMillis(normalized);
if (epoch.isPresent()) {
return Optional.of(Instant.ofEpochMilli(epoch.get()).atZone(DEFAULT_ZONE).toOffsetDateTime());
}
try {
return Optional.of(OffsetDateTime.parse(normalized, DateTimeFormatter.ISO_OFFSET_DATE_TIME));
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
try {
return Optional.of(ZonedDateTime.parse(normalized, DateTimeFormatter.ISO_ZONED_DATE_TIME).toOffsetDateTime());
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
String candidate = normalized.replace('/', '-').replace('.', '-');
candidate = candidate.replace('年', '-').replace('月', '-').replace('日', ' ');
candidate = candidate.replace('时', ':').replace('分', ':').replace("秒", "");
candidate = candidate.replace('T', ' ').replace('t', ' ');
candidate = candidate.replaceAll("(?i)(Z|[+-]\\d{2}:?\\d{2})$", "");
candidate = candidate.trim();
candidate = candidate.replaceAll("\\s+", " ");
if (candidate.endsWith(" ")) {
candidate = candidate.substring(0, candidate.length() - 1).trim();
}
try {
return Optional.of(LocalDateTime.parse(candidate, DATE_TIME_FORMATTER)
.atZone(DEFAULT_ZONE)
.toOffsetDateTime());
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
try {
return Optional.of(LocalDate.parse(candidate, DATE_FORMATTER)
.atStartOfDay(DEFAULT_ZONE)
.toOffsetDateTime());
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
if (candidate.matches("\\d{8}")) {
try {
return Optional.of(LocalDate.parse(candidate, COMPACT_DATE_FORMATTER)
.atStartOfDay(DEFAULT_ZONE)
.toOffsetDateTime());
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
}
if (candidate.matches("\\d{14}")) {
try {
return Optional.of(LocalDateTime.parse(candidate, COMPACT_DATE_TIME_FORMATTER)
.atZone(DEFAULT_ZONE)
.toOffsetDateTime());
} catch (DateTimeParseException ignored) {
// try the next supported representation
}
}
return Optional.empty();
}
public static Optional<LocalDate> parseLocalDate(String rawValue) {
Optional<OffsetDateTime> dateTime = parseOffsetDateTime(rawValue);
return dateTime.map(OffsetDateTime::toLocalDate);
}
private static String normalize(String rawValue) {
if (rawValue == null) {
return null;
}
String trimmed = rawValue.trim();
if (trimmed.isEmpty() || "null".equalsIgnoreCase(trimmed)) {
return null;
}
return trimmed;
}
private static Optional<Long> parseEpochMillis(String value) {
if (!value.matches("-?\\d{10}|-?\\d{13}")) {
return Optional.empty();
}
try {
long numeric = Long.parseLong(value);
long magnitude = Math.abs(numeric);
if (magnitude >= 1_000_000_000_000L) {
return Optional.of(numeric / 1_000L);
}
if (magnitude >= 1_000_000_000L) {
return Optional.of(numeric * 1_000L);
}
return Optional.empty();
} catch (NumberFormatException | DateTimeException exception) {
return Optional.empty();
}
}
}

View File

@ -0,0 +1,54 @@
package com.unis.crm.common;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class UserMcpKeySchemaInitializer implements ApplicationRunner {
private final DataSource dataSource;
public UserMcpKeySchemaInitializer(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public void run(ApplicationArguments args) {
try (Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("""
create table if not exists crm_user_mcp_key (
id bigint generated by default as identity primary key,
key_id varchar(64) not null,
secret_hash varchar(255) not null,
user_id bigint not null,
name varchar(64) not null default '',
status varchar(16) not null default '0',
expire_time timestamp,
last_access_time timestamp,
last_access_ip varchar(128),
created_at timestamp not null default now(),
updated_at timestamp not null default now(),
constraint uk_crm_user_mcp_key_id unique (key_id)
)
""");
statement.execute("""
create index if not exists idx_crm_user_mcp_key_user
on crm_user_mcp_key (user_id, created_at desc)
""");
// Key 明文副本:只给页面重复查看用,认证仍只比对 secret_hash。
// 已有环境补列,不动既有数据;补列前创建的 Key 没有明文,页面会提示重建。
statement.execute("""
alter table if exists crm_user_mcp_key
add column if not exists secret_plain varchar(128)
""");
} catch (SQLException exception) {
throw new IllegalStateException("Failed to initialize user MCP key schema", exception);
}
}
}

View File

@ -0,0 +1,71 @@
package com.unis.crm.controller;
import com.unis.crm.common.ApiResponse;
import com.unis.crm.common.CurrentUserUtils;
import com.unis.crm.dto.mcp.CreateUserMcpKeyRequest;
import com.unis.crm.dto.mcp.LegacyBotCredentialDTO;
import com.unis.crm.dto.mcp.UserMcpKeyDTO;
import com.unis.crm.service.UserMcpKeyService;
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/profile/mcp-keys")
public class UserMcpKeyController {
private final UserMcpKeyService service;
public UserMcpKeyController(UserMcpKeyService service) {
this.service = service;
}
@GetMapping
public ApiResponse<List<UserMcpKeyDTO>> list(@RequestHeader("X-User-Id") Long userId) {
return ApiResponse.success(service.listMyKeys(CurrentUserUtils.requireCurrentUserId(userId)));
}
@GetMapping("/legacy")
public ApiResponse<LegacyBotCredentialDTO> getLegacy(@RequestHeader("X-User-Id") Long userId) {
return ApiResponse.success(service.getLegacyCredential(CurrentUserUtils.requireCurrentUserId(userId)));
}
@PostMapping("/legacy/generate")
public ApiResponse<LegacyBotCredentialDTO> generateLegacy(@RequestHeader("X-User-Id") Long userId) {
return ApiResponse.success(service.generateLegacyCredential(CurrentUserUtils.requireCurrentUserId(userId)));
}
@PostMapping
public ApiResponse<UserMcpKeyDTO> create(
@RequestHeader("X-User-Id") Long userId,
@RequestBody(required = false) @Valid CreateUserMcpKeyRequest request) {
CreateUserMcpKeyRequest payload = request == null ? new CreateUserMcpKeyRequest() : request;
return ApiResponse.success(service.createKey(CurrentUserUtils.requireCurrentUserId(userId), payload.getName()));
}
@PutMapping("/{keyId}/status")
public ApiResponse<Void> updateStatus(
@RequestHeader("X-User-Id") Long userId,
@PathVariable("keyId") Long keyId,
@RequestParam("status") String status) {
service.updateStatus(CurrentUserUtils.requireCurrentUserId(userId), keyId, status);
return ApiResponse.success(null);
}
@DeleteMapping("/{keyId}")
public ApiResponse<Void> delete(
@RequestHeader("X-User-Id") Long userId,
@PathVariable("keyId") Long keyId) {
service.deleteKey(CurrentUserUtils.requireCurrentUserId(userId), keyId);
return ApiResponse.success(null);
}
}

View File

@ -0,0 +1,17 @@
package com.unis.crm.dto.mcp;
import jakarta.validation.constraints.Size;
public class CreateUserMcpKeyRequest {
@Size(max = 64, message = "名称不能超过64个字符")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,70 @@
package com.unis.crm.dto.mcp;
import java.time.LocalDateTime;
public class LegacyBotCredentialDTO {
private boolean bound;
private String keyId;
private String secret;
private String status;
private LocalDateTime expireTime;
private LocalDateTime lastAccessTime;
private String lastAccessIp;
public boolean isBound() {
return bound;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public String getKeyId() {
return keyId;
}
public void setKeyId(String keyId) {
this.keyId = keyId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
public LocalDateTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalDateTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public String getLastAccessIp() {
return lastAccessIp;
}
public void setLastAccessIp(String lastAccessIp) {
this.lastAccessIp = lastAccessIp;
}
}

View File

@ -0,0 +1,88 @@
package com.unis.crm.dto.mcp;
import java.time.LocalDateTime;
public class UserMcpKeyDTO {
private Long id;
private String keyId;
private String secret;
private String name;
private String status;
private LocalDateTime expireTime;
private LocalDateTime lastAccessTime;
private String lastAccessIp;
private LocalDateTime createdAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getKeyId() {
return keyId;
}
public void setKeyId(String keyId) {
this.keyId = keyId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
public LocalDateTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalDateTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public String getLastAccessIp() {
return lastAccessIp;
}
public void setLastAccessIp(String lastAccessIp) {
this.lastAccessIp = lastAccessIp;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
}

View File

@ -2,8 +2,14 @@ package com.unis.crm.dto.opportunity;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.unis.crm.common.LenientDateTimeParser;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.Size;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.OffsetDateTime;
@ -30,6 +36,7 @@ public class UpdateOpportunityIntegrationRequest {
@JsonAlias("actual_signed_amount")
private BigDecimal actualSignedAmount;
@JsonDeserialize(using = LenientLocalDateDeserializer.class)
private LocalDate expectedCloseDate;
private String confidencePct;
@ -60,10 +67,12 @@ public class UpdateOpportunityIntegrationRequest {
private Boolean archived;
@JsonDeserialize(using = LenientOffsetDateTimeDeserializer.class)
private OffsetDateTime archivedAt;
private Boolean pushedToOms;
@JsonDeserialize(using = LenientOffsetDateTimeDeserializer.class)
private OffsetDateTime omsPushTime;
@JsonAlias("is_poc")
@ -279,4 +288,44 @@ public class UpdateOpportunityIntegrationRequest {
public void setDescription(String description) {
this.description = description;
}
public static class LenientOffsetDateTimeDeserializer extends JsonDeserializer<OffsetDateTime> {
@Override
public OffsetDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String value = parser.getValueAsString();
return LenientDateTimeParser.parseOffsetDateTime(value)
.orElseGet(() -> {
try {
return (OffsetDateTime) context.handleWeirdStringValue(
OffsetDateTime.class,
value,
"Unsupported date-time format: %s",
value);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
});
}
}
public static class LenientLocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String value = parser.getValueAsString();
return LenientDateTimeParser.parseLocalDate(value)
.orElseGet(() -> {
try {
return (LocalDate) context.handleWeirdStringValue(
LocalDate.class,
value,
"Unsupported date format: %s",
value);
} catch (IOException exception) {
throw new RuntimeException(exception);
}
});
}
}
}

View File

@ -0,0 +1,117 @@
package com.unis.crm.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import java.time.LocalDateTime;
@TableName("crm_user_mcp_key")
public class UserMcpKey {
private Long id;
private String keyId;
private String secretHash;
private String secretPlain;
private Long userId;
private String name;
private String status;
private LocalDateTime expireTime;
private LocalDateTime lastAccessTime;
private String lastAccessIp;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getKeyId() {
return keyId;
}
public void setKeyId(String keyId) {
this.keyId = keyId;
}
public String getSecretHash() {
return secretHash;
}
public void setSecretHash(String secretHash) {
this.secretHash = secretHash;
}
public String getSecretPlain() {
return secretPlain;
}
public void setSecretPlain(String secretPlain) {
this.secretPlain = secretPlain;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
public LocalDateTime getLastAccessTime() {
return lastAccessTime;
}
public void setLastAccessTime(LocalDateTime lastAccessTime) {
this.lastAccessTime = lastAccessTime;
}
public String getLastAccessIp() {
return lastAccessIp;
}
public void setLastAccessIp(String lastAccessIp) {
this.lastAccessIp = lastAccessIp;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
}

View File

@ -0,0 +1,164 @@
package com.unis.crm.llm.security;
import com.unis.crm.entity.UserMcpKey;
import com.unis.crm.service.UserMcpKeyService;
import com.unisbase.llm.auth.McpAuthenticationException;
import com.unisbase.llm.auth.McpBotAuthService;
import com.unisbase.entity.SysBotCredential;
import com.unisbase.mapper.SysBotCredentialMapper;
import com.unisbase.mapper.SysTenantUserMapper;
import com.unisbase.mapper.SysUserMapper;
import com.unisbase.security.LoginUser;
import com.unisbase.service.AuthScopeService;
import com.unisbase.service.SysPermissionService;
import java.time.LocalDateTime;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
/**
* /mcp 统一认证入口:原有 {@code bot_} 凭证与「我的 - MCP Key 管理」里创建的 {@code mcp_} Key
* 走完全相同的校验、身份装载和访问记录逻辑。
*
* <p>必须标 {@link Primary}:框架的 UnisBaseCoreAutoConfiguration 会 @ComponentScan("com.unisbase")
* 扫到自带的 {@link com.unisbase.llm.auth.McpBotAuthServiceImpl}(它本身是 @Service),于是
* {@link com.unisbase.llm.auth.McpBotAuthService} 有两个候选 bean,而 McpBotAuthenticationFilter
* 按类型注入 —— 不指定首选会直接启动失败(原 key 也就一起用不了)。
*
* <p>原有 Bot 凭证(sys_bot_credential,一人一条)只读取、不迁移、不改写;生成/重置仍由框架
* {@link com.unisbase.service.UserBotCredentialService} 处理,因此 bot id 仍然永远只有一个。
*/
@Primary
@Service
public class CompositeMcpBotAuthService implements McpBotAuthService {
private final UserMcpKeyService userMcpKeyService;
private final SysBotCredentialMapper sysBotCredentialMapper;
private final SysUserMapper sysUserMapper;
private final SysTenantUserMapper sysTenantUserMapper;
private final SysPermissionService sysPermissionService;
private final AuthScopeService authScopeService;
private final PasswordEncoder passwordEncoder;
public CompositeMcpBotAuthService(
UserMcpKeyService userMcpKeyService,
SysBotCredentialMapper sysBotCredentialMapper,
SysUserMapper sysUserMapper,
SysTenantUserMapper sysTenantUserMapper,
SysPermissionService sysPermissionService,
AuthScopeService authScopeService,
PasswordEncoder passwordEncoder) {
this.userMcpKeyService = userMcpKeyService;
this.sysUserMapper = sysUserMapper;
this.sysTenantUserMapper = sysTenantUserMapper;
this.sysPermissionService = sysPermissionService;
this.authScopeService = authScopeService;
this.sysBotCredentialMapper = sysBotCredentialMapper;
this.passwordEncoder = passwordEncoder;
}
@Override
public LoginUser authenticate(String botId, String botSecret, String requestedTenantHeader, String accessIp) {
if (botId == null || botId.isBlank() || botSecret == null || botSecret.isBlank()) {
throw new McpAuthenticationException("X-Bot-Id and X-Bot-Secret are required");
}
String keyId = botId.trim();
String secret = botSecret.trim();
UserMcpKey newKey = userMcpKeyService.findUsableKey(keyId, secret);
if (newKey != null) {
LoginUser result = buildLoginUser(newKey.getUserId(), requestedTenantHeader);
LocalDateTime now = LocalDateTime.now();
userMcpKeyService.recordAccess(newKey.getId(), now, accessIp);
return result;
}
SysBotCredential legacyKey = findUsableLegacyKey(keyId, secret);
if (legacyKey != null) {
LoginUser result = buildLoginUser(legacyKey.getUserId(), requestedTenantHeader);
LocalDateTime now = LocalDateTime.now();
sysBotCredentialMapper.updateAccessInfo(legacyKey.getId(), now, accessIp, now);
return result;
}
throw new McpAuthenticationException("Invalid bot credentials");
}
private SysBotCredential findUsableLegacyKey(String botId, String secret) {
SysBotCredential credential = sysBotCredentialMapper.selectByBotId(botId);
if (credential == null) {
return null;
}
if (credential.getStatus() == null || !"0".equals(credential.getStatus().trim())) {
throw new McpAuthenticationException("Bot credential is disabled");
}
LocalDateTime now = LocalDateTime.now();
if (credential.getExpireTime() != null && credential.getExpireTime().isBefore(now)) {
throw new McpAuthenticationException("Bot credential has expired");
}
if (credential.getSecretHash() == null || !passwordEncoder.matches(secret, credential.getSecretHash())) {
return null;
}
return credential;
}
private LoginUser buildLoginUser(Long userId, String requestedTenantHeader) {
var user = sysUserMapper.selectByIdIgnoreTenant(userId);
if (user == null || user.getIsDeleted() != null && user.getIsDeleted() != 0
|| user.getStatus() != null && user.getStatus() != 1) {
throw new McpAuthenticationException("Bound user is unavailable");
}
List<Long> tenantIds = sysTenantUserMapper.selectTenantIdsByUserIdIgnoreTenant(userId);
if (tenantIds == null) {
tenantIds = List.of();
}
boolean platformAdmin = Boolean.TRUE.equals(user.getIsPlatformAdmin());
Long tenantId = resolveTenantId(platformAdmin, tenantIds, requestedTenantHeader);
Set<String> permissions = new LinkedHashSet<>(sysPermissionService.listPermissionCodesByUserId(userId, tenantId));
boolean effectivePlatformAdmin = platformAdmin && tenantId != null && tenantId == 0L;
LoginUser result = new LoginUser(
userId, tenantId, user.getUsername(),
effectivePlatformAdmin, authScopeService.isTenantAdmin(userId, tenantId), permissions);
result.setDisplayName(user.getDisplayName());
return result;
}
private Long resolveTenantId(boolean platformAdmin, List<Long> tenantIds, String requestedTenantHeader) {
Long parsedTenantId = parseTenantId(requestedTenantHeader);
if (parsedTenantId != null) {
if (platformAdmin && parsedTenantId == 0L) {
return 0L;
}
if (tenantIds.contains(parsedTenantId)) {
return parsedTenantId;
}
throw new McpAuthenticationException("Bot user does not belong to the requested tenant");
}
if (platformAdmin) {
return 0L;
}
if (tenantIds.size() == 1) {
return tenantIds.get(0);
}
if (tenantIds.size() > 1) {
throw new McpAuthenticationException("X-Tenant-Id is required when the bot user belongs to multiple tenants");
}
throw new McpAuthenticationException("Bot user is not bound to any tenant");
}
private Long parseTenantId(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Long.valueOf(value.trim());
} catch (NumberFormatException exception) {
throw new McpAuthenticationException("X-Tenant-Id must be numeric");
}
}
}

View File

@ -0,0 +1,60 @@
package com.unis.crm.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.unis.crm.entity.UserMcpKey;
import java.time.LocalDateTime;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface UserMcpKeyMapper extends BaseMapper<UserMcpKey> {
@Select("""
select id, key_id, secret_hash, secret_plain, user_id, name, status, expire_time,
last_access_time, last_access_ip, created_at, updated_at
from crm_user_mcp_key
where key_id = #{keyId}
""")
UserMcpKey selectByKeyId(@Param("keyId") String keyId);
@Select("""
select id, key_id, secret_hash, secret_plain, user_id, name, status, expire_time,
last_access_time, last_access_ip, created_at, updated_at
from crm_user_mcp_key
where user_id = #{userId}
order by created_at desc, id desc
""")
List<UserMcpKey> selectByUserId(@Param("userId") Long userId);
@Insert("""
insert into crm_user_mcp_key
(key_id, secret_hash, secret_plain, user_id, name, status, expire_time, last_access_time, last_access_ip,
created_at, updated_at)
values
(#{keyId}, #{secretHash}, #{secretPlain}, #{userId}, #{name}, #{status}, #{expireTime},
#{lastAccessTime}, #{lastAccessIp}, #{createdAt}, #{updatedAt})
""")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insertKey(UserMcpKey entity);
@Update("""
update crm_user_mcp_key
set status = #{status}, updated_at = now()
where id = #{id} and user_id = #{userId}
""")
int updateStatus(@Param("id") Long id, @Param("userId") Long userId, @Param("status") String status);
@Update("""
update crm_user_mcp_key
set last_access_time = #{accessTime}, last_access_ip = #{accessIp}, updated_at = #{accessTime}
where id = #{id}
""")
int updateAccessInfo(@Param("id") Long id, @Param("accessTime") LocalDateTime accessTime,
@Param("accessIp") String accessIp);
}

View File

@ -0,0 +1,186 @@
package com.unis.crm.service;
import com.unis.crm.common.BusinessException;
import com.unis.crm.dto.mcp.LegacyBotCredentialDTO;
import com.unis.crm.dto.mcp.UserMcpKeyDTO;
import com.unis.crm.entity.UserMcpKey;
import com.unis.crm.mapper.UserMcpKeyMapper;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.unisbase.dto.BotCredentialDTO;
import com.unisbase.service.UserBotCredentialService;
@Service
public class UserMcpKeyService {
public static final String STATUS_ACTIVE = "0";
public static final String STATUS_DISABLED = "1";
public static final int MAX_KEYS_PER_USER = 20;
private static final String KEY_PREFIX = "mcp_";
private static final String ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
private static final int KEY_ID_LENGTH = 24;
private static final int SECRET_LENGTH = 48;
private static final Set<String> ALLOWED_STATUSES = Set.of(STATUS_ACTIVE, STATUS_DISABLED);
private final UserMcpKeyMapper mapper;
private final PasswordEncoder passwordEncoder;
private final UserBotCredentialService legacyCredentialService;
private final SecureRandom secureRandom = new SecureRandom();
public UserMcpKeyService(UserMcpKeyMapper mapper, PasswordEncoder passwordEncoder,
UserBotCredentialService legacyCredentialService) {
this.mapper = mapper;
this.passwordEncoder = passwordEncoder;
this.legacyCredentialService = legacyCredentialService;
}
public LegacyBotCredentialDTO getLegacyCredential(Long userId) {
return toLegacyDto(legacyCredentialService.getCurrentUserCredential());
}
public LegacyBotCredentialDTO generateLegacyCredential(Long userId) {
return toLegacyDto(legacyCredentialService.generateCurrentUserCredential());
}
private LegacyBotCredentialDTO toLegacyDto(BotCredentialDTO source) {
LegacyBotCredentialDTO target = new LegacyBotCredentialDTO();
if (source == null) {
return target;
}
target.setBound(source.isBound());
target.setKeyId(source.getBotId());
target.setSecret(source.getBotSecret());
target.setStatus(source.getStatus());
target.setExpireTime(source.getExpireTime());
target.setLastAccessTime(source.getLastAccessTime());
target.setLastAccessIp(source.getLastAccessIp());
return target;
}
public List<UserMcpKeyDTO> listMyKeys(Long userId) {
List<UserMcpKeyDTO> result = new ArrayList<>();
for (UserMcpKey entity : mapper.selectByUserId(userId)) {
result.add(toDto(entity, entity.getSecretPlain()));
}
return result;
}
public UserMcpKeyDTO createKey(Long userId, String name) {
List<UserMcpKey> existing = listOwnedKeys(userId);
int activeCount = 0;
for (UserMcpKey item : existing) {
if (STATUS_ACTIVE.equals(item.getStatus())) {
activeCount++;
}
}
if (activeCount >= MAX_KEYS_PER_USER) {
throw new BusinessException("最多只能创建 " + MAX_KEYS_PER_USER + " 个有效的 MCP Key");
}
String keyId = generateUniqueKeyId();
String secret = randomValue(SECRET_LENGTH);
LocalDateTime now = LocalDateTime.now();
UserMcpKey entity = new UserMcpKey();
entity.setKeyId(keyId);
entity.setSecretHash(passwordEncoder.encode(secret));
entity.setSecretPlain(secret);
entity.setUserId(userId);
entity.setName(normalizeName(name));
entity.setStatus(STATUS_ACTIVE);
entity.setCreatedAt(now);
entity.setUpdatedAt(now);
mapper.insertKey(entity);
return toDto(entity, secret);
}
public void updateStatus(Long userId, Long keyId, String status) {
if (!ALLOWED_STATUSES.contains(status)) {
throw new BusinessException("不支持的状态");
}
UserMcpKey entity = requireOwnedKey(userId, keyId);
if (ALLOWED_STATUSES.contains(entity.getStatus()) && !status.equals(entity.getStatus())) {
mapper.updateStatus(keyId, userId, status);
}
}
public void deleteKey(Long userId, Long keyId) {
requireOwnedKey(userId, keyId);
mapper.deleteById(keyId);
}
private List<UserMcpKey> listOwnedKeys(Long userId) {
return mapper.selectByUserId(userId);
}
public UserMcpKey findUsableKey(String keyId, String secret) {
UserMcpKey entity = mapper.selectByKeyId(keyId);
if (entity == null || !STATUS_ACTIVE.equals(entity.getStatus())) {
return null;
}
if (entity.getExpireTime() != null && entity.getExpireTime().isBefore(LocalDateTime.now())) {
return null;
}
if (entity.getSecretHash() == null || !passwordEncoder.matches(secret, entity.getSecretHash())) {
return null;
}
return entity;
}
public void recordAccess(Long keyId, LocalDateTime accessTime, String accessIp) {
mapper.updateAccessInfo(keyId, accessTime, accessIp);
}
private UserMcpKey requireOwnedKey(Long userId, Long keyId) {
UserMcpKey entity = mapper.selectById(keyId);
if (entity == null || !userId.equals(entity.getUserId())) {
throw new BusinessException("MCP Key 不存在");
}
return entity;
}
private String generateUniqueKeyId() {
for (int attempt = 0; attempt < 10; attempt++) {
String candidate = KEY_PREFIX + randomValue(KEY_ID_LENGTH);
if (mapper.selectByKeyId(candidate) == null) {
return candidate;
}
}
throw new IllegalStateException("Failed to generate unique MCP key id");
}
private String randomValue(int length) {
StringBuilder builder = new StringBuilder(length);
for (int index = 0; index < length; index++) {
builder.append(ALPHABET.charAt(secureRandom.nextInt(ALPHABET.length())));
}
return builder.toString();
}
private String normalizeName(String name) {
if (name == null) {
return "";
}
String trimmed = name.trim();
return trimmed.length() > 64 ? trimmed.substring(0, 64) : trimmed;
}
private UserMcpKeyDTO toDto(UserMcpKey entity, String secret) {
UserMcpKeyDTO dto = new UserMcpKeyDTO();
dto.setId(entity.getId());
dto.setKeyId(entity.getKeyId());
dto.setSecret(secret);
dto.setName(entity.getName());
dto.setStatus(entity.getStatus());
dto.setExpireTime(entity.getExpireTime());
dto.setLastAccessTime(entity.getLastAccessTime());
dto.setLastAccessIp(entity.getLastAccessIp());
dto.setCreatedAt(entity.getCreatedAt());
return dto;
}
}

View File

@ -1,5 +1,6 @@
package com.unis.crm.controller;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@ -11,9 +12,15 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
import com.unis.crm.common.CrmGlobalExceptionHandler;
import com.unis.crm.config.InternalAuthProperties;
import com.unis.crm.dto.opportunity.UpdateOpportunityIntegrationRequest;
import com.unis.crm.service.OpportunityService;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ -115,4 +122,57 @@ class OpportunityIntegrationControllerWebMvcTest {
verify(opportunityService).updateOpportunityByIntegration(any());
}
@Test
void updateOpportunityShouldAcceptPlainDateForArchivedAt() throws Exception {
when(opportunityService.updateOpportunityByIntegration(any())).thenReturn(1L);
mockMvc.perform(put("/api/opportunities/integration/update")
.header(INTERNAL_SECRET_HEADER, INTERNAL_SECRET_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"opportunityCode\":\"OPP-20260401-001\",\"archivedAt\":\"2026-07-08\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("0"));
ArgumentCaptor<UpdateOpportunityIntegrationRequest> captor =
ArgumentCaptor.forClass(UpdateOpportunityIntegrationRequest.class);
verify(opportunityService).updateOpportunityByIntegration(captor.capture());
OffsetDateTime expected = LocalDateTime.of(2026, 7, 8, 0, 0)
.atZone(ZoneId.systemDefault())
.toOffsetDateTime();
assertEquals(expected.toInstant(), captor.getValue().getArchivedAt().toInstant());
}
@Test
void updateOpportunityShouldAcceptCommonDateFormats() throws Exception {
when(opportunityService.updateOpportunityByIntegration(any())).thenReturn(1L);
mockMvc.perform(put("/api/opportunities/integration/update")
.header(INTERNAL_SECRET_HEADER, INTERNAL_SECRET_VALUE)
.contentType(MediaType.APPLICATION_JSON)
.content("""
{
"opportunityCode":"OPP-20260401-001",
"expectedCloseDate":"2026/07/08",
"archivedAt":"2026年07月08日 17时05分06秒",
"omsPushTime":"20260708170506"
}
"""))
.andExpect(status().isOk())
.andExpect(jsonPath("$.code").value("0"));
ArgumentCaptor<UpdateOpportunityIntegrationRequest> captor =
ArgumentCaptor.forClass(UpdateOpportunityIntegrationRequest.class);
verify(opportunityService).updateOpportunityByIntegration(captor.capture());
UpdateOpportunityIntegrationRequest request = captor.getValue();
assertEquals(LocalDate.of(2026, 7, 8), request.getExpectedCloseDate());
assertEquals(LocalDateTime.of(2026, 7, 8, 17, 5, 6)
.atZone(ZoneId.systemDefault())
.toOffsetDateTime()
.toInstant(), request.getArchivedAt().toInstant());
assertEquals(LocalDateTime.of(2026, 7, 8, 17, 5, 6)
.atZone(ZoneId.systemDefault())
.toOffsetDateTime()
.toInstant(), request.getOmsPushTime().toInstant());
}
}

View File

@ -0,0 +1,71 @@
package com.unis.crm.llm.security;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.unisbase.llm.auth.McpBotAuthServiceImpl;
import com.unisbase.llm.auth.McpBotAuthService;
import java.nio.file.Files;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.stereotype.Service;
/**
* /mcp 认证 bean 的唯一首选门。
*
* <p>框架的 UnisBaseCoreAutoConfiguration 带 {@code @ComponentScan("com.unisbase")},会把自带的
* {@link McpBotAuthServiceImpl}({@code @Service})扫成 bean;本仓库的 {@link CompositeMcpBotAuthService}
* 实现同一个 {@link McpBotAuthService},于是容器里有两个候选。而 starter 里的
* {@code McpBotAuthenticationFilter} 是按类型注入 {@code McpBotAuthService} 的 —— 没有首选 bean
* 就直接 NoUniqueBeanDefinitionException,整个 /mcp 起不来,**原有 Bot 凭证会跟着一起用不了**。
*
* <p>统一认证要求:{@link CompositeMcpBotAuthService} 必须同时识别旧 {@code bot_} 凭证和
* 新 {@code mcp_} Key,并用同一套 buildLoginUser/resolveTenantId 身份装载逻辑,不能把旧
* 凭证整权委托给框架实现。"调用逻辑一样" 是这次需求的核心,不是可选优化。
*
* <p>为什么用注解显式钉而不是跑一次上下文:这条约束只在启动期暴露,且踩到的时候症状是
* 「/mcp 全挂」,看不出和「新加了多 key 支持」有什么联系。删掉 @Primary 的改动看起来完全无害。
*
* <p>同时钉住「只有一个实现标了 @Primary」:将来再加第三种 key 来源时,两个 @Primary 等于没有 @Primary。
*/
class McpAuthServicePrimaryBeanTest {
@Test
void compositeServiceIsThePrimaryMcpAuthService() {
assertTrue(AnnotatedElementUtils.hasAnnotation(CompositeMcpBotAuthService.class, Primary.class),
"CompositeMcpBotAuthService 缺少 @Primary:与框架的 McpBotAuthServiceImpl 构成两个候选 bean,"
+ "McpBotAuthenticationFilter 按类型注入会失败,/mcp 连同原有 Bot 凭证一起不可用");
assertNotNull(AnnotatedElementUtils.findMergedAnnotation(CompositeMcpBotAuthService.class, Service.class),
"CompositeMcpBotAuthService 需要被组件扫描登记成 bean");
assertTrue(McpBotAuthService.class.isAssignableFrom(CompositeMcpBotAuthService.class),
"必须实现框架的 McpBotAuthService,否则替换不到过滤器上");
}
@Test
void frameworkImplementationStaysUnannotatedSoOnlyOnePrimaryExists() {
assertTrue(AnnotatedElementUtils.hasAnnotation(McpBotAuthServiceImpl.class, Service.class),
"框架自带实现仍是 @Service(@Primary 的前提就在这:它确实会变成一个候选 bean)");
assertTrue(!AnnotatedElementUtils.hasAnnotation(McpBotAuthServiceImpl.class, Primary.class),
"框架实现也被标了 @Primary:两个首选等于没有首选,注入仍然歧义");
}
@Test
void unifiedAuthenticationReadsBothCredentialTables() throws Exception {
Path source = Path.of("src/main/java/com/unis/crm/llm/security/CompositeMcpBotAuthService.java");
assertTrue(Files.exists(source), "源文件应存在:" + source.toAbsolutePath());
String code = Files.readString(source);
assertTrue(code.contains("sysBotCredentialMapper.selectByBotId"),
"统一认证必须自己读取 sys_bot_credential(旧 bot 凭证)");
assertTrue(code.contains("userMcpKeyService.findUsableKey"),
"统一认证必须自己读取 crm_user_mcp_key(新 MCP Key)");
assertTrue(!code.contains("legacyAuthService"),
"不能把旧凭证整权委托给框架实现,否则新旧 key 的调用逻辑不一致");
assertTrue(code.contains("buildLoginUser(legacyKey.getUserId()"),
"旧 bot 凭证必须走与新 key 相同的身份装载逻辑");
assertTrue(code.contains("sysBotCredentialMapper.updateAccessInfo(legacyKey.getId()"),
"旧 bot 凭证必须走统一逻辑里的访问时间/IP 记录");
}
}

View File

@ -0,0 +1,114 @@
package com.unis.crm.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.unis.crm.common.BusinessException;
import com.unis.crm.dto.mcp.UserMcpKeyDTO;
import com.unis.crm.entity.UserMcpKey;
import com.unis.crm.mapper.UserMcpKeyMapper;
import java.time.LocalDateTime;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
class UserMcpKeyServiceTest {
private UserMcpKeyMapper mapper;
private PasswordEncoder passwordEncoder;
private UserMcpKeyService service;
@BeforeEach
void setUp() {
mapper = mock(UserMcpKeyMapper.class);
passwordEncoder = new BCryptPasswordEncoder();
service = new UserMcpKeyService(mapper, passwordEncoder, mock(com.unisbase.service.UserBotCredentialService.class));
}
@Test
void createShouldReturnPlainSecretOnlyOnceAndPersistHash() {
when(mapper.selectByUserId(99L)).thenReturn(List.of());
when(mapper.selectByKeyId(any())).thenReturn(null);
when(mapper.insertKey(any())).thenAnswer(invocation -> {
UserMcpKey entity = invocation.getArgument(0);
entity.setId(12L);
entity.setCreatedAt(LocalDateTime.now());
return 1;
});
UserMcpKeyDTO created = service.createKey(99L, "Cursor");
assertNotNull(created.getSecret());
assertTrue(created.getKeyId().startsWith("mcp_"));
assertEquals("Cursor", created.getName());
assertEquals(created.getKeyId(), capturedEntity().getKeyId());
assertTrue(passwordEncoder.matches(created.getSecret(), capturedEntity().getSecretHash()));
}
@Test
void listShouldNeverExposeSecret() {
UserMcpKey entity = key(1L, 99L, "mcp_existing", "hash");
when(mapper.selectByUserId(99L)).thenReturn(List.of(entity));
List<UserMcpKeyDTO> keys = service.listMyKeys(99L);
assertEquals(1, keys.size());
assertNull(keys.get(0).getSecret());
assertEquals("mcp_existing", keys.get(0).getKeyId());
}
@Test
void findUsableKeyShouldVerifyHashAndStatus() {
UserMcpKey entity = key(1L, 99L, "mcp_existing", passwordEncoder.encode("secret"));
when(mapper.selectByKeyId("mcp_existing")).thenReturn(entity);
assertEquals(entity, service.findUsableKey("mcp_existing", "secret"));
assertNull(service.findUsableKey("mcp_existing", "wrong"));
entity.setStatus(UserMcpKeyService.STATUS_DISABLED);
assertNull(service.findUsableKey("mcp_existing", "secret"));
}
@Test
void deleteShouldRejectKeysOwnedByOtherUsers() {
UserMcpKey entity = key(1L, 100L, "mcp_other", "hash");
when(mapper.selectById(1L)).thenReturn(entity);
assertThrows(BusinessException.class, () -> service.deleteKey(99L, 1L));
verify(mapper, org.mockito.Mockito.never()).deleteById(1L);
}
@Test
void entityShouldMapToActualTableName() {
com.baomidou.mybatisplus.annotation.TableName tableName =
UserMcpKey.class.getAnnotation(com.baomidou.mybatisplus.annotation.TableName.class);
org.junit.jupiter.api.Assertions.assertNotNull(tableName,
"UserMcpKey 必须显式绑定表名,否则 MyBatis-Plus 会推断成不存在的 user_mcp_key");
org.junit.jupiter.api.Assertions.assertEquals("crm_user_mcp_key", tableName.value());
}
private UserMcpKey capturedEntity() {
org.mockito.ArgumentCaptor<UserMcpKey> captor = org.mockito.ArgumentCaptor.forClass(UserMcpKey.class);
verify(mapper, org.mockito.Mockito.atLeastOnce()).insertKey(captor.capture());
return captor.getValue();
}
private UserMcpKey key(Long id, Long userId, String keyId, String secretHash) {
UserMcpKey entity = new UserMcpKey();
entity.setId(id);
entity.setUserId(userId);
entity.setKeyId(keyId);
entity.setSecretHash(secretHash);
entity.setName("test");
entity.setStatus(UserMcpKeyService.STATUS_ACTIVE);
return entity;
}
}

View File

@ -125,6 +125,22 @@ class OpportunityServiceImplTest {
verify(opportunityMapper, never()).insertOpportunity(any(), any(), any());
}
@Test
void updateOpportunity_shouldAllowLowAmountAfterConfirmation() {
when(opportunityMapper.countOwnedOpportunity(1L, 10L)).thenReturn(1);
when(opportunityMapper.selectArchived(1L, 10L)).thenReturn(Boolean.FALSE);
when(opportunityMapper.selectOpportunityCustomerSnapshot(1L, 10L)).thenReturn(customerSnapshot(200L, "客户A"));
when(opportunityMapper.updateOpportunity(eq(1L), eq(10L), eq(200L), any(CreateOpportunityRequest.class))).thenReturn(1);
when(opportunityMapper.selectOpportunityOmsPushData(1L, 10L)).thenReturn(null);
CreateOpportunityRequest request = updateRequest("客户A");
request.setAmount(new BigDecimal("999.99"));
Long result = opportunityService.updateOpportunity(1L, 10L, request);
assertEquals(10L, result);
}
@Test
void createOpportunity_shouldRejectMissingChannelBeforeWriting() {
when(permissionService.hasPermi("opportunity:create")).thenReturn(true);

View File

@ -324,7 +324,7 @@ OMS返回成功,但未返回项目编号
| `operatorName` | string | 运作方,最大 100 字符。 |
| `amount` | number | 预计金额;历史数据回写不再限制必须大于 0。 |
| `actualSignedAmount` | number | 实际签约金额;兼容字段名 `actual_signed_amount`。 |
| `expectedCloseDate` | string | 预计结单日期,格式 `YYYY-MM-DD`。 |
| `expectedCloseDate` | string | 预计结单日期,推荐 `YYYY-MM-DD`;同时兼容斜杠、中文、紧凑日期等常见写法。 |
| `confidencePct` | string | 项目把握度,支持 `A`、`B`、`C`,兼容 `40`、`60`、`80`。 |
| `stage` | string | 项目阶段,支持 CRM 字典值,也兼容部分中文阶段名。 |
| `opportunityType` | string | 建设类型,最大 50 字符。 |
@ -336,9 +336,9 @@ OMS返回成功,但未返回项目编号
| `preSalesName` | string | 售前姓名,最大 100 字符;空字符串会存为 `null`。 |
| `competitorName` | string | 竞品名称,最大 200 字符;空字符串会存为 `null`。 |
| `archived` | boolean | 是否归档。 |
| `archivedAt` | string | 归档时间,ISO 8601 格式。传该字段且未传 `archived` 时会自动视为归档。 |
| `archivedAt` | string | 归档时间,推荐 ISO 8601;兼容常见日期时间写法及秒/毫秒时间戳,纯日期按当日 00:00 处理。传该字段且未传 `archived` 时会自动视为归档。 |
| `pushedToOms` | boolean | 是否已推送 OMS。传 `true` 且未传 `omsPushTime` 时自动填当前时间。 |
| `omsPushTime` | string | 推送 OMS 时间,ISO 8601 格式。 |
| `omsPushTime` | string | 推送 OMS 时间,推荐 ISO 8601;兼容常见日期时间写法及秒/毫秒时间戳,纯日期按当日 00:00 处理。 |
| `isPoc` | boolean | 是否 POC 测试项目;兼容字段名 `is_poc`。 |
| `status` | string | 商机状态,支持 `active`、`closed`、`won`、`lost`,但 `won/lost` 需配合对应阶段。 |
| `description` | string | 备注;空字符串会存为 `null`。 |

View File

@ -32,7 +32,7 @@
| `operatorName` | string | 运作方 |
| `amount` | number | 商机金额,历史数据回写不再限制必须大于 0 |
| `actualSignedAmount` | number | 实际签约金额,兼容字段名 `actual_signed_amount` |
| `expectedCloseDate` | string | 预计结单日期,格式 `YYYY-MM-DD` |
| `expectedCloseDate` | string | 预计结单日期,推荐 `YYYY-MM-DD`;同时兼容斜杠、中文、紧凑日期等常见写法 |
| `confidencePct` | string | 把握度,建议传 `A`、`B`、`C` |
| `stage` | string | 项目阶段,建议传 CRM 当前字典码值 |
| `opportunityType` | string | 建设类型 |
@ -45,7 +45,7 @@
| `competitorName` | string | 竞品名称 |
| `archived` | boolean | 是否归档 |
| `pushedToOms` | boolean | 是否已推送 OMS |
| `omsPushTime` | string | 推送 OMS 时间,建议 ISO 8601 格式 |
| `omsPushTime` | string | 推送 OMS 时间,推荐 ISO 8601;兼容常见日期时间写法及秒/毫秒时间戳,纯日期按当日 00:00 处理 |
| `isPoc` | boolean | 是否 POC 测试项目,兼容字段名 `is_poc` |
| `status` | string | 商机状态,支持 `active`、`closed`、`won`、`lost` |
| `description` | string | 备注 |

View File

@ -56,6 +56,13 @@ const DEFAULT_WECOM_OPTIONS: ExpansionDictOption[] = [
export const CHANNEL_CONTACT_HINT_MESSAGE =
"请至少完整填写一行联系人(姓名、职务、联系电话、是否加企业微信、特别说明为必填,生日选填),空行可留空";
export const LOW_OPPORTUNITY_AMOUNT_THRESHOLD = 1000;
export const LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE = "预计签约金额单位为:元 ,请确认是否有误。";
export function isLowOpportunityAmount(amount?: number | null) {
return Number(amount) > 0 && Number(amount) < LOW_OPPORTUNITY_AMOUNT_THRESHOLD;
}
function normalizeContactText(value?: string | null) {
const trimmed = value?.trim();
return !trimmed || trimmed === "无" ? "" : trimmed;

View File

@ -311,6 +311,28 @@ export interface UpdateCurrentUserPasswordPayload {
newPassword: string;
}
export interface UserMcpKey {
id?: CrmId;
keyId?: string;
secret?: string;
name?: string;
status?: string;
expireTime?: string;
lastAccessTime?: string;
lastAccessIp?: string;
createdAt?: string;
}
export interface LegacyBotCredential {
bound?: boolean;
keyId?: string;
secret?: string;
status?: string;
expireTime?: string;
lastAccessTime?: string;
lastAccessIp?: string;
}
export interface OwnerTransferConflict {
employeeNo: string;
candidateName: string;
@ -1778,6 +1800,39 @@ export async function updateCurrentUserPassword(payload: UpdateCurrentUserPasswo
}, true);
}
export async function listMyMcpKeys() {
return request<UserMcpKey[]>("/api/profile/mcp-keys", undefined, true);
}
export async function createMyMcpKey(name?: string) {
return request<UserMcpKey>("/api/profile/mcp-keys", {
method: "POST",
body: JSON.stringify({ name: name || "" }),
}, true);
}
export async function updateMyMcpKeyStatus(keyId: CrmId, status: "0" | "1") {
return request<boolean>(`/api/profile/mcp-keys/${keyId}/status?status=${status}`, {
method: "PUT",
}, true);
}
export async function deleteMyMcpKey(keyId: CrmId) {
return request<boolean>(`/api/profile/mcp-keys/${keyId}`, {
method: "DELETE",
}, true);
}
export async function getLegacyBotCredential() {
return request<LegacyBotCredential>("/api/profile/mcp-keys/legacy", undefined, true);
}
export async function generateLegacyBotCredential() {
return request<LegacyBotCredential>("/api/profile/mcp-keys/legacy/generate", {
method: "POST",
}, true);
}
export async function updateUserProfileById(userId: CrmId, payload: UpdateCurrentUserProfilePayload) {
return request<boolean>(`/api/sys/api/users/${userId}`, {
method: "PUT",

View File

@ -48,6 +48,8 @@ import {
type SalesCreateField,
defaultQuickChannelForm as sharedDefaultQuickChannelForm,
defaultQuickSalesForm as sharedDefaultQuickSalesForm,
isLowOpportunityAmount,
LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE,
isOtherOption as isSharedOtherOption,
normalizeChannelPayload as normalizeSharedChannelPayload,
normalizeSalesPayload as normalizeSharedSalesPayload,
@ -1579,6 +1581,7 @@ export default function Opportunities() {
const [editOpen, setEditOpen] = useState(false);
const [pushConfirmOpen, setPushConfirmOpen] = useState(false);
const [duplicateCheckOpen, setDuplicateCheckOpen] = useState(false);
const [lowAmountConfirmOpen, setLowAmountConfirmOpen] = useState(false);
const [duplicateCheckItems, setDuplicateCheckItems] = useState<OpportunityDuplicateItem[]>([]);
const [duplicateCheckExact, setDuplicateCheckExact] = useState(false);
const [submitting, setSubmitting] = useState(false);
@ -1643,7 +1646,7 @@ export default function Opportunities() {
const [loadingSalesExpansionOptions, setLoadingSalesExpansionOptions] = useState(false);
const [loadingChannelExpansionOptions, setLoadingChannelExpansionOptions] = useState(false);
const hasLoadedOpportunityExpansionOptionsRef = useRef(false);
const hasForegroundModal = createOpen || editOpen || pushConfirmOpen || duplicateCheckOpen || exportFilterOpen || quickCreateOpen;
const hasForegroundModal = createOpen || editOpen || pushConfirmOpen || duplicateCheckOpen || lowAmountConfirmOpen || exportFilterOpen || quickCreateOpen;
const canCreateOpportunity = permissionCodes !== null && canUsePermission(OPPORTUNITY_CREATE_PERMISSION, permissionCodes);
const fetchOpportunityExpansionOptions = async (query?: string) => getOpportunityExpansionOptions({
@ -2574,6 +2577,7 @@ export default function Opportunities() {
const resetCreateState = () => {
setCreateOpen(false);
setEditOpen(false);
setLowAmountConfirmOpen(false);
setSubmitting(false);
setError("");
setFieldErrors({});
@ -2615,6 +2619,15 @@ export default function Opportunities() {
await doCreateOpportunity();
};
const handleConfirmLowAmount = async () => {
setLowAmountConfirmOpen(false);
if (editOpen) {
await doUpdateOpportunity();
} else {
await doCreateOpportunity();
}
};
const handleCreateSubmit = async () => {
if (submitting) {
return;
@ -2643,6 +2656,11 @@ export default function Opportunities() {
}
}
if (isLowOpportunityAmount(form.amount)) {
setLowAmountConfirmOpen(true);
return;
}
await doCreateOpportunity();
};
@ -2678,6 +2696,21 @@ export default function Opportunities() {
setEditOpen(true);
};
const doUpdateOpportunity = async () => {
if (!selectedItem) {
return;
}
setSubmitting(true);
try {
await updateOpportunity(selectedItem.id, buildOpportunitySubmitPayload(form, selectedCompetitors, customCompetitorName, operatorMode));
await reload(selectedItem.id);
resetCreateState();
} catch (updateError) {
setError(updateError instanceof Error ? updateError.message : "编辑商机失败");
setSubmitting(false);
}
};
const handleEditSubmit = async () => {
if (!selectedItem || submitting) {
return;
@ -2699,16 +2732,12 @@ export default function Opportunities() {
return;
}
setSubmitting(true);
try {
await updateOpportunity(selectedItem.id, buildOpportunitySubmitPayload(form, selectedCompetitors, customCompetitorName, operatorMode));
await reload(selectedItem.id);
resetCreateState();
} catch (updateError) {
setError(updateError instanceof Error ? updateError.message : "编辑商机失败");
setSubmitting(false);
if (isLowOpportunityAmount(form.amount)) {
setLowAmountConfirmOpen(true);
return;
}
await doUpdateOpportunity();
};
const handlePushToOms = async () => {
@ -3562,6 +3591,66 @@ export default function Opportunities() {
)}
</AnimatePresence>
<AnimatePresence>
{lowAmountConfirmOpen ? (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setLowAmountConfirmOpen(false)}
className="fixed inset-0 z-[90] bg-slate-900/40 backdrop-blur-sm dark:bg-slate-950/70"
/>
<motion.div
initial={{ opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 24 }}
className="fixed inset-x-0 bottom-0 z-[100] px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 sm:inset-0 sm:flex sm:items-center sm:justify-center sm:p-6"
>
<div className="mx-auto w-full max-w-md rounded-3xl border border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-900">
<div className="border-b border-slate-100 px-5 py-4 dark:border-slate-800 sm:px-6">
<div className="mx-auto mb-3 h-1.5 w-10 rounded-full bg-slate-200 dark:bg-slate-700 sm:hidden" />
<div className="flex items-start gap-3">
<div className="crm-tone-warning mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl">
<AlertTriangle className="crm-icon-lg" />
</div>
<div className="min-w-0">
<h3 className="text-base font-semibold text-slate-900 dark:text-white">金额确认</h3>
<p className="mt-1 text-sm leading-6 text-slate-500 dark:text-slate-400">
{LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE}
</p>
</div>
</div>
</div>
<div className="px-5 py-4 text-sm text-slate-600 dark:text-slate-300 sm:px-6">
<div className="crm-form-section">
<p className="text-xs text-slate-400 dark:text-slate-500">当前录入的预计签约金额</p>
<p className="mt-1 font-medium text-slate-900 dark:text-white">¥{formatAmount(form.amount)}</p>
</div>
</div>
<div className="flex flex-col-reverse gap-3 px-5 pb-[calc(1rem+env(safe-area-inset-bottom))] pt-1 sm:flex-row sm:justify-end sm:px-6 sm:pb-5">
<button
type="button"
onClick={() => setLowAmountConfirmOpen(false)}
className="crm-btn crm-btn-secondary min-h-0 rounded-2xl px-4 py-3"
>
返回修改
</button>
<button
type="button"
onClick={() => void handleConfirmLowAmount()}
disabled={submitting}
className="crm-btn crm-btn-primary min-h-0 rounded-2xl px-4 py-3 disabled:cursor-not-allowed disabled:opacity-60"
>
{submitting ? "保存中..." : editOpen ? "确认保存" : "确认新增"}
</button>
</div>
</div>
</motion.div>
</>
) : null}
</AnimatePresence>
<AnimatePresence>
{detailItem && (
<>

View File

@ -2,9 +2,12 @@ import { useEffect, useState, type ReactNode } from "react";
import { AnimatePresence, motion } from "motion/react";
import {
BriefcaseBusiness,
Check,
ChevronRight,
CircleUserRound,
Copy,
HelpCircle,
KeyRound,
LogOut,
Mail,
MapPinned,
@ -14,6 +17,7 @@ import {
Phone,
Settings,
Shield,
Server,
Sun,
User,
X,
@ -31,17 +35,25 @@ import {
getProfileOverview,
updateCurrentUserProfile,
updateCurrentUserPassword,
listMyMcpKeys,
createMyMcpKey,
updateMyMcpKeyStatus,
deleteMyMcpKey,
getLegacyBotCredential,
generateLegacyBotCredential,
type IdpFallbackModeResponse,
type ProfileOverview,
type UpdateCurrentUserProfilePayload,
type UpdateCurrentUserPasswordPayload,
type LegacyBotCredential,
type UserMcpKey,
type UserProfile,
} from "@/lib/auth";
import { getIdpPortalUrl, isIdpEnabled, resolvePasswordLocallyManaged } from "@/lib/idp";
import OwnerTransfer from "./OwnerTransfer";
type MenuItem = {
key: "personal" | "security" | "ownerTransfer" | "help";
key: "personal" | "security" | "mcpKeys" | "ownerTransfer" | "help";
icon: typeof User;
label: string;
color: string;
@ -53,6 +65,7 @@ type EditableProfileForm = UpdateCurrentUserProfilePayload;
const MENU_ITEMS: MenuItem[] = [
{ key: "personal", icon: User, label: "个人资料", color: "text-blue-500 dark:text-blue-400", bg: "bg-blue-50 dark:bg-blue-500/10" },
{ key: "security", icon: Shield, label: "账号安全", color: "text-emerald-500 dark:text-emerald-400", bg: "bg-emerald-50 dark:bg-emerald-500/10" },
{ key: "mcpKeys", icon: KeyRound, label: "MCP Key 管理", color: "text-fuchsia-500 dark:text-fuchsia-400", bg: "bg-fuchsia-50 dark:bg-fuchsia-500/10" },
{ key: "ownerTransfer", icon: BriefcaseBusiness, label: "项目归属转移", color: "text-amber-500 dark:text-amber-400", bg: "bg-amber-50 dark:bg-amber-500/10" },
{ key: "help", icon: HelpCircle, label: "帮助中心", color: "text-violet-500 dark:text-violet-400", bg: "bg-violet-50 dark:bg-violet-500/10" },
];
@ -81,6 +94,100 @@ function numericValue(value?: number | null) {
return typeof value === "number" && Number.isFinite(value) ? value : 0;
}
/** 后端回的是 ISO 带微秒的时间串,直接铺在页面上没法看,统一收成「年-月-日 时:分」。 */
function formatDateTime(value?: string | null) {
if (!value) {
return "";
}
const parsed = new Date(value.includes("T") ? value : value.replace(" ", "T"));
if (Number.isNaN(parsed.getTime())) {
return value;
}
const pad = (input: number) => String(input).padStart(2, "0");
return `${parsed.getFullYear()}-${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
}
/**
* 一行放一个凭证字段(ID / Key),明文常驻可反复查看:眼睛切换显隐,勾表示刚复制成功。
* 补 secret_plain 列之前创建的 Key 没有明文副本,这时提示重建,而不是显示一串假的掩码。
*/
function SecretField({
label,
value,
revealed,
copied,
onToggle,
onCopy,
revealable = true,
disabled = false,
emptyHint = "未保存明文,重新创建后可随时查看",
}: {
label: string;
value?: string | null;
revealed: boolean;
copied: boolean;
onToggle: () => void;
onCopy: () => void;
/** ID 和地址本来就整串可见,不需要眼睛;只有 Key 需要显隐。 */
revealable?: boolean;
/** 凭证被停用时,值仍然能看和复制,但明确标出「不可用」。 */
disabled?: boolean;
emptyHint?: string;
}) {
const masked = value ? `${value.slice(0, 6)}${"•".repeat(Math.max(value.length - 6, 8))}` : "";
const hasValue = Boolean(value);
return (
<div className="flex items-center gap-2 rounded-xl border border-slate-200/80 bg-slate-50/80 px-3 py-2 dark:border-slate-800 dark:bg-slate-800/30">
<span className="w-14 shrink-0 text-[11px] font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500">
{label}
</span>
{hasValue ? (
<code className="min-w-0 flex-1 break-all text-xs font-medium text-slate-700 dark:text-slate-200">
{revealed ? value : masked}
</code>
) : (
<span className="min-w-0 flex-1 text-xs text-slate-400 dark:text-slate-500">
{emptyHint}
</span>
)}
{hasValue ? (
<div className="flex shrink-0 items-center gap-1">
{disabled ? (
<span className="rounded-md bg-rose-50 px-2 py-0.5 text-[11px] font-medium text-rose-600 dark:bg-rose-500/10 dark:text-rose-400">
不可用
</span>
) : null}
{revealable ? (
<button
type="button"
onClick={onToggle}
aria-label={revealed ? `隐藏${label}` : `显示${label}`}
className="rounded-lg p-1.5 text-slate-400 transition-colors hover:bg-white hover:text-slate-600 dark:hover:bg-slate-700 dark:hover:text-slate-200"
>
{revealed ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
</button>
) : null}
<button
type="button"
onClick={onCopy}
aria-label={`复制${label}`}
className={`rounded-lg p-1.5 transition-colors ${
copied
? "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-300"
: "text-slate-400 hover:bg-white hover:text-slate-600 dark:hover:bg-slate-700 dark:hover:text-slate-200"
}`}
>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</button>
</div>
) : null}
</div>
);
}
function PageModal({
title,
subtitle,
@ -145,6 +252,17 @@ export default function Profile() {
const [securityDrawerOpen, setSecurityDrawerOpen] = useState(false);
const [ownerTransferDrawerOpen, setOwnerTransferDrawerOpen] = useState(false);
const [ownerTransferFooter, setOwnerTransferFooter] = useState<ReactNode>(null);
const [mcpDrawerOpen, setMcpDrawerOpen] = useState(false);
const [mcpKeys, setMcpKeys] = useState<UserMcpKey[]>([]);
const [legacyCredential, setLegacyCredential] = useState<LegacyBotCredential | null>(null);
const [mcpLoading, setMcpLoading] = useState(false);
const [mcpSaving, setMcpSaving] = useState(false);
const [mcpError, setMcpError] = useState("");
const [mcpName, setMcpName] = useState("");
// 明文常驻可见,所以不再需要「只显示一次」的临时区;这里只记刚创建的那条,用于高亮 + 默认展开
const [freshKeyId, setFreshKeyId] = useState<string | null>(null);
const [copiedField, setCopiedField] = useState<string | null>(null);
const [visibleSecretIds, setVisibleSecretIds] = useState<Set<string>>(new Set());
const [form, setForm] = useState<EditableProfileForm>(EMPTY_FORM);
const [detailLoading, setDetailLoading] = useState(false);
const [saving, setSaving] = useState(false);
@ -338,6 +456,146 @@ export default function Profile() {
setOwnerTransferFooter(null);
};
const loadMcpKeys = async () => {
setMcpLoading(true);
setMcpError("");
try {
const [keys, legacy] = await Promise.all([
listMyMcpKeys(),
getLegacyBotCredential().catch(() => null),
]);
setMcpKeys(keys);
setLegacyCredential(legacy);
} catch (loadError) {
setMcpError(loadError instanceof Error ? loadError.message : "加载 MCP Key 失败");
} finally {
setMcpLoading(false);
}
};
const handleOpenMcpKeys = () => {
setMcpName("");
setFreshKeyId(null);
setCopiedField(null);
setVisibleSecretIds(new Set());
setMcpDrawerOpen(true);
void loadMcpKeys();
};
const handleCloseMcpKeys = () => {
if (mcpSaving) {
return;
}
setMcpDrawerOpen(false);
setMcpError("");
};
const handleCreateMcpKey = async () => {
if (mcpSaving) {
return;
}
setMcpSaving(true);
setMcpError("");
try {
const created = await createMyMcpKey(mcpName.trim());
setMcpName("");
// 新建的这条默认把 Key 展开,省一次点击;其余保持掩码
setFreshKeyId(created.keyId || null);
if (created.secret) {
setVisibleSecretIds((current) => new Set(current).add(String(created.keyId)));
}
await loadMcpKeys();
} catch (createError) {
setMcpError(createError instanceof Error ? createError.message : "创建 MCP Key 失败");
} finally {
setMcpSaving(false);
}
};
const handleGenerateLegacyCredential = async () => {
if (mcpSaving) {
return;
}
setMcpSaving(true);
setMcpError("");
try {
const generated = await generateLegacyBotCredential();
setLegacyCredential(generated);
if (generated.secret) {
setVisibleSecretIds((current) => new Set(current).add("legacy"));
}
} catch (generateError) {
setMcpError(generateError instanceof Error ? generateError.message : "生成旧版凭证失败");
} finally {
setMcpSaving(false);
}
};
const toggleSecretVisibility = (key: string) => {
setVisibleSecretIds((current) => {
const next = new Set(current);
if (next.has(key)) {
next.delete(key);
} else {
next.add(key);
}
return next;
});
};
/** 复制成功的勾只留 1.6 秒,之后自己回到复制图标。 */
const markCopied = (fieldKey: string) => {
setCopiedField(fieldKey);
window.setTimeout(() => {
setCopiedField((current) => (current === fieldKey ? null : current));
}, 1600);
};
const handleToggleMcpKey = async (key: UserMcpKey) => {
if (key.id === undefined || mcpSaving) {
return;
}
setMcpSaving(true);
setMcpError("");
try {
await updateMyMcpKeyStatus(key.id, key.status === "0" ? "1" : "0");
await loadMcpKeys();
} catch (updateError) {
setMcpError(updateError instanceof Error ? updateError.message : "更新 MCP Key 失败");
} finally {
setMcpSaving(false);
}
};
const handleDeleteMcpKey = async (key: UserMcpKey) => {
if (key.id === undefined || mcpSaving) {
return;
}
setMcpSaving(true);
setMcpError("");
try {
await deleteMyMcpKey(key.id);
await loadMcpKeys();
} catch (deleteError) {
setMcpError(deleteError instanceof Error ? deleteError.message : "删除 MCP Key 失败");
} finally {
setMcpSaving(false);
}
};
const copyText = async (value: string, fieldKey?: string) => {
try {
await navigator.clipboard.writeText(value);
if (fieldKey) {
markCopied(fieldKey);
}
} catch {
setMcpError("复制失败,请手动选中后复制");
}
};
const mcpEndpoint = `${window.location.origin}/mcp`;
const handleUpdatePassword = async () => {
if (securitySaving) {
return;
@ -457,6 +715,8 @@ export default function Profile() {
? () => void handleOpenProfile()
: item.key === "security"
? handleOpenSecurity
: item.key === "mcpKeys"
? handleOpenMcpKeys
: item.key === "ownerTransfer"
? handleOpenOwnerTransfer
: item.key === "help"
@ -778,6 +1038,228 @@ export default function Profile() {
/>
</PageModal>
) : null}
{mcpDrawerOpen ? (
<PageModal
title="MCP Key 管理"
subtitle="一个 ID 对应一个 Key;一个账号可创建多个 Key,均用于同一个 MCP 地址。"
onClose={handleCloseMcpKeys}
>
<div className="crm-modal-stack">
<div className="rounded-2xl border border-violet-200/70 bg-gradient-to-br from-violet-50 to-white p-4 dark:border-violet-900/60 dark:from-violet-500/10 dark:to-slate-900/40">
<div className="flex items-center gap-2 text-sm font-semibold text-violet-700 dark:text-violet-300">
<Server className="crm-icon-md" />
MCP 地址
</div>
<div className="mt-3">
<SecretField
label="地址"
value={mcpEndpoint}
revealed
revealable={false}
copied={copiedField === "endpoint"}
onToggle={() => undefined}
onCopy={() => void copyText(mcpEndpoint, "endpoint")}
/>
</div>
<p className="mt-3 text-xs leading-5 text-slate-500 dark:text-slate-400">
请求头 <code>X-Bot-Id</code> 填 ID,<code>X-Bot-Secret</code> 填 Key。Key 创建后长期可见,忘了随时回来复制。
</p>
</div>
<div className="crm-form-section">
<div className="flex flex-wrap items-end justify-between gap-3">
<label className="min-w-[16rem] flex-1 space-y-2">
<span className="text-sm font-medium text-slate-700 dark:text-slate-300">新建 Key</span>
<input
value={mcpName}
maxLength={64}
onChange={(event) => setMcpName(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") {
void handleCreateMcpKey();
}
}}
placeholder="用途备注,例如:Claude Desktop / Cursor / 自动化脚本"
className="crm-input-box crm-input-text w-full border border-slate-200 bg-white outline-none focus:border-violet-500 focus:ring-1 focus:ring-violet-500 dark:border-slate-800 dark:bg-slate-900/50"
/>
</label>
<button
onClick={() => void handleCreateMcpKey()}
disabled={mcpSaving || mcpLoading}
className="crm-btn crm-btn-primary shrink-0 disabled:cursor-not-allowed disabled:opacity-60"
>
{mcpSaving ? "处理中..." : "创建 Key"}
</button>
</div>
</div>
{mcpError ? (
<div className="crm-alert crm-alert-error">
{mcpError}
</div>
) : null}
<div className="crm-section-stack">
<div className="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-white">
<KeyRound className="crm-icon-md text-fuchsia-500" />
我的 Key
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500 dark:bg-slate-800 dark:text-slate-400">
{mcpKeys.length}
</span>
</div>
{mcpLoading ? (
<div className="crm-alert crm-alert-info">正在加载 MCP Key...</div>
) : mcpKeys.length === 0 ? (
<div className="crm-alert crm-alert-info">还没有创建过 MCP Key,先创建一个试试。</div>
) : (
<div className="space-y-3">
{mcpKeys.map((key) => {
const rowKey = String(key.keyId ?? key.id);
const isFresh = Boolean(freshKeyId) && key.keyId === freshKeyId;
return (
<div
key={rowKey}
className={`rounded-2xl border p-4 transition-colors ${
isFresh
? "border-emerald-300 bg-emerald-50/60 dark:border-emerald-700 dark:bg-emerald-500/10"
: key.status !== "0"
? "border-slate-200 bg-slate-50/60 opacity-75 dark:border-slate-800 dark:bg-slate-900/30"
: "border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900/50"
}`}
>
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm font-semibold text-slate-900 dark:text-white">
{displayText(key.name)}
</span>
<span className={`shrink-0 rounded-full px-2 py-0.5 text-xs font-medium ${key.status === "0" ? "bg-emerald-50 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-300" : "bg-slate-100 text-slate-500 dark:bg-slate-800 dark:text-slate-400"}`}>
{key.status === "0" ? "已启用" : "已禁用"}
</span>
{isFresh ? (
<span className="shrink-0 rounded-full bg-emerald-500 px-2 py-0.5 text-xs font-medium text-white">
新创建
</span>
) : null}
</div>
<div className="flex shrink-0 gap-2">
<button
onClick={() => void handleToggleMcpKey(key)}
disabled={mcpSaving}
className="crm-btn crm-btn-secondary disabled:opacity-60"
>
{key.status === "0" ? "禁用" : "启用"}
</button>
<button
onClick={() => void handleDeleteMcpKey(key)}
disabled={mcpSaving}
className="crm-btn crm-btn-danger disabled:opacity-60"
>
删除
</button>
</div>
</div>
<div className="mt-3 space-y-2">
<SecretField
label="ID"
value={key.keyId}
revealed
revealable={false}
copied={copiedField === `${rowKey}-id`}
onToggle={() => undefined}
onCopy={() => void copyText(key.keyId || "", `${rowKey}-id`)}
/>
<SecretField
label="Key"
value={key.secret}
disabled={key.status !== "0"}
revealed={visibleSecretIds.has(rowKey)}
copied={copiedField === `${rowKey}-secret`}
onToggle={() => toggleSecretVisibility(rowKey)}
onCopy={() => void copyText(key.secret || "", `${rowKey}-secret`)}
/>
</div>
<div className="mt-3 flex flex-wrap gap-x-4 gap-y-1 text-xs text-slate-400 dark:text-slate-500">
<span>创建:{formatDateTime(key.createdAt) || "未知"}</span>
<span>最近访问:{formatDateTime(key.lastAccessTime) || "从未"}</span>
{key.lastAccessIp ? <span>IP:{key.lastAccessIp}</span> : null}
</div>
</div>
);
})}
</div>
)}
</div>
<details className="group rounded-2xl border border-slate-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-900/50">
<summary className="flex cursor-pointer list-none items-center justify-between gap-2 text-sm font-semibold text-slate-900 dark:text-white">
<span className="flex items-center gap-2">
<Shield className="crm-icon-md text-violet-500" />
原有 Bot 凭证
<span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-medium text-slate-500 dark:bg-slate-800 dark:text-slate-400">
一人一个
</span>
</span>
<ChevronRight className="h-4 w-4 shrink-0 text-slate-400 transition-transform group-open:rotate-90" />
</summary>
<div className="mt-3 space-y-3">
<p className="text-xs leading-5 text-slate-500 dark:text-slate-400">
这是系统管理端「Bot 凭证」那一把,历史客户端大多用它。数据不迁移、不改写,和新建 Key 用同一个 MCP 地址与调用方式。
</p>
{legacyCredential?.keyId ? (
<div className="space-y-2">
<SecretField
label="ID"
value={legacyCredential.keyId}
revealed
revealable={false}
copied={copiedField === "legacy-id"}
onToggle={() => undefined}
onCopy={() => void copyText(legacyCredential.keyId || "", "legacy-id")}
/>
<SecretField
label="Key"
value={legacyCredential.secret}
revealed={visibleSecretIds.has("legacy")}
copied={copiedField === "legacy-secret"}
emptyHint="旧凭证只在重置后显示一次,需要新的请点下方重置"
onToggle={() => toggleSecretVisibility("legacy")}
onCopy={() => void copyText(legacyCredential.secret || "", "legacy-secret")}
/>
</div>
) : (
<div className="crm-alert crm-alert-info">还没有生成过 Bot 凭证。</div>
)}
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs text-slate-400 dark:text-slate-500">
状态:{legacyCredential?.bound ? "已生成" : "未生成"}
{legacyCredential?.lastAccessTime ? ` · 最近访问:${formatDateTime(legacyCredential.lastAccessTime)}` : ""}
{legacyCredential?.lastAccessIp ? ` · IP:${legacyCredential.lastAccessIp}` : ""}
</span>
<button
onClick={() => void handleGenerateLegacyCredential()}
disabled={mcpSaving}
className="crm-btn crm-btn-primary disabled:opacity-60"
>
{legacyCredential?.bound ? "重置凭证" : "生成凭证"}
</button>
</div>
{legacyCredential?.bound ? (
<p className="text-xs leading-5 text-amber-600 dark:text-amber-400">
重置会立刻让旧 Key 失效,且这把凭证的 Key 只在重置后显示一次,请先确认所有客户端都能同步更新。
</p>
) : null}
</div>
</details>
</div>
</PageModal>
) : null}
{helpDialogOpen ? (
<ActionDialog
title="帮助中心"

View File

@ -68,6 +68,8 @@ import {
type SalesCreateField,
defaultQuickChannelForm as sharedDefaultQuickChannelForm,
defaultQuickSalesForm as sharedDefaultQuickSalesForm,
isLowOpportunityAmount,
LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE,
isOtherOption as isSharedOtherOption,
normalizeChannelPayload as normalizeSharedChannelPayload,
normalizeSalesPayload as normalizeSharedSalesPayload,
@ -906,6 +908,7 @@ export default function Work() {
const [quickChannelForm, setQuickChannelForm] = useState<CreateChannelExpansionPayload>(sharedDefaultQuickChannelForm);
const [quickOpportunityForm, setQuickOpportunityForm] = useState<CreateOpportunityPayload>(defaultQuickOpportunityForm);
const [quickOpportunityDuplicateOpen, setQuickOpportunityDuplicateOpen] = useState(false);
const [quickOpportunityLowAmountConfirmOpen, setQuickOpportunityLowAmountConfirmOpen] = useState(false);
const [quickOpportunityDuplicateExact, setQuickOpportunityDuplicateExact] = useState(false);
const [quickOpportunityDuplicateItems, setQuickOpportunityDuplicateItems] = useState<OpportunityDuplicateItem[]>([]);
const [quickOpportunityCompetitors, setQuickOpportunityCompetitors] = useState<CompetitorOption[]>([]);
@ -1606,6 +1609,7 @@ export default function Work() {
setQuickSalesDuplicateMessage("");
setQuickChannelDuplicateMessage("");
setQuickOpportunityDuplicateOpen(false);
setQuickOpportunityLowAmountConfirmOpen(false);
setQuickOpportunityDuplicateExact(false);
setQuickOpportunityDuplicateItems([]);
};
@ -1796,11 +1800,25 @@ export default function Work() {
}
}
if (isLowOpportunityAmount(quickOpportunityForm.amount)) {
setQuickOpportunityLowAmountConfirmOpen(true);
return;
}
await performQuickCreateSubmit();
};
const handleQuickCreateConfirmWithDuplicate = async () => {
setQuickOpportunityDuplicateOpen(false);
if (isLowOpportunityAmount(quickOpportunityForm.amount)) {
setQuickOpportunityLowAmountConfirmOpen(true);
return;
}
await performQuickCreateSubmit();
};
const handleQuickCreateConfirmLowAmount = async () => {
setQuickOpportunityLowAmountConfirmOpen(false);
await performQuickCreateSubmit();
};
@ -3060,6 +3078,64 @@ export default function Work() {
</>
) : null}
{quickOpportunityLowAmountConfirmOpen ? (
<>
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
onClick={() => setQuickOpportunityLowAmountConfirmOpen(false)}
className="fixed inset-0 z-[90] bg-slate-900/40 backdrop-blur-sm dark:bg-slate-950/70"
/>
<motion.div
initial={{ opacity: 0, y: 24 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 24 }}
className="fixed inset-x-0 bottom-0 z-[100] px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 sm:inset-0 sm:flex sm:items-center sm:justify-center sm:p-6"
>
<div className="mx-auto w-full max-w-md rounded-3xl border border-slate-200 bg-white shadow-2xl dark:border-slate-800 dark:bg-slate-900">
<div className="border-b border-slate-100 px-5 py-4 dark:border-slate-800 sm:px-6">
<div className="mx-auto mb-3 h-1.5 w-10 rounded-full bg-slate-200 dark:bg-slate-700 sm:hidden" />
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl bg-amber-500/15 text-amber-500 dark:bg-amber-500/20 dark:text-amber-400">
<AlertTriangle className="h-5 w-5" />
</div>
<div className="min-w-0">
<h3 className="text-base font-semibold text-slate-900 dark:text-white">金额确认</h3>
<p className="mt-1 text-sm leading-6 text-slate-500 dark:text-slate-400">
{LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE}
</p>
</div>
</div>
</div>
<div className="px-5 py-4 text-sm text-slate-600 dark:text-slate-300 sm:px-6">
<div className="crm-form-section">
<p className="text-xs text-slate-400 dark:text-slate-500">当前录入的预计签约金额</p>
<p className="mt-1 font-medium text-slate-900 dark:text-white">¥{new Intl.NumberFormat("zh-CN").format(Number(quickOpportunityForm.amount || 0))}</p>
</div>
</div>
<div className="flex flex-col-reverse gap-3 px-5 pb-[calc(1rem+env(safe-area-inset-bottom))] pt-1 sm:flex-row sm:justify-end sm:px-6 sm:pb-5">
<button
type="button"
onClick={() => setQuickOpportunityLowAmountConfirmOpen(false)}
className="h-10 rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-600 transition-colors hover:border-violet-200 hover:text-violet-600 dark:border-slate-700 dark:bg-slate-900/60 dark:text-slate-300 dark:hover:border-violet-500/40 dark:hover:text-violet-200"
>
返回修改
</button>
<button
type="button"
onClick={() => void handleQuickCreateConfirmLowAmount()}
disabled={quickCreateSubmitting}
className="inline-flex h-10 items-center justify-center rounded-xl bg-violet-600 px-4 text-sm font-semibold text-white transition-colors hover:bg-violet-700 disabled:cursor-not-allowed disabled:bg-violet-300 dark:bg-violet-500 dark:hover:bg-violet-400 dark:disabled:bg-violet-500/40"
>
{quickCreateSubmitting ? "提交中..." : "确认仍要新增"}
</button>
</div>
</div>
</motion.div>
</>
) : null}
{locationAdjustOpen && checkInForm.latitude && checkInForm.longitude ? (
<LocationAdjustModal
origin={locationAdjustOrigin ?? { latitude: checkInForm.latitude, longitude: checkInForm.longitude }}

View File

@ -0,0 +1,31 @@
-- “我的 - MCP Key”独立表。
-- 刻意不碰框架自带的 sys_bot_credential:管理端现有 Bot 凭证继续按原逻辑使用,
-- 本表只承载业务端用户自助创建的多把 MCP key。
create table if not exists crm_user_mcp_key (
id bigint generated by default as identity primary key,
key_id varchar(64) not null,
secret_hash varchar(255) not null,
user_id bigint not null,
name varchar(64) not null default '',
status varchar(16) not null default '0',
expire_time timestamp,
last_access_time timestamp,
last_access_ip varchar(128),
created_at timestamp not null default now(),
updated_at timestamp not null default now(),
constraint uk_crm_user_mcp_key_id unique (key_id)
);
create index if not exists idx_crm_user_mcp_key_user
on crm_user_mcp_key (user_id, created_at desc);
-- secret_plain:Key 明文,给「我的 - MCP Key 管理」重复查看用。
-- 认证仍然只比对 secret_hash(BCrypt),明文只是展示副本,不参与校验;
-- 没有这一列时用户只能看一次,而 MCP 客户端经常要回头取 Key。
alter table if exists crm_user_mcp_key
add column if not exists secret_plain varchar(128);
-- 回滚:
-- drop index if exists idx_crm_user_mcp_key_user;
-- drop table if exists crm_user_mcp_key;