Compare commits

48 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
MHW
cc01c9ece8 Merge remote-tracking branch 'origin/master' 2026-03-15 09:33:09 +08:00
MHW
8f29e230d0 Merge branch 'refs/heads/develop' 2026-03-15 09:32:14 +08:00
MHW
711d7bf3da 26-03-15-09:31 场景模块:分页查询所有场景,保存场景 2026-03-15 09:31:45 +08:00
libertyspy
29e17773af UPDATE: VERSION-20260314 2026-03-14 22:35:40 +08:00
libertyspy
db97d8a026 UPDATE: VERSION-20260314 2026-03-14 22:35:31 +08:00
libertyspy
2e55254412 UPDATE: VERSION-20260314 2026-03-14 22:35:21 +08:00
libertyspy
1504c3fc1b UPDATE: VERSION-20260314 2026-03-14 21:37:18 +08:00
libertyspy
0cf4c9b47e UPDATE: VERSION-20260314 2026-03-14 21:37:07 +08:00
libertyspy
fa0c93044c Merge remote-tracking branch 'origin/master' 2026-03-14 20:55:23 +08:00
libertyspy
33a77428db UPDATE: VERSION-20260314 2026-03-14 20:55:15 +08:00
MHW
26a89a66d1 Merge branch 'refs/heads/develop' 2026-03-14 20:47:07 +08:00
MHW
f72105134f 26-03-14-20:46 通过平台id获取平台下所有组件 2026-03-14 20:46:49 +08:00
libertyspy
2198e108a4 UPDATE: VERSION-20260314 2026-03-14 18:08:20 +08:00
libertyspy
fe94cec559 Merge remote-tracking branch 'origin/master' 2026-03-14 17:57:05 +08:00
MHW
af3a97175a Merge branch 'refs/heads/develop' 2026-03-14 14:31:12 +08:00
MHW
c1c67e826b 26-03-14-14:30 规则CRUD 2026-03-14 14:30:52 +08:00
libertyspy
7b578f5d63 UPDATE: VERSION-20260313 2026-03-13 17:05:08 +08:00
78 changed files with 3724 additions and 622 deletions

View File

@@ -76,6 +76,11 @@
<artifactId>solution-rule</artifactId>
</dependency>
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-scene</artifactId>
</dependency>
</dependencies>
<build>

View File

@@ -3,7 +3,6 @@ package com.solution.web.controller.behaviour;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.solution.system.domain.AfsimScenario;
import com.solution.web.core.BehaviortreeProcessor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@@ -116,15 +115,4 @@ public class BehaviortreeController extends BaseController
return toAjax(behaviortreeService.deleteBehaviortreeByIds(ids));
}
/**
* 保存场景配置
*/
@ApiOperation("保存场景配置")
@PostMapping("/saveSceneConfig")
@Log(title = "行为树主", businessType = BusinessType.INSERT)
public AjaxResult saveSceneConfig(@RequestBody AfsimScenario afsimScenario)
{
return toAjax(behaviortreeService.insert(afsimScenario));
}
}

View File

@@ -0,0 +1,81 @@
package com.solution.web.controller.rule;
import com.solution.common.core.controller.BaseController;
import com.solution.common.core.domain.AjaxResult;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.service.FireRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api("火力规则")
@RestController
@RequestMapping("/api/system/firerule")
public class FireRuleController extends BaseController {
@Autowired
private FireRuleService ruleService;
/**
* 开始执行规则匹配
* @param fireRuleExecuteDTO 敌方参数
* @return
*/
@PostMapping("/start")
@ApiOperation("开始执行规则匹配")
public AjaxResult execute(@RequestBody FireRuleExecuteDTO fireRuleExecuteDTO){
return success(ruleService.execute(fireRuleExecuteDTO));
}
/**
* 获取所有武器平台和组件
* @return
*/
@GetMapping("/weapon")
@ApiOperation("获取所有武器平台和组件")
public AjaxResult getPlatformComponentNames(){
return success(ruleService.getPlatformComponentNames());
}
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
*/
@GetMapping("/comm")
@ApiOperation("获取通信组件的所有平台和组件")
public AjaxResult getCommPlatformComponentNames(Integer scenarioId){
return success(ruleService.getCommPlatformComponentNames(scenarioId));
}
/**
* 根据场景id获取所有平台及其组件
* @param scenarioId
* @return
*/
@GetMapping("/platforms/{scenarioId}")
public AjaxResult platformsScenarioId(@PathVariable Integer scenarioId){
return success(ruleService.findPlatformComponents(scenarioId));
}
@GetMapping("/platforms")
public AjaxResult platforms(){
return success(ruleService.findAllPlatformComponents());
}
/**
* 根据平台id获取平台下所有组件
* @param platformId
* @return
*/
@GetMapping("/component/{platformId}")
@ApiOperation("根据平台id获取平台下所有组件")
public AjaxResult getComponents(@PathVariable Integer platformId){
return success(ruleService.getComponents(platformId));
}
}

View File

@@ -1,55 +1,65 @@
package com.solution.web.controller.rule;
import com.solution.common.annotation.Log;
import com.solution.common.core.controller.BaseController;
import com.solution.common.core.domain.AjaxResult;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.service.RuleService;
import com.solution.common.core.page.TableDataInfo;
import com.solution.common.enums.BusinessType;
import com.solution.rule.domain.Rule;
import com.solution.rule.service.IRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api("火力规则")
@Api("红蓝对抗规则管理")
@RestController
@RequestMapping("/api/system/firerule")
@RequestMapping("/api/system/rule")
public class RuleController extends BaseController {
@Autowired
private RuleService ruleService;
private IRuleService ruleService;
/**
* 开始执行规则匹配
* @param fireRuleExecuteDTO 敌方参数
* @return
*/
@PostMapping("/start")
@ApiOperation("开始执行规则匹配")
public AjaxResult execute(@RequestBody FireRuleExecuteDTO fireRuleExecuteDTO){
return success(ruleService.execute(fireRuleExecuteDTO));
@PreAuthorize("@ss.hasPermi('system:rule:list')")
@GetMapping("/list")
@ApiOperation("查询规则列表")
public TableDataInfo list(Rule rule) {
startPage();
List<Rule> list = ruleService.selectRuleList(rule);
return getDataTable(list);
}
/**
* 获取所有武器平台和组件
* @return
*/
@GetMapping("/weapon")
@ApiOperation("获取所有武器平台和组件")
public AjaxResult getPlatformComponentNames(){
return success(ruleService.getPlatformComponentNames());
@PreAuthorize("@ss.hasPermi('system:rule:query')")
@GetMapping("/{id}")
@ApiOperation("获取规则详情")
public AjaxResult getInfo(@PathVariable Integer id) {
return success(ruleService.selectRuleById(id));
}
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
*/
@GetMapping("/comm")
@ApiOperation("获取通信组件的所有平台和组件")
public AjaxResult getCommPlatformComponentNames(Integer scenarioId){
return success(ruleService.getCommPlatformComponentNames(scenarioId));
@PreAuthorize("@ss.hasPermi('system:rule:add')")
@Log(title = "规则管理", businessType = BusinessType.INSERT)
@PostMapping
@ApiOperation("新增规则")
public AjaxResult add(@RequestBody Rule rule) {
return toAjax(ruleService.insertRule(rule));
}
@PreAuthorize("@ss.hasPermi('system:rule:edit')")
@Log(title = "规则管理", businessType = BusinessType.UPDATE)
@PutMapping
@ApiOperation("修改规则")
public AjaxResult edit(@RequestBody Rule rule) {
return toAjax(ruleService.updateRule(rule));
}
@PreAuthorize("@ss.hasPermi('system:rule:remove')")
@Log(title = "规则管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
@ApiOperation("删除规则")
public AjaxResult remove(@PathVariable Integer[] ids) {
return toAjax(ruleService.deleteRuleByIds(ids));
}
}

View File

@@ -0,0 +1,52 @@
package com.solution.web.controller.scene;
import com.solution.common.annotation.Log;
import com.solution.common.core.controller.BaseController;
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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 场景管理
*/
@Api("场景管理")
@RestController
@RequestMapping("/api/system/scene")
public class SceneController extends BaseController {
@Autowired
private SceneService sceneService;
/**
* 保存场景配置
*/
@ApiOperation("保存场景配置")
@PostMapping("/saveSceneConfig")
@Log(title = "行为树主", businessType = BusinessType.INSERT)
public AjaxResult saveSceneConfig(@RequestBody AfsimScenario afsimScenario)
{
return toAjax(sceneService.saveOrUpdate(afsimScenario));
}
/**
* 获取场景列表
* @return
*/
@GetMapping("/list")
@ApiOperation("获取场景列表")
public TableDataInfo list(){
startPage();
List<AfsimScenario> list = sceneService.selectSceneList();
return getDataTable(list);
}
}

View File

@@ -2,7 +2,6 @@ package com.solution.system.mapper;
import java.util.List;
import com.solution.system.domain.AfsimScenario;
import com.solution.system.domain.Behaviortree;
/**
@@ -60,11 +59,4 @@ public interface BehaviortreeMapper
* @return 结果
*/
public int deleteBehaviortreeByIds(Long[] ids);
/**
* 保存场景配置
* @param afsimScenario
* @return
*/
int insert(AfsimScenario afsimScenario);
}

View File

@@ -2,7 +2,6 @@ package com.solution.system.service;
import java.util.List;
import com.solution.system.domain.AfsimScenario;
import com.solution.system.domain.Behaviortree;
/**
@@ -60,11 +59,4 @@ public interface IBehaviortreeService
* @return 结果
*/
public int deleteBehaviortreeById(Long id);
/**
* 保存场景配置
* @param afsimScenario
* @return
*/
int insert(AfsimScenario afsimScenario);
}

View File

@@ -4,7 +4,6 @@ import java.util.List;
import cn.hutool.core.util.ObjectUtil;
import com.solution.common.constant.ExceptionConstants;
import com.solution.system.domain.AfsimScenario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.solution.system.mapper.BehaviortreeMapper;
@@ -94,17 +93,4 @@ public class BehaviortreeServiceImpl implements IBehaviortreeService
{
return behaviortreeMapper.deleteBehaviortreeById(id);
}
/**
* 保存场景配置
* @param afsimScenario
* @return
*/
@Override
public int insert(AfsimScenario afsimScenario) {
if(ObjectUtil.isEmpty(afsimScenario) || ObjectUtil.isEmpty(afsimScenario.getCommunicationGraph())){
throw new RuntimeException(ExceptionConstants.SCENE_CONFIG_NOT_NULL);
}
return behaviortreeMapper.insert(afsimScenario);
}
}

View File

@@ -55,7 +55,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</trim>
</insert>
<insert id="insert" parameterType="com.solution.system.domain.AfsimScenario">
<insert id="insert" parameterType="com.solution.scene.domain.AfsimScenario">
INSERT INTO afsim_scenario (name, description, scenario_path, communication_graph)
VALUES (#{name}, #{description}, #{scenarioPath}, #{communicationGraph})
</insert>

View File

@@ -18,7 +18,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
select id, template_id, param_key, data_type, default_value, description, template_type from templateparameterdef
</sql>
<select id="selectTemplateparameterdefList" parameterType="Templateparameterdef" resultMap="TemplateparameterdefResult">
<select id="selectTemplateparameterdefList" parameterType="templateparameterdef" resultMap="TemplateparameterdefResult">
<include refid="selectTemplateparameterdefVo"/>
<where>
<if test="templateId != null "> and template_id = #{templateId}</if>

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,56 @@
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 Platform implements Serializable {
private Integer id;
private String name;
private String description;
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;
}
public void setComponents(List<PlatformComponent> components) {
this.components = components;
}
}

View File

@@ -0,0 +1,37 @@
package com.solution.rule.domain;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
@Data
@ApiModel("红蓝对抗规则")
public class Rule {
@ApiModelProperty("规则ID")
private Integer id;
@ApiModelProperty("规则名称")
private String name;
@ApiModelProperty("场景类型0-防御1-空降null表示通用")
private Integer sceneType;
@ApiModelProperty("触发条件JSON格式")
private String conditions;
@ApiModelProperty("响应动作JSON格式")
private String actions;
@ApiModelProperty("优先级(数值越小优先级越高)")
private Integer priority;
@ApiModelProperty("是否启用0禁用1启用")
private Boolean enabled;
@ApiModelProperty("创建时间")
private Date createdTime;
@ApiModelProperty("更新时间")
private Date updatedTime;
}

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

@@ -0,0 +1,47 @@
package com.solution.rule.mapper;
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface FireRuleMapper {
/**
* 获取所有武器平台和组件
* @return
*/
List<WeaponModelVO> getWeapon();
List<WeaponModelVO> getPlatformComponentNames();
/**
* 获取所有组件以及数量
* @return
*/
List<ComponentCountVO> getModuleAndCount();
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
*/
List<PlatformComponentNamesVO> getCommPlatformComponentNames(Integer scenarioId);
/**
* 根据平台id获取平台下所有组件
* @param platformId
* @return
*/
List<PlatformComponent> getComponents(Integer platformId);
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
}

View File

@@ -1,34 +1,38 @@
package com.solution.rule.mapper;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import org.apache.ibatis.annotations.Mapper;
import com.solution.rule.domain.Rule;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface RuleMapper {
/**
* 根据ID查询规则
*/
Rule selectRuleById(Integer id);
/**
* 获取所有武器平台和组件
* @return
* 查询规则列表(支持分页)
*/
List<WeaponModelVO> getWeapon();
List<WeaponModelVO> getPlatformComponentNames();
List<Rule> selectRuleList(Rule rule);
/**
* 获取所有组件以及数量
* @return
* 新增规则
*/
List<ComponentCountVO> getModuleAndCount();
int insertRule(Rule rule);
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
* 修改规则
*/
List<PlatformComponentNamesVO> getCommPlatformComponentNames(Integer scenarioId);
int updateRule(Rule rule);
/**
* 删除规则
*/
int deleteRuleById(Integer id);
/**
* 批量删除规则
*/
int deleteRuleByIds(@Param("ids")Integer[] ids);
}

View File

@@ -1,16 +1,14 @@
package com.solution.rule.service;
import com.solution.rule.domain.FireRuleExecuteDTO;
import com.solution.rule.domain.dto.RequestDTO;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.domain.Platform;
import com.solution.rule.domain.PlatformComponent;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import java.util.HashMap;
import java.util.List;
public interface RuleService {
public interface FireRuleService {
/**
* 开始执行规则匹配
@@ -33,4 +31,20 @@ public interface RuleService {
* @return
*/
List<PlatformComponentNamesVO> getCommPlatformComponentNames(Integer scenarioId);
/**
* 根据平台id获取平台下所有组件
* @param platformId
* @return
*/
List<PlatformComponent> getComponents(Integer platformId);
/**
* 根据场景id获取所有平台及其组件
* @param scenarioId
* @return
*/
List<Platform> findPlatformComponents(Integer scenarioId);
List<Platform> findAllPlatformComponents();
}

View File

@@ -0,0 +1,36 @@
package com.solution.rule.service;
import com.solution.rule.domain.Rule;
import java.util.List;
public interface IRuleService {
/**
* 根据ID查询规则
*/
Rule selectRuleById(Integer id);
/**
* 查询规则列表
*/
List<Rule> selectRuleList(Rule rule);
/**
* 新增规则
*/
int insertRule(Rule rule);
/**
* 修改规则
*/
int updateRule(Rule rule);
/**
* 删除规则
*/
int deleteRuleById(Integer id);
/**
* 批量删除规则
*/
int deleteRuleByIds(Integer[] ids);
}

View File

@@ -0,0 +1,184 @@
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.dto.WeaponModelDTO;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import com.solution.rule.mapper.FireRuleMapper;
import com.solution.rule.service.FireRuleService;
import com.solution.rule.strategy.SceneStrategy;
import com.solution.rule.strategy.SceneStrategyFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class FireRuleServiceImpl implements FireRuleService {
private static final long COMPONENT_QUANTITY_THRESHOLD = 1;
@Autowired
private SceneStrategyFactory strategyFactory;
@Autowired
private FireRuleMapper ruleMapper;
/* @Override
public WeaponModelVO execute(Integer sceneType, WeaponModelDTO weaponModelDTO) {
if(ObjectUtil.isNull(sceneType) || ObjectUtil.isEmpty(weaponModelDTO)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
//TODO 查数据库获取我方装备
List<PlatformWeaponAggregateVO> weapon = this.getWeapon();
SceneStrategy strategy = strategyFactory.getStrategy(sceneType);
WeaponModelVO result = strategy.execute(weaponModelDTO);
if(ObjectUtil.isEmpty(result)){
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
}
return result;
}*/
@Override
public List<PlatformWeaponAggregateVO> execute(FireRuleExecuteDTO fireRuleExecuteDTO) {
if(ObjectUtil.isEmpty(fireRuleExecuteDTO)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
List<WeaponModelDTO> weaponModelDTOs = fireRuleExecuteDTO.getWeaponModelDTOs();
Integer sceneType = fireRuleExecuteDTO.getSceneType();
// 查数据库获取我方装备
List<ComponentCountVO> weapon = this.getModuleAndCount();
// 创建RuleParam并设置数据
RuleParam ruleParam = new RuleParam();
ruleParam.setWeaponModelDTOList(weaponModelDTOs);
ruleParam.setDatabaseWeapons(weapon);
// 执行策略
SceneStrategy strategy = strategyFactory.getStrategy(sceneType);
List<PlatformWeaponAggregateVO> result = strategy.execute(ruleParam);
return result;
}
@Override
public List<PlatformWeaponAggregateVO> getWeapon() {
List<WeaponModelVO> flatList = ruleMapper.getWeapon();
if (CollUtil.isEmpty(flatList)) {
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
}
Map<String, List<WeaponModelVO>> groupByPlatform = flatList.stream()
.collect(Collectors.groupingBy(WeaponModelVO::getPlatformName));
List<PlatformWeaponAggregateVO> result = new ArrayList<>();
for (Map.Entry<String, List<WeaponModelVO>> entry : groupByPlatform.entrySet()) {
PlatformWeaponAggregateVO platformVO = new PlatformWeaponAggregateVO();
platformVO.setPlatformName(entry.getKey());
List<ComponentCountVO> components = entry.getValue().stream()
.map(item -> {
ComponentCountVO comp = new ComponentCountVO();
comp.setComponentName(item.getComponentName());
comp.setCount(item.getCount());
return comp;
})
.collect(Collectors.toList());
platformVO.setComponentCountVOS(components);
result.add(platformVO);
}
return result;
}
/**
* 获取所有武器平台和组件
* @return
*/
@Override
public List<PlatformComponentNamesVO> getPlatformComponentNames() {
List<WeaponModelVO> flatList = ruleMapper.getPlatformComponentNames();
if (CollUtil.isEmpty(flatList)) {
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
}
Map<String, List<String>> groupByPlatform = flatList.stream()
.collect(Collectors.groupingBy(
WeaponModelVO::getPlatformName,
Collectors.mapping(WeaponModelVO::getComponentName, Collectors.toList())
));
return groupByPlatform.entrySet().stream()
.map(entry -> {
PlatformComponentNamesVO vo = new PlatformComponentNamesVO();
vo.setPlatformName(entry.getKey());
vo.setComponentNames(entry.getValue());
return vo;
})
.collect(Collectors.toList());
}
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
*/
@Override
public List<PlatformComponentNamesVO> getCommPlatformComponentNames(Integer scenarioId) {
return ruleMapper.getCommPlatformComponentNames(scenarioId);
}
/**
* 根据平台id获取平台下所有组件
* @param platformId
* @return
*/
@Override
public List<PlatformComponent> getComponents(Integer platformId) {
return ruleMapper.getComponents(platformId);
}
/**
* 获取所有组件以及数量
* @return
*/
private List<ComponentCountVO> getModuleAndCount(){
List<ComponentCountVO> componentCountVOS = ruleMapper.getModuleAndCount();
if(CollUtil.isEmpty(componentCountVOS)){
return new ArrayList<>();
}
return componentCountVOS;
}
@Override
public List<Platform> findPlatformComponents(Integer scenarioId) {
List<Platform> platforms = ruleMapper.findPlatformComponents(scenarioId);
if(!CollUtil.isEmpty(platforms)){
return platforms;
}
return new ArrayList<>();
}
@Override
public List<Platform> findAllPlatformComponents() {
return ruleMapper.findAllPlatformComponents();
}
}

View File

@@ -1,156 +1,46 @@
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.RuleParam;
import com.solution.rule.domain.dto.WeaponModelDTO;
import com.solution.rule.domain.vo.ComponentCountVO;
import com.solution.rule.domain.vo.PlatformComponentNamesVO;
import com.solution.rule.domain.vo.PlatformWeaponAggregateVO;
import com.solution.rule.domain.vo.WeaponModelVO;
import com.solution.rule.domain.Rule;
import com.solution.rule.mapper.RuleMapper;
import com.solution.rule.service.RuleService;
import com.solution.rule.strategy.SceneStrategy;
import com.solution.rule.strategy.SceneStrategyFactory;
import com.solution.rule.service.IRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class RuleServiceImpl implements RuleService {
private static final long COMPONENT_QUANTITY_THRESHOLD = 1;
@Autowired
private SceneStrategyFactory strategyFactory;
public class RuleServiceImpl implements IRuleService {
@Autowired
private RuleMapper ruleMapper;
/* @Override
public WeaponModelVO execute(Integer sceneType, WeaponModelDTO weaponModelDTO) {
if(ObjectUtil.isNull(sceneType) || ObjectUtil.isEmpty(weaponModelDTO)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
//TODO 查数据库获取我方装备
List<PlatformWeaponAggregateVO> weapon = this.getWeapon();
SceneStrategy strategy = strategyFactory.getStrategy(sceneType);
WeaponModelVO result = strategy.execute(weaponModelDTO);
if(ObjectUtil.isEmpty(result)){
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
}
return result;
}*/
@Override
public List<PlatformWeaponAggregateVO> execute(FireRuleExecuteDTO fireRuleExecuteDTO) {
if(ObjectUtil.isEmpty(fireRuleExecuteDTO)){
throw new RuntimeException(ExceptionConstants.PARAMETER_EXCEPTION);
}
List<WeaponModelDTO> weaponModelDTOs = fireRuleExecuteDTO.getWeaponModelDTOs();
Integer sceneType = fireRuleExecuteDTO.getSceneType();
// 查数据库获取我方装备
List<ComponentCountVO> weapon = this.getModuleAndCount();
// 创建RuleParam并设置数据
RuleParam ruleParam = new RuleParam();
ruleParam.setWeaponModelDTOList(weaponModelDTOs);
ruleParam.setDatabaseWeapons(weapon);
// 执行策略
SceneStrategy strategy = strategyFactory.getStrategy(sceneType);
List<PlatformWeaponAggregateVO> result = strategy.execute(ruleParam);
return result;
public Rule selectRuleById(Integer id) {
return ruleMapper.selectRuleById(id);
}
@Override
public List<PlatformWeaponAggregateVO> getWeapon() {
List<WeaponModelVO> flatList = ruleMapper.getWeapon();
if (CollUtil.isEmpty(flatList)) {
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
public List<Rule> selectRuleList(Rule rule) {
return ruleMapper.selectRuleList(rule);
}
Map<String, List<WeaponModelVO>> groupByPlatform = flatList.stream()
.collect(Collectors.groupingBy(WeaponModelVO::getPlatformName));
List<PlatformWeaponAggregateVO> result = new ArrayList<>();
for (Map.Entry<String, List<WeaponModelVO>> entry : groupByPlatform.entrySet()) {
PlatformWeaponAggregateVO platformVO = new PlatformWeaponAggregateVO();
platformVO.setPlatformName(entry.getKey());
List<ComponentCountVO> components = entry.getValue().stream()
.map(item -> {
ComponentCountVO comp = new ComponentCountVO();
comp.setComponentName(item.getComponentName());
comp.setCount(item.getCount());
return comp;
})
.collect(Collectors.toList());
platformVO.setComponentCountVOS(components);
result.add(platformVO);
}
return result;
}
/**
* 获取所有武器平台和组件
* @return
*/
@Override
public List<PlatformComponentNamesVO> getPlatformComponentNames() {
List<WeaponModelVO> flatList = ruleMapper.getPlatformComponentNames();
if (CollUtil.isEmpty(flatList)) {
throw new RuntimeException(ExceptionConstants.RESULT_EXCEPTION);
public int insertRule(Rule rule) {
return ruleMapper.insertRule(rule);
}
Map<String, List<String>> groupByPlatform = flatList.stream()
.collect(Collectors.groupingBy(
WeaponModelVO::getPlatformName,
Collectors.mapping(WeaponModelVO::getComponentName, Collectors.toList())
));
return groupByPlatform.entrySet().stream()
.map(entry -> {
PlatformComponentNamesVO vo = new PlatformComponentNamesVO();
vo.setPlatformName(entry.getKey());
vo.setComponentNames(entry.getValue());
return vo;
})
.collect(Collectors.toList());
}
/**
* 获取通信组件的所有平台和组件
* @param scenarioId
* @return
*/
@Override
public List<PlatformComponentNamesVO> getCommPlatformComponentNames(Integer scenarioId) {
return ruleMapper.getCommPlatformComponentNames(scenarioId);
public int updateRule(Rule rule) {
return ruleMapper.updateRule(rule);
}
/**
* 获取所有组件以及数量
* @return
*/
private List<ComponentCountVO> getModuleAndCount(){
List<ComponentCountVO> componentCountVOS = ruleMapper.getModuleAndCount();
if(CollUtil.isEmpty(componentCountVOS)){
return new ArrayList<>();
@Override
public int deleteRuleById(Integer id) {
return ruleMapper.deleteRuleById(id);
}
return componentCountVOS;
@Override
public int deleteRuleByIds(Integer[] ids) {
return ruleMapper.deleteRuleByIds(ids);
}
}

View File

@@ -0,0 +1,114 @@
<?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.rule.mapper.FireRuleMapper">
<resultMap id="platformComponentCountMap" type="com.solution.rule.domain.vo.WeaponModelVO">
<result property="platformName" column="platform_name"/>
<result property="componentName" column="component_name"/>
<result property="count" column="count"/>
</resultMap>
<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>
</resultMap>
<select id="getWeapon" resultMap="platformComponentCountMap">
SELECT
p.name AS platform_name,
pc.name AS component_name,
COUNT(pc.name) AS count
FROM platform p
LEFT JOIN platform_component pc ON p.id = pc.platform_id
GROUP BY p.id, p.name, pc.name
ORDER BY p.id, pc.name
</select>
<select id="getPlatformComponentNames" resultType="com.solution.rule.domain.vo.WeaponModelVO">
SELECT DISTINCT
p.name AS platformName,
pc.name AS componentName
FROM platform p
INNER JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.name IS NOT NULL
ORDER BY p.name, pc.name
</select>
<select id="getModuleAndCount" resultType="com.solution.rule.domain.vo.ComponentCountVO">
SELECT
name AS componentName,
COUNT(*) AS count
FROM platform_component
WHERE name IS NOT NULL
GROUP BY name
ORDER BY count DESC;
</select>
<select id="getCommPlatformComponentNames" resultMap="PlatformComponentNamesVOResultMap"
parameterType="java.lang.Integer">
SELECT
p.name AS platformName,
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'
AND p.scenario_id = #{scenarioId}
</select>
<select id="getComponents" resultType="com.solution.rule.domain.PlatformComponent"
parameterType="java.lang.Integer">
SELECT id,name,type,description,platform_id
FROM platform_component
WHERE platform_id = #{platformId}
</select>
<resultMap id="VPlatformComponentMap" type="com.solution.rule.domain.PlatformComponent">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="type" column="type"/>
<result property="description" column="description"/>
<result property="platformId" column="platform_id"/>
<result property="num" column="num"/>
</resultMap>
<select id="findComponentsByPlatformId" resultMap="VPlatformComponentMap">
SELECT * FROM platform_component
WHERE platform_id=#{platformId}
</select>
<resultMap id="VPlatformMap" type="com.solution.rule.domain.Platform">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="description" column="description"/>
<collection property="components"
ofType="com.solution.rule.domain.PlatformComponent"
column="id"
select="findComponentsByPlatformId"/>
</resultMap>
<select id="findPlatformComponents" resultMap="VPlatformMap"
parameterType="java.lang.Integer">
SELECT DISTINCT
p.*,
pc.*
FROM platform p
LEFT JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.type = 'comm'
AND p.scenario_id = #{scenarioId}
ORDER BY p.name,pc.name
</select>
<select id="findAllPlatformComponents" resultMap="VPlatformMap">
SELECT *
FROM platform
</select>
</mapper>

View File

@@ -1,66 +1,97 @@
<?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">
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.solution.rule.mapper.RuleMapper">
<resultMap id="platformComponentCountMap" type="com.solution.rule.domain.vo.WeaponModelVO">
<result property="platformName" column="platform_name"/>
<result property="componentName" column="component_name"/>
<result property="count" column="count"/>
<resultMap id="RuleResult" type="com.solution.rule.domain.Rule">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sceneType" column="scene_type"/>
<result property="conditions" column="conditions"/>
<result property="actions" column="actions"/>
<result property="priority" column="priority"/>
<result property="enabled" column="enabled"/>
<result property="createdTime" column="created_time"/>
<result property="updatedTime" column="updated_time"/>
</resultMap>
<resultMap id="PlatformComponentNamesVOResultMap" type="com.solution.rule.domain.vo.PlatformComponentNamesVO">
<result property="platformName" column="platformName"/>
<collection property="componentNames" ofType="java.lang.String">
<result column="componentName"/>
</collection>
</resultMap>
<select id="getWeapon" resultMap="platformComponentCountMap">
SELECT
p.name AS platform_name,
pc.name AS component_name,
COUNT(pc.name) AS count
FROM platform p
LEFT JOIN platform_component pc ON p.id = pc.platform_id
GROUP BY p.id, p.name, pc.name
ORDER BY p.id, pc.name
<sql id="selectRuleVo">
select id, name, scene_type, conditions, actions, priority, enabled, created_time, updated_time
from rule
</sql>
<select id="selectRuleById" parameterType="Integer" resultMap="RuleResult">
<include refid="selectRuleVo"/>
where id = #{id}
</select>
<select id="getPlatformComponentNames" resultType="com.solution.rule.domain.vo.WeaponModelVO">
SELECT DISTINCT
p.name AS platformName,
pc.name AS componentName
FROM platform p
INNER JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.name IS NOT NULL
ORDER BY p.name, pc.name
<select id="selectRuleList" parameterType="com.solution.rule.domain.Rule" resultMap="RuleResult">
<include refid="selectRuleVo"/>
<where>
<if test="name != null and name != ''">
AND name like concat('%', #{name}, '%')
</if>
<if test="sceneType != null">
AND scene_type = #{sceneType}
</if>
<if test="enabled != null">
AND enabled = #{enabled}
</if>
</where>
</select>
<insert id="insertRule" parameterType="com.solution.rule.domain.Rule" useGeneratedKeys="true" keyProperty="id">
insert into rule
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null and name != ''">name,</if>
<if test="sceneType != null">scene_type,</if>
<if test="conditions != null">conditions,</if>
<if test="actions != null">actions,</if>
<if test="priority != null">priority,</if>
<if test="enabled != null">enabled,</if>
created_time,
updated_time
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null and name != ''">#{name},</if>
<if test="sceneType != null">#{sceneType},</if>
<if test="conditions != null">#{conditions},</if>
<if test="actions != null">#{actions},</if>
<if test="priority != null">#{priority},</if>
<if test="enabled != null">#{enabled},</if>
now(),
now()
</trim>
</insert>
<select id="getModuleAndCount" resultType="com.solution.rule.domain.vo.ComponentCountVO">
SELECT
name AS componentName,
COUNT(*) AS count
FROM platform_component
WHERE name IS NOT NULL
GROUP BY name
ORDER BY count DESC;
</select>
<update id="updateRule" parameterType="com.solution.rule.domain.Rule">
update rule
<set>
<if test="name != null and name != ''">name = #{name},</if>
<if test="sceneType != null">scene_type = #{sceneType},</if>
<if test="conditions != null">conditions = #{conditions},</if>
<if test="actions != null">actions = #{actions},</if>
<if test="priority != null">priority = #{priority},</if>
<if test="enabled != null">enabled = #{enabled},</if>
updated_time = now()
</set>
where id = #{id}
</update>
<select id="getCommPlatformComponentNames" resultMap="PlatformComponentNamesVOResultMap"
parameterType="java.lang.Integer">
SELECT
p.name AS platformName,
pc.name AS componentName
FROM platform p
INNER JOIN platform_component pc ON p.id = pc.platform_id
WHERE pc.type = "comm"
AND p.scenario_id = #{scenarioId}
</select>
<delete id="deleteRuleById" parameterType="Integer">
delete from rule where id = #{id}
</delete>
<!--<delete id="deleteRuleByIds" parameterType="String">
delete from rule where id in
<foreach item="id" collection="array" open="(" separator="," close=")">
#{id}
</foreach>
</delete>-->
<delete id="deleteRuleByIds">
delete from rule where id in
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
</mapper>

View File

@@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>solution</artifactId>
<groupId>com.solution</groupId>
<version>3.9.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>solution-scene</artifactId>
<description>
scene模块
</description>
<dependencies>
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-rule</artifactId>
</dependency>
<!-- 通用工具-->
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-common</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -1,4 +1,6 @@
package com.solution.system.domain;
package com.solution.scene.domain;
import java.util.List;
/**
* 场景配置表
@@ -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

@@ -0,0 +1,27 @@
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;
@Mapper
public interface SceneMapper {
/**
* 保存场景配置
* @param afsimScenario
* @return
*/
int insert(AfsimScenario afsimScenario);
int update(AfsimScenario afsimScenario);
/**
* 获取场景列表
* @return
*/
List<AfsimScenario> selectSceneList();
}

View File

@@ -0,0 +1,26 @@
package com.solution.scene.service;
import com.solution.scene.domain.AfsimScenario;
import com.solution.scene.domain.AfsimScenarioForm;
import java.util.List;
public interface SceneService {
/**
* 保存场景配置
* @param afsimScenario
* @return
*/
int insert(AfsimScenario afsimScenario);
int update(AfsimScenarioForm afsimScenario);
int saveOrUpdate(AfsimScenario afsimScenario);
/**
* 获取场景列表
* @return
*/
List<AfsimScenario> selectSceneList();
}

View File

@@ -0,0 +1,67 @@
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;
@Service
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
*/
@Override
public List<AfsimScenario> selectSceneList() {
return sceneMapper.selectSceneList();
}
}

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

@@ -0,0 +1,33 @@
<?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.SceneMapper">
<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" 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

@@ -32,7 +32,15 @@ export const routes: RouteRecordRaw[] = [
meta: {
title: '决策树',
},
component: () => import('@/views/decision/designer.vue'),
component: () => import('@/views/decision/designer/designer.vue'),
},
{
name: 'decision-communication',
path: '/app/decision/communication',
meta: {
title: '通信',
},
component: () => import('@/views/decision/communication/communication.vue'),
},
{
name: 'decision-algorithm-management',
@@ -42,4 +50,12 @@ export const routes: RouteRecordRaw[] = [
},
component: () => import('@/views/decision/algorithm/management.vue'),
},
{
name: 'decision-fire-rule',
path: '/app/decision/fire-rule',
meta: {
title: '活力规则',
},
component: () => import('@/views/decision/rule/management.vue'),
},
]

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
@@ -1648,3 +1650,183 @@
color: #eeeeee;
}
}
.ant-switch {
background: rgb(8 30 59);
}
.ks-algorithm-card {
.ant-card-head-title {
span.text {
display: block;
line-height: 30px;
}
}
}
.ks-sidebar-header {
line-height: 40px;
background: #081d36;
min-height: 40px;
background: url(@/assets/icons/card-head.png) left / 180% 100%;
padding: 0 10px;
.ks-sidebar-title {
color: #7ae8fc;
font-size: 16px;
.icon {
background: url(@/assets/icons/list.png) center / 100% 100%;
width: 25px;
height: 25px;
display: block;
margin-top: 7px;
}
.text{
margin-left: 40px;
font-size: 16px;
color: #eee;
}
}
.ks-sidebar-add {
position: absolute;
right: 7px;
top: 8px;
font-size: 12px;
.anticon {
display: block;
float: left;
line-height: 16px;
}
}
}
.ant-list {
&.ks-sidebar-list {
.ant-list-item {
cursor: pointer;
transition: all 0.5s;
border-left: 2px solid transparent;
position: relative;
&.selected,
&:hover {
background: #0a1b3c;
border-left: 2px solid #11377e;
}
}
.ks-sidebar-list-type {
position: absolute;
right: 10px;
.ant-badge {
.ant-badge-count {
color: #c3c2c2;
background: #333f7d;
box-shadow: 0 0 0 1px #325478;
}
}
}
.ant-list-item-meta {
.ant-list-item-meta-title {
color: #7ae8fc;
}
.ant-list-item-meta-description {
color: #4d8c98;
font-size: 13px;
}
}
}
}
.ks-sidebar-list-param-list {
padding: 15px;
border: 1px solid #475f71;
border-radius: 2px;
.ks-sidebar-list-param-item {
margin-bottom: 15px;
&:last-child {
margin-bottom: 0;
}
}
}
.ks-sidebar-list-param-actions {
.anticon {
color: #7ae8fc;
font-size: 20px;
display: block;
line-height: 26px;
cursor: pointer;
}
}
.ant-collapse {
.ant-list-sm {
.ant-list-item {
padding: 4px 15px;
cursor: pointer;
color: rgb(130 196 233);
position: relative;
.ks-tree-actions {
position: absolute;
right: 10px;
display: none;
}
&:hover {
background: #0d2d4e;
.ks-tree-actions {
display: block;
}
}
}
}
&.ks-trees-collapse {
.ant-collapse-content-box {
padding: 0;
height: 40vh;
position: relative;
}
}
}
.create-tree-icon {
cursor: pointer;
}
.ant-list-item {
padding: 3px 5px;
cursor: pointer;
color: rgb(130 196 233);
&:hover {
background: #0d2d4e;
}
}
.ks-model-builder-body .ks-model-builder-left .ant-collapse {
&.platform-collapse{
.ant-collapse-content-box{
max-height: 45.5vh;
}
}
}

View File

@@ -11,13 +11,13 @@
新增
</a-button>
</div>
<a-list item-layout="horizontal" :data-source="algorithms" class="ks-algorithm-list">
<a-list item-layout="horizontal" :data-source="algorithms" class="ks-sidebar-list">
<template #renderItem="{ item }">
<a-list-item @click="()=> handleSelect(item)" :class="selectedAlgorithm?.id === item.id ? 'selected' : null">
<a-list-item-meta :description="substring(item.description,20)">
<template #title>
<span class="ks-algorithm-name">{{ substring(item.name, 20) }}</span>
<span class="ks-algorithm-type"><a-badge size="small" :count="getAlgorithmTypeName(item.type)"></a-badge></span>
<span class="ks-sidebar-list-type"><a-badge size="small" :count="getAlgorithmTypeName(item.type)"></a-badge></span>
</template>
</a-list-item-meta>
</a-list-item>
@@ -95,8 +95,8 @@
:name="['algorithmParamList']"
>
<a-form-item-rest>
<div class="ks-algorithm-param-list">
<div class="ks-algorithm-param-item" v-for="(item,index) in selectedAlgorithm.algorithmParamList">
<div class="ks-sidebar-list-param-list">
<div class="ks-sidebar-list-param-item" v-for="(item,index) in selectedAlgorithm.algorithmParamList">
<a-row :gutter="15">
<a-col :span="7">
<a-input v-model:value="item.paramName" placeholder="请输入参数名" />
@@ -108,7 +108,7 @@
<a-input v-model:value="item.description" placeholder="请输入描述" />
</a-col>
<a-col :span="3">
<a-space class="ks-algorithm-param-actions">
<a-space class="ks-sidebar-list-param-actions">
<MinusCircleOutlined @click="()=> handleMinus(index)" />
<PlusCircleOutlined @click="handleAdd" v-if="index === 0" />
</a-space>
@@ -125,8 +125,8 @@
:name="['algoConfig']"
>
<a-form-item-rest>
<div class="ks-algorithm-param-list">
<div class="ks-algorithm-param-item" v-for="(t,index) in selectedAlgorithm.algoConfigList">
<div class="ks-sidebar-list-param-list">
<div class="ks-sidebar-list-param-item" v-for="(t,index) in selectedAlgorithm.algoConfigList">
<a-row :gutter="15">
<a-col :span="7">
<a-select placeholder="请选择参数" v-model:value="t.name" @change="(v: any)=> t.name = v">
@@ -139,7 +139,7 @@
</a-select>
</a-col>
<a-col :span="3">
<a-space class="ks-algorithm-param-actions">
<a-space class="ks-sidebar-list-param-actions">
<MinusCircleOutlined @click="()=> handleMinusConfig(index)" />
<PlusCircleOutlined @click="handleAddConfig" v-if="index === 0" />
</a-space>
@@ -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 ?? [];
@@ -290,6 +293,7 @@ const handleCreate = () => {
const handleSelect = (item: Algorithm) => {
selectedAlgorithm.value = resolveItem(item);
formRef.value?.resetFields();
};
const handleAdd = () => {
@@ -394,120 +398,3 @@ const handleChange = (page: number, pageSize: number) => {
onMounted(() => load());
</script>
<style lang="less">
.ks-algorithm-card {
.ant-card-head-title {
span.text {
display: block;
line-height: 30px;
}
}
}
.ks-sidebar-header {
line-height: 40px;
padding: 5px 15px;
background: #081d36;
min-height: 40px;
background: url(@/assets/icons/card-head.png) left / 180% 100%;
padding: 0 10px;
.ks-sidebar-title {
color: #7ae8fc;
font-size: 16px;
.icon {
background: url(@/assets/icons/list.png) center / 100% 100%;
width: 25px;
height: 25px;
display: block;
margin-top: 7px;
}
.text{
margin-left: 40px;
font-size: 16px;
color: #eee;
}
}
.ks-sidebar-add {
position: absolute;
right: 7px;
top: 8px;
font-size: 12px;
.anticon {
display: block;
float: left;
line-height: 16px;
}
}
}
.ant-list {
&.ks-algorithm-list {
.ant-list-item {
cursor: pointer;
transition: all 0.5s;
border-left: 2px solid transparent;
position: relative;
&.selected,
&:hover {
background: #0a1b3c;
border-left: 2px solid #11377e;
}
}
.ks-algorithm-type {
position: absolute;
right: 10px;
.ant-badge {
.ant-badge-count {
color: #c3c2c2;
background: #333f7d;
box-shadow: 0 0 0 1px #325478;
}
}
}
.ant-list-item-meta {
.ant-list-item-meta-title {
color: #7ae8fc;
}
.ant-list-item-meta-description {
color: #4d8c98;
font-size: 13px;
}
}
}
}
.ks-algorithm-param-list {
padding: 15px;
border: 1px solid #475f71;
border-radius: 2px;
.ks-algorithm-param-item {
margin-bottom: 15px;
&:last-child {
margin-bottom: 0;
}
}
}
.ks-algorithm-param-actions {
.anticon {
color: #7ae8fc;
font-size: 20px;
display: block;
line-height: 26px;
cursor: pointer;
}
}
</style>

View File

@@ -0,0 +1,33 @@
/*
* 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 { HttpRequestClient } from '@/utils/request';
import type { Scenario, ScenarioPageableResponse, ScenarioRequest } from './types';
import type { PlatformWithComponentsResponse } from '../types';
import type { BasicResponse } from '@/types';
const req = HttpRequestClient.create<BasicResponse>({
baseURL: '/api',
});
export const findScenarioByQuery = (_query: Partial<ScenarioRequest> = {}): Promise<ScenarioPageableResponse> => {
return req.get('/system/scene/list', _query);
};
export const deleteOneScenarioById = (id: number): Promise<BasicResponse> => {
return req.delete(`/system/behaviortree/${id}`);
};
export const findPlatformWithComponents = (id: number): Promise<PlatformWithComponentsResponse> => {
return req.get(`/system/firerule/platforms/${id}`);
};
export const saveScenario = (scenario: Scenario): Promise<BasicResponse> => {
return req.postJson(`/system/scene/saveSceneConfig`,scenario);
};

View File

@@ -0,0 +1,424 @@
<template>
<Wrapper>
<a-layout class="bg-transparent" style="background: transparent">
<Header />
<a-layout class="ks-layout-body">
<div class="ks-model-builder-body">
<div class="ks-model-builder-left">
<PlatformCard
ref="scenariosCardRef"
@create="handleCreate"
@select="handleSelect"
/>
<NodesCard
v-if="currentScenario && currentScenario.id >0"
:scenario="currentScenario"
@drag-item-start="handleDragStart"
@drag-item-end="handleDragEnd"
/>
</div>
<div class="ks-model-builder-content" style="width: calc(100% - 250px);">
<div class="ks-model-builder-actions">
<a-space>
<a-button v-if="graph && currentScenario" 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"
@dragenter="handleDragEnter"
@dragleave="handleDragLeave"
@drop="handleDrop"
@dragover.prevent
></div>
<TeleportContainer />
</div>
</div>
</a-layout>
</a-layout>
</Wrapper>
</template>
<script lang="ts">
import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';
import { getTeleport } from '@antv/x6-vue-shape';
import { Graph, Node, type NodeProperties } from '@antv/x6';
import { CheckCircleOutlined, CheckOutlined, RollbackOutlined, SaveOutlined } from '@ant-design/icons-vue';
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 { 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());
registerScenarioElement();
export default defineComponent({
components: {
PlatformCard,
NodesCard,
Wrapper,
Header,
SaveOutlined,
CheckCircleOutlined,
CheckOutlined,
RollbackOutlined,
TeleportContainer,
},
setup() {
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
const draggedNodeData = ref<PlatformWithComponents | null>(null);
const isDraggingOver = ref(false);
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 scenariosCardRef = ref<InstanceType<typeof PlatformCard> | null>(null);
const {
handleGraphEvent,
createCanvas,
zoomIn,
zoomOut,
fitToScreen,
centerContent,
resizeCanvas,
} = useGraphCanvas();
// 处理拖动开始
const handleDragStart = (nm: PlatformWithComponents) => {
draggedNodeData.value = nm;
};
// 处理拖动结束
const handleDragEnd = () => {
isDraggingOver.value = false;
};
// 处理拖动进入
const handleDragEnter = (e: DragEvent) => {
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = true;
};
// 处理拖动离开
const handleDragLeave = (e: DragEvent) => {
safePreventDefault(e);
safeStopPropagation(e);
if (canvas.value && e.relatedTarget &&
typeof e.relatedTarget === 'object' &&
'nodeType' in e.relatedTarget) {
// 使用 Element 类型而不是 x6 的 Node 类型
if (!canvas.value.contains(e.relatedTarget as Element)) {
isDraggingOver.value = false;
}
}
};
// 处理放置
const handleDrop = (e: DragEvent) => {
console.info('handleDrop', e);
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = false;
currentScenarioEditing.value = false;
if (!currentScenario.value) {
message.error('请先选择场景.');
return;
}
if (!graph.value || !canvas.value || !draggedNodeData.value) {
message.error('无法放置节点,缺少必要数据');
return;
}
try {
// 获取拖动的数据
const pwc = draggedNodeData.value as PlatformWithComponents;
// if (!hasElements(graph.value as Graph)) {
// message.error('请先添加根节点.');
// return;
// }
// if (hasRootElementNode(graph.value as Graph)) {
// message.error('根节点已经存在.');
// return;
// }
// 计算相对于画布的位置(考虑缩放)
const rect = canvas.value.getBoundingClientRect();
const scale = currentZoom.value || 1;
const x = (e.clientX - rect.left) / scale;
const y = (e.clientY - rect.top) / scale;
console.log('放置节点:', { ...pwc, x, y });
// 创建节点数据
const settingTaskElement: GraphTaskElement = createGraphTaskElementFromScenario(pwc, { x, y });
// 创建节点
const settingTaskNode = createGraphScenarioElement(settingTaskElement);
console.info('create settingTaskNode: ', settingTaskElement, settingTaskNode);
// 将节点添加到画布
graph.value?.addNode(settingTaskNode as any);
console.log('节点已添加到画布:', settingTaskNode.id);
// 重置拖动数据
draggedNodeData.value = null;
} catch (error) {
console.error('放置节点时出错:', error);
}
};
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 = () => {
nextTick(() => {
try {
graph.value?.clearCells();
} catch (e: any) {
console.error('clear cells error, cause:', e);
}
setTimeout(() => {
if (currentScenario.value?.graph && graph.value) {
if (currentScenario.value?.graph.nodes) {
currentScenario.value?.graph.nodes.forEach(ele => {
const node = createGraphScenarioElement(ele as GraphTaskElement);
// 将节点添加到画布
graph.value?.addNode(node as Node);
});
}
if (currentScenario.value?.graph.edges) {
// 然后添加所有边,确保包含桩点信息
setTimeout(() => {
currentScenario.value?.graph.edges.forEach(edgeData => {
graph.value?.addEdge({
...edgeData,
...createLineOptions(),
});
});
}, 100); // 延迟一会儿,免得连线错位
}
}
}, 100);
});
};
const handleCreate = () => {
currentScenario.value = {
id: 0,
name: null,
description: null,
communicationGraph: null,
relations: [],
graph: {
edges: [],
nodes: [],
},
};
currentGraph.value = {
edges: [],
nodes: [],
};
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
createElements();
};
// 初始化X6画布
const initGraph = () => {
if (!canvas.value) {
console.error('画布容器不存在');
return;
}
try {
graph.value = createCanvas(canvas.value);
console.log('画布初始化成功');
createElements();
// 监听缩放变化
handleGraphEvent('scale', ({ sx }: { sx: number }) => {
currentZoom.value = sx;
});
handleGraphEvent('blank:click', () => {
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
currentScenarioEditing.value = null !== currentScenario.value;
});
handleGraphEvent('node:click', (args: any) => {
const node = args.node as Node<NodeProperties>;
const newElement = node.getData() as GraphTaskElement;
selectedModelNode.value = node;
selectedNodeTaskElement.value = JSON.parse(JSON.stringify(newElement || {})) as GraphTaskElement;
});
// 监听节点鼠标事件,显示/隐藏连接点
handleGraphEvent('node:mouseenter', (_ctx: any) => {
});
handleGraphEvent('node:mouseleave', (_ctx: any) => {
});
} catch (error) {
console.error('初始化画布失败:', error);
}
};
// 监听窗口大小变化
const handleResize = () => {
nextTick(() => {
resizeCanvas();
});
};
const init = () => {
console.info('init');
nextTick(() => {
initGraph();
window.addEventListener('resize', handleResize);
console.log('节点挂载完成');
});
};
const handleUpdateElement = (element: GraphTaskElement) => {
// 更新选中的节点数据
if (selectedModelNode.value) {
selectedModelNode.value.replaceData(element);
}
console.info('handleUpdateElement', element);
// 更新本地引用
selectedNodeTaskElement.value = element;
changed.value = true;
};
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('当前决策树不存在');
return;
}
const newScenario: Scenario = {
...currentScenario.value,
graph: graphData,
communicationGraph: JSON.stringify(graphData),
relations: relations
};
if (!newScenario.name) {
message.error('场景名称不能为空.');
return;
}
let res = null;
if (currentScenario.value.id > 0) {
res = saveScenario(newScenario);
} else {
res = saveScenario(newScenario);
}
res.then(r => {
if (r.code === 200) {
scenariosCardRef.value?.refresh();
message.success(r.msg ?? '操作成功.');
} else {
message.error(r.msg ?? '操作失败.');
}
});
};
// 初始化
onMounted(() => {
init();
});
// 清理
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize);
if (graph.value) {
try {
graph.value.clearCells();
} catch (error) {
console.warn('销毁画布时出错:', error);
}
graph.value = null;
console.log('画布已销毁');
}
});
return {
scenariosCardRef,
handleCreate,
currentScenarioEditing,
currentScenario,
currentGraph,
selectedNodeTaskElement,
selectedModelNode,
graph,
canvas,
zoomIn,
zoomOut,
fitToScreen,
centerContent,
handleDragStart,
handleDragEnd,
handleDragEnter,
handleDragLeave,
handleDrop,
isDraggingOver,
handleSave,
handleUpdateElement,
handleSelect,
};
},
});
</script>

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

@@ -0,0 +1,110 @@
<template>
<div class="w-full">
<a-collapse v-model:activeKey="activeKey" :accordion="true" class="platform-collapse">
<a-collapse-panel key="1">
<template #header>
<span class="ks-model-builder-title-icon icon-model"></span>平台名称
</template>
<div class="w-full h-full">
<a-row>
<a-col v-for="nm in templateData" :span="12">
<div
:key="nm.id"
class="ks-model-drag-item"
@dragend="handleDragEnd"
@dragstart="handleDragStart($event, nm)"
>
<img :alt="nm.description ?? nm.name ?? ''" class="icon" src="@/assets/icons/model.svg" />
<span class="desc">{{ nm.description ?? nm.name }}</span>
</div>
</a-col>
</a-row>
</div>
</a-collapse-panel>
</a-collapse>
</div>
</template>
<script lang="ts">
import { defineComponent, type PropType, ref, watch } from 'vue';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import { findPlatformWithComponents } from './api';
import { type Scenario } from './types';
import { type PlatformWithComponents } from '../types';
export default defineComponent({
emits: ['drag-item-start', 'drag-item-end'],
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 currentScenario = ref<Scenario|null>(props.scenario)
const handleDragStart = (e: DragEvent, nm: PlatformWithComponents) => {
let dragNode: PlatformWithComponents = { ...nm };
draggedNodeData.value = dragNode as PlatformWithComponents;
if (e.dataTransfer) {
e.dataTransfer.setData('text/plain', JSON.stringify(draggedNodeData.value));
e.dataTransfer.effectAllowed = 'copyMove';
const dragPreview = document.createElement('div');
dragPreview.textContent = dragNode.name || '';
dragPreview.style.cssText = `
position: absolute;
top: -1000px;
padding: 6px 12px;
background: #3b82f6;
color: white;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
`;
document.body.appendChild(dragPreview);
e.dataTransfer.setDragImage(dragPreview, dragPreview.offsetWidth / 2, dragPreview.offsetHeight / 2);
emit('drag-item-start', dragNode, isDraggingOver.value, e);
console.log('开始拖动:', dragNode);
setTimeout(() => document.body.removeChild(dragPreview), 0);
}
};
const handleDragEnd = (e: DragEvent) => {
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = false;
console.log('拖动结束');
emit('drag-item-end', isDraggingOver.value, e);
};
const load = (id: number)=> {
findPlatformWithComponents(id).then(re=> {
templateData.value = re.data ?? []
})
}
watch(()=> props.scenario,(n: Scenario|null|undefined )=> {
if(n){
load(n.id);
}
}, {deep: true, immediate: true} )
return {
activeKey,
templateData,
handleDragStart,
handleDragEnd,
};
},
});
</script>

View File

@@ -0,0 +1,143 @@
<template>
<a-collapse v-model:activeKey="activeKey" :accordion="false" class="ks-trees-collapse">
<a-collapse-panel key="1" style="position: relative">
<template #header>
<a-flex>
<span class="ks-model-builder-title-icon icon-model"></span>
<span style="color: #82c4e9;font-size: 16px;">场景</span>
<!-- <span style="position: absolute; right: 15px;"><PlusOutlined @click="$emit('create-tree')"/></span>-->
</a-flex>
</template>
<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-flex>
</div>
<a-list :data-source="scenario || []" size="small" style="min-height: 25vh">
<template #renderItem="{ item }">
<a-list-item>
<a-flex>
<a-tooltip placement="bottom">
<template #title>
<p>名称: {{ item.name }}</p>
<p>说明: {{ item.description }}</p>
</template>
<span>{{ substring(item.name, 15) }}</span>
</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-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"
simple size="small" @change="handleChange" />
</a-collapse-panel>
</a-collapse>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { CheckOutlined, DeleteOutlined, EditFilled, PlusOutlined } from '@ant-design/icons-vue';
import type { Scenario, ScenarioRequest } from './types';
import { deleteOneScenarioById, findScenarioByQuery } from './api';
import { substring } from '@/utils/strings';
export default defineComponent({
emits: ['select', 'create'],
components: {
CheckOutlined,
PlusOutlined,
DeleteOutlined,
EditFilled,
},
setup(_props, { emit }) {
const scenario = ref<Scenario[]>([]);
const scenarioQuery = ref<Partial<ScenarioRequest>>({
name: null,
pageNum: 1,
pageSize: 8,
});
const activeKey = ref<number>(1);
const totalTress = ref<number>(0);
const loadTress = () => {
findScenarioByQuery(scenarioQuery.value).then(r => {
scenario.value = r.rows;
totalTress.value = r.total ?? 0;
// emit('select', r.rows[0]);
});
};
const handleChange = (page: number, pageSize: number) => {
scenarioQuery.value.pageNum = page;
scenarioQuery.value.pageSize = pageSize;
loadTress();
};
const handleDelete = (item: Scenario) => {
deleteOneScenarioById(item.id).then(r => {
if (r.code === 200) {
loadTress();
}
});
};
const columns = [
{
title: '名称',
dataIndex: 'name',
},
];
const handleSelect = (record: Scenario) => {
emit('select', record);
};
const customRow = (record: Scenario) => {
return {
onClick: (event: any) => {
emit('select', record, event);
},
};
};
const refresh = () => loadTress();
onMounted(() => {
loadTress();
});
return {
refresh,
totalTress,
substring,
activeKey,
scenario,
scenarioQuery,
loadTress,
columns,
customRow,
handleSelect,
handleChange,
handleDelete,
};
},
});
</script>

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

@@ -0,0 +1,46 @@
/*
* 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, 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 {
pageNum: number,
pageSize: number,
}
export interface ScenarioPageableResponse extends PageableResponse<Scenario> {
}

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"
@@ -72,16 +57,16 @@ import { Graph, Node, type NodeProperties } from '@antv/x6';
import { CheckCircleOutlined, CheckOutlined, RollbackOutlined, SaveOutlined } from '@ant-design/icons-vue';
import { Wrapper } from '@/components/wrapper';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
import Header from './header.vue';
import Header from '../header.vue';
import Properties from './properties.vue';
import type { BehaviorTree, 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';
@@ -106,11 +91,11 @@ export default defineComponent({
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
const draggedNodeData = ref<NodeTemplate | null>(null);
const draggedNodeData = ref<NodeDragTemplate | null>(null);
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);
@@ -127,7 +112,7 @@ export default defineComponent({
} = useGraphCanvas();
//
const handleDragStart = (nm: NodeTemplate) => {
const handleDragStart = (nm: NodeDragTemplate) => {
draggedNodeData.value = nm;
};
@@ -178,7 +163,7 @@ export default defineComponent({
try {
//
const template = draggedNodeData.value as NodeTemplate;
const template = draggedNodeData.value as NodeDragTemplate;
if (!hasElements(graph.value as Graph) && template.type !== 'root') {
message.error('请先添加根节点.');
@@ -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

@@ -3,35 +3,33 @@
<a-card
:class="[
'ks-designer-node',
`ks-designer-${element?.category ?? 'model'}-node`
`ks-designer-${element?.category ?? 'model'}-node`,
`ks-designer-group-${element?.group ?? 'general'}`
]"
hoverable
>
<template #title>
<a-space>
<span class="ks-designer-node-icon"></span>
<!-- <span class="ks-designer-node-icon"></span>-->
<span class="ks-designer-node-title">{{ element?.name ?? '-' }}</span>
</a-space>
</template>
<div class="port port-in">
<div class="triangle-left" data-port="in-0" magnet="passive"></div>
<div class="port port-in" data-port="in-0" magnet="passive">
<div class="triangle-left"></div>
</div>
<div class="w-full ks-designer-node-text">
<a-tooltip v-if="(element?.description ?? (element?.name ?? '-')).length >= 38">
<a-tooltip >
<template #title>
{{ element?.description ?? element?.name }}
</template>
<p class="ks-designer-node-label">
{{ substring(element?.description ?? (element?.name ?? '-'), 40) }}
{{ substring(element?.name ?? (element?.name ?? '-'), 40) }}
</p>
</a-tooltip>
<p v-else class="ks-designer-node-label">
{{ substring(element?.description ?? (element?.name ?? '-'), 40) }}
</p>
</div>
<div class="port port-out">
<div class="triangle-right" data-port="out-0" magnet="active"></div>
<div class="port port-out" data-port="out-0" magnet="active">
<div class="triangle-right" ></div>
</div>
</a-card>
@@ -50,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';
@@ -190,7 +188,7 @@ export default defineComponent({
border-radius: 0;
font-size: 12px;
padding: 10px 30px !important;
border-top: 1px solid rgba(108, 99, 255, 0.5);
//border-top: 1px solid rgba(108, 99, 255, 0.5);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -234,39 +232,42 @@ export default defineComponent({
.triangle-left {
width: 0;
height: 0;
border-top: 5px solid transparent;
border-right: 10px solid #3c82f6;
border-bottom: 6px solid transparent;
border-top: 4px solid transparent;
border-right: 5px solid #5da1df;
border-bottom: 4px solid transparent;
position: absolute;
left: -8px;
top: 2px;
top: 0.5px;
magnet: passive;
}
/* 右三角形 */
.triangle-right {
width: 0;
height: 0;
border-top: 5px solid transparent;
border-left: 10px solid #3c82f6;
border-bottom: 6px solid transparent;
border-top: 4px solid transparent;
border-left: 5px solid #5da1df;
border-bottom: 4px solid transparent;
position: absolute;
right: -8px;
top: 2px;
top: 0.5px;
magnet: passive;
}
}
//
.port-in {
background-color: #6C63FF;
//background-color: #3c82f6;
margin-right: 8px;
//border: 1px solid #093866;
magnet: passive;
box-shadow: none;
width: 15px;
height: 15px;
width: 13px;
height: 13px;
display: block;
background: url('@/assets/icons/point.svg') center / 100% 100%;
//background: url('@/assets/icons/point.svg') center / 100% 100%;
border: 2px solid #5da1df;
position: absolute;
//top: 7px;
@@ -279,10 +280,12 @@ export default defineComponent({
margin-right: 5px;
magnet: active;
box-shadow: none;
width: 15px;
height: 15px;
width: 13px;
height: 13px;
display: block;
background: url('@/assets/icons/point.svg') center / 100% 100%;
//background: url('@/assets/icons/point.svg') center / 100% 100%;
border: 2px solid #5da1df;
background:#5da1df;
position: absolute;
//right: 8px;
@@ -302,9 +305,6 @@ export default defineComponent({
}
&.ks-designer-root-node{
.ant-card-head {
background: url('@/assets/icons/card-head-gray.png') center / 100% 100%;
}
.ks-designer-node-icon {
background: url('@/assets/icons/icon-root.svg') center / 100% 100%;
}
@@ -320,32 +320,66 @@ export default defineComponent({
}
&.ks-designer-sequence-node{
.ant-card-head {
background: url('@/assets/icons/card-head-green.png') center / 100% 100%;
}
.ks-designer-node-icon {
background: url('@/assets/icons/icon-sequence.svg') center / 100% 100%;
}
}
&.ks-designer-parallel-node{
.ant-card-head {
background: url('@/assets/icons/card-head-blue.png') center / 100% 100%;
}
.ks-designer-node-icon {
background: url('@/assets/icons/icon-parallel.svg') center / 100% 100%;
}
}
&.ks-designer-precondition-node{
.ant-card-head {
background: url('@/assets/icons/card-head-dark.png') center / 100% 100%;
}
.ks-designer-node-icon {
background: url('@/assets/icons/icon-branch.svg') center / 100% 100%;
}
}
&.ks-designer-group-control,
&.ks-designer-group-condition {
.ant-card-head{
display:none;
}
.ant-card-body {
height: calc(100%);
border-radius: 8px;
background: url('@/assets/icons/card-head-gray.png') center / 100% 100%;
}
&.ks-designer-root-node{
.ant-card-body {
background: url('@/assets/icons/card-head-dark.png') center / 100% 100%;
}
}
&.ks-designer-sequence-node{
.ant-card-body {
background: url('@/assets/icons/card-head-green.png') center / 100% 100%;
}
}
&.ks-designer-parallel-node{
.ant-card-body {
background: url('@/assets/icons/card-head-blue.png') center / 100% 100%;
}
}
&.ks-designer-precondition-node{
.ant-card-body {
background: url('@/assets/icons/card-head-dark.png') center / 100% 100%;
}
}
.port-in,
.port-out {
top: 40%;
}
.ks-designer-node-text{
line-height: 38px;
}
}
//&.ks-designer-precondition-node{
// border:0;
// box-shadown:none;

View File

@@ -13,7 +13,7 @@
:data-type="nm.type"
class="ks-model-drag-item"
@dragend="handleDragEnd"
@dragstart="handleDragStart($event, nm)"
@dragstart="handleDragStart($event, nm, 'control')"
>
<img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
<span class="desc">{{ nm.name }}</span>
@@ -34,7 +34,7 @@
:data-type="nm.type"
class="ks-model-drag-item"
@dragend="handleDragEnd"
@dragstart="handleDragStart($event, nm)"
@dragstart="handleDragStart($event, nm, 'condition')"
>
<img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
<span class="desc">{{ nm.name }}</span>
@@ -55,7 +55,7 @@
:data-type="nm.type"
class="ks-model-drag-item"
@dragend="handleDragEnd"
@dragstart="handleDragStart($event, nm)"
@dragstart="handleDragStart($event, nm, 'action')"
>
<img :alt="nm.name ?? ''" class="icon" src="@/assets/icons/model-4.svg" />
<span class="desc">{{ nm.name }}</span>
@@ -71,7 +71,7 @@
<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import type { NodeTemplate } from './types';
import type { NodeDragTemplate, NodeTemplate } from './template';
import { findNodeTemplates } from './api';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
@@ -82,7 +82,7 @@ export default defineComponent({
const activeKey = ref<number>(1);
const templateData = ref<NodeTemplate[]>([]);
const isDraggingOver = ref<boolean>(false);
const draggedNodeData = ref<NodeTemplate | null>(null);
const draggedNodeData = ref<NodeDragTemplate | null>(null);
//
const controlTemplates = ref<NodeTemplate[]>([]);
//
@@ -111,15 +111,16 @@ export default defineComponent({
});
};
const handleDragStart = (e: DragEvent, nm: NodeTemplate) => {
draggedNodeData.value = nm;
const handleDragStart = (e: DragEvent, nm: NodeTemplate, group: String) => {
let dragNode: NodeDragTemplate = { ...nm, group: group };
draggedNodeData.value = dragNode as NodeDragTemplate;
if (e.dataTransfer) {
e.dataTransfer.setData('text/plain', JSON.stringify(draggedNodeData.value));
e.dataTransfer.effectAllowed = 'copyMove';
const dragPreview = document.createElement('div');
dragPreview.textContent = draggedNodeData.value.name || '';
dragPreview.textContent = dragNode.name || '';
dragPreview.style.cssText = `
position: absolute;
top: -1000px;
@@ -132,8 +133,8 @@ export default defineComponent({
`;
document.body.appendChild(dragPreview);
e.dataTransfer.setDragImage(dragPreview, dragPreview.offsetWidth / 2, dragPreview.offsetHeight / 2);
emit('drag-item-start', nm, isDraggingOver.value, e);
console.log('开始拖动:', nm);
emit('drag-item-start', dragNode, group, isDraggingOver.value, e);
console.log('开始拖动:', dragNode);
setTimeout(() => document.body.removeChild(dragPreview), 0);
}
};

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;
@@ -21,6 +21,10 @@ export interface NodeTemplate {
parameters: ElementParameter[],
}
export interface NodeDragTemplate extends NodeTemplate {
group: String
}
export interface NodeTemplatesResponse extends ApiDataResponse<NodeTemplate[]> {
}

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';
@@ -139,54 +139,3 @@ export default defineComponent({
</script>
<style lang="less">
.ant-collapse {
.ant-list-sm {
.ant-list-item {
padding: 4px 15px;
cursor: pointer;
color: rgb(130 196 233);
position: relative;
.ks-tree-actions {
position: absolute;
right: 10px;
display: none;
}
&:hover {
background: #0d2d4e;
.ks-tree-actions {
display: block;
}
}
}
}
&.ks-trees-collapse {
.ant-collapse-content-box {
padding: 0;
height: 40vh;
position: relative;
}
}
}
.create-tree-icon {
cursor: pointer;
}
.ant-list-item {
padding: 3px 5px;
cursor: pointer;
color: rgb(130 196 233);
&:hover {
background: #0d2d4e;
}
}
</style>

View File

@@ -7,13 +7,13 @@
* that was distributed with this source code.
*/
import type { NodeTemplate } 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: NodeTemplate,
rect?: GraphTaskRect,
template: NodeDragTemplate,
rect?: GraphRect,
): GraphTaskElement => {
let realRect = { width: 120, height: 80, x: 0, y: 0, ...rect || {} };
console.info('rect', rect);
@@ -25,6 +25,7 @@ export const createGraphTaskElementFromTemplate = (
templateType: template.templateType,
name: template.name,
category: template.type,
group: template.group,
description: template.description,
order: 0,
position: {

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,
@@ -79,7 +78,7 @@ export const createGraphConnectingAttributes = (): Partial<Connecting> => {
const targetData = targetCell.getData() as ModelElement;
// 根节点不能作为子节点
if (targetData.type === 'startEvent') {
if (targetData.category === 'root') {
return false;
}

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,24 +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.category === 'precondition') {
// width = 100;
// realHeight = 100;
// }
if (element.group === 'condition' || element.group === 'control') {
realHeight = 60;
}
return {
shape: 'task',
shape: shape ?? 'task',
id: element.key,
position: {
x: element.position?.x || 0,
@@ -75,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,
@@ -87,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

@@ -0,0 +1,39 @@
/*
* 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 { 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>({
baseURL: '/api',
});
export const findFireRuleByQuery = (query: Partial<FireRuleRequest> = {}): Promise<FireRulePageableResponse> => {
return req.get('/system/rule/list', query);
};
export const createFireRule = (fireRule: FireRule): Promise<BasicResponse> => {
return req.postJson('/system/rule', fireRule);
};
export const updateFireRule = (fireRule: FireRule): Promise<BasicResponse> => {
return req.putJson('/system/rule', fireRule);
};
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

@@ -1,11 +1,8 @@
/*
* 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.
*/
export { createGraphCanvas } from './graph';
export * from './hooks';

View File

@@ -0,0 +1,394 @@
<template>
<Layout>
<template #sidebar>
<div class="ks-sidebar-header">
<a-flex class="ks-sidebar-title">
<span class="icon"></span>
<span class="text">火力规则管理</span>
</a-flex>
<a-button class="ks-sidebar-add" size="small" @click="handleCreate">
<PlusOutlined />
新增
</a-button>
</div>
<a-list item-layout="horizontal" :data-source="datasource" class="ks-sidebar-list">
<template #renderItem="{ item }">
<a-list-item @click="()=> handleSelect(item)" :class="selectedFireRule?.id === item.id ? 'selected' : null">
<a-list-item-meta :description="substring(item.description,20)">
<template #title>
<span class="ks-algorithm-name">{{ substring(item.name, 20) }}</span>
<span class="ks-sidebar-list-type"><a-badge size="small" :count="getSceneTypeName(item)"></a-badge></span>
</template>
</a-list-item-meta>
</a-list-item>
</template>
</a-list>
<a-pagination
v-model:current="query.pageNum"
:page-size="query.pageSize"
:total="datasourceTotal"
simple size="small" @change="handleChange" />
</template>
<div class="w-full h-full">
<a-card class="ks-page-card ks-algorithm-card">
<template #title>
<a-space>
<span class="point"></span>
<span class="text">规则配置</span>
</a-space>
</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
ref="formRef"
:label-col="{span: 6}"
:model="selectedFireRule"
autocomplete="off"
layout="horizontal"
name="basic"
>
<a-form-item
label="规则名称"
:rules="[{ required: true, message: '请输入规则名称!', trigger: ['input', 'change'] }]"
name="name"
>
<a-input v-model:value="selectedFireRule.name" placeholder="请输入规则名称" />
</a-form-item>
<a-form-item
label="场景类型"
name="sceneType"
>
<a-select v-model:value="selectedFireRule.sceneType" placeholder="请选择场景类型">
<a-select-option :value="null">通用</a-select-option>
<a-select-option :value="0">防御</a-select-option>
<a-select-option :value="1">空降</a-select-option>
</a-select>
</a-form-item>
<!-- 触发条件 - 传递ID保持PlatformComponentPayload结构 -->
<a-form-item
label="触发条件"
:rules="[{ required: true, message: '请输入触发条件!', trigger: ['change'] }]"
name="conditionsArray"
>
<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: ['change'] }]"
name="actionsArray"
>
<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"
>
<a-input-number style="width:100%;" v-model:value="selectedFireRule.priority" placeholder="请输入优先级" />
</a-form-item>
<a-form-item
label="是否启用"
name="enabled"
>
<a-switch v-model:checked="selectedFireRule.enabled" />
</a-form-item>
<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="确定删除?"
@confirm="handleDelete"
>
<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 { nextTick, onMounted, ref } from 'vue';
import { type FormInstance, message } from 'ant-design-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, FireRulePageableResponse, FireRuleRequest } from './types';
import type { PlatformComponentPayload } from '../types';
import { substring } from '@/utils/strings';
import PlatformSelect from './PlatformSelect.vue';
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: '',
sceneType: null,
conditions: '',
conditionsArray: [JSON.parse(JSON.stringify(defaultPayload))],
actions: '',
actionsArray: [JSON.parse(JSON.stringify(defaultPayload))],
priority: 0,
enabled: true,
};
const getSceneTypeName = (item: FireRule): string => {
if (item.sceneType === 0) return '防御';
if (item.sceneType === 1) return '空降';
return '通用';
};
const resolveItem = (item: FireRule) => {
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>(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();
});
}
findFireRuleByQuery(query.value).then((r: FireRulePageableResponse) => {
datasource.value = r.rows ?? [];
datasourceTotal.value = r.total ?? 0;
});
};
const handleCreate = () => {
formRef.value?.resetFields();
selectedFireRule.value = JSON.parse(JSON.stringify(defaultFireRule));
};
const handleSelect = (item: FireRule) => {
formRef.value?.resetFields();
nextTick(() => {
selectedFireRule.value = resolveItem(item);
});
};
const handleDelete = () => {
if (selectedFireRule.value?.id > 0) {
deleteFireRule(selectedFireRule.value.id).then(r => {
if (r.code === 200) {
load();
message.success(r.msg ?? '删除成功');
} else {
message.error(r.msg ?? '删除失败');
}
});
}
};
const handleSave = () => {
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 {
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;
query.value.pageSize = pageSize;
load();
};
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

@@ -0,0 +1,37 @@
/*
* 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 { NullableString, PageableResponse } from '@/types';
import type { PlatformComponentPayload } from '../types';
export interface FireRule {
id: number,
// 规则名称
name: NullableString,
// 场景类型0-防御1-空降null表示通用
sceneType: Number | null,
// 触发条件JSON格式
conditions: NullableString,
conditionsArray: PlatformComponentPayload[],
// 响应动作JSON格式
actions: NullableString,
actionsArray: PlatformComponentPayload[],
// 优先级(数值越小优先级越高)
priority: number,
// 是否启用0禁用1启用
enabled: boolean,
}
export interface FireRuleRequest extends FireRule {
pageNum: number,
pageSize: number,
}
export interface FireRulePageableResponse extends PageableResponse<FireRule> {
}

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']

30
pom.xml
View File

@@ -238,6 +238,12 @@
<version>${solution.version}</version>
</dependency>
<dependency>
<groupId>com.solution</groupId>
<artifactId>solution-scene</artifactId>
<version>${solution.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
@@ -252,6 +258,7 @@
<module>auto-solution-generator</module>
<module>auto-solution-common</module>
<module>auto-solution-rule</module>
<module>auto-solution-scene</module>
</modules>
<packaging>pom</packaging>
@@ -267,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>