Compare commits

37 Commits

Author SHA1 Message Date
libertyspy
2838938cfa UPDATE: VERSION-20260327 2026-03-27 14:02:18 +08:00
libertyspy
d1f720f691 UPDATE: VERSION-20260327 2026-03-27 10:54:44 +08:00
libertyspy
cb1019b7d7 UPDATE: VERSION-20260327 2026-03-27 10:35:23 +08:00
libertyspy
168ced6b27 UPDATE: VERSION-20260327 2026-03-27 10:03:25 +08:00
libertyspy
499734efe8 UPDATE: VERSION-20260327 2026-03-27 10:03:16 +08:00
libertyspy
27c8fc13c6 UPDATE: VERSION-20260327 2026-03-27 10:03:07 +08:00
libertyspy
505092bcf4 UPDATE: VERSION-20260327 2026-03-27 10:02:59 +08:00
libertyspy
41ba11dc9b UPDATE: VERSION-20260327 2026-03-27 09:33:46 +08:00
libertyspy
158512cd12 UPDATE: VERSION-20260326 2026-03-27 00:08:48 +08:00
libertyspy
3a3ab0c9c6 UPDATE: VERSION-20260326 2026-03-27 00:05:50 +08:00
libertyspy
b08c74260d UPDATE: VERSION-20260326 2026-03-27 00:05:04 +08:00
libertyspy
02e9ca26a1 UPDATE: VERSION-20260326 2026-03-26 23:59:15 +08:00
libertyspy
8958ecd6dc UPDATE: VERSION-20260326 2026-03-26 23:36:47 +08:00
libertyspy
6656479327 UPDATE: VERSION-20260326 2026-03-26 22:05:31 +08:00
libertyspy
18ccf490e4 UPDATE: VERSION-20260326 2026-03-26 21:45:31 +08:00
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
65 changed files with 1589 additions and 294 deletions

View File

@@ -42,6 +42,12 @@ public class BehaviortreeController extends BaseController
@Autowired
private BehaviortreeProcessor behaviortreeProcessor;
@GetMapping(value = "/platform/{id}")
public AjaxResult fromPlatform(@PathVariable("id") Integer id)
{
return success(behaviortreeService.findOneByPlatformId(id));
}
/**
* 查询行为树主列表
*/

View File

@@ -59,10 +59,20 @@ public class FireRuleController extends BaseController {
* @return
*/
@GetMapping("/platforms/{scenarioId}")
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());
}
@GetMapping("/platforms/basic")
public AjaxResult platformsBasic(){
return success(ruleService.findAllBasicPlatformComponents());
}
/**
* 根据平台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;

View File

@@ -20,8 +20,11 @@ import com.solution.web.core.graph.GraphEdge;
import com.solution.web.core.graph.GraphNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@@ -98,12 +101,19 @@ public class BehaviortreeProcessor {
instanceKeyMap.put(node.getKey(), instance);
if (node.hasParameters()) {
if (node.isMultiable()) {
List<Nodeparameter> nodeparameters = createMultiableNodeparameter(behaviortree, node, instance);
for (Nodeparameter nodeparameter : nodeparameters) {
nodeparameterService.insertNodeparameter(nodeparameter);
}
} else {
// 插入parameter nodeparameter
for (Templateparameterdef parameter : node.getParameters()) {
Nodeparameter nodeparameter = createNodeParameter(behaviortree, parameter, instance);
nodeparameterService.insertNodeparameter(nodeparameter);
}
}
}
nodeKeyIndexMap.put(node.getKey(), index);
index++;
@@ -148,6 +158,47 @@ public class BehaviortreeProcessor {
return connection;
}
private List<Nodeparameter> createMultiableNodeparameter(Behaviortree behaviortree, GraphNode node,
Treenodeinstance instance) {
List<Nodeparameter> nodeparameters = new ArrayList<>();
Map<Long, List<String>> idValues = new HashMap<>();
List<String> tmpValues = null;
Map<Long, List<Templateparameterdef>> mappedValues = new HashMap<>();
List<Templateparameterdef> tmpDefs = null;
for (Templateparameterdef parameter : node.getParameters()) {
tmpDefs = mappedValues.get(parameter.getId() );
if (null == tmpDefs) {
tmpDefs = new ArrayList<>();
}
tmpDefs.add(parameter);
mappedValues.put(parameter.getId(), tmpDefs);
tmpValues = idValues.get(parameter.getId() );
if (null == tmpValues) {
tmpValues = new ArrayList<>();
}
tmpValues.add(parameter.getDefaultValue());
idValues.put(parameter.getId(), tmpValues);
}
int index = 0;
for (Long id : idValues.keySet()) {
tmpValues = idValues.get(id);
Nodeparameter nodeparameter = new Nodeparameter();
nodeparameter.setTreeId(behaviortree.getId());
nodeparameter.setNodeInstanceId(instance.getId());
nodeparameter.setParamDefId(id);
nodeparameter.setValue(StringUtils.collectionToCommaDelimitedString(tmpValues));
nodeparameter.setGroupIndex(index);
nodeparameters.add(nodeparameter);
index++;
}
return nodeparameters;
}
private Nodeparameter createNodeParameter(Behaviortree behaviortree, Templateparameterdef parameter,
Treenodeinstance instance) {
Nodeparameter nodeparameter = new Nodeparameter();
@@ -155,6 +206,7 @@ public class BehaviortreeProcessor {
nodeparameter.setNodeInstanceId(instance.getId());
nodeparameter.setParamDefId(parameter.getId());
nodeparameter.setValue(parameter.getDefaultValue());
nodeparameter.setGroupIndex(parameter.getGroupIndex());
return nodeparameter;
}

View File

@@ -33,6 +33,8 @@ public class GraphNode implements Serializable {
private String category;
private boolean multiable;
private List<Templateparameterdef> parameters;
private List<GraphVariable> variables;
@@ -61,6 +63,14 @@ public class GraphNode implements Serializable {
'}';
}
public boolean isMultiable() {
return multiable;
}
public void setMultiable(boolean multiable) {
this.multiable = multiable;
}
public String getCategory() {
return category;
}

View File

@@ -32,6 +32,8 @@ public class Nodeparameter extends BaseEntity
@Excel(name = "节点实例设置的具体参数值 (覆盖模板默认值)")
private String value;
private int groupIndex;
public void setId(Long id)
{
this.id = id;
@@ -80,6 +82,14 @@ public class Nodeparameter extends BaseEntity
return value;
}
public int getGroupIndex() {
return groupIndex;
}
public void setGroupIndex(int groupIndex) {
this.groupIndex = groupIndex;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)

View File

@@ -42,6 +42,8 @@ public class Nodetemplate extends BaseEntity
@Excel(name = "模版类型节点模版或者条件判断例如“node”precondition“")
private String templateType;
private boolean multiable;
public Nodetemplate() {
}
@@ -53,6 +55,7 @@ public class Nodetemplate extends BaseEntity
this.description = template.description;
this.englishName = template.englishName;
this.templateType = template.templateType;
this.multiable = template.multiable;
}
public void setId(Long id)
@@ -125,6 +128,14 @@ public class Nodetemplate extends BaseEntity
return templateType;
}
public boolean isMultiable() {
return multiable;
}
public void setMultiable(boolean multiable) {
this.multiable = multiable;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)

View File

@@ -42,6 +42,8 @@ public class Templateparameterdef extends BaseEntity
@Excel(name = "判断参数模版是节点的参数模版还是条件的参数模版")
private String templateType;
private int groupIndex;
public void setId(Long id)
{
this.id = id;
@@ -112,6 +114,14 @@ public class Templateparameterdef extends BaseEntity
return templateType;
}
public int getGroupIndex() {
return groupIndex;
}
public void setGroupIndex(int groupIndex) {
this.groupIndex = groupIndex;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)

View File

@@ -12,6 +12,9 @@ import com.solution.system.domain.Behaviortree;
*/
public interface BehaviortreeMapper
{
Behaviortree findOneByPlatformId(Integer platformId);
/**
* 查询行为树主
*

View File

@@ -12,6 +12,9 @@ import com.solution.system.domain.Behaviortree;
*/
public interface IBehaviortreeService
{
Behaviortree findOneByPlatformId(Integer platformId);
/**
* 查询行为树主
*

View File

@@ -22,6 +22,12 @@ public class BehaviortreeServiceImpl implements IBehaviortreeService
@Autowired
private BehaviortreeMapper behaviortreeMapper;
@Override
public Behaviortree findOneByPlatformId(Integer platformId)
{
return behaviortreeMapper.findOneByPlatformId(platformId);
}
/**
* 查询行为树主
*

View File

@@ -14,6 +14,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="xmlContent" column="xml_content" />
</resultMap>
<select id="findOneByPlatformId" resultMap="BehaviortreeResult">
select * from behaviortree
where platform_id=#{platformId}
limit 1
</select>
<sql id="selectBehaviortreeVo">
select id, name, description, created_at, updated_at, english_name, xml_content from behaviortree
</sql>

View File

@@ -10,6 +10,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="nodeInstanceId" column="node_instance_id" />
<result property="paramDefId" column="param_def_id" />
<result property="value" column="value" />
<result property="groupIndex" column="group_index" />
</resultMap>
<delete id="deleteByTreeId">
@@ -17,7 +18,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</delete>
<sql id="selectNodeparameterVo">
select id, treeId, node_instance_id, param_def_id, value from nodeparameter
select id, treeId, node_instance_id, param_def_id,`value`, group_index from nodeparameter
</sql>
<select id="selectNodeparameterList" parameterType="Nodeparameter" resultMap="NodeparameterResult">
@@ -41,12 +42,14 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="nodeInstanceId != null">node_instance_id,</if>
<if test="paramDefId != null">param_def_id,</if>
<if test="value != null">value,</if>
group_index
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="treeId != null">#{treeId},</if>
<if test="nodeInstanceId != null">#{nodeInstanceId},</if>
<if test="paramDefId != null">#{paramDefId},</if>
<if test="value != null">#{value},</if>
#{groupIndex}
</trim>
</insert>
@@ -57,6 +60,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<if test="nodeInstanceId != null">node_instance_id = #{nodeInstanceId},</if>
<if test="paramDefId != null">param_def_id = #{paramDefId},</if>
<if test="value != null">value = #{value},</if>
group_index=#{groupIndex}
</trim>
where id = #{id}
</update>

View File

@@ -12,10 +12,11 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="description" column="description" />
<result property="englishName" column="english_name" />
<result property="templateType" column="templete_type" />
<result property="multiable" column="is_multiable" />
</resultMap>
<sql id="selectNodetemplateVo">
select id, type, name, logic_handler, description, english_name, templete_type from nodetemplate
select id, type, name, logic_handler, description, english_name, templete_type, is_multiable from nodetemplate
</sql>
<select id="selectNodetemplateList" parameterType="Nodetemplate" resultMap="NodetemplateResult">

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

@@ -0,0 +1,47 @@
package com.solution.rule.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.io.Serializable;
import java.util.List;
public class BasicPlatform implements Serializable {
private Integer id;
private String name;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}

View File

@@ -8,43 +8,12 @@ package com.solution.rule.domain;
* that was distributed with this source code.
*/
import java.io.Serializable;
import java.util.List;
public class Platform implements Serializable {
private Integer id;
private String name;
private String description;
public class Platform extends BasicPlatform {
private List<PlatformComponent> components;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<PlatformComponent> getComponents() {
return components;
}
@@ -52,5 +21,4 @@ public class Platform implements Serializable {
public void setComponents(List<PlatformComponent> components) {
this.components = components;
}
}

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

@@ -1,5 +1,6 @@
package com.solution.rule.mapper;
import com.solution.rule.domain.BasicPlatform;
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.vo.ComponentCountVO;
@@ -42,4 +43,8 @@ public interface FireRuleMapper {
List<PlatformComponent> getComponents(Integer platformId);
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
List<BasicPlatform> findAllBasicPlatformComponents();
}

View File

@@ -1,5 +1,6 @@
package com.solution.rule.service;
import com.solution.rule.domain.BasicPlatform;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
@@ -45,4 +46,8 @@ public interface FireRuleService {
* @return
*/
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
List<BasicPlatform> findAllBasicPlatformComponents();
}

View File

@@ -3,10 +3,7 @@ package com.solution.rule.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.solution.common.constant.ExceptionConstants;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.RuleParam;
import com.solution.rule.domain.*;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
@@ -176,4 +173,14 @@ public class FireRuleServiceImpl implements FireRuleService {
return new ArrayList<>();
}
@Override
public List<Platform> findAllPlatformComponents() {
return ruleMapper.findAllPlatformComponents();
}
@Override
public List<BasicPlatform> findAllBasicPlatformComponents() {
return ruleMapper.findAllBasicPlatformComponents();
}
}

View File

@@ -85,6 +85,16 @@
WHERE platform_id=#{platformId}
</select>
<resultMap id="VPBasicPlatformMap" type="com.solution.rule.domain.BasicPlatform">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="description" column="description"/>
</resultMap>
<select id="findAllBasicPlatformComponents" resultMap="VPBasicPlatformMap">
SELECT *
FROM platform
</select>
<resultMap id="VPlatformMap" type="com.solution.rule.domain.Platform">
<result property="id" column="id"/>
<result property="name" column="name"/>
@@ -96,14 +106,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;

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,7 +14,7 @@ public interface SceneService {
*/
int insert(AfsimScenario afsimScenario);
int update(AfsimScenario afsimScenario);
int update(AfsimScenarioForm afsimScenario);
int saveOrUpdate(AfsimScenario afsimScenario);

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,22 +18,42 @@ 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(AfsimScenario afsimScenario) {
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) {
return sceneMapper.update(afsimScenario);
// 更新场景
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 insert(afsimScenario);
}
/**

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

@@ -12,7 +12,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="communicationGraph" column="communication_graph" />
</resultMap>
<insert id="insert" parameterType="com.solution.scene.domain.AfsimScenario">
<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>

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
@@ -1828,3 +1830,44 @@
}
}
.ks-add-parameter-action{
color: #eee;
position: absolute;
right: 14px;
top: 6px;
cursor: pointer;
}
.ks-parameter-setting-tabs{
.ant-tabs-nav{
background: none;
}
.ant-tabs-nav-list{
margin-left: 0;
}
&.ant-tabs-left >.ant-tabs-content-holder,
&.ant-tabs-left >div>.ant-tabs-content-holder{
border-left-color: #09264b;
}
.ant-tabs-tab-remove{
//position: absolute;
//right: 10px;
//top: 7px;
.anticon{
color: rgb(173 206 224);
}
}
&.ant-tabs-left >.ant-tabs-nav .ant-tabs-tab{
border-radius: 0!important;
}
&.ant-tabs-card >.ant-tabs-nav .ant-tabs-tab-active,
&.ant-tabs-card >div>.ant-tabs-nav .ant-tabs-tab-active {
background: #09264c;
}
&.ant-tabs-left >.ant-tabs-content-holder >.ant-tabs-content>.ant-tabs-tabpane,
&.ant-tabs-left >div>.ant-tabs-content-holder >.ant-tabs-content>.ant-tabs-tabpane{
padding-left: 5px;
}
}

View File

@@ -1,7 +1,7 @@
/*
* This file is part of the kernelstudio package.
*
* (c) 2014-2025 zlin <admin@kernelstudio.com>
* (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.
@@ -23,7 +23,7 @@ export class EventError {
export class EventListener {
private readonly _listeners: Record<string, Function[]>;
private _listeners: Record<string, Function[]>;
constructor(listeners: Record<string, Function[]> = {}) {
this._listeners = listeners;
@@ -55,16 +55,24 @@ export class EventListener {
[...listeners].forEach(f => f(options));
}
}
clear(){
for (const key in this._listeners) {
if (this._listeners.hasOwnProperty(key)) {
delete this._listeners[key];
}
}
}
}
export const safePreventDefault = (event: any) => {
if (event && typeof event.preventDefault === 'function') {
event.preventDefault();
}
}
};
export const safeStopPropagation = (event: any) => {
if (event && typeof event.stopPropagation === 'function') {
event.stopPropagation();
}
}
};

View File

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

View File

@@ -0,0 +1,21 @@
/*
* 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 { HttpRequestClient } from '@/utils/request';
import type { BasicResponse } from '@/types';
import type { PlatformListableResponse } from './types';
const req = HttpRequestClient.create<BasicResponse>({
baseURL: '/api',
});
export const findAllBasicPlatforms = (): Promise<PlatformListableResponse> => {
return req.get<PlatformListableResponse>('/system/firerule/platforms/basic');
};

View File

@@ -8,7 +8,8 @@
*/
import { HttpRequestClient } from '@/utils/request';
import type { PlatformWithComponentsResponse, ScenarioPageableResponse, ScenarioRequest, Scenario } from './types';
import type { Scenario, ScenarioPageableResponse, ScenarioRequest } from './types';
import type { PlatformWithComponentsResponse } from '../types';
import type { BasicResponse } from '@/types';
const req = HttpRequestClient.create<BasicResponse>({

View File

@@ -46,6 +46,7 @@
<script lang="ts">
import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import {useRouter} from 'vue-router';
import { message } from 'ant-design-vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { Graph, Node, type NodeProperties } from '@antv/x6';
@@ -54,8 +55,9 @@ import { Wrapper } from '@/components/wrapper';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import Header from '../header.vue';
import type { PlatformWithComponents, Scenario } from './types';
import { createGraphTaskElement, createLineOptions, type GraphContainer, type GraphTaskElement, resolveGraph, useGraphCanvas } from '../graph';
import type { Scenario } from './types';
import type { PlatformWithComponents } from '../types';
import { createLineOptions, type GraphContainer, type GraphTaskElement, resolveGraph, useGraphCanvas } from '../graph';
import { registerScenarioElement } from './register';
import { createGraphScenarioElement, createGraphTaskElementFromScenario } from './utils';
@@ -63,6 +65,7 @@ import { createGraphScenarioElement, createGraphTaskElementFromScenario } from '
import PlatformCard from './platform-card.vue';
import NodesCard from './nodes-card.vue';
import { saveScenario } from './api';
import { resolveConnectionRelation } from './relation';
const TeleportContainer = defineComponent(getTeleport());
@@ -81,6 +84,7 @@ export default defineComponent({
TeleportContainer,
},
setup() {
const router = useRouter();
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
@@ -104,6 +108,19 @@ export default defineComponent({
resizeCanvas,
} = useGraphCanvas();
const destroy = ()=> {
window.removeEventListener('resize', handleResize);
if (graph.value) {
try {
graph.value.clearCells();
} catch (error) {
console.warn('销毁画布时出错:', error);
}
graph.value = null;
console.log('画布已销毁');
}
}
// 处理拖动开始
const handleDragStart = (nm: PlatformWithComponents) => {
draggedNodeData.value = nm;
@@ -194,7 +211,6 @@ export default defineComponent({
};
const handleSelect = (scenario: Scenario) => {
console.info('handleSelect', scenario);
let nodeGraph: GraphContainer | null = null;
try {
nodeGraph = JSON.parse(scenario.communicationGraph as unknown as string) as unknown as GraphContainer;
@@ -210,10 +226,10 @@ export default defineComponent({
currentScenario.value = {
...scenario,
graph: nodeGraph,
relations: []
};
currentScenarioEditing.value = true;
createElements();
};
const createElements = () => {
@@ -228,7 +244,6 @@ export default defineComponent({
if (currentScenario.value?.graph.nodes) {
currentScenario.value?.graph.nodes.forEach(ele => {
const node = createGraphScenarioElement(ele as GraphTaskElement);
console.info('create node: ', ele);
// 将节点添加到画布
graph.value?.addNode(node as Node);
});
@@ -255,10 +270,11 @@ export default defineComponent({
name: null,
description: null,
communicationGraph: null,
relations: [],
graph: {
edges: [],
nodes: [],
}
},
};
currentGraph.value = {
edges: [],
@@ -293,6 +309,23 @@ export default defineComponent({
currentScenarioEditing.value = null !== currentScenario.value;
});
handleGraphEvent('node:dblclick', (args: any) => {
const node = args.node as Node<NodeProperties>;
const element = node.getData() as GraphTaskElement;
console.error('element',element)
if(element && element.platformId ){
window.location.href = `/app/decision/designer?platform=${element.platformId}`
} else {
window.location.href = '/app/decision/designer'
}
// destroy()
// window.location.href = '/app/decision/designer'
// router.push({
// path: '/app/decision/designer'
// })
});
handleGraphEvent('node:click', (args: any) => {
const node = args.node as Node<NodeProperties>;
const newElement = node.getData() as GraphTaskElement;
@@ -341,6 +374,10 @@ export default defineComponent({
const handleSave = () => {
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('当前决策树不存在');
@@ -350,6 +387,7 @@ export default defineComponent({
...currentScenario.value,
graph: graphData,
communicationGraph: JSON.stringify(graphData),
relations: relations
};
if (!newScenario.name) {
message.error('场景名称不能为空.');
@@ -377,18 +415,7 @@ export default defineComponent({
});
// 清理
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
if (graph.value) {
try {
graph.value.clearCells();
} catch (error) {
console.warn('销毁画布时出错:', error);
}
graph.value = null;
console.log('画布已销毁');
}
});
onBeforeUnmount(() => destroy());
return {
scenariosCardRef,

View File

@@ -23,9 +23,11 @@
>
<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>
@@ -38,9 +40,11 @@
<!-- 右侧出桩只能作为连线源 -->
<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>
@@ -130,7 +134,6 @@ export default defineComponent({
onMounted(() => {
_props.node?.on('change:data', handleDataChange);
console.error('element',element.value)
});
onUnmounted(() => {

View File

@@ -27,10 +27,11 @@
</template>
<script lang="ts">
import { defineComponent, onMounted, type PropType, ref } from 'vue';
import { defineComponent, type PropType, ref, watch } from 'vue';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import {findPlatformWithComponents} from './api'
import { type PlatformWithComponents, type Scenario } 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'],
@@ -40,20 +41,13 @@ export default defineComponent({
required: true,
}
},
setup(_props, { emit }) {
setup(props, { emit }) {
const activeKey = ref<number>(1);
const templateData = ref<PlatformWithComponents[]>([]);
const isDraggingOver = ref<boolean>(false);
const draggedNodeData = ref<PlatformWithComponents | null>(null);
const currentScenario = ref<Scenario|null>(_props.scenario)
const loadTress = () => {
templateData.value = []
findPlatformWithComponents(_props.scenario?.id).then(r => {
templateData.value = r.data ?? []
});
};
const currentScenario = ref<Scenario|null>(props.scenario)
const handleDragStart = (e: DragEvent, nm: PlatformWithComponents) => {
let dragNode: PlatformWithComponents = { ...nm };
@@ -92,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

@@ -79,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

@@ -0,0 +1,135 @@
/*
* 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 { Edge, Graph, Node } from '@antv/x6';
import type { PlatformRelation } from './types';
import type { Platform, PlatformComponent } 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

@@ -8,8 +8,22 @@
*/
import type { ApiDataResponse, NullableString, PageableResponse } from '@/types';
import type { 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,
@@ -18,6 +32,7 @@ export interface Scenario {
// 用于存储场景中的通讯关系
communicationGraph: NullableString,
graph: GraphContainer
relations: PlatformRelation[]
}
export interface ScenarioRequest extends Scenario {
@@ -29,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

@@ -9,7 +9,7 @@
import type { GraphRect, GraphTaskElement } from '../graph';
import { generateKey } from '@/utils/strings';
import type { PlatformWithComponents } from './types';
import type { PlatformWithComponents } from '../types';
export const createGraphTaskElementFromScenario = (
platform: PlatformWithComponents,
@@ -28,6 +28,7 @@ export const createGraphTaskElementFromScenario = (
template: 0,
templateType: null,
category: null,
multiable: false,
group: null,
description: platform.description,
order: 0,
@@ -44,6 +45,33 @@ export const createGraphTaskElementFromScenario = (
} 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;
@@ -58,6 +86,24 @@ export const createGraphScenarioElement = (element: GraphTaskElement): any => {
}
}
// 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,
@@ -75,5 +121,9 @@ export const createGraphScenarioElement = (element: GraphTaskElement): any => {
},
},
data: element,
// ports: {
// groups: portsGroups,
// items: portsItems,
// },
};
};

View File

@@ -24,6 +24,10 @@ export const findTreesByQuery = (query: Partial<BehaviorTreeRequest> = {}): Prom
return req.get<BehaviorTreePageResponse>('/system/behaviortree/list', query);
};
export const findOneTreeByPlatformId = (platformId: number): Promise<BehaviorTreeDetailsResponse> => {
return req.get(`/system/behaviortree/platform/${platformId}`);
};
export const findOneTreeById = (id: number): Promise<BehaviorTreeDetailsResponse> => {
return req.get(`/system/behaviortree/${id}`);
};

View File

@@ -37,6 +37,7 @@
</div>
<Properties
v-if="graph"
:platforms="platforms"
:element="selectedNodeTaskElement"
:graph="graph as any"
:node="selectedModelNode as any"
@@ -51,6 +52,7 @@
<script lang="ts">
import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { Graph, Node, type NodeProperties } from '@antv/x6';
@@ -65,8 +67,9 @@ 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 { findAllBasicPlatforms } from '../api';
import type { Platform } from '../types';
import { createTree, findOneTreeById, updateTree, findOneTreeByPlatformId } from './api';
import TressCard from './trees-card.vue';
import NodesCard from './nodes-card.vue';
@@ -88,6 +91,7 @@ export default defineComponent({
TeleportContainer,
},
setup() {
const currentRoute = useRoute();
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
@@ -100,6 +104,7 @@ export default defineComponent({
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
const changed = ref<boolean>(false);
const treesCardRef = ref<InstanceType<typeof TressCard> | null>(null);
const platforms = ref<Platform[]>([]);
const {
handleGraphEvent,
@@ -109,8 +114,23 @@ export default defineComponent({
fitToScreen,
centerContent,
resizeCanvas,
destroyGraph,
clearGraph,
} = useGraphCanvas();
const destroy = ()=> {
window.removeEventListener('resize', handleResize);
destroyGraph();
graph.value = null;
}
const loadPlatforms = () => {
platforms.value = [];
findAllBasicPlatforms().then(r => {
platforms.value = r.data ?? [];
});
};
// 处理拖动开始
const handleDragStart = (nm: NodeDragTemplate) => {
draggedNodeData.value = nm;
@@ -201,6 +221,8 @@ export default defineComponent({
};
const handleSelectTree = (tree: BehaviorTree) => {
destroyGraph();
console.info('handleSelectTree', tree);
findOneTreeById(tree.id).then(r => {
if (r.data) {
@@ -221,7 +243,9 @@ export default defineComponent({
graph: nodeGraph,
};
currentTreeEditing.value = true;
createElements();
nextTick(() => {
initGraph();
});
} else {
message.error(r.msg ?? '行为树不存在.');
}
@@ -229,12 +253,8 @@ export default defineComponent({
};
const createElements = () => {
clearGraph();
nextTick(() => {
try {
graph.value?.clearCells();
} catch (e: any) {
console.error('clear cells error, cause:', e);
}
setTimeout(() => {
if (currentBehaviorTree.value?.graph && graph.value) {
if (currentBehaviorTree.value?.graph.nodes) {
@@ -262,6 +282,8 @@ export default defineComponent({
};
const handleCreateTree = () => {
destroyGraph();
currentBehaviorTree.value = {
id: 0,
name: '行为树',
@@ -282,7 +304,9 @@ export default defineComponent({
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
createElements();
nextTick(() => {
initGraph();
});
};
// 初始化X6画布
@@ -340,6 +364,18 @@ export default defineComponent({
initGraph();
window.addEventListener('resize', handleResize);
console.log('节点挂载完成');
const platformId = currentRoute.query.platform;
if (platformId) {
const id = Number(platformId);
if (!isNaN(id)) {
findOneTreeByPlatformId(id).then(r => {
if (r.data) {
handleSelectTree(r.data);
}
});
}
}
});
};
@@ -393,23 +429,14 @@ export default defineComponent({
// 初始化
onMounted(() => {
init();
loadPlatforms();
});
// 清理
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
if (graph.value) {
try {
graph.value.clearCells();
} catch (error) {
console.warn('销毁画布时出错:', error);
}
graph.value = null;
console.log('画布已销毁');
}
});
onBeforeUnmount(() => destroy());
return {
platforms,
treesCardRef,
handleCreateTree,
currentTreeEditing,

View File

@@ -69,61 +69,71 @@
</a-tabs>
<a-tabs v-if="currentElement" v-model:activeKey="activeBottomTabsKey" class="ks-model-builder-tabs parameters-tabs">
<a-tabs v-if="currentElement?.parameters && currentElement?.parameters.length > 0" v-model:activeKey="activeBottomTabsKey" class="ks-model-builder-tabs parameters-tabs">
<template #leftExtra>
<span class="ks-model-builder-title-icon icon-input"></span>
</template>
<template #rightExtra v-if="multiableParameters">
<a-tooltip title="添加平台" placement="left">
<div class="ks-add-parameter-action" @click="()=> addParameterTab()">
<a-space>
<PlusCircleOutlined/>
<span>添加</span>
</a-space>
</div>
</a-tooltip>
</template>
<a-tab-pane key="1" tab="节点变量">
<template v-if="currentElement.parameters && currentElement.parameters.length > 0">
<a-form
v-if="currentElement.parameters && currentElement.parameters.length > 0"
autocomplete="off"
layout="vertical"
name="basic"
style="padding-bottom:15px;"
>
<a-form-item v-for="setting in currentElement.parameters" :label="setting.description">
<a-input-number v-if="setting.dataType === 'double'" v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" style="width:100%;" />
<a-input v-else v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" />
</a-form-item>
</a-form>
<a-empty v-else>
</a-empty>
<!-- <div class="w-full">-->
<!-- <a-space>-->
<!-- <a-button size="small" type="primary" @click="addVariable">添加</a-button>-->
<!-- </a-space>-->
<!-- <a-table-->
<!-- :columns="actionSpaceColumns"-->
<!-- :dataSource="currentElement.variables"-->
<!-- :pagination="false"-->
<!-- :scroll="{ x: 500 }"-->
<!-- class="mt-1"-->
<!-- row-key="key"-->
<!-- size="small"-->
<!-- style="overflow-y:auto;height:35vh;"-->
<!-- >-->
<!-- <template #bodyCell="{column, record, index}">-->
<!-- <template v-if="column.dataIndex === 'index'">-->
<!-- {{ index + 1 }}-->
<!-- </template>-->
<!-- <template v-else-if="column.dataIndex === '_actions'">-->
<!-- <a-button-->
<!-- class="btn-link-delete"-->
<!-- danger-->
<!-- size="small"-->
<!-- type="text"-->
<!-- @click="()=> removeVariable(record)"-->
<!-- >-->
<!-- 删除-->
<template v-if="multiableParameters">
<a-tabs class="ks-parameter-setting-tabs"
v-model:activeKey="groupedParametersActiveTab"
tab-position="left"
hide-add
size="small"
type="editable-card"
@edit="onEditParameterTab">
<a-tab-pane v-for="(grouped,index) in groupedParameters" :key="index" :tab="`平台 ${index + 1}`" :closable="true">
<a-form-item v-for="setting in grouped" :label="setting.description">
<a-input-number v-if="setting.dataType === 'double'"
v-model:value="setting.defaultValue"
:placeholder="setting.description" size="small" style="width:100%;" />
<a-select :placeholder="`请选择${setting.description}`"
allow-clear
v-else-if="setting.paramKey === 'platforms'" v-model:value="setting.defaultValue">
<a-select-option v-for="pl in platforms" :value="pl.name">{{pl.description}}</a-select-option>
</a-select>
<a-input v-else v-model:value="setting.defaultValue"
:placeholder="setting.description" size="small" />
</a-form-item>
</a-tab-pane>
<!-- <template #leftExtra>-->
<!-- <a-button class="ks-btn" size="small" style="margin-bottom: 15px; width: 100%" block @click="()=> addParameterTab()">-->
<!-- <PlusOutlined />-->
<!--&lt;!&ndash; <span>添加</span>&ndash;&gt;-->
<!-- </a-button>-->
<!-- </template>-->
<!-- <template v-else>-->
<!-- <a-input v-model:value="record[column.dataIndex]" size="small" />-->
<!-- </template>-->
<!-- </template>-->
<!-- </a-table>-->
<!-- </div>-->
</a-tabs>
</template>
<template v-else>
<a-form-item v-for="setting in currentElement.parameters" :label="setting.description">
<a-input-number v-if="setting.dataType === 'double'" v-model:value="setting.defaultValue"
:placeholder="setting.description" size="small" style="width:100%;" />
<a-input v-else v-model:value="setting.defaultValue" :placeholder="setting.description" size="small" />
</a-form-item>
</template>
</a-form>
</template>
<a-empty v-else>
</a-empty>
</a-tab-pane>
</a-tabs>
@@ -146,11 +156,12 @@
<script lang="ts">
import { defineComponent, onMounted, type PropType, ref, watch } from 'vue';
import { CheckOutlined } from '@ant-design/icons-vue';
import type { ElementVariable, GraphTaskElement } from '../graph';
import { CheckOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import type { ElementParameter, ElementVariable, GraphTaskElement } from '../graph';
import type { BehaviorTree } from './tree';
import type { Graph, Node, NodeProperties } from '@antv/x6';
import { generateKey } from '@/utils/strings';
import type { Platform } from '@/views/decision/types';
const actionSpaceColumns = [
{ title: '序号', dataIndex: 'index', key: 'index', width: 40 },
@@ -161,15 +172,18 @@ const actionSpaceColumns = [
];
export default defineComponent({
components: { CheckOutlined },
components: { CheckOutlined, PlusOutlined, PlusCircleOutlined },
props: {
tree: { type: [Object, null] as PropType<BehaviorTree | null | undefined>, required: false },
treeEditing: { type: Boolean as PropType<boolean>, required: true, default: false },
node: { type: [Object, null] as PropType<Node<NodeProperties> | null | undefined>, required: false },
graph: { type: [Object, null] as PropType<Graph | null | undefined>, required: true },
platforms: { type: Array as PropType<Platform[]>, required: true },
},
emits: ['update-element', 'update-tree'],
setup(props, { emit }) {
const platforms = ref<Platform[]>(props.platforms ?? []);
const activeTopTabsKey = ref<string>('1');
const activeBottomTabsKey = ref<string>('1');
const activeBottomTabs2Key = ref<string>('1');
@@ -179,10 +193,98 @@ export default defineComponent({
const currentNode = ref<Node | null>(props.node ?? null);
const currentElement = ref<GraphTaskElement | null>(null);
const load = () => {
const emptyParameters = ref<ElementParameter[]>([]);
const groupedParameters = ref<Array<ElementParameter[]>>([]);
const multiableParameters = ref<boolean>(false);
const groupedParametersActiveTab = ref<number>(0);
const createEmptyParameters = (): ElementParameter[] => {
try {
return JSON.parse(JSON.stringify(currentElement.value?.parameters ?? [])) as ElementParameter[];
} catch (e: any) {
return [];
}
};
const dumpParameters = (): ElementParameter[] => {
return JSON.parse(JSON.stringify(emptyParameters.value)) as ElementParameter[];
};
const addParameterTab = () => {
let newParameters = dumpParameters();
// 新增一个空的参数分组
groupedParameters.value.push(newParameters);
// 自动切换到新增的分组
groupedParametersActiveTab.value = groupedParameters.value.length - 1;
};
const removeParameterTab = (index: number) => {
// 边界判断:防止删除不存在的分组 / 只剩一个分组时禁止删除
if (index < 0 || index >= groupedParameters.value.length) return;
if (groupedParameters.value.length <= 1) return;
// 从数组中删除对应索引的分组
groupedParameters.value.splice(index, 1);
if (groupedParameters.value.length === 0) {
groupedParameters.value.push(dumpParameters());
}
// 删除后处理激活状态:
// 如果删除的是最后一个分组,激活前一个
if (groupedParametersActiveTab.value >= groupedParameters.value.length) {
groupedParametersActiveTab.value = groupedParameters.value.length - 1;
}
};
const onEditParameterTab = (targetKey: number | MouseEvent, action: string) => {
if (action === 'add') {
addParameterTab();
} else {
removeParameterTab(targetKey as number);
}
};
const resolveGroupedParameters = () => {
emptyParameters.value = createEmptyParameters();
// 解构获取当前元素的关键属性,简化代码
const { multiable, parameters } = currentElement.value || {};
// 1. 不满足多分组条件:直接清空分组
if (multiable !== true || !parameters || parameters.length === 0) {
groupedParameters.value = [];
multiableParameters.value = multiable === true;
return;
}
// 2. 满足条件:根据 groupIndex 对参数进行分组
// 第一步:用 Map 做临时分组key=groupIndexvalue=当前分组的参数数组)
const groupMap = new Map<number, ElementParameter[]>();
parameters.forEach(param => {
const index = param.groupIndex;
// 如果 Map 中没有该分组,先初始化空数组
if (!groupMap.has(index)) {
groupMap.set(index, []);
}
// 将当前参数推入对应分组
groupMap.get(index)!.push(param);
});
// 第二步:将 Map 转换为二维数组(按 groupIndex 升序排序)
groupedParameters.value = Array.from(groupMap.entries())
// 按分组索引从小到大排序(保证分组顺序正确)
.sort((a, b) => a[0] - b[0])
// 只保留分组后的参数数组,丢弃 key
.map(item => item[1]);
multiableParameters.value = multiable === true && groupedParameters.value.length > 0;
};
const resolveNode = (n?: Node | null | undefined) => {
groupedParametersActiveTab.value = 0;
currentNode.value = n ?? null;
if (n) {
const data = n.getData();
@@ -190,6 +292,7 @@ export default defineComponent({
} else {
currentElement.value = null;
}
resolveGroupedParameters();
};
const addVariable = () => {
@@ -220,6 +323,17 @@ export default defineComponent({
if (currentNode.value && currentElement.value) {
// 深拷贝当前元素数据
const newElement = JSON.parse(JSON.stringify(currentElement.value)) as GraphTaskElement;
if (multiableParameters.value) {
newElement.parameters = groupedParameters.value.flatMap((group, groupIndex) => {
// 遍历每个分组,给组内所有参数统一设置/保持 groupIndex
return group.map(param => ({
...param,
groupIndex: groupIndex // 强制保证:当前参数的分组索引 = 所在分组的索引
}));
});
}
// 更新节点数据
currentNode.value.replaceData(newElement);
// 触发事件通知父组件
@@ -227,6 +341,9 @@ export default defineComponent({
}
};
const load = () => {
};
watch(
() => props.node,
(n?: Node | null | undefined) => resolveNode(n),
@@ -249,11 +366,21 @@ export default defineComponent({
{ deep: true, immediate: true },
);
watch(() => groupedParameters.value, () => updateNode(), { deep: true });
watch(() => currentElement.value, () => updateNode(), { deep: true });
watch(() => props.platforms, (n: Platform[] | null | undefined) => platforms.value = n ?? [], { deep: true, immediate: true });
onMounted(() => load());
return {
platforms,
addParameterTab,
groupedParametersActiveTab,
multiableParameters,
onEditParameterTab,
groupedParameters,
actionSpaceColumns,
activeTopTabsKey,
activeBottomTabsKey,

View File

@@ -19,6 +19,7 @@ export interface NodeTemplate {
templateType: NullableString;
englishName: NullableString;
parameters: ElementParameter[],
multiable?: boolean,
}
export interface NodeDragTemplate extends NodeTemplate {

View File

@@ -27,6 +27,7 @@ export const createGraphTaskElementFromTemplate = (
category: template.type,
group: template.group,
description: template.description,
multiable: template.multiable === true,
order: 0,
position: {
x: realRect.x ?? 0,

View File

@@ -58,7 +58,7 @@ export const createGraphConnectingAttributes = (): Partial<Connecting> => {
...lineOptions.attrs?.line,
targetMarker: null,
sourceMarker: null,
}
},
},
animation: lineOptions.animation,
markup: lineOptions.markup,

View File

@@ -53,7 +53,7 @@ export interface GraphBaseElement {
position: GraphPosition;
category: NullableString;
element?: GraphDraggableElement;
components?: GraphComponentElement[]
components?: GraphComponentElement[];
[key: string]: unknown;
}
@@ -67,6 +67,7 @@ export interface ElementParameter {
defaultValue: NullableString,
description: NullableString,
templateType: NullableString,
groupIndex: number,
}
@@ -84,6 +85,7 @@ export interface GraphTaskElement extends GraphBaseElement {
inputs: any;
outputs: any;
order: number;
multiable:boolean,
variables: ElementVariable[];
parameters: ElementParameter[];
children?: GraphTaskElement[],

View File

@@ -7,7 +7,7 @@
* that was distributed with this source code.
*/
import { computed, type ComputedRef, ref, type Ref } from 'vue';
import { computed, type ComputedRef, ref, type Ref, nextTick } from 'vue';
import { type Dom, Graph, Node } from '@antv/x6';
import type { NodeViewPositionEventArgs } from '@antv/x6/es/view/node/type';
import { createGraphCanvas } from './canvas';
@@ -24,6 +24,8 @@ export interface UseGraphCanvas {
graph: ComputedRef<Graph>;
zoomIn: () => void;
zoomOut: () => void;
destroyGraph: () => void;
clearGraph: () => void;
fitToScreen: () => void;
centerContent: () => void;
resizeCanvas: () => void;
@@ -39,6 +41,36 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
const eventListener = new EventListener();
const currentZoom = ref<number>(0);
const clearGraph = ()=> {
if (graph.value) {
try {
// graph.value.off();
graph.value.clearCells();
} catch (e) {
console.error('清空画布失败:', e);
}
}
}
const destroyGraph = ()=> {
eventListener.clear();
if (graph.value) {
clearGraph();
// 等待 Vue 完成卸载
nextTick(() => {
graph.value?.dispose(); // 销毁 Graph 实例
graph.value = null;
if (container.value) {
container.value.innerHTML = ''; // 清空容器内容
}
});
} else if (container.value) {
container.value.innerHTML = '';
}
}
const handleGraphEvent = (name: string, fn: Function) => {
eventListener.on(name, fn);
};
@@ -183,6 +215,11 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
emitGraphEvent('node:click', ctx);
});
graph.value.on('node:dblclick', (ctx: NodeViewPositionEventArgs<Dom.ClickEvent>) => {
console.info('node:dblclick', ctx);
emitGraphEvent('node:dblclick', ctx);
});
// 监听节点选中事件
graph.value.on('node:selected', ({ node }) => {
console.info('node select', node);
@@ -224,6 +261,7 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
const createCanvas = (c: HTMLDivElement): Graph => {
container.value = c;
graph.value = createGraphCanvas(c, readonly);
initEvents();
@@ -237,6 +275,8 @@ export const useGraphCanvas = (readonly: boolean = false): UseGraphCanvas => {
return {
container,
readonly,
destroyGraph,
clearGraph,
graph: graphInstance,
eventListener,
currentZoom,

View File

@@ -7,10 +7,10 @@
* 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'
export * from './line';
export * from './ports';
export * from './element';
export * from './canvas';
export * from './hooks';
export * from './props';
export * from './utils';

View File

@@ -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,

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;
if(selectedFireRule.value.id <= 0){
selectedFireRule.value = JSON.parse(JSON.stringify(defaultFireRule));
nextTick(() => {
formRef.value?.resetFields();
selectedFireRule.value = resolveItem(defaultFireRule);
});
}
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);
} else {
res = createFireRule(savedValue);
}
if (res) {
res.then(r => {
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.info(r.msg ?? '操作成功');
message.success(r.msg ?? '操作成功');
} else {
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,
conditionsArray: PlatformComponentPayload[],
// 响应动作JSON格式
actions: NullableString,
actionsArray: PlatformComponentPayload[],
// 优先级(数值越小优先级越高)
priority: number,
// 是否启用0禁用1启用

View File

@@ -0,0 +1,10 @@
/*
* 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 './platform'

View File

@@ -0,0 +1,47 @@
/*
* 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 PlatformListableResponse extends ApiDataResponse<Platform[]> {
}
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

@@ -44,6 +44,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']
@@ -87,6 +88,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>