Compare commits

31 Commits

Author SHA1 Message Date
MHW
4a0602ce4e Merge branch 'refs/heads/develop' 2026-03-17 21:22:30 +08:00
MHW
8844830afc 修复lombok导致打包冲突 2026-03-17 21:21:48 +08:00
MHW
bcc450141e 保存场景关系 2026-03-17 11:08:30 +08:00
MHW
25e6ac1cbe Merge branch 'refs/heads/develop' 2026-03-17 11:07:52 +08:00
MHW
8b2f4dab89 保存场景关系 2026-03-17 11:07:35 +08:00
MHW
4f60d68c4f Merge remote-tracking branch 'origin/master' 2026-03-17 10:49:52 +08:00
MHW
b63ad360d0 新增通信关系 2026-03-17 10:49:21 +08:00
libertyspy
c724a7acf7 UPDATE: VERSION-20260317 2026-03-17 10:21:00 +08:00
libertyspy
185e490560 UPDATE: VERSION-20260317 2026-03-17 10:06:55 +08:00
libertyspy
d13359c803 UPDATE: VERSION-20260317 2026-03-17 00:36:54 +08:00
libertyspy
65ea1cfd6b UPDATE: VERSION-20260317 2026-03-17 00:36:46 +08:00
libertyspy
4455d38a61 UPDATE: VERSION-20260317 2026-03-17 00:36:40 +08:00
libertyspy
6dd4392f0c UPDATE: VERSION-20260317 2026-03-17 00:36:16 +08:00
libertyspy
974f403784 UPDATE: VERSION-20260316 2026-03-16 22:43:12 +08:00
libertyspy
82bbfb83ca UPDATE: VERSION-20260316 2026-03-16 15:49:43 +08:00
libertyspy
fc7b5e6c63 Merge remote-tracking branch 'origin/master' 2026-03-16 15:48:53 +08:00
libertyspy
8dc867acb6 UPDATE: VERSION-20260316 2026-03-16 15:48:33 +08:00
libertyspy
c17197d6e5 UPDATE: VERSION-20260316 2026-03-16 15:48:23 +08:00
76022cf09a 修改xml 中的sql 解决,报错问题 2026-03-16 11:24:32 +08:00
MHW
4ff5bf500c Merge remote-tracking branch 'origin/master' 2026-03-16 10:47:48 +08:00
MHW
be417189e0 Merge branch 'refs/heads/develop' 2026-03-16 10:47:38 +08:00
MHW
a88d74ea1d 26-03-16-10:46 FireRuleMapper.xml文件名更正 2026-03-16 10:47:06 +08:00
libertyspy
c2bfb43d41 UPDATE: VERSION-20260315 2026-03-15 20:28:06 +08:00
libertyspy
c5d81a4c52 UPDATE: VERSION-20260315 2026-03-15 20:24:50 +08:00
libertyspy
6d76cb8d5e UPDATE: VERSION-20260315 2026-03-15 20:21:07 +08:00
libertyspy
b97837ec6a UPDATE: VERSION-20260315 2026-03-15 20:20:56 +08:00
libertyspy
f2e81c6e5c UPDATE: VERSION-20260315 2026-03-15 19:32:20 +08:00
libertyspy
83a38c6db8 UPDATE: VERSION-20260315 2026-03-15 16:36:07 +08:00
libertyspy
22e71a24d3 UPDATE: VERSION-20260315 2026-03-15 16:15:23 +08:00
libertyspy
6019738aca UPDATE: VERSION-20260314 2026-03-15 16:05:41 +08:00
MHW
7847dbc89f 26-03-15-09:53 火力规则模块:获取通信组件的所有平台和组件 增加返回平台description字段 2026-03-15 09:54:20 +08:00
61 changed files with 1657 additions and 350 deletions

View File

@@ -53,12 +53,21 @@ public class FireRuleController extends BaseController {
return success(ruleService.getCommPlatformComponentNames(scenarioId));
}
/**
* 根据场景id获取所有平台及其组件
* @param scenarioId
* @return
*/
@GetMapping("/platforms/{scenarioId}")
@ApiOperation("获取通信组件的所有平台和组件")
public AjaxResult platforms(@PathVariable Integer scenarioId){
public AjaxResult platformsScenarioId(@PathVariable Integer scenarioId){
return success(ruleService.findPlatformComponents(scenarioId));
}
@GetMapping("/platforms")
public AjaxResult platforms(){
return success(ruleService.findAllPlatformComponents());
}
/**
* 根据平台id获取平台下所有组件
* @param platformId

View File

@@ -1,4 +1,4 @@
package com.solution.scene.controller;
package com.solution.web.controller.scene;
import com.solution.common.annotation.Log;
import com.solution.common.core.controller.BaseController;
@@ -6,6 +6,7 @@ import com.solution.common.core.domain.AjaxResult;
import com.solution.common.core.page.TableDataInfo;
import com.solution.common.enums.BusinessType;
import com.solution.scene.domain.AfsimScenario;
import com.solution.scene.domain.AfsimScenarioForm;
import com.solution.scene.service.SceneService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -34,7 +35,7 @@ public class SceneController extends BaseController {
@Log(title = "行为树主", businessType = BusinessType.INSERT)
public AjaxResult saveSceneConfig(@RequestBody AfsimScenario afsimScenario)
{
return toAjax(sceneService.insert(afsimScenario));
return toAjax(sceneService.saveOrUpdate(afsimScenario));
}
/**

View File

@@ -113,6 +113,12 @@
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>

View File

@@ -6,4 +6,6 @@ public class PlatformAndModuleConstants {
public static final String RED_NEBO_M_1 = "red_nebo_m_1";
public static final String RED_NEBO_M_2 = "red_nebo_m_2";
public static final String RED_TANK_1 = "red_tank_1";
}

View File

@@ -24,10 +24,6 @@
<artifactId>solution-common</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>

View File

@@ -14,4 +14,7 @@ public class PlatformComponentNamesVO {
@ApiModelProperty("该平台下的组件名称列表(去重)")
private List<String> componentNames;
@ApiModelProperty("平台描述")
private String platformDescription;
}

View File

@@ -38,8 +38,6 @@ public class WarplaneHandler extends AbstractRuleChainHandler {
List<PlatformWeaponAggregateVO> resultWeapons = new ArrayList<>();
//TODO获取所有组件以及count
Iterator<WeaponModelDTO> iterator = dtoList.iterator();
while (iterator.hasNext()) {
WeaponModelDTO dto = iterator.next();

View File

@@ -42,4 +42,6 @@ public interface FireRuleMapper {
List<PlatformComponent> getComponents(Integer platformId);
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
}

View File

@@ -39,5 +39,12 @@ public interface FireRuleService {
*/
List<PlatformComponent> getComponents(Integer platformId);
/**
* 根据场景id获取所有平台及其组件
* @param scenarioId
* @return
*/
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
}

View File

@@ -176,4 +176,9 @@ public class FireRuleServiceImpl implements FireRuleService {
return new ArrayList<>();
}
@Override
public List<Platform> findAllPlatformComponents() {
return ruleMapper.findAllPlatformComponents();
}
}

View File

@@ -13,6 +13,7 @@
<resultMap id="PlatformComponentNamesVOResultMap" type="com.solution.rule.domain.vo.PlatformComponentNamesVO">
<result property="platformName" column="platformName"/>
<result property="platformDescription" column="description"/>
<collection property="componentNames" ofType="java.lang.String">
<result column="componentName"/>
</collection>
@@ -55,10 +56,11 @@
parameterType="java.lang.Integer">
SELECT
p.name AS platformName,
pc.name AS componentName
pc.name AS componentName,
p.description AS description
FROM platform p
INNER JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.type = "comm"
WHERE pc.type = 'comm'
AND p.scenario_id = #{scenarioId}
</select>
<select id="getComponents" resultType="com.solution.rule.domain.PlatformComponent"
@@ -94,14 +96,19 @@
</resultMap>
<select id="findPlatformComponents" resultMap="VPlatformMap"
parameterType="java.lang.Integer">
SELECT
SELECT DISTINCT
p.*,
pc.*
FROM platform p
LEFT JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.type = "comm"
WHERE pc.type = 'comm'
AND p.scenario_id = #{scenarioId}
GROUP BY p.id;
ORDER BY p.name,pc.name
</select>
<select id="findAllPlatformComponents" resultMap="VPlatformMap">
SELECT *
FROM platform
</select>
</mapper>

View File

@@ -18,16 +18,18 @@
<dependencies>
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-rule</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-common</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>

View File

@@ -1,5 +1,7 @@
package com.solution.scene.domain;
import java.util.List;
/**
* 场景配置表
* 对应表 afsim_scenario
@@ -11,6 +13,16 @@ public class AfsimScenario {
private String scenarioPath;
private String communicationGraph; // 用于存储场景中的通讯关系
public List<ScenarioRelation> getRelations() {
return relations;
}
public void setRelations(List<ScenarioRelation> relations) {
this.relations = relations;
}
private List<ScenarioRelation> relations;
public Integer getId() {
return id;
}

View File

@@ -0,0 +1,25 @@
package com.solution.scene.domain;
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import java.util.List;
public class AfsimScenarioForm extends AfsimScenario {
private List<ScenarioRelation> relations;
public List<ScenarioRelation> getRelations() {
return relations;
}
public void setRelations(List<ScenarioRelation> relations) {
this.relations = relations;
}
}

View File

@@ -0,0 +1,108 @@
package com.solution.scene.domain;
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
import java.io.Serializable;
public class ScenarioRelation implements Serializable {
private String edgeId;
private String sourceId;
private String sourcePort;
private Platform sourcePlatform;
private PlatformComponent sourceComponent;
private String targetId;
private String targetPort;
private Platform targetPlatform;
private PlatformComponent targetComponent;
public String getEdgeId() {
return edgeId;
}
public void setEdgeId(String edgeId) {
this.edgeId = edgeId;
}
public String getSourceId() {
return sourceId;
}
public void setSourceId(String sourceId) {
this.sourceId = sourceId;
}
public String getSourcePort() {
return sourcePort;
}
public void setSourcePort(String sourcePort) {
this.sourcePort = sourcePort;
}
public Platform getSourcePlatform() {
return sourcePlatform;
}
public void setSourcePlatform(Platform sourcePlatform) {
this.sourcePlatform = sourcePlatform;
}
public PlatformComponent getSourceComponent() {
return sourceComponent;
}
public void setSourceComponent(PlatformComponent sourceComponent) {
this.sourceComponent = sourceComponent;
}
public String getTargetId() {
return targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
public String getTargetPort() {
return targetPort;
}
public void setTargetPort(String targetPort) {
this.targetPort = targetPort;
}
public Platform getTargetPlatform() {
return targetPlatform;
}
public void setTargetPlatform(Platform targetPlatform) {
this.targetPlatform = targetPlatform;
}
public PlatformComponent getTargetComponent() {
return targetComponent;
}
public void setTargetComponent(PlatformComponent targetComponent) {
this.targetComponent = targetComponent;
}
}

View File

@@ -0,0 +1,27 @@
package com.solution.scene.mapper;
import com.solution.scene.domain.AfsimScenarioForm;
import com.solution.scene.domain.ScenarioRelation;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface PlatFormCommunicationMapper {
/**
* 存储通信关系
* @param scenaryId,afsimScenarios
*/
int insert(@Param("scenaryId") Integer scenaryId,
@Param("afsimScenarios") List<ScenarioRelation> afsimScenarios);
/**
* 删除通信关系
* @param scenaryId
* @return
*/
int delete(Integer scenaryId);
}

View File

@@ -1,6 +1,7 @@
package com.solution.scene.mapper;
import com.solution.scene.domain.AfsimScenario;
import com.solution.scene.domain.AfsimScenarioForm;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@@ -15,6 +16,8 @@ public interface SceneMapper {
*/
int insert(AfsimScenario afsimScenario);
int update(AfsimScenario afsimScenario);
/**
* 获取场景列表

View File

@@ -1,6 +1,7 @@
package com.solution.scene.service;
import com.solution.scene.domain.AfsimScenario;
import com.solution.scene.domain.AfsimScenarioForm;
import java.util.List;
@@ -13,6 +14,10 @@ public interface SceneService {
*/
int insert(AfsimScenario afsimScenario);
int update(AfsimScenarioForm afsimScenario);
int saveOrUpdate(AfsimScenario afsimScenario);
/**
* 获取场景列表
* @return

View File

@@ -1,10 +1,13 @@
package com.solution.scene.service.impl;
import com.solution.scene.domain.AfsimScenario;
import com.solution.scene.domain.AfsimScenarioForm;
import com.solution.scene.mapper.PlatFormCommunicationMapper;
import com.solution.scene.mapper.SceneMapper;
import com.solution.scene.service.SceneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@@ -15,11 +18,44 @@ public class SceneServiceImpl implements SceneService {
@Autowired
private SceneMapper sceneMapper;
@Autowired
private PlatFormCommunicationMapper platFormCommunicationMapper;
@Override
public int insert(AfsimScenario afsimScenario) {
return sceneMapper.insert(afsimScenario);
}
@Override
public int update(AfsimScenarioForm afsimScenario) {
return sceneMapper.update(afsimScenario);
}
@Transactional(rollbackFor = Exception.class)
@Override
public int saveOrUpdate(AfsimScenario afsimScenario) {
if (null != afsimScenario.getId() && afsimScenario.getId() > 0) {
// 更新场景
int updated = sceneMapper.update(afsimScenario);
// 先删除通信关系
platFormCommunicationMapper.delete(afsimScenario.getId());
// 再插入通信关系
if (afsimScenario.getRelations() != null && !afsimScenario.getRelations().isEmpty()) {
platFormCommunicationMapper.insert(afsimScenario.getId(), afsimScenario.getRelations());
}
return updated;
} else {
// 新增场景
int inserted = sceneMapper.insert(afsimScenario);
// 确保获取到生成的 ID
if (afsimScenario.getId() != null && afsimScenario.getRelations() != null && !afsimScenario.getRelations().isEmpty()) {
// 存储通信关系
platFormCommunicationMapper.insert(afsimScenario.getId(), afsimScenario.getRelations());
}
return inserted;
}
}
/**
* 获取场景列表
* @return

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.solution.scene.mapper.PlatFormCommunicationMapper">
<insert id="insert" parameterType="com.solution.scene.domain.AfsimScenarioForm">
INSERT INTO platform_communication (scenary_id, command_platform, subordinate_platform, command_comm, subordinate_comm)
VALUES
<foreach collection="afsimScenarios" item="item" separator=",">
(#{scenaryId}, #{item.sourcePlatform.name}, #{item.targetPlatform.name}, #{item.sourceComponent.name}, #{item.targetComponent.name})
</foreach>
</insert>
<delete id="delete" parameterType="java.lang.Integer">
DELETE FROM platform_communication
WHERE scenary_id = #{scenaryId}
</delete>
</mapper>

View File

@@ -4,13 +4,30 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.solution.scene.mapper.SceneMapper">
<insert id="insert" parameterType="com.solution.scene.domain.AfsimScenario">
<resultMap id="SceneMap" type="com.solution.scene.domain.AfsimScenario">
<result property="id" column="id" />
<result property="name" column="name" />
<result property="description" column="description" />
<result property="scenarioPath" column="scenario_path" />
<result property="communicationGraph" column="communication_graph" />
</resultMap>
<insert id="insert" parameterType="com.solution.scene.domain.AfsimScenario" useGeneratedKeys="true" keyProperty="id">
INSERT INTO afsim_scenario (name, description, scenario_path, communication_graph)
VALUES (#{name}, #{description}, #{scenarioPath}, #{communicationGraph})
</insert>
<select id="selectSceneList" resultType="com.solution.scene.domain.AfsimScenario">
<select id="selectSceneList" resultMap="SceneMap">
SELECT id, name, description, scenario_path, communication_graph FROM afsim_scenario
</select>
<insert id="update" parameterType="com.solution.scene.domain.AfsimScenario">
update afsim_scenario
set name=#{name},
description=#{description},
scenario_path=#{scenarioPath},
communication_graph=#{communicationGraph}
where id=#{id}
</insert>
</mapper>

View File

@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1773577091908" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7408" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M285.952 623.616c-94.464 0-171.264-76.8-171.264-171.264s76.8-171.264 171.264-171.264c11.008 0 21.76 1.024 32.512 3.072 16.64 3.072 27.648 19.2 24.32 35.84-3.072 16.64-19.2 27.648-35.84 24.32-6.912-1.28-13.824-2.048-20.736-2.048-60.672 0-109.824 49.152-109.824 109.824s49.152 109.824 109.824 109.824c16.896 0 30.72 13.824 30.72 30.72s-14.08 30.976-30.976 30.976z" fill="#FFFFFF" p-id="7409"></path><path d="M313.088 343.296c-13.824 0-26.624-9.472-29.952-23.552-3.84-15.872-5.632-32.256-5.632-48.896 0-116.48 94.72-211.456 211.456-211.456 55.552 0 108.032 21.504 147.712 60.16 39.68 38.912 62.208 90.624 63.488 146.176 0.512 16.896-13.056 30.976-29.952 31.488h-0.768c-16.64 0-30.208-13.312-30.72-29.952-1.792-80.64-69.12-146.432-150.016-146.432-82.688 0-150.016 67.328-150.016 150.016 0 11.776 1.28 23.296 4.096 34.816 3.84 16.384-6.4 33.024-22.784 36.864-2.304 0.512-4.608 0.768-6.912 0.768z" fill="#FFFFFF" p-id="7410"></path><path d="M702.72 623.616c-16.896 0-30.72-13.824-30.72-30.72s13.824-30.72 30.72-30.72c73.472 0 133.12-59.648 133.12-133.12s-59.648-133.12-133.12-133.12c-8.96 0-18.176 1.024-26.88 2.816-16.64 3.328-32.768-7.424-36.352-24.064-3.328-16.64 7.424-32.768 23.808-36.352 12.8-2.56 26.112-3.84 39.168-3.84 107.264 0 194.56 87.296 194.56 194.56s-87.04 194.56-194.304 194.56z" fill="#FFFFFF" p-id="7411"></path><path d="M286.976 562.176h415.744v61.44H286.976z" fill="#FFFFFF" p-id="7412"></path><path d="M272.896 794.88H209.152v-61.44h63.744c4.608 0 8.448-3.84 8.448-8.448V599.04h61.44v125.952c0 38.656-31.232 69.888-69.888 69.888zM474.112 608.256h61.44v189.44h-61.44zM837.376 807.68H734.72c-38.4 0-69.888-31.232-69.888-69.888v-129.792h61.44v129.792c0 4.608 3.84 8.448 8.448 8.448h102.656v61.44z" fill="#FFFFFF" p-id="7413"></path><path d="M142.336 875.776c-59.392 0-107.52-48.128-107.52-107.52s48.128-107.52 107.52-107.52 107.52 48.128 107.52 107.52-48.128 107.52-107.52 107.52z m0-153.6c-25.344 0-46.08 20.736-46.08 46.08s20.736 46.08 46.08 46.08 46.08-20.736 46.08-46.08-20.736-46.08-46.08-46.08zM501.76 977.152c-59.392 0-107.52-48.128-107.52-107.52s48.128-107.52 107.52-107.52 107.52 48.128 107.52 107.52-48.384 107.52-107.52 107.52z m0-153.6c-25.344 0-46.08 20.736-46.08 46.08s20.736 46.08 46.08 46.08 46.08-20.736 46.08-46.08-20.736-46.08-46.08-46.08zM888.576 881.664c-59.392 0-107.52-48.128-107.52-107.52s48.128-107.52 107.52-107.52 107.52 48.128 107.52 107.52-48.384 107.52-107.52 107.52z m0-153.6c-25.344 0-46.08 20.736-46.08 46.08s20.736 46.08 46.08 46.08 46.08-20.736 46.08-46.08-20.736-46.08-46.08-46.08z" fill="#FFFFFF" p-id="7414"></path></svg>

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@@ -1291,6 +1291,10 @@
}
}
.ant-select:not(.ant-select-customize-input) .ant-select-selector{
border: 1px solid #475f71
}
.ant-input-affix-wrapper.ant-input-password input:-webkit-autofill,
.ant-input-affix-wrapper.ant-input-password input:-webkit-autofill:hover,
.ant-input-affix-wrapper.ant-input-password input:-webkit-autofill:focus,
@@ -1504,9 +1508,7 @@
border-inline-end-width: 1px;
}
}
.ant-select:not(.ant-select-customize-input) .ant-select-selector{
border: 1px solid #2c2a2a;
}
.ant-select .ant-select-selection-placeholder,
.ant-select .ant-select-selection-search-input{
background: transparent

View File

@@ -274,8 +274,11 @@ const getAlgorithmTypeName = (type: NullableString): NullableString => {
const load = () => {
algorithms.value = [];
algorithmsTotal.value = 0;
formRef.value?.resetFields();
selectedAlgorithm.value = resolveItem(defaultAlgorithm);
if(selectedAlgorithm.value.id <= 0){
formRef.value?.resetFields();
selectedAlgorithm.value = resolveItem(defaultAlgorithm);
}
findAlgorithmsByQuery(query.value).then(r => {
algorithms.value = r.rows ?? [];

View File

@@ -1,11 +0,0 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
export { createGraphCanvas } from './graph';
export * from './hooks';

View File

@@ -8,7 +8,8 @@
*/
import { HttpRequestClient } from '@/utils/request';
import type { PlatformWithComponentsResponse, ScenarioPageableResponse, ScenarioRequest } from './types';
import type { Scenario, ScenarioPageableResponse, ScenarioRequest } from './types';
import type { PlatformWithComponentsResponse } from '../types';
import type { BasicResponse } from '@/types';
const req = HttpRequestClient.create<BasicResponse>({
@@ -16,20 +17,7 @@ const req = HttpRequestClient.create<BasicResponse>({
});
export const findScenarioByQuery = (_query: Partial<ScenarioRequest> = {}): Promise<ScenarioPageableResponse> => {
return new Promise((resolve) => {
resolve({
code: 200,
msg: null,
total: 1,
rows: [
{
id: 1,
name: '空战场景',
description: null,
},
],
});
});
return req.get('/system/scene/list', _query);
};
export const deleteOneScenarioById = (id: number): Promise<BasicResponse> => {
@@ -37,5 +25,9 @@ export const deleteOneScenarioById = (id: number): Promise<BasicResponse> => {
};
export const findPlatformWithComponents = (id: number): Promise<PlatformWithComponentsResponse> => {
return req.get(`system/firerule/platforms/${id}`);
return req.get(`/system/firerule/platforms/${id}`);
};
export const saveScenario = (scenario: Scenario): Promise<BasicResponse> => {
return req.postJson(`/system/scene/saveSceneConfig`,scenario);
};

View File

@@ -6,11 +6,13 @@
<div class="ks-model-builder-body">
<div class="ks-model-builder-left">
<PlatformCard
ref="treesCardRef"
@create-tree="handleCreateTree"
@select-tree="handleSelectTree"
ref="scenariosCardRef"
@create="handleCreate"
@select="handleSelect"
/>
<NodesCard
v-if="currentScenario && currentScenario.id >0"
:scenario="currentScenario"
@drag-item-start="handleDragStart"
@drag-item-end="handleDragEnd"
/>
@@ -52,21 +54,20 @@ import { Wrapper } from '@/components/wrapper';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import Header from '../header.vue';
import type { currentScenario, NodeDragTemplate, NodeTemplate } from '../types';
import type { GraphTaskElement, NodeGraph } from '../builder/element';
import { useGraphCanvas } from '../builder/hooks';
import { registerNodeElement } from '../builder/register';
import { createLineOptions } from '../builder/line';
import { createTree, findOneTreeById, updateTree } from '../designer/api';
import { createGraphTaskElement, hasElements, hasRootElementNode, resolveNodeGraph } from '../builder/utils';
import { createGraphTaskElementFromTemplate } from '../utils/node';
import type { PlatformWithComponents, Scenario } from './types';
import { createGraphTaskElement, createLineOptions, type GraphContainer, type GraphTaskElement, resolveGraph, useGraphCanvas } from '../graph';
import { registerScenarioElement } from './register';
import { createGraphScenarioElement, createGraphTaskElementFromScenario } from './utils';
import PlatformCard from './platform-card.vue';
import NodesCard from './nodes-card.vue';
import { saveScenario } from './api';
import {resolveConnectionRelation} from './relation'
const TeleportContainer = defineComponent(getTeleport());
registerNodeElement();
registerScenarioElement();
export default defineComponent({
components: {
@@ -84,15 +85,15 @@ export default defineComponent({
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
const draggedNodeData = ref<NodeDragTemplate | null>(null);
const draggedNodeData = ref<PlatformWithComponents | null>(null);
const isDraggingOver = ref(false);
const currentTreeEditing = ref<boolean>(false);
const currentScenario = ref<currentScenario | null>(null);
const currentNodeGraph = ref<NodeGraph | null>(null);
const currentScenarioEditing = ref<boolean>(false);
const currentScenario = ref<Scenario | null>(null);
const currentGraph = ref<GraphContainer | null>(null);
const selectedModelNode = ref<Node<NodeProperties> | null>(null);
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
const changed = ref<boolean>(false);
const treesCardRef = ref<InstanceType<typeof PlatformCard> | null>(null);
const scenariosCardRef = ref<InstanceType<typeof PlatformCard> | null>(null);
const {
handleGraphEvent,
@@ -105,7 +106,7 @@ export default defineComponent({
} = useGraphCanvas();
// 处理拖动开始
const handleDragStart = (nm: NodeDragTemplate) => {
const handleDragStart = (nm: PlatformWithComponents) => {
draggedNodeData.value = nm;
};
@@ -142,10 +143,10 @@ export default defineComponent({
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = false;
currentTreeEditing.value = false;
currentScenarioEditing.value = false;
if (!currentScenario.value) {
message.error('请先选择或者创建行为树.');
message.error('请先选择场景.');
return;
}
@@ -156,17 +157,17 @@ export default defineComponent({
try {
// 获取拖动的数据
const template = draggedNodeData.value as NodeDragTemplate;
const pwc = draggedNodeData.value as PlatformWithComponents;
if (!hasElements(graph.value as Graph) && template.type !== 'root') {
message.error('请先添加根节点.');
return;
}
// if (!hasElements(graph.value as Graph)) {
// message.error('请先添加根节点.');
// return;
// }
if (hasRootElementNode(graph.value as Graph) && template.type === 'root') {
message.error('根节点已经存在.');
return;
}
// if (hasRootElementNode(graph.value as Graph)) {
// message.error('根节点已经存在.');
// return;
// }
// 计算相对于画布的位置(考虑缩放)
const rect = canvas.value.getBoundingClientRect();
@@ -174,12 +175,12 @@ export default defineComponent({
const x = (e.clientX - rect.left) / scale;
const y = (e.clientY - rect.top) / scale;
console.log('放置节点:', { ...template, x, y });
console.log('放置节点:', { ...pwc, x, y });
// 创建节点数据
const settingTaskElement: GraphTaskElement = createGraphTaskElementFromTemplate(template, { x, y });
const settingTaskElement: GraphTaskElement = createGraphTaskElementFromScenario(pwc, { x, y });
// 创建节点
const settingTaskNode = createGraphTaskElement(settingTaskElement);
const settingTaskNode = createGraphScenarioElement(settingTaskElement);
console.info('create settingTaskNode: ', settingTaskElement, settingTaskNode);
// 将节点添加到画布
@@ -193,32 +194,26 @@ export default defineComponent({
}
};
const handleSelectTree = (tree: currentScenario) => {
console.info('handleSelectTree', tree);
findOneTreeById(tree.id).then(r => {
if (r.data) {
let nodeGraph: NodeGraph | null = null;
try {
nodeGraph = JSON.parse(r.data?.xmlContent as unknown as string) as unknown as NodeGraph;
} catch (e: any) {
console.error('parse error,cause:', e);
}
if (!nodeGraph) {
nodeGraph = {
nodes: [],
edges: [],
};
}
currentScenario.value = {
...r.data,
graph: nodeGraph,
};
currentTreeEditing.value = true;
createElements();
} else {
message.error(r.msg ?? '行为树不存在.');
}
});
const handleSelect = (scenario: Scenario) => {
let nodeGraph: GraphContainer | null = null;
try {
nodeGraph = JSON.parse(scenario.communicationGraph as unknown as string) as unknown as GraphContainer;
} catch (e: any) {
console.error('parse error,cause:', e);
}
if (!nodeGraph) {
nodeGraph = {
nodes: [],
edges: [],
};
}
currentScenario.value = {
...scenario,
graph: nodeGraph,
relations: []
};
currentScenarioEditing.value = true;
createElements();
};
const createElements = () => {
@@ -232,8 +227,7 @@ export default defineComponent({
if (currentScenario.value?.graph && graph.value) {
if (currentScenario.value?.graph.nodes) {
currentScenario.value?.graph.nodes.forEach(ele => {
const node = createGraphTaskElement(ele as GraphTaskElement);
console.info('create node: ', ele);
const node = createGraphScenarioElement(ele as GraphTaskElement);
// 将节点添加到画布
graph.value?.addNode(node as Node);
});
@@ -254,21 +248,19 @@ export default defineComponent({
});
};
const handleCreateTree = () => {
const handleCreate = () => {
currentScenario.value = {
id: 0,
name: '行为树',
name: null,
description: null,
englishName: null,
xmlContent: null,
createdAt: null,
communicationGraph: null,
relations: [],
graph: {
edges: [],
nodes: [],
},
updatedAt: null,
};
currentNodeGraph.value = {
currentGraph.value = {
edges: [],
nodes: [],
};
@@ -298,7 +290,7 @@ export default defineComponent({
handleGraphEvent('blank:click', () => {
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
currentTreeEditing.value = null !== currentScenario.value;
currentScenarioEditing.value = null !== currentScenario.value;
});
handleGraphEvent('node:click', (args: any) => {
@@ -348,34 +340,35 @@ export default defineComponent({
};
const handleSave = () => {
const graphData: NodeGraph = resolveNodeGraph(graph.value as Graph);
const graphData: GraphContainer = resolveGraph(graph.value as Graph);
const relations = resolveConnectionRelation(graph.value as Graph);
console.error('relations',relations)
console.info('handleSave', graphData);
if (!currentScenario.value) {
message.error('当前决策树不存在');
return;
}
const newTree: currentScenario = {
const newScenario: Scenario = {
...currentScenario.value,
graph: graphData,
xmlContent: JSON.stringify(graphData),
communicationGraph: JSON.stringify(graphData),
relations: relations
};
if (!newTree.name) {
message.error('行为树名称不能为空.');
return;
}
if (!newTree.englishName) {
message.error('行为树英文名称不能为空.');
if (!newScenario.name) {
message.error('场景名称不能为空.');
return;
}
let res = null;
if (currentScenario.value.id > 0) {
res = createTree(newTree);
res = saveScenario(newScenario);
} else {
res = updateTree(newTree);
res = saveScenario(newScenario);
}
res.then(r => {
if (r.code === 200) {
treesCardRef.value?.refresh();
scenariosCardRef.value?.refresh();
message.success(r.msg ?? '操作成功.');
} else {
message.error(r.msg ?? '操作失败.');
@@ -403,11 +396,11 @@ export default defineComponent({
});
return {
treesCardRef,
handleCreateTree,
currentTreeEditing,
scenariosCardRef,
handleCreate,
currentScenarioEditing,
currentScenario,
currentNodeGraph,
currentGraph,
selectedNodeTaskElement,
selectedModelNode,
graph,
@@ -424,7 +417,7 @@ export default defineComponent({
isDraggingOver,
handleSave,
handleUpdateElement,
handleSelectTree,
handleSelect,
};
},
});

View File

@@ -0,0 +1,322 @@
<template>
<a-dropdown :trigger="['contextmenu']" @openChange="handleVisibleChange">
<a-card
:class="[
'ks-scenario-node',
`ks-scenario-${element?.category ?? 'model'}-node`
]"
hoverable
>
<template #title>
<a-space>
<span class="ks-scenario-node-title">{{ element?.description ?? element?.name ?? '-' }}</span>
</a-space>
</template>
<!-- 节点内容区域 -->
<div class="w-full">
<div class="ks-scenario-node-content">
<div
v-for="(item, index) in element?.components || []"
:key="item.id || index"
class="ks-scenario-node-row"
>
<div
:data-port="`in-${item.id || index}`"
:port="`in-${item.id || index}`"
:title="`入桩: ${item.name}`"
class="port port-in"
magnet="passive"
:data-item="JSON.stringify(item)"
>
<div class="triangle-left"></div>
</div>
<!-- child名称 -->
<div class="ks-scenario-node-name">
{{ substring(item.description ?? item.name, 20) }}
</div>
<!-- 右侧出桩只能作为连线源 -->
<div
:data-port="`out-${item.id || index}`"
:port="`out-${item.id || index}`"
:title="`出桩: ${item.name}`"
class="port port-out"
magnet="active"
:data-item="JSON.stringify(item)"
>
<div class="triangle-right" ></div>
</div>
</div>
</div>
</div>
</a-card>
<template #overlay>
<a-menu @click="handleMenuClick">
<a-menu-item key="delete">
<template #icon>
<DeleteOutlined />
</template>
删除
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import { elementProps, type ModelElement } from '../graph';
import { DeleteOutlined, SettingOutlined } from '@ant-design/icons-vue';
import type { Graph } from '@antv/x6';
import { substring } from '@/utils/strings';
export default defineComponent({
name: 'ModelElement',
components: {
SettingOutlined,
DeleteOutlined,
},
props: elementProps,
setup(_props) {
const element = ref<ModelElement | null>(
_props.node ? (_props.node.getData() as ModelElement) : null,
);
const updateKey = ref(0);
const isMenuVisible = ref(false);
// 获取画布实例
const getGraph = (): Graph | null => {
return _props.graph as Graph || null;
};
// 监听节点数据变化
const handleDataChange = () => {
if (_props.node) {
element.value = _props.node.getData() as ModelElement;
} else {
element.value = null;
}
updateKey.value++;
};
const handleVisibleChange = (visible: boolean) => {
isMenuVisible.value = visible;
};
const handleMenuClick = ({ key }: { key: string }) => {
if (key === 'delete') {
handleDelete();
}
};
const handleDelete = () => {
if (!_props.node) return;
const graph = getGraph();
if (graph) {
try {
// 先删除关联边
const connectedEdges = graph.getConnectedEdges(_props.node);
connectedEdges.forEach(edge => graph.removeEdge(edge));
// 再删除节点
graph.removeNode(_props.node);
console.info(`节点 ${_props.node.id} 已删除`);
} catch (error) {
console.error('删除节点失败:', error);
}
}
isMenuVisible.value = false;
};
onMounted(() => {
_props.node?.on('change:data', handleDataChange);
});
onUnmounted(() => {
_props.node?.off('change:data', handleDataChange);
});
return {
element,
substring,
handleMenuClick,
handleVisibleChange,
};
},
});
</script>
<style lang="less">
.ks-scenario-node {
background: linear-gradient(150deg, rgba(108, 99, 255) 1%, rgba(108, 99, 255) 100%);
border-radius: 8px;
width: 100%;
height: 100%;
cursor: pointer;
position: relative;
background: #1e2533;
border: 1px solid #4a7aff;
border: 2px solid #000000;
&:hover {
border: 2px solid #4a7aff;
box-shadow: 0 0 10px rgba(74, 122, 255, 0.3);
}
.ant-card-head {
border: 0;
height: 28px;
min-height: 25px;
border-radius: 0;
color: #fff;
font-size: 12px;
font-weight: normal;
padding: 0 20px;
//background: linear-gradient(to bottom, #3a4c70, #2d3a56);
border-top-left-radius: 8px;
border-top-right-radius: 8px;
background: linear-gradient(to bottom, rgba(108, 99, 255, 0.15), rgba(108, 99, 255, 0.05));
//background: url('@/assets/icons/bg-node-head.png') center / 100% 100%;
//background: linear-gradient(to bottom, rgb(234 234 234 / 20%), rgb(191 191 191 / 58%));
background: url('@/assets/icons/card-head-red.png') center / 100% 100%;
}
.ks-scenario-node-icon {
width: 15px;
height: 15px;
display: block;
position: absolute;
left: 8px;
top: 6px;
background: url('@/assets/icons/icon-node.svg') center / 100% 100%;
}
.ks-scenario-node-title {
font-size: 12px;
color: #fff;
margin-top: -7px;
display: block;
}
.ant-card-body {
color: #f5f5f5;
height: calc(100% - 25px);
border-radius: 0;
font-size: 12px;
padding: 10px 30px !important;
//border-top: 1px solid rgba(108, 99, 255, 0.5);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-shadow: 0 0 10px rgba(74, 122, 255, 0.3);
white-space: normal; // 恢复默认的换行行为
word-wrap: break-word; // 允许长单词换行
word-break: break-all; // 允许在任意字符处换行
line-height: 1.4; // 增加行高提升可读性
box-shadow: 0 0 10px rgba(74, 122, 255, 0.3);
}
// 连接桩容器样式
.ks-scenario-node-content {
width: 100%;
display: flex;
flex-direction: column;
gap: 6px;
}
.ks-scenario-node-row {
width: 100%;
display: flex;
align-items: center;
position: relative;
min-height: 24px;
}
.port {
width: 12px;
height: 12px;
border-radius: 50%;
cursor: crosshair;
flex-shrink: 0;
box-shadow: 0 0 0 2px rgb(108, 99, 255, 0.8);
z-index: 10;
magnet: true;
position: relative;
.triangle-left {
width: 0;
height: 0;
border-top: 4px solid transparent;
border-right: 5px solid #5da1df;
border-bottom: 4px solid transparent;
position: absolute;
left: -8px;
top: 0.5px;
magnet: passive;
}
/* 右三角形 */
.triangle-right {
width: 0;
height: 0;
border-top: 4px solid transparent;
border-left: 5px solid #5da1df;
border-bottom: 4px solid transparent;
position: absolute;
right: -8px;
top: 0.5px;
magnet: passive;
}
}
// 左侧入桩样式
.port-in {
//background-color: #3c82f6;
margin-right: 8px;
//border: 1px solid #093866;
magnet: passive;
box-shadow: none;
width: 13px;
height: 13px;
display: block;
//background: url('@/assets/icons/point.svg') center / 100% 100%;
border: 2px solid #5da1df;
position: absolute;
//top: 7px;
left: -17px;
}
.port-out {
margin-left: 8px;
margin-right: 5px;
magnet: active;
box-shadow: none;
width: 13px;
height: 13px;
display: block;
border: 2px solid #5da1df;
background:#5da1df;
position: absolute;
right: -17px;
}
// 节点文本样式
.ks-scenario-node-name {
flex: 1;
line-height: 24px;
overflow: hidden;
text-overflow: ellipsis;
}
}
</style>

View File

@@ -14,7 +14,7 @@
@dragend="handleDragEnd"
@dragstart="handleDragStart($event, nm)"
>
<img :alt="nm.description ?? nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
<img :alt="nm.description ?? nm.name ?? ''" class="icon" src="@/assets/icons/model.svg" />
<span class="desc">{{ nm.description ?? nm.name }}</span>
</div>
</a-col>
@@ -27,27 +27,28 @@
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { defineComponent, type PropType, ref, watch } from 'vue';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import {findPlatformWithComponents} from './api'
import {type PlatformWithComponents} from './types'
import { findPlatformWithComponents } from './api';
import { type Scenario } from './types';
import { type PlatformWithComponents } from '../types';
export default defineComponent({
emits: ['drag-item-start', 'drag-item-end'],
setup(_props, { emit }) {
props: {
scenario: {
type: Object as PropType<Scenario>,
required: true,
}
},
setup(props, { emit }) {
const activeKey = ref<number>(1);
const templateData = ref<PlatformWithComponents[]>([]);
const isDraggingOver = ref<boolean>(false);
const draggedNodeData = ref<PlatformWithComponents | null>(null);
const loadTress = () => {
templateData.value = []
findPlatformWithComponents(1).then(r => {
templateData.value = r.data ?? []
});
};
const currentScenario = ref<Scenario|null>(props.scenario)
const handleDragStart = (e: DragEvent, nm: PlatformWithComponents) => {
let dragNode: PlatformWithComponents = { ...nm };
draggedNodeData.value = dragNode as PlatformWithComponents;
@@ -70,7 +71,7 @@ export default defineComponent({
`;
document.body.appendChild(dragPreview);
e.dataTransfer.setDragImage(dragPreview, dragPreview.offsetWidth / 2, dragPreview.offsetHeight / 2);
emit('drag-item-start', dragNode, group, isDraggingOver.value, e);
emit('drag-item-start', dragNode, isDraggingOver.value, e);
console.log('开始拖动:', dragNode);
setTimeout(() => document.body.removeChild(dragPreview), 0);
}
@@ -85,16 +86,17 @@ export default defineComponent({
};
const load = ()=> {
findPlatformWithComponents(1).then(re=> {
console.error(re);
const load = (id: number)=> {
findPlatformWithComponents(id).then(re=> {
templateData.value = re.data ?? []
})
}
onMounted(() => {
loadTress();
load();
});
watch(()=> props.scenario,(n: Scenario|null|undefined )=> {
if(n){
load(n.id);
}
}, {deep: true, immediate: true} )
return {
activeKey,

View File

@@ -11,9 +11,9 @@
<div class="w-full" style="padding: 5px;">
<a-flex>
<a-input-search v-model:value="scenarioQuery.name" allowClear placeholder="场景名称" size="small" @search="loadTress" />
<!-- <a-button size="small" style="margin-left: 10px;">-->
<!-- <PlusOutlined style="margin-top: 0px;display: block;" @click="$emit('create-tree')" />-->
<!-- </a-button>-->
<!-- <a-button size="small" style="margin-left: 10px;">-->
<!-- <PlusOutlined style="margin-top: 0px;display: block;" @click="$emit('create-tree')" />-->
<!-- </a-button>-->
</a-flex>
</div>
<a-list :data-source="scenario || []" size="small" style="min-height: 25vh">
@@ -29,18 +29,19 @@
</a-tooltip>
<a-flex class="ks-tree-actions">
<span style="margin-right: 10px" @click="()=> handleSelect(item)"><EditFilled /></span>
<a-popconfirm
title="确定删除?"
@confirm="()=> handleDelete(item)"
>
<span class="ks-tree-action ks-tree-action-delete"><DeleteOutlined /></span>
</a-popconfirm>
<!-- <a-popconfirm-->
<!-- title="确定删除?"-->
<!-- @confirm="()=> handleDelete(item)"-->
<!-- >-->
<!-- <span class="ks-tree-action ks-tree-action-delete"><DeleteOutlined /></span>-->
<!-- </a-popconfirm>-->
</a-flex>
</a-flex>
</a-list-item>
</template>
</a-list>
<a-pagination
v-if="totalTress > Number(scenarioQuery?.pageSize ?? 0)"
v-model:current="scenarioQuery.pageNum"
:page-size="scenarioQuery.pageSize"
:total="totalTress"
@@ -57,7 +58,7 @@ import { deleteOneScenarioById, findScenarioByQuery } from './api';
import { substring } from '@/utils/strings';
export default defineComponent({
emits: ['select-tree', 'create-tree'],
emits: ['select', 'create'],
components: {
CheckOutlined,
PlusOutlined,
@@ -78,6 +79,7 @@ export default defineComponent({
findScenarioByQuery(scenarioQuery.value).then(r => {
scenario.value = r.rows;
totalTress.value = r.total ?? 0;
// emit('select', r.rows[0]);
});
};

View File

@@ -18,10 +18,10 @@
import { register } from '@antv/x6-vue-shape';
import ModelElement from './node.vue';
export const registerNodeElement = () => {
console.info('registerNodeElement');
export const registerScenarioElement = () => {
console.info('registerScenarioElement');
register({
shape: 'task',
shape: 'scenario',
component: ModelElement,
width: 120,
attrs: {

View File

@@ -0,0 +1,134 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { Graph, Node,Edge } from '@antv/x6';
import type { Platform, PlatformComponent, PlatformRelation } from './types';
import type { GraphTaskElement } from '../graph';
/**
* 解析节点端口连接关系(去重版)
* @param graph X6 画布实例
* @returns 去重后的端口连接关系列表
*/
export function resolveConnectionRelation(graph: Graph): PlatformRelation[] {
const edges: Edge[] = graph.getEdges();
const items: PlatformRelation[] = [];
const existsKeys: Set<string> = new Set(); // 改用 Set 提升查询性能
const tempEdgeIds: Set<string> = new Set(); // 存储临时边 ID
// 过滤无效/临时边
const validEdges = edges.filter(edge => {
// 过滤临时边X6 拖拽连线时生成的未完成边)
const isTempEdge = edge?.attr('line/stroke') === 'transparent' || edge.id.includes('temp');
if (isTempEdge) {
tempEdgeIds.add(edge.id);
return false;
}
// 过滤未正确关联节点的边
const sourceCell = edge.getSourceCell();
const targetCell = edge.getTargetCell();
if (!sourceCell || !targetCell || !(sourceCell instanceof Node) || !(targetCell instanceof Node)) {
return false;
}
// 过滤端口 ID 为空的边
const sourcePortId = edge.getSourcePortId();
const targetPortId = edge.getTargetPortId();
if (!sourcePortId || !targetPortId) {
return false;
}
return true;
});
validEdges.forEach(edge => {
try {
const sourceCell = edge.getSourceCell() as Node;
const targetCell = edge.getTargetCell() as Node;
const sourcePortId = edge.getSourcePortId()!;
const targetPortId = edge.getTargetPortId()!;
// 1. 获取端口 DOM 元素和数据
const sourceView = graph.findViewByCell(sourceCell);
const targetView = graph.findViewByCell(targetCell);
if (!sourceView || !targetView) return;
const sourcePortEl = sourceView.container.querySelector(`[data-port="${sourcePortId}"]`);
const targetPortEl = targetView.container.querySelector(`[data-port="${targetPortId}"]`);
if (!sourcePortEl || !targetPortEl) return;
// 2. 解析端口数据
let sourcePortData: PlatformComponent | null = null;
let targetPortData: PlatformComponent | null = null;
try {
const sourceDataAttr = sourcePortEl.getAttribute('data-item');
sourcePortData = sourceDataAttr ? JSON.parse(sourceDataAttr) : null;
} catch (e) {
console.warn(`解析源节点 ${sourceCell.id} 端口 ${sourcePortId} 数据失败`, e);
return; // 数据解析失败直接跳过
}
try {
const targetDataAttr = targetPortEl.getAttribute('data-item');
targetPortData = targetDataAttr ? JSON.parse(targetDataAttr) : null;
} catch (e) {
console.warn(`解析目标节点 ${targetCell.id} 端口 ${targetPortId} 数据失败`, e);
return; // 数据解析失败直接跳过
}
// 过滤端口数据为空的情况
if (!sourcePortData || !targetPortData) return;
// 解析节点平台数据
const sourceData = sourceCell.getData() as GraphTaskElement;
const targetData = targetCell.getData() as GraphTaskElement;
// 过滤平台数据不完整的节点
if (!sourceData.platformId || !targetData.platformId) return;
const sourcePlatform: Platform = {
id: sourceData.platformId as number,
key: sourceData.key,
name: sourceData.name,
description: sourceData.description,
scenarioId: sourceData.scenarioId as number,
};
const targetPlatform: Platform = {
id: targetData.platformId as number,
key: targetData.key,
name: targetData.name,
description: targetData.description,
scenarioId: targetData.scenarioId as number,
};
// 生成唯一标识(支持单向/双向去重
const uniqueKey = `${sourceCell.id}@${sourcePortId}->${targetCell.id}@${targetPortId}`;
if (!existsKeys.has(uniqueKey)) {
existsKeys.add(uniqueKey);
items.push({
sourceId: sourceCell.id,
sourcePort: sourcePortId,
sourcePlatform: sourcePlatform,
sourceComponent: sourcePortData,
targetId: targetCell.id,
targetPort: targetPortId,
targetPlatform: targetPlatform,
targetComponent: targetPortData,
edgeId: edge.id,
});
}
} catch (error) {
console.error(`解析边 ${edge.id} 连接关系失败`, error);
}
});
return items;
}

View File

@@ -9,11 +9,30 @@
import type { ApiDataResponse, NullableString, PageableResponse } from '@/types';
import type { GraphContainer } from '../graph';
import type { Platform, PlatformComponent } from '../types';
export interface PlatformRelation {
sourceId: NullableString,
sourcePort: NullableString,
sourcePlatform: Platform,
sourceComponent: PlatformComponent,
targetId: NullableString,
targetPort: NullableString,
targetPlatform: Platform,
targetComponent: PlatformComponent,
[key: string]: unknown;
}
export interface Scenario {
id: number,
name: NullableString,
description: NullableString,
// 用于存储场景中的通讯关系
communicationGraph: NullableString,
graph: GraphContainer
relations: PlatformRelation[]
}
export interface ScenarioRequest extends Scenario {
@@ -25,25 +44,3 @@ export interface ScenarioPageableResponse extends PageableResponse<Scenario> {
}
export interface Platform {
id: number,
name: NullableString,
description: NullableString,
scenarioId: number,
}
export interface PlatformComponent {
id: number,
name: NullableString,
type: NullableString,
description: NullableString,
platformId: number,
}
export interface PlatformWithComponents extends Platform {
components: PlatformComponent[],
}
export interface PlatformWithComponentsResponse extends ApiDataResponse<PlatformWithComponents[]> {
}

View File

@@ -0,0 +1,128 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import type { GraphRect, GraphTaskElement } from '../graph';
import { generateKey } from '@/utils/strings';
import type { PlatformWithComponents } from './types';
export const createGraphTaskElementFromScenario = (
platform: PlatformWithComponents,
rect?: GraphRect,
): GraphTaskElement => {
let realRect = { width: 120, height: 80, x: 0, y: 0, ...rect || {} };
console.info('rect', rect);
return {
id: 0,
key: generateKey(),
type: 'scenario',
name: platform.name,
platformId: platform.id,
scenarioId: platform.scenarioId,
components: platform.components ?? [],
template: 0,
templateType: null,
category: null,
group: null,
description: platform.description,
order: 0,
position: {
x: realRect.x ?? 0,
y: realRect.y ?? 0,
},
width: realRect.width,
height: realRect.height,
inputs: null,
outputs: null,
parameters: [],
variables: [],
} as GraphTaskElement;
};
const portsGroups = {
in: {
position: 'left', // 入桩在左侧
attrs: {
circle: {
r: 6,
magnet: 'passive', // 被动吸附(仅作为连线目标)
stroke: '#5da1df',
strokeWidth: 2,
fill: '#fff',
},
},
},
out: {
position: 'right', // 出桩在右侧
attrs: {
circle: {
r: 6,
magnet: 'active', // 主动吸附(作为连线源)
stroke: '#5da1df',
strokeWidth: 2,
fill: '#5da1df',
},
},
},
};
export const createGraphScenarioElement = (element: GraphTaskElement): any => {
let realHeight = 120;
let width: number = 250;
if (!realHeight) {
realHeight = 120;
}
if(element?.components){
if(element?.components?.length > 2){
realHeight = 90 + element?.components?.length * 25
} else if(element?.components?.length <=1){
realHeight = 120
}
}
// const portsItems = (element.components || []).map((comp, index) => {
// const compId = comp.id || index;
// return [
// // 入桩(对应 DOM: data-port="in-${compId}"
// {
// id: `in-${compId}`, // portId 必须和 DOM 的 data-port 一致
// group: 'in',
// data: comp, // 直接存储 port 数据,避免后续解析 DOM
// },
// // 出桩(对应 DOM: data-port="out-${compId}"
// {
// id: `out-${compId}`,
// group: 'out',
// data: comp,
// },
// ];
// }).flat(); // 扁平化数组
return {
shape: 'scenario',
id: element.key,
position: {
x: element.position?.x || 0,
y: element.position?.y || 0,
},
size: {
width: width,
height: realHeight,
},
attrs: {
label: {
text: element.name,
},
},
data: element,
// ports: {
// groups: portsGroups,
// items: portsItems,
// },
};
};

View File

@@ -8,7 +8,8 @@
*/
import { HttpRequestClient } from '@/utils/request';
import type { BehaviorTree, BehaviorTreeDetailsResponse, BehaviorTreePageResponse, BehaviorTreeRequest, NodeTemplatesResponse } from '../types';
import type { NodeTemplatesResponse } from './template';
import type { BehaviorTree, BehaviorTreeDetailsResponse, BehaviorTreePageResponse, BehaviorTreeRequest } from './tree';
import type { BasicResponse } from '@/types';
const req = HttpRequestClient.create<BasicResponse>({

View File

@@ -19,27 +19,12 @@
<div class="ks-model-builder-content">
<div class="ks-model-builder-actions">
<a-space>
<!-- <a-tooltip v-if="graph && currentBehaviorTree" placement="top">-->
<!-- <template #title>-->
<!-- 保存-->
<!-- </template>-->
<!-- <a-popconfirm-->
<!-- title="确定保存?"-->
<!-- @confirm="handleSave"-->
<!-- >-->
<!-- <a-button class="ks-model-builder-save" size="small">-->
<!-- <CheckOutlined />-->
<!-- <span>保存</span>-->
<!-- </a-button>-->
<!-- </a-popconfirm>-->
<!-- </a-tooltip>-->
<a-button v-if="graph && currentBehaviorTree" class="ks-model-builder-save" size="small" @click="handleSave">
<CheckOutlined />
<span>保存</span>
</a-button>
</a-space>
</div>
<!-- 画布容器添加拖放事件 -->
<div
ref="canvas"
class="ks-model-builder-canvas"
@@ -74,14 +59,14 @@ import { Wrapper } from '@/components/wrapper';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import Header from '../header.vue';
import Properties from './properties.vue';
import type { BehaviorTree, NodeDragTemplate, NodeTemplate } from '../types';
import type { GraphTaskElement, NodeGraph } from '../builder/element';
import { useGraphCanvas } from '../builder/hooks';
import { registerNodeElement } from '../builder/register';
import { createLineOptions } from '../builder/line';
import type { NodeDragTemplate } from './template';
import type { BehaviorTree } from './tree';
import { createGraphTaskElementFromTemplate } from './utils';
import { createGraphTaskElement, createLineOptions, type GraphContainer, type GraphTaskElement, hasElements, hasRootElementNode, resolveGraph, useGraphCanvas } from '../graph';
import { registerNodeElement } from './register';
import { createTree, findOneTreeById, updateTree } from './api';
import { createGraphTaskElement, hasElements, hasRootElementNode, resolveNodeGraph } from '../builder/utils';
import { createGraphTaskElementFromTemplate } from '../utils/node';
import TressCard from './trees-card.vue';
import NodesCard from './nodes-card.vue';
@@ -110,7 +95,7 @@ export default defineComponent({
const isDraggingOver = ref(false);
const currentTreeEditing = ref<boolean>(false);
const currentBehaviorTree = ref<BehaviorTree | null>(null);
const currentNodeGraph = ref<NodeGraph | null>(null);
const currentGraph = ref<GraphContainer | null>(null);
const selectedModelNode = ref<Node<NodeProperties> | null>(null);
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
const changed = ref<boolean>(false);
@@ -219,9 +204,9 @@ export default defineComponent({
console.info('handleSelectTree', tree);
findOneTreeById(tree.id).then(r => {
if (r.data) {
let nodeGraph: NodeGraph | null = null;
let nodeGraph: GraphContainer | null = null;
try {
nodeGraph = JSON.parse(r.data?.xmlContent as unknown as string) as unknown as NodeGraph;
nodeGraph = JSON.parse(r.data?.xmlContent as unknown as string) as unknown as GraphContainer;
} catch (e: any) {
console.error('parse error,cause:', e);
}
@@ -290,7 +275,7 @@ export default defineComponent({
},
updatedAt: null,
};
currentNodeGraph.value = {
currentGraph.value = {
edges: [],
nodes: [],
};
@@ -370,7 +355,7 @@ export default defineComponent({
};
const handleSave = () => {
const graphData: NodeGraph = resolveNodeGraph(graph.value as Graph);
const graphData: GraphContainer = resolveGraph(graph.value as Graph);
console.info('handleSave', graphData);
if (!currentBehaviorTree.value) {
message.error('当前决策树不存在');
@@ -429,7 +414,7 @@ export default defineComponent({
handleCreateTree,
currentTreeEditing,
currentBehaviorTree,
currentNodeGraph,
currentGraph,
selectedNodeTaskElement,
selectedModelNode,
graph,

View File

@@ -48,8 +48,8 @@
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref } from 'vue';
import { elementProps } from './props';
import type { ModelElement } from './element';
import { elementProps, type ModelElement } from '../graph';
import { DeleteOutlined, SettingOutlined } from '@ant-design/icons-vue';
import type { Graph } from '@antv/x6';
import { substring } from '@/utils/strings';

View File

@@ -71,7 +71,7 @@
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import type { NodeDragTemplate, NodeTemplate } from '../types';
import type { NodeDragTemplate, NodeTemplate } from './template';
import { findNodeTemplates } from './api';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';

View File

@@ -147,8 +147,8 @@
<script lang="ts">
import { defineComponent, onMounted, type PropType, ref, watch } from 'vue';
import { CheckOutlined } from '@ant-design/icons-vue';
import type { ElementVariable, GraphTaskElement } from '../builder/element';
import type { BehaviorTree } from '../types';
import type { ElementVariable, GraphTaskElement } from '../graph';
import type { BehaviorTree } from './tree';
import type { Graph, Node, NodeProperties } from '@antv/x6';
import { generateKey } from '@/utils/strings';

View File

@@ -0,0 +1,41 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { register } from '@antv/x6-vue-shape';
import ModelElement from './node.vue';
export const registerNodeElement = () => {
console.info('registerNodeElement');
register({
shape: 'task',
component: ModelElement,
width: 120,
attrs: {
body: {
stroke: 'transparent',
strokeWidth: 0,
fill: 'transparent',
rx: 4,
ry: 4,
},
},
dragging: {
enabled: true,
},
// 配置端口识别规则,
portMarkup: [
{
tagName: 'div',
selector: 'port-body',
},
],
// 告诉 X6 如何识别 Vue 组件内的端口
portAttribute: 'data-port',
});
};

View File

@@ -8,7 +8,7 @@
*/
import type { ApiDataResponse, NullableString } from '@/types';
import type { ElementParameter } from '../builder/element';
import type { ElementParameter } from '../graph';
export interface NodeTemplate {
id: number;

View File

@@ -8,7 +8,7 @@
*/
import type { ApiDataResponse, NullableString, PageableResponse } from '@/types';
import type { NodeGraph } from '../builder/element';
import type { GraphContainer } from '../graph';
export interface BehaviorTree {
id: number,
@@ -18,7 +18,7 @@ export interface BehaviorTree {
updatedAt: NullableString,
englishName: NullableString,
xmlContent: NullableString,
graph: NodeGraph
graph: GraphContainer
}
export interface BehaviorTreeRequest extends BehaviorTree {

View File

@@ -52,7 +52,7 @@
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { CheckOutlined, DeleteOutlined, EditFilled, PlusOutlined } from '@ant-design/icons-vue';
import type { BehaviorTree, BehaviorTreeRequest } from '../types';
import type { BehaviorTree, BehaviorTreeRequest } from './tree';
import { deleteOneTreeById, findTreesByQuery } from './api';
import { substring } from '@/utils/strings';

View File

@@ -7,13 +7,13 @@
* that was distributed with this source code.
*/
import type { NodeDragTemplate } from '../types';
import type { GraphTaskElement, GraphTaskRect } from '../builder/element';
import type { NodeDragTemplate } from './template';
import type { GraphRect, GraphTaskElement } from '../graph';
import { generateKey } from '@/utils/strings';
export const createGraphTaskElementFromTemplate = (
template: NodeDragTemplate,
rect?: GraphTaskRect,
rect?: GraphRect,
): GraphTaskElement => {
let realRect = { width: 120, height: 80, x: 0, y: 0, ...rect || {} };
console.info('rect', rect);

View File

@@ -8,9 +8,8 @@
*/
import { Edge, Graph, Path, Selection } from '@antv/x6';
import type { ModelElement } from './element';
import { createLineOptions, type ModelElement } from '../graph';
import type { Connecting } from '@antv/x6/lib/graph/options';
import { createLineOptions } from './line';
Graph.registerConnector(
'sequenceFlowConnector',
@@ -59,7 +58,7 @@ export const createGraphConnectingAttributes = (): Partial<Connecting> => {
...lineOptions.attrs?.line,
targetMarker: null,
sourceMarker: null,
}
},
},
animation: lineOptions.animation,
markup: lineOptions.markup,

View File

@@ -7,22 +7,57 @@
* that was distributed with this source code.
*/
import type { NullableString } from '@/types';
export interface DraggableElement {
export interface GraphComponentElement {
id: number,
name: NullableString,
type: NullableString,
description: NullableString,
}
export interface GraphPosition {
x: number;
y: number;
}
export interface GraphRect {
width?: number;
height?: number;
x?: number;
y?: number;
}
export interface GraphDraggableElement {
id: number | null,
key?: NullableString,
name: NullableString,
description: NullableString,
category: NullableString,
draggable: boolean,
parent?: DraggableElement,
children: DraggableElement[]
parent?: GraphDraggableElement,
children: GraphDraggableElement[]
[key: string]: unknown;
}
export interface GraphBaseElement {
id: number;
key: NullableString;
name: NullableString;
description: NullableString;
type: NullableString;
width: number;
height: number;
position: GraphPosition;
category: NullableString;
element?: GraphDraggableElement;
components?: GraphComponentElement[];
[key: string]: unknown;
}
export type ElementStatus = 'default' | 'success' | 'failed' | 'running' | string | null
export interface ElementParameter {
id: number,
@@ -34,10 +69,6 @@ export interface ElementParameter {
templateType: NullableString,
}
export interface GraphPosition {
x: number;
y: number;
}
export interface ElementVariable {
key: NullableString;
@@ -47,29 +78,7 @@ export interface ElementVariable {
unit: NullableString;
}
export interface GraphTaskRect {
width?: number;
height?: number;
x?: number;
y?: number;
}
export interface BaseElement {
id: number;
key: NullableString;
name: NullableString;
description: NullableString;
type: NullableString;
width: number;
height: number;
position: GraphPosition;
category: NullableString;
element?: DraggableElement;
[key: string]: unknown;
}
export interface GraphTaskElement extends BaseElement {
export interface GraphTaskElement extends GraphBaseElement {
template: number;
templateType: NullableString,
inputs: any;
@@ -82,7 +91,7 @@ export interface GraphTaskElement extends BaseElement {
[key: string]: unknown;
}
export interface ModelElement extends BaseElement {
export interface ModelElement extends GraphBaseElement {
edges: GraphEdgeElement[];
}
@@ -98,7 +107,7 @@ export interface GraphEdgeElement {
[key: string]: unknown;
}
export interface NodeGraph {
export interface GraphContainer {
edges: GraphEdgeElement[];
nodes: GraphTaskElement[];
}

View File

@@ -10,7 +10,7 @@
import { computed, type ComputedRef, ref, type Ref } from 'vue';
import { type Dom, Graph, Node } from '@antv/x6';
import type { NodeViewPositionEventArgs } from '@antv/x6/es/view/node/type';
import { createGraphCanvas } from './graph';
import { createGraphCanvas } from './canvas';
import { EventListener } from '@/utils/event';
import type { ModelElement } from './element';
@@ -224,6 +224,7 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
const createCanvas = (c: HTMLDivElement): Graph => {
container.value = c;
graph.value = createGraphCanvas(c, readonly);
initEvents();

View File

@@ -0,0 +1,16 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
export * from './line';
export * from './ports';
export * from './element';
export * from './canvas';
export * from './hooks';
export * from './props';
export * from './utils';

View File

@@ -6,23 +6,23 @@
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import type { GraphEdgeElement, GraphTaskElement, NodeGraph } from './element';
import type { GraphContainer, GraphEdgeElement, GraphTaskElement } from '../graph';
import { Edge, Graph, Node } from '@antv/x6';
export const defaultHeight: Record<string, number> = {
component: 110,
};
export const createGraphTaskElement = (element: GraphTaskElement, width: number = 250, height: number = 120): any => {
export const createGraphTaskElement = (element: GraphTaskElement, width: number = 250, height: number = 120, shape: string = 'task'): any => {
let realHeight = defaultHeight[element.category as string];
if (!realHeight) {
realHeight = 120;
}
if(element.group === 'condition' || element.group === 'control') {
if (element.group === 'condition' || element.group === 'control') {
realHeight = 60;
}
return {
shape: 'task',
shape: shape ?? 'task',
id: element.key,
position: {
x: element.position?.x || 0,
@@ -74,8 +74,10 @@ export const resolveGraphEdgeElements = (graph: Graph): GraphEdgeElement[] => {
key: edge.id,
type: 'edge',
status: nodeData?.status,
sourcePort: edge.getSourcePortId(),
source: edge.getSource() ? edge.getSource() as unknown as string : null,
target: edge.getSource() ? edge.getTarget() as unknown as string : null,
targetPort: edge.getTargetPortId(),
attrs: edge.getAttrs() ?? {},
router: edge.getRouter() ?? {},
connector: edge.getConnector() ?? null,
@@ -86,7 +88,7 @@ export const resolveGraphEdgeElements = (graph: Graph): GraphEdgeElement[] => {
return edgeElements;
};
export const resolveNodeGraph = (graph: Graph): NodeGraph => {
export const resolveGraph = (graph: Graph): GraphContainer => {
const nodes: GraphTaskElement[] = resolveGraphTaskElements(graph);
const edges: GraphEdgeElement[] = resolveGraphEdgeElements(graph);
return {

View File

@@ -0,0 +1,118 @@
<template>
<a-space>
<!-- 平台选择框 -->
<a-select
style="width:280px"
v-model:value="innerPlatformId"
placeholder="请选择平台"
:disabled="loading"
>
<a-select-option
v-for="item in platforms"
:key="`platform-${item.id}`"
:value="item.id"
>
{{ item.description || item.name || '未命名平台' }}
</a-select-option>
</a-select>
<!-- 组件选择框 -->
<a-select
style="width:280px;"
v-model:value="innerComponentId"
placeholder="请选择组件"
:disabled="!innerPlatformId || loading"
>
<a-select-option
v-for="item in selectedPlatformComponents"
:key="`component-${item.id}`"
:value="item.id"
>
{{ item.description || item.name || '未命名组件' }}
</a-select-option>
</a-select>
</a-space>
</template>
<script lang="ts">
import { computed, defineComponent, type PropType, ref, watch } from 'vue';
import type { PlatformComponentPayload } from '../types';
import { usePlatformComponents } from './store';
export default defineComponent({
name: 'PlatformSelect',
props: {
platformId: {
type: [Number, null] as PropType<number | null>,
required: false,
default: null,
},
componentId: {
type: [Number, null] as PropType<number | null>,
required: false,
default: null,
},
},
emits: {
change: (payload: PlatformComponentPayload) => true,
},
setup(props, { emit }) {
const { loading, platforms, platformMap, componentMap } = usePlatformComponents();
const innerPlatformId = ref<number | null>(props.platformId);
const innerComponentId = ref<number | null>(props.componentId);
const selectedPlatformComponents = computed(() => {
const platform = platforms.value.find(p => p.id === innerPlatformId.value);
return platform?.components || [];
});
const emitChange = () => {
// 根据ID获取完整对象
const platform = platformMap.value.get(innerPlatformId.value || -1) || null;
const component = componentMap.value.get(innerComponentId.value || -1) || null;
const validComponent = component && component.platformId === innerPlatformId.value
? component
: null;
emit('change', {
platform: platform ? {
id: platform.id,
name: platform.name,
description: platform.description,
scenarioId: platform.scenarioId,
} : null,
component: validComponent,
} as PlatformComponentPayload);
};
watch([() => props.platformId, () => props.componentId],
([newPlatformId, newComponentId]) => {
if (!loading.value) {
innerPlatformId.value = newPlatformId;
innerComponentId.value = newComponentId;
}
},
{ immediate: true, deep: false },
);
watch(innerPlatformId, (newVal) => {
if (newVal !== innerPlatformId.value) {
innerComponentId.value = null;
}
emitChange();
});
watch(innerComponentId, emitChange);
return {
loading,
platforms,
selectedPlatformComponents,
innerPlatformId,
innerComponentId,
};
}
});
</script>

View File

@@ -9,6 +9,7 @@
import { HttpRequestClient } from '@/utils/request';
import type { FireRule, FireRulePageableResponse, FireRuleRequest } from './types';
import type { PlatformWithComponentsResponse } from '../types';
import type { BasicResponse } from '@/types';
const req = HttpRequestClient.create<BasicResponse>({
@@ -31,5 +32,8 @@ export const deleteFireRule = (id: number): Promise<BasicResponse> => {
return req.delete(`/system/rule/${id}`);
};
export const findAllPlatformWithComponents = (): Promise<PlatformWithComponentsResponse> => {
return req.get(`/system/firerule/platforms`);
};

View File

@@ -32,9 +32,7 @@
</template>
<div class="w-full h-full">
<a-card class="ks-page-card ks-algorithm-card">
<template #title>
<a-space>
<span class="point"></span>
@@ -43,7 +41,6 @@
</template>
<div class="ks-scrollable" style="height: 80.5vh;overflow-y: auto;padding-right: 10px">
<a-row :gutter="15">
<a-col :span="16">
<a-form
@@ -57,14 +54,14 @@
<a-form-item
label="规则名称"
:rules="[{ required: true, message: '请输入规则名称!', trigger: ['input', 'change'] }]"
:name="['name']"
name="name"
>
<a-input v-model:value="selectedFireRule.name" placeholder="请输入规则名称" />
</a-form-item>
<a-form-item
label="场景类型"
:name="['sceneType']"
name="sceneType"
>
<a-select v-model:value="selectedFireRule.sceneType" placeholder="请选择场景类型">
<a-select-option :value="null">通用</a-select-option>
@@ -73,43 +70,92 @@
</a-select>
</a-form-item>
<!-- 触发条件 - 传递ID保持PlatformComponentPayload结构 -->
<a-form-item
label="触发条件"
:rules="[{ required: true, message: '请输入触发条件!', trigger: ['input', 'change'] }]"
:name="['conditions']"
:rules="[{ required: true, message: '请输入触发条件!', trigger: ['change'] }]"
name="conditionsArray"
>
<a-input v-model:value="selectedFireRule.conditions" placeholder="请输入触发条件" />
<a-form-item-rest>
<div class="ks-sidebar-list-param-list">
<div
class="ks-sidebar-list-param-item"
v-for="(item,index) in selectedFireRule.conditionsArray"
:key="`condition-${index}-${item.platform?.id || 'null'}-${item.component?.id || 'null'}`"
>
<a-row :gutter="15">
<a-col :span="21">
<!-- 只传递ID参数 -->
<PlatformSelect
:platform-id="item.platform?.id || null"
:component-id="item.component?.id || null"
@change="(payload)=> handleUpdateCondition(payload, index)"
/>
</a-col>
<a-col :span="3">
<a-space class="ks-sidebar-list-param-actions">
<MinusCircleOutlined @click.stop="()=> handleMinusCondition(index)" />
<PlusCircleOutlined @click.stop="()=> handleAddCondition()" v-if="index === 0" />
</a-space>
</a-col>
</a-row>
</div>
</div>
</a-form-item-rest>
</a-form-item>
<!-- 响应动作 - 传递ID保持PlatformComponentPayload结构 -->
<a-form-item
label="响应动作"
:rules="[{ required: true, message: '请输入响应动作!', trigger: ['input', 'change'] }]"
:name="['actions']"
:rules="[{ required: true, message: '请输入响应动作!', trigger: ['change'] }]"
name="actionsArray"
>
<a-input v-model:value="selectedFireRule.actions" placeholder="请输入响应动作" />
<a-form-item-rest>
<div class="ks-sidebar-list-param-list">
<div
class="ks-sidebar-list-param-item"
v-for="(item,index) in selectedFireRule.actionsArray"
:key="`action-${index}-${item.platform?.id || 'null'}-${item.component?.id || 'null'}`"
>
<a-row :gutter="15">
<a-col :span="21">
<!-- 只传递ID参数 -->
<PlatformSelect
:platform-id="item.platform?.id || null"
:component-id="item.component?.id || null"
@change="(payload)=> handleUpdateAction(payload, index)"
/>
</a-col>
<a-col :span="3">
<a-space class="ks-sidebar-list-param-actions">
<MinusCircleOutlined @click.stop="()=> handleMinusAction(index)" />
<PlusCircleOutlined @click.stop="()=> handleAddAction()" v-if="index === 0" />
</a-space>
</a-col>
</a-row>
</div>
</div>
</a-form-item-rest>
</a-form-item>
<a-form-item
label="优先级(数值越小优先级越高)"
:rules="[{ required: true, message: '请输入优先级!', trigger: ['input', 'change'] }]"
:name="['priority']"
name="priority"
>
<a-input-number style="width:100%;" v-model:value="selectedFireRule.priority" placeholder="请输入优先级" />
</a-form-item>
<a-form-item
label="是否启用"
:name="['priority']"
name="enabled"
>
<a-switch v-model:checked="selectedFireRule.enabled" />
</a-form-item>
<a-form-item
:wrapper-col="{offset: 6}"
>
<a-form-item :wrapper-col="{offset: 6}">
<a-space>
<a-button @click="handleSave" type="primary">保存规则</a-button>
<a-popconfirm
v-if="selectedFireRule && selectedFireRule.id > 0"
title="确定删除?"
@@ -117,100 +163,134 @@
>
<a-button danger>删除规则</a-button>
</a-popconfirm>
</a-space>
</a-form-item>
</a-form>
</a-col>
</a-row>
</div>
</a-card>
</div>
</Layout>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { nextTick, onMounted, ref } from 'vue';
import { type FormInstance, message } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import Layout from '../layout.vue';
import { createFireRule, deleteFireRule, findFireRuleByQuery, updateFireRule } from './api';
import type { FireRule, FireRuleRequest } from './types';
import type { FireRule, FireRulePageableResponse, FireRuleRequest } from './types';
import type { PlatformComponentPayload } from '../types';
import { substring } from '@/utils/strings';
import PlatformSelect from './PlatformSelect.vue';
const query = ref<Partial<FireRuleRequest>>({
const query = ref<FireRuleRequest>({
id: 0,
name: '',
sceneType: null,
conditions: '',
conditionsArray: [],
actions: '',
actionsArray: [],
priority: 0,
enabled: true,
pageNum: 1,
pageSize: 10,
});
const defaultPayload: PlatformComponentPayload = {
platform: null,
component: null,
};
const defaultFireRule: FireRule = {
id: 0,
// 规则名称
name: null,
// 场景类型0-防御1-空降null表示通用
name: '',
sceneType: null,
// 触发条件JSON格式
conditions: null,
// 响应动作JSON格式
actions: null,
// 优先级(数值越小优先级越高)
conditions: '',
conditionsArray: [JSON.parse(JSON.stringify(defaultPayload))],
actions: '',
actionsArray: [JSON.parse(JSON.stringify(defaultPayload))],
priority: 0,
// 是否启用0禁用1启用
enabled: true,
};
const getSceneTypeName = (item: FireRule): string => {
if (0 === item.sceneType) {
return '防御';
}
if (1 === item.sceneType) {
return '空降';
}
if (item.sceneType === 0) return '防御';
if (item.sceneType === 1) return '空降';
return '通用';
};
const resolveItem = (item: FireRule) => {
let newItem = JSON.parse(JSON.stringify(item));
const newItem: FireRule = JSON.parse(JSON.stringify(item)) as FireRule;
try {
newItem.conditionsArray = item.conditions
? (JSON.parse(item.conditions) as PlatformComponentPayload[])
: [JSON.parse(JSON.stringify(defaultPayload))];
} catch (e) {
newItem.conditionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
}
try {
newItem.actionsArray = item.actions
? (JSON.parse(item.actions) as PlatformComponentPayload[])
: [JSON.parse(JSON.stringify(defaultPayload))];
} catch (e) {
newItem.actionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
}
// 确保数组不为空
if (!Array.isArray(newItem.conditionsArray) || newItem.conditionsArray.length === 0) {
newItem.conditionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
}
if (!Array.isArray(newItem.actionsArray) || newItem.actionsArray.length === 0) {
newItem.actionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
}
return newItem;
};
const datasource = ref<FireRule[]>([]);
const datasourceTotal = ref<number>(0);
const selectedFireRule = ref<FireRule>(resolveItem(defaultFireRule));
const selectedFireRule = ref<FireRule>(JSON.parse(JSON.stringify(defaultFireRule)));
const formRef = ref<FormInstance | null>(null);
const load = () => {
datasource.value = [];
datasourceTotal.value = 0;
formRef.value?.resetFields();
selectedFireRule.value = resolveItem(defaultFireRule);
if(selectedFireRule.value.id <= 0){
selectedFireRule.value = JSON.parse(JSON.stringify(defaultFireRule));
nextTick(() => {
formRef.value?.resetFields();
});
}
findFireRuleByQuery(query.value).then(r => {
findFireRuleByQuery(query.value).then((r: FireRulePageableResponse) => {
datasource.value = r.rows ?? [];
datasourceTotal.value = r.total ?? 0;
});
};
const handleCreate = () => {
selectedFireRule.value = resolveItem(defaultFireRule);
formRef.value?.resetFields();
selectedFireRule.value = JSON.parse(JSON.stringify(defaultFireRule));
};
const handleSelect = (item: FireRule) => {
selectedFireRule.value = resolveItem(item);
formRef.value?.resetFields();
nextTick(() => {
selectedFireRule.value = resolveItem(item);
});
};
const handleDelete = () => {
if (selectedFireRule.value && selectedFireRule.value.id > 0) {
if (selectedFireRule.value?.id > 0) {
deleteFireRule(selectedFireRule.value.id).then(r => {
if (r.code === 200) {
load();
message.info(r.msg ?? '删除成功');
message.success(r.msg ?? '删除成功');
} else {
message.error(r.msg ?? '删除失败');
}
@@ -219,29 +299,90 @@ const handleDelete = () => {
};
const handleSave = () => {
if (formRef.value) {
formRef.value.validate().then(() => {
let res = null;
let savedValue: FireRule = JSON.parse(JSON.stringify(selectedFireRule.value)) as any as FireRule;
if (savedValue.id > 0) {
res = updateFireRule(savedValue);
formRef.value?.validate().then(() => {
const savedValue: FireRule = JSON.parse(JSON.stringify(selectedFireRule.value));
savedValue.conditions = JSON.stringify(savedValue.conditionsArray);
savedValue.actions = JSON.stringify(savedValue.actionsArray);
const request = savedValue.id > 0
? updateFireRule(savedValue)
: createFireRule(savedValue);
request.then(r => {
if (r.code === 200) {
load();
message.success(r.msg ?? '操作成功');
} else {
res = createFireRule(savedValue);
}
if (res) {
res.then(r => {
if (r.code === 200) {
load();
message.info(r.msg ?? '操作成功');
} else {
message.error(r.msg ?? '操作失败');
}
});
message.error(r.msg ?? '操作失败');
}
}).catch(err => {
message.error('请求失败:' + err.message);
});
}).catch(err => {
message.error('表单验证失败:' + err.message);
});
};
const handleUpdateCondition = (payload: PlatformComponentPayload, index: number) => {
if (selectedFireRule.value && selectedFireRule.value.conditionsArray[index]) {
const newArray = [...selectedFireRule.value.conditionsArray];
newArray[index] = {
platform: payload.platform,
component: payload.component,
};
selectedFireRule.value.conditionsArray = newArray;
}
};
const handleUpdateAction = (payload: PlatformComponentPayload, index: number) => {
if (selectedFireRule.value && selectedFireRule.value.actionsArray[index]) {
const newArray = [...selectedFireRule.value.actionsArray];
newArray[index] = {
platform: payload.platform,
component: payload.component,
};
selectedFireRule.value.actionsArray = newArray;
}
};
// 添加触发条件
const handleAddCondition = () => {
if (selectedFireRule.value) {
selectedFireRule.value.conditionsArray.push(JSON.parse(JSON.stringify(defaultPayload)));
}
};
// 删除触发条件
const handleMinusCondition = (index: number) => {
if (!selectedFireRule.value) return;
const list = [...selectedFireRule.value.conditionsArray];
if (list.length <= 1) {
selectedFireRule.value.conditionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
} else {
list.splice(index, 1);
selectedFireRule.value.conditionsArray = list;
}
};
// 添加响应动作
const handleAddAction = () => {
if (selectedFireRule.value) {
selectedFireRule.value.actionsArray.push(JSON.parse(JSON.stringify(defaultPayload)));
}
};
// 删除响应动作
const handleMinusAction = (index: number) => {
if (!selectedFireRule.value) return;
const list = [...selectedFireRule.value.actionsArray];
if (list.length <= 1) {
selectedFireRule.value.actionsArray = [JSON.parse(JSON.stringify(defaultPayload))];
} else {
list.splice(index, 1);
selectedFireRule.value.actionsArray = list;
}
};
const handleChange = (page: number, pageSize: number) => {
query.value.pageNum = page;
@@ -250,5 +391,4 @@ const handleChange = (page: number, pageSize: number) => {
};
onMounted(() => load());
</script>

View File

@@ -0,0 +1,64 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import { onMounted, ref, type Ref } from 'vue';
import type { Platform, PlatformComponent, PlatformWithComponents, PlatformWithComponentsResponse } from '../types';
import { findAllPlatformWithComponents } from './api';
const loading: Ref<boolean> = ref<boolean>(true);
const platforms: Ref<PlatformWithComponents[]> = ref<PlatformWithComponents[]>([]);
const platformMap: Ref<Map<number, Platform>> = ref<Map<number, Platform>>(new Map());
const componentMap: Ref<Map<number, PlatformComponent>> = ref<Map<number, PlatformComponent>>(new Map());
const loaded: Ref<boolean> = ref<boolean>(false);
export interface UsePlatformComponentsReturn {
loading: Ref<boolean>;
platforms: Ref<PlatformWithComponents[]>;
platformMap: Ref<Map<number, Platform>>;
componentMap: Ref<Map<number, PlatformComponent>>;
loaded: Ref<boolean>;
}
export const usePlatformComponents = (): UsePlatformComponentsReturn => {
const load = () => {
if (!loaded.value) {
loading.value = true;
platformMap.value.clear();
componentMap.value.clear();
findAllPlatformWithComponents()
.then((res: PlatformWithComponentsResponse) => { // 显式标注响应类型
platforms.value = res.data || [];
platforms.value.forEach(platform => {
platformMap.value.set(platform.id, platform);
platform.components?.forEach(component => {
componentMap.value.set(component.id, component);
});
});
loaded.value = true;
})
.catch((err: unknown) => {
console.error('加载平台组件失败:', err);
})
.finally(() => {
loading.value = false;
});
}
};
onMounted(() => load());
return {
loading,
platforms,
platformMap,
componentMap,
loaded,
};
};

View File

@@ -8,6 +8,7 @@
*/
import type { NullableString, PageableResponse } from '@/types';
import type { PlatformComponentPayload } from '../types';
export interface FireRule {
id: number,
@@ -17,8 +18,10 @@ export interface FireRule {
sceneType: Number | null,
// 触发条件JSON格式
conditions: NullableString,
// 响应动作JSON格式
actions: NullableString,
conditionsArray: PlatformComponentPayload[],
// 响应动作JSON格式
actions: NullableString,
actionsArray: PlatformComponentPayload[],
// 优先级(数值越小优先级越高)
priority: number,
// 是否启用0禁用1启用

View File

@@ -7,5 +7,4 @@
* that was distributed with this source code.
*/
export * from './tree';
export * from './template';
export * from './platform'

View File

@@ -0,0 +1,43 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2026 zlin <admin@kernelstudio.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
import type { ApiDataResponse, NullableString } from '@/types';
export interface Platform {
id: number,
name: NullableString,
description: NullableString,
scenarioId: number,
[key: string]: unknown;
}
export interface PlatformComponent {
id: number,
name: NullableString,
type: NullableString,
description: NullableString,
platformId: number,
[key: string]: unknown;
}
export interface PlatformWithComponents extends Platform {
components: PlatformComponent[],
[key: string]: unknown;
}
export interface PlatformComponentPayload {
platform: Platform | null;
component: PlatformComponent | null;
[key: string]: unknown;
}
export interface PlatformWithComponentsResponse extends ApiDataResponse<PlatformWithComponents[]> {
}

View File

@@ -15,6 +15,7 @@ declare module 'vue' {
ABadge: typeof import('ant-design-vue/es')['Badge']
AButton: typeof import('ant-design-vue/es')['Button']
ACard: typeof import('ant-design-vue/es')['Card']
ACascader: typeof import('ant-design-vue/es')['Cascader']
ACol: typeof import('ant-design-vue/es')['Col']
ACollapse: typeof import('ant-design-vue/es')['Collapse']
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
@@ -44,6 +45,7 @@ declare module 'vue' {
ASelect: typeof import('ant-design-vue/es')['Select']
ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
ASpace: typeof import('ant-design-vue/es')['Space']
ASwitch: typeof import('ant-design-vue/es')['Switch']
ATabPane: typeof import('ant-design-vue/es')['TabPane']
ATabs: typeof import('ant-design-vue/es')['Tabs']
ATextarea: typeof import('ant-design-vue/es')['Textarea']
@@ -58,6 +60,7 @@ declare global {
const ABadge: typeof import('ant-design-vue/es')['Badge']
const AButton: typeof import('ant-design-vue/es')['Button']
const ACard: typeof import('ant-design-vue/es')['Card']
const ACascader: typeof import('ant-design-vue/es')['Cascader']
const ACol: typeof import('ant-design-vue/es')['Col']
const ACollapse: typeof import('ant-design-vue/es')['Collapse']
const ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
@@ -87,6 +90,7 @@ declare global {
const ASelect: typeof import('ant-design-vue/es')['Select']
const ASelectOption: typeof import('ant-design-vue/es')['SelectOption']
const ASpace: typeof import('ant-design-vue/es')['Space']
const ASwitch: typeof import('ant-design-vue/es')['Switch']
const ATabPane: typeof import('ant-design-vue/es')['TabPane']
const ATabs: typeof import('ant-design-vue/es')['Tabs']
const ATextarea: typeof import('ant-design-vue/es')['Textarea']

23
pom.xml
View File

@@ -274,6 +274,29 @@
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<!-- 顺序无关,但每个都需要指定版本 -->
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.34</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.5.Final</version>
</path>
<!-- 如果有其他 processor 也加在这里 -->
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>