diff --git a/backend/src/main/java/com/unis/crm/common/LenientDateTimeParser.java b/backend/src/main/java/com/unis/crm/common/LenientDateTimeParser.java new file mode 100644 index 00000000..b0aa1bf8 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/common/LenientDateTimeParser.java @@ -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 parseOffsetDateTime(String rawValue) { + String normalized = normalize(rawValue); + if (normalized == null) { + return Optional.empty(); + } + + Optional 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 parseLocalDate(String rawValue) { + Optional 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 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(); + } + } +} diff --git a/backend/src/main/java/com/unis/crm/common/UserMcpKeySchemaInitializer.java b/backend/src/main/java/com/unis/crm/common/UserMcpKeySchemaInitializer.java new file mode 100644 index 00000000..ef4e2259 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/common/UserMcpKeySchemaInitializer.java @@ -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); + } + } +} diff --git a/backend/src/main/java/com/unis/crm/controller/UserMcpKeyController.java b/backend/src/main/java/com/unis/crm/controller/UserMcpKeyController.java new file mode 100644 index 00000000..2aea019b --- /dev/null +++ b/backend/src/main/java/com/unis/crm/controller/UserMcpKeyController.java @@ -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(@RequestHeader("X-User-Id") Long userId) { + return ApiResponse.success(service.listMyKeys(CurrentUserUtils.requireCurrentUserId(userId))); + } + + @GetMapping("/legacy") + public ApiResponse getLegacy(@RequestHeader("X-User-Id") Long userId) { + return ApiResponse.success(service.getLegacyCredential(CurrentUserUtils.requireCurrentUserId(userId))); + } + + @PostMapping("/legacy/generate") + public ApiResponse generateLegacy(@RequestHeader("X-User-Id") Long userId) { + return ApiResponse.success(service.generateLegacyCredential(CurrentUserUtils.requireCurrentUserId(userId))); + } + + @PostMapping + public ApiResponse 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 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 delete( + @RequestHeader("X-User-Id") Long userId, + @PathVariable("keyId") Long keyId) { + service.deleteKey(CurrentUserUtils.requireCurrentUserId(userId), keyId); + return ApiResponse.success(null); + } +} diff --git a/backend/src/main/java/com/unis/crm/dto/mcp/CreateUserMcpKeyRequest.java b/backend/src/main/java/com/unis/crm/dto/mcp/CreateUserMcpKeyRequest.java new file mode 100644 index 00000000..0158dff6 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/dto/mcp/CreateUserMcpKeyRequest.java @@ -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; + } +} diff --git a/backend/src/main/java/com/unis/crm/dto/mcp/LegacyBotCredentialDTO.java b/backend/src/main/java/com/unis/crm/dto/mcp/LegacyBotCredentialDTO.java new file mode 100644 index 00000000..f94dd04a --- /dev/null +++ b/backend/src/main/java/com/unis/crm/dto/mcp/LegacyBotCredentialDTO.java @@ -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; + } +} diff --git a/backend/src/main/java/com/unis/crm/dto/mcp/UserMcpKeyDTO.java b/backend/src/main/java/com/unis/crm/dto/mcp/UserMcpKeyDTO.java new file mode 100644 index 00000000..314481fd --- /dev/null +++ b/backend/src/main/java/com/unis/crm/dto/mcp/UserMcpKeyDTO.java @@ -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; + } +} diff --git a/backend/src/main/java/com/unis/crm/dto/opportunity/UpdateOpportunityIntegrationRequest.java b/backend/src/main/java/com/unis/crm/dto/opportunity/UpdateOpportunityIntegrationRequest.java index 40a568af..20e88641 100644 --- a/backend/src/main/java/com/unis/crm/dto/opportunity/UpdateOpportunityIntegrationRequest.java +++ b/backend/src/main/java/com/unis/crm/dto/opportunity/UpdateOpportunityIntegrationRequest.java @@ -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 { + + @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 { + + @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); + } + }); + } + } } diff --git a/backend/src/main/java/com/unis/crm/entity/UserMcpKey.java b/backend/src/main/java/com/unis/crm/entity/UserMcpKey.java new file mode 100644 index 00000000..052abff7 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/entity/UserMcpKey.java @@ -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; + } +} diff --git a/backend/src/main/java/com/unis/crm/llm/security/CompositeMcpBotAuthService.java b/backend/src/main/java/com/unis/crm/llm/security/CompositeMcpBotAuthService.java new file mode 100644 index 00000000..a22b0620 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/llm/security/CompositeMcpBotAuthService.java @@ -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 + * 走完全相同的校验、身份装载和访问记录逻辑。 + * + *

必须标 {@link Primary}:框架的 UnisBaseCoreAutoConfiguration 会 @ComponentScan("com.unisbase") + * 扫到自带的 {@link com.unisbase.llm.auth.McpBotAuthServiceImpl}(它本身是 @Service),于是 + * {@link com.unisbase.llm.auth.McpBotAuthService} 有两个候选 bean,而 McpBotAuthenticationFilter + * 按类型注入 —— 不指定首选会直接启动失败(原 key 也就一起用不了)。 + * + *

原有 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 tenantIds = sysTenantUserMapper.selectTenantIdsByUserIdIgnoreTenant(userId); + if (tenantIds == null) { + tenantIds = List.of(); + } + boolean platformAdmin = Boolean.TRUE.equals(user.getIsPlatformAdmin()); + Long tenantId = resolveTenantId(platformAdmin, tenantIds, requestedTenantHeader); + + Set 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 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"); + } + } +} diff --git a/backend/src/main/java/com/unis/crm/mapper/UserMcpKeyMapper.java b/backend/src/main/java/com/unis/crm/mapper/UserMcpKeyMapper.java new file mode 100644 index 00000000..bec9f354 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/mapper/UserMcpKeyMapper.java @@ -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 { + + @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 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); + +} diff --git a/backend/src/main/java/com/unis/crm/service/UserMcpKeyService.java b/backend/src/main/java/com/unis/crm/service/UserMcpKeyService.java new file mode 100644 index 00000000..f45b3744 --- /dev/null +++ b/backend/src/main/java/com/unis/crm/service/UserMcpKeyService.java @@ -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 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 listMyKeys(Long userId) { + List 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 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 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; + } +} diff --git a/backend/src/test/java/com/unis/crm/controller/OpportunityIntegrationControllerWebMvcTest.java b/backend/src/test/java/com/unis/crm/controller/OpportunityIntegrationControllerWebMvcTest.java index 28c4149e..c8ee110e 100644 --- a/backend/src/test/java/com/unis/crm/controller/OpportunityIntegrationControllerWebMvcTest.java +++ b/backend/src/test/java/com/unis/crm/controller/OpportunityIntegrationControllerWebMvcTest.java @@ -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 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 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()); + } } diff --git a/backend/src/test/java/com/unis/crm/llm/security/McpAuthServicePrimaryBeanTest.java b/backend/src/test/java/com/unis/crm/llm/security/McpAuthServicePrimaryBeanTest.java new file mode 100644 index 00000000..5d8428bb --- /dev/null +++ b/backend/src/test/java/com/unis/crm/llm/security/McpAuthServicePrimaryBeanTest.java @@ -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 的唯一首选门。 + * + *

框架的 UnisBaseCoreAutoConfiguration 带 {@code @ComponentScan("com.unisbase")},会把自带的 + * {@link McpBotAuthServiceImpl}({@code @Service})扫成 bean;本仓库的 {@link CompositeMcpBotAuthService} + * 实现同一个 {@link McpBotAuthService},于是容器里有两个候选。而 starter 里的 + * {@code McpBotAuthenticationFilter} 是按类型注入 {@code McpBotAuthService} 的 —— 没有首选 bean + * 就直接 NoUniqueBeanDefinitionException,整个 /mcp 起不来,**原有 Bot 凭证会跟着一起用不了**。 + * + *

统一认证要求:{@link CompositeMcpBotAuthService} 必须同时识别旧 {@code bot_} 凭证和 + * 新 {@code mcp_} Key,并用同一套 buildLoginUser/resolveTenantId 身份装载逻辑,不能把旧 + * 凭证整权委托给框架实现。"调用逻辑一样" 是这次需求的核心,不是可选优化。 + * + *

为什么用注解显式钉而不是跑一次上下文:这条约束只在启动期暴露,且踩到的时候症状是 + * 「/mcp 全挂」,看不出和「新加了多 key 支持」有什么联系。删掉 @Primary 的改动看起来完全无害。 + * + *

同时钉住「只有一个实现标了 @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 记录"); + } +} diff --git a/backend/src/test/java/com/unis/crm/service/UserMcpKeyServiceTest.java b/backend/src/test/java/com/unis/crm/service/UserMcpKeyServiceTest.java new file mode 100644 index 00000000..91d7ac60 --- /dev/null +++ b/backend/src/test/java/com/unis/crm/service/UserMcpKeyServiceTest.java @@ -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 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 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; + } +} diff --git a/backend/src/test/java/com/unis/crm/service/impl/OpportunityServiceImplTest.java b/backend/src/test/java/com/unis/crm/service/impl/OpportunityServiceImplTest.java index e1c8864f..ab018bc3 100644 --- a/backend/src/test/java/com/unis/crm/service/impl/OpportunityServiceImplTest.java +++ b/backend/src/test/java/com/unis/crm/service/impl/OpportunityServiceImplTest.java @@ -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); diff --git a/docs/OMS接口整理.md b/docs/OMS接口整理.md index 41c41858..36ae6c99 100644 --- a/docs/OMS接口整理.md +++ b/docs/OMS接口整理.md @@ -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`。 | diff --git a/docs/opportunity-integration-api.md b/docs/opportunity-integration-api.md index bd13de82..c1427866 100644 --- a/docs/opportunity-integration-api.md +++ b/docs/opportunity-integration-api.md @@ -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 | 备注 | diff --git a/frontend/src/features/crmQuickCreate/shared.tsx b/frontend/src/features/crmQuickCreate/shared.tsx index e54bc623..f0efe5d4 100644 --- a/frontend/src/features/crmQuickCreate/shared.tsx +++ b/frontend/src/features/crmQuickCreate/shared.tsx @@ -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; diff --git a/frontend/src/lib/auth.ts b/frontend/src/lib/auth.ts index c9805379..f4f4f669 100644 --- a/frontend/src/lib/auth.ts +++ b/frontend/src/lib/auth.ts @@ -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("/api/profile/mcp-keys", undefined, true); +} + +export async function createMyMcpKey(name?: string) { + return request("/api/profile/mcp-keys", { + method: "POST", + body: JSON.stringify({ name: name || "" }), + }, true); +} + +export async function updateMyMcpKeyStatus(keyId: CrmId, status: "0" | "1") { + return request(`/api/profile/mcp-keys/${keyId}/status?status=${status}`, { + method: "PUT", + }, true); +} + +export async function deleteMyMcpKey(keyId: CrmId) { + return request(`/api/profile/mcp-keys/${keyId}`, { + method: "DELETE", + }, true); +} + +export async function getLegacyBotCredential() { + return request("/api/profile/mcp-keys/legacy", undefined, true); +} + +export async function generateLegacyBotCredential() { + return request("/api/profile/mcp-keys/legacy/generate", { + method: "POST", + }, true); +} + export async function updateUserProfileById(userId: CrmId, payload: UpdateCurrentUserProfilePayload) { return request(`/api/sys/api/users/${userId}`, { method: "PUT", diff --git a/frontend/src/pages/Opportunities.tsx b/frontend/src/pages/Opportunities.tsx index d27414e3..43957901 100644 --- a/frontend/src/pages/Opportunities.tsx +++ b/frontend/src/pages/Opportunities.tsx @@ -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([]); 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() { )} + + {lowAmountConfirmOpen ? ( + <> + setLowAmountConfirmOpen(false)} + className="fixed inset-0 z-[90] bg-slate-900/40 backdrop-blur-sm dark:bg-slate-950/70" + /> + +

+
+
+
+
+ +
+
+

金额确认

+

+ {LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE} +

+
+
+
+
+
+

当前录入的预计签约金额

+

¥{formatAmount(form.amount)}

+
+
+
+ + +
+
+ + + ) : null} + + {detailItem && ( <> diff --git a/frontend/src/pages/Profile.tsx b/frontend/src/pages/Profile.tsx index e1f14e46..6a72d232 100644 --- a/frontend/src/pages/Profile.tsx +++ b/frontend/src/pages/Profile.tsx @@ -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 ( +
+ + {label} + + {hasValue ? ( + + {revealed ? value : masked} + + ) : ( + + {emptyHint} + + )} + {hasValue ? ( +
+ {disabled ? ( + + 不可用 + + ) : null} + {revealable ? ( + + ) : null} + +
+ ) : null} +
+ ); +} + 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(null); + const [mcpDrawerOpen, setMcpDrawerOpen] = useState(false); + const [mcpKeys, setMcpKeys] = useState([]); + const [legacyCredential, setLegacyCredential] = useState(null); + const [mcpLoading, setMcpLoading] = useState(false); + const [mcpSaving, setMcpSaving] = useState(false); + const [mcpError, setMcpError] = useState(""); + const [mcpName, setMcpName] = useState(""); + // 明文常驻可见,所以不再需要「只显示一次」的临时区;这里只记刚创建的那条,用于高亮 + 默认展开 + const [freshKeyId, setFreshKeyId] = useState(null); + const [copiedField, setCopiedField] = useState(null); + const [visibleSecretIds, setVisibleSecretIds] = useState>(new Set()); const [form, setForm] = useState(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() { /> ) : null} + {mcpDrawerOpen ? ( + +
+
+
+ + MCP 地址 +
+
+ undefined} + onCopy={() => void copyText(mcpEndpoint, "endpoint")} + /> +
+

+ 请求头 X-Bot-Id 填 ID,X-Bot-Secret 填 Key。Key 创建后长期可见,忘了随时回来复制。 +

+
+ +
+
+ + +
+
+ + {mcpError ? ( +
+ {mcpError} +
+ ) : null} + +
+
+ + 我的 Key + + {mcpKeys.length} + +
+ + {mcpLoading ? ( +
正在加载 MCP Key...
+ ) : mcpKeys.length === 0 ? ( +
还没有创建过 MCP Key,先创建一个试试。
+ ) : ( +
+ {mcpKeys.map((key) => { + const rowKey = String(key.keyId ?? key.id); + const isFresh = Boolean(freshKeyId) && key.keyId === freshKeyId; + return ( +
+
+
+ + {displayText(key.name)} + + + {key.status === "0" ? "已启用" : "已禁用"} + + {isFresh ? ( + + 新创建 + + ) : null} +
+
+ + +
+
+ +
+ undefined} + onCopy={() => void copyText(key.keyId || "", `${rowKey}-id`)} + /> + toggleSecretVisibility(rowKey)} + onCopy={() => void copyText(key.secret || "", `${rowKey}-secret`)} + /> +
+ +
+ 创建:{formatDateTime(key.createdAt) || "未知"} + 最近访问:{formatDateTime(key.lastAccessTime) || "从未"} + {key.lastAccessIp ? IP:{key.lastAccessIp} : null} +
+
+ ); + })} +
+ )} +
+ +
+ + + + 原有 Bot 凭证 + + 一人一个 + + + + + +
+

+ 这是系统管理端「Bot 凭证」那一把,历史客户端大多用它。数据不迁移、不改写,和新建 Key 用同一个 MCP 地址与调用方式。 +

+ + {legacyCredential?.keyId ? ( +
+ undefined} + onCopy={() => void copyText(legacyCredential.keyId || "", "legacy-id")} + /> + toggleSecretVisibility("legacy")} + onCopy={() => void copyText(legacyCredential.secret || "", "legacy-secret")} + /> +
+ ) : ( +
还没有生成过 Bot 凭证。
+ )} + +
+ + 状态:{legacyCredential?.bound ? "已生成" : "未生成"} + {legacyCredential?.lastAccessTime ? ` · 最近访问:${formatDateTime(legacyCredential.lastAccessTime)}` : ""} + {legacyCredential?.lastAccessIp ? ` · IP:${legacyCredential.lastAccessIp}` : ""} + + +
+ + {legacyCredential?.bound ? ( +

+ 重置会立刻让旧 Key 失效,且这把凭证的 Key 只在重置后显示一次,请先确认所有客户端都能同步更新。 +

+ ) : null} +
+
+
+
+ ) : null} {helpDialogOpen ? ( (sharedDefaultQuickChannelForm); const [quickOpportunityForm, setQuickOpportunityForm] = useState(defaultQuickOpportunityForm); const [quickOpportunityDuplicateOpen, setQuickOpportunityDuplicateOpen] = useState(false); + const [quickOpportunityLowAmountConfirmOpen, setQuickOpportunityLowAmountConfirmOpen] = useState(false); const [quickOpportunityDuplicateExact, setQuickOpportunityDuplicateExact] = useState(false); const [quickOpportunityDuplicateItems, setQuickOpportunityDuplicateItems] = useState([]); const [quickOpportunityCompetitors, setQuickOpportunityCompetitors] = useState([]); @@ -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 ? ( + <> + setQuickOpportunityLowAmountConfirmOpen(false)} + className="fixed inset-0 z-[90] bg-slate-900/40 backdrop-blur-sm dark:bg-slate-950/70" + /> + +
+
+
+
+
+ +
+
+

金额确认

+

+ {LOW_OPPORTUNITY_AMOUNT_CONFIRM_MESSAGE} +

+
+
+
+
+
+

当前录入的预计签约金额

+

¥{new Intl.NumberFormat("zh-CN").format(Number(quickOpportunityForm.amount || 0))}

+
+
+
+ + +
+
+ + + ) : null} + {locationAdjustOpen && checkInForm.latitude && checkInForm.longitude ? (