Commit 65888600 authored by caotao's avatar caotao

知识库代码提交

parent 5167791c
package com.yeejoin.amos.boot.biz.common.aop; package com.yeejoin.amos.boot.biz.common.aop;
import java.util.HashMap; import com.alibaba.fastjson.JSONObject;
import java.util.List; import com.google.common.collect.Lists;
import java.util.Map; import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import javax.servlet.http.HttpServletRequest; import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterReturning;
...@@ -25,22 +36,11 @@ import org.typroject.tyboot.core.foundation.utils.Bean; ...@@ -25,22 +36,11 @@ import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import com.alibaba.fastjson.JSONObject; import javax.servlet.http.HttpServletRequest;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo; import java.util.HashMap;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo; import java.util.List;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams; import java.util.Map;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo; import java.util.regex.Pattern;
import com.yeejoin.amos.boot.biz.common.interceptors.PermissionInterceptorContext;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
/** /**
* controller层切面 用于用户数据缓存 供 sql自动填充使用 (使用粒度过大的Aop会创建大量代理对象,影响性能,占用内存,考虑使用 * controller层切面 用于用户数据缓存 供 sql自动填充使用 (使用粒度过大的Aop会创建大量代理对象,影响性能,占用内存,考虑使用
...@@ -80,21 +80,27 @@ public class ControllerAop { ...@@ -80,21 +80,27 @@ public class ControllerAop {
} else { } else {
return; return;
} }
// 不需要添加请求头的接口 // 不需要添加请求头的接口,如使用url中有PathVariable,则使用正则表达式匹配
String[] url = new String[] { "/api/user/save/curCompany", "/jcs/command/lookHtmlText", List<String> urls = Lists.newArrayList();
"/jcs/common/duty-person/findByDutyAreaId", "/tzs/wechatBack", "/tzs/elevator/getElevatorInfo", urls.add("/api/user/save/curCompany");
"/openapi/bizToken/applyToken" urls.add("/jcs/command/lookHtmlText");
,"/tzs/flc-unit-info/region/tree" urls.add("^/jcs/common/duty-person/findByDutyAreaId/[A-Za-z0-9]+$");
// ,"/tzs/reg-unit-info/management-unit/tree", urls.add("/tzs/wechatBack");
//"/tzs/reg-unit-info/unit-type/list" urls.add("/tzs/elevator/getElevatorInfo");
//+ ",/tzs/reg-unit-info/management-unit/tree","/tzs/flc-unit-info/region/tree", "/tzs/reg-unit-info/unit-type/list" urls.add("/openapi/bizToken/applyToken");
}; urls.add("/tzs/flc-unit-info/region/tree");
if (request.getRequestURI().contains("/tzs/reg-unit-info") || request.getRequestURI().contains("/tzs/flc-unit-info")) { urls.add("/tzs/reg-unit-info/management-unit/tree");
return; urls.add("/tzs/reg-unit-info/unit-type/list");
} urls.add("^/tzs/flc-unit-info/hasExistPhone/[0-9]+$");
urls.add("^/tzs/flc-unit-info/sendTelCode/[0-9]+$");
urls.add("^/tzs/reg-unit-info/[A-Za-z0-9]+/check$");
urls.add("^/tzs/flc-unit-info/verifyTelCode/[A-Za-z0-9]+/[A-Za-z0-9]+");
urls.add("^/tzs/flc-unit-info/hasExistUser/[A-Za-z0-9_-]+");
urls.add("/tzs/reg-unit-info/save");
// 获取请求路径 // 获取请求路径
for (String uri : url) { for (String uri : urls) {
if (request.getRequestURI().indexOf(uri) != -1) { Pattern p = Pattern.compile(uri);
if (p.matcher(request.getRequestURI()).matches()) {
return; return;
} }
} }
......
...@@ -21,6 +21,10 @@ ...@@ -21,6 +21,10 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 规则模块 --> <!-- 规则模块 -->
<dependency> <dependency>
<groupId>com.yeejoin</groupId> <groupId>com.yeejoin</groupId>
...@@ -74,20 +78,28 @@ ...@@ -74,20 +78,28 @@
<artifactId>html2pdf</artifactId> <artifactId>html2pdf</artifactId>
<version>2.0.1</version> <version>2.0.1</version>
</dependency> </dependency>
<!-- 解析excel --> <!-- 解析excel -->
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId> <artifactId>poi</artifactId>
<version>4.0.1</version> <version>4.1.2</version>
</dependency> </dependency>
<dependency> <!-- 针对2007以上版本的库 -->
<groupId>org.apache.poi</groupId> <dependency>
<artifactId>poi-ooxml</artifactId> <groupId>org.apache.poi</groupId>
<version>4.0.1</version> <artifactId>poi-ooxml</artifactId>
</dependency> <version>4.1.2</version>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId> <!-- 针对2003版本的库 -->
<artifactId>spring-boot-starter-data-elasticsearch</artifactId> <dependency>
</dependency> <groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
...@@ -9,7 +10,7 @@ import java.util.Map; ...@@ -9,7 +10,7 @@ import java.util.Map;
/** /**
* <p> * <p>
* 知识库文档存储 Mapper 接口 * 知识库文档存储 Mapper 接口
* </p> * </p>
* *
* @author 子杨 * @author 子杨
...@@ -18,18 +19,24 @@ import java.util.Map; ...@@ -18,18 +19,24 @@ import java.util.Map;
public interface DocContentMapper extends BaseMapper<KnowledgeDocContent> { public interface DocContentMapper extends BaseMapper<KnowledgeDocContent> {
List<Map<String,Long>> searchForDocIds(@Param("agencyCode") String agencyCode, List<Map<String, Long>> searchForDocIds(
@Param("queryStr") String queryStr, @Param("agencyCode") String agencyCode,
@Param("docStatus")String []docStatus, @Param("queryStr") String queryStr,
@Param("auditStatus")String [] auditStatus, @Param("docStatus") String[] docStatus,
@Param("userId")String userId, @Param("auditStatus") String[] auditStatus,
@Param("orgCode")String orgCode, @Param("userId") String userId,
@Param("offset") long offset, @Param("orgCode") String orgCode,
@Param("length") long length); @Param("offset") long offset,
@Param("length") long length);
List<Map<String,Object>> queryDocBaseInfoList(Map<String, Object> paramMap); List<Map<String, Object>> queryDocBaseInfoList(Map<String, Object> paramMap);
int queryDocBaseInfoTotal(Map<String, Object> paramMap); int queryDocBaseInfoTotal(Map<String, Object> paramMap);
List<Long> getAllPublishedDocIds(); List<Long> getAllPublishedDocIds();
IPage<KnowledgeDocContent> pageByType(
IPage<KnowledgeDocContent> page,
@Param("typeId") Long typeId,
@Param("tagId") Long tagId);
} }
\ No newline at end of file
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity; import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
public interface ESDocRepository extends ElasticsearchCrudRepository<ESDocEntity, Long> { public interface ESDocRepository extends ElasticsearchCrudRepository<ESDocEntity, Long> {
......
...@@ -2,7 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.dao; ...@@ -2,7 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
...@@ -37,5 +39,21 @@ public interface StatisticsRecordMapper extends BaseMapper<KnowlegeStatisticsRec ...@@ -37,5 +39,21 @@ public interface StatisticsRecordMapper extends BaseMapper<KnowlegeStatisticsRec
* 按类型查询/按时间分段总计 * 按类型查询/按时间分段总计
*/ */
List<Map<String, Object>> selectCountByNameAndDateRange(Map<String, Object> queryMap); List<Map<String, Object>> selectCountByNameAndDateRange(Map<String, Object> queryMap);
List<Map<String, Object>> tagStatisticsMonth(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> tagStatisticsYear(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docStatisticsMonth(@Param("categoryName")String categoryName, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docStatisticsYear(@Param("categoryName")String categoryName, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> tagChartStatistics(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate,@Param("splitSQL")String splitSQL);
List<Map<String, Object>> tagTimeChartStatistics(@Param("startDate")Date startDate, @Param("endDate")Date endDate,@Param("splitSQL")String splitSQL);
List<Map<String, Object>> docChartStatistics(@Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docBurnChartStatistics(@Param("startDate")Date startDate,@Param("endDate") Date endDate);
} }
\ No newline at end of file
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import java.util.Date; import java.util.Date;
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity; ...@@ -2,9 +2,9 @@ package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.TableName;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/** /**
* <p> * <p>
......
...@@ -24,6 +24,29 @@ ...@@ -24,6 +24,29 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- 解析excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 针对2007以上版本的库 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 针对2003版本的库 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
//package com.yeejoin.amos.knowledgebase.config; package com.yeejoin.amos.knowledgebase.config;
//
//import com.baomidou.mybatisplus.core.toolkit.Sequence; import com.baomidou.mybatisplus.core.toolkit.Sequence;
//import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
//
///** /**
// * @author 杨博超 * @author 杨博超
// * @ClassName Config * @ClassName Config
// * @Deacription TODO * @Deacription TODO
// **/ **/
//@Configuration @Configuration
//public class Config { public class Config {
//
// @Bean @Bean
// public Sequence sequence() { public Sequence sequence() {
// return new Sequence(); return new Sequence();
// } }
//} }
...@@ -2,12 +2,7 @@ package com.yeejoin.amos.knowledgebase.config; ...@@ -2,12 +2,7 @@ package com.yeejoin.amos.knowledgebase.config;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost; import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder; import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.RestHighLevelClient;
...@@ -21,31 +16,17 @@ public class ElasticSearchClientConfig { ...@@ -21,31 +16,17 @@ public class ElasticSearchClientConfig {
@Value("${spring.elasticsearch.rest.uris}") @Value("${spring.elasticsearch.rest.uris}")
private String uris; private String uris;
@Value("${elasticsearch.username}")
private String username;
@Value("${elasticsearch.password}")
private String password;
@Bean @Bean
@Qualifier("highLevelClient") @Qualifier("highLevelClient")
public RestHighLevelClient restHighLevelClient() { public RestHighLevelClient restHighLevelClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username, password));
try { try {
String url = uris.replace("http://", ""); String url = uris.replace("http://", "");
final String[] parts = StringUtils.split(url, ":"); final String[] parts = StringUtils.split(url, ":");
HttpHost httpHost = new HttpHost(parts[0], Integer.parseInt(parts[1]), "http"); HttpHost httpHost = new HttpHost(parts[0], Integer.parseInt(parts[1]), "http");
RestClientBuilder builder = RestClient.builder(httpHost); RestClientBuilder builder = RestClient.builder(httpHost);
builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() { builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
// 该方法接收一个RequestConfig.Builder对象,对该对象进行修改后然后返回。 // 该方法接收一个RequestConfig.Builder对象,对该对象进行修改后然后返回。
@Override @Override
......
...@@ -34,6 +34,7 @@ import java.util.List; ...@@ -34,6 +34,7 @@ import java.util.List;
public class DocAnnotateResource { public class DocAnnotateResource {
private final Logger logger = LogManager.getLogger(DocAnnotateResource.class); private final Logger logger = LogManager.getLogger(DocAnnotateResource.class);
@Autowired @Autowired
private DocAnnotateService docAnnotateService; private DocAnnotateService docAnnotateService;
......
...@@ -86,7 +86,7 @@ public class DocCategoryResource { ...@@ -86,7 +86,7 @@ public class DocCategoryResource {
return ResponseHelper.buildResponse(docCategoryService.queryForKnowledgeDocCategoryList(parentId)); return ResponseHelper.buildResponse(docCategoryService.queryForKnowledgeDocCategoryList(parentId));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
@ApiOperation(value = "文档分类树查询") @ApiOperation(value = "文档分类树查询")
@RequestMapping(value = "/tree", method = RequestMethod.GET) @RequestMapping(value = "/tree", method = RequestMethod.GET)
public ResponseModel<Collection<KnowledgeDocCategoryModel>> docCategoryTree() { public ResponseModel<Collection<KnowledgeDocCategoryModel>> docCategoryTree() {
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCommentsModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCommentsModel;
import com.yeejoin.amos.knowledgebase.face.service.DocCommentsService; import com.yeejoin.amos.knowledgebase.face.service.DocCommentsService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
...@@ -11,11 +10,11 @@ import org.apache.logging.log4j.Logger; ...@@ -11,11 +10,11 @@ import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.StringUtil; import org.typroject.tyboot.core.foundation.utils.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource; import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest; import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import java.util.List; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Map; import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import javax.servlet.http.HttpServletRequest; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.service.DocContentService;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService;
import com.yeejoin.amos.knowledgebase.face.service.DynamicsOptionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.StringUtil; import org.typroject.tyboot.core.foundation.utils.StringUtil;
...@@ -22,16 +21,9 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest; ...@@ -22,16 +21,9 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import javax.servlet.http.HttpServletRequest;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional; import java.util.List;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel; import java.util.Map;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.service.DocContentService;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService;
import com.yeejoin.amos.knowledgebase.face.service.DynamicsOptionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/** /**
* <p> * <p>
...@@ -129,7 +121,7 @@ public class DocContentResource { ...@@ -129,7 +121,7 @@ public class DocContentResource {
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
@ApiOperation(value = "查询单个文档内容信息") @ApiOperation(value = "查询单个文档内容信息")
@RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.GET) @RequestMapping(value = "/{sequenceNbr}", method = RequestMethod.GET)
public ResponseModel<KnowledgeDocContentModel> seleteOne(@PathVariable("sequenceNbr") Long sequenceNbr) { public ResponseModel<KnowledgeDocContentModel> seleteOne(@PathVariable("sequenceNbr") Long sequenceNbr) {
...@@ -145,48 +137,6 @@ public class DocContentResource { ...@@ -145,48 +137,6 @@ public class DocContentResource {
} }
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @ApiOperation(value = "分页查询文档信息")
// @RequestMapping(value = "/page", method = RequestMethod.GET)
// public ResponseModel<Page> queryDocPage(HttpServletRequest request) {
// Map paramMap = request.getParameterMap();
//
// String[] auditStatus = request.getParameterValues("auditStatus");
// String[] docStatus = request.getParameterValues("docStatus");
//
// if (!ValidationUtil.isEmpty(auditStatus) && auditStatus[0].length() == 0) {
// auditStatus = null;
// }
// if (!ValidationUtil.isEmpty(docStatus) && docStatus[0].length() == 0) {
// docStatus = null;
// }
// Date createTimeLeft = null;
// Date createTimeRight = null;
// try {
// if (!ValidationUtil.isEmpty(paramMap.get("createTimeLeft"))) {
// createTimeLeft = DateUtil.formatStringToDate(request.getParameterValues("createTimeLeft")[0], null);
// }
// if (!ValidationUtil.isEmpty(paramMap.get("createTimeRight"))) {
// createTimeRight = DateUtil.formatStringToDate(request.getParameterValues("createTimeRight")[0], null);
// }
// } catch (Exception e) {
// throw new BadRequest("时间范围参数格式有误");
// }
// int offset = Integer.parseInt(request.getParameterValues("offset")[0]);
// int end = Integer.parseInt(request.getParameterValues("end")[0]);
//
// paramMap.remove("offset");
// paramMap.remove("end");
// paramMap.remove("total");
// paramMap.remove("auditStatus");
// paramMap.remove("docStatus");
// paramMap.remove("createTimeLeft");
// paramMap.remove("createTimeRight");
//
// return ResponseHelper.buildResponse(docContentService.queryDocPage(offset, end, paramMap, auditStatus, docStatus, createTimeLeft, createTimeRight));
// }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "分页查询文档信息") @ApiOperation(value = "分页查询文档信息")
@RequestMapping(value = "/page", method = RequestMethod.GET) @RequestMapping(value = "/page", method = RequestMethod.GET)
...@@ -206,20 +156,6 @@ public class DocContentResource { ...@@ -206,20 +156,6 @@ public class DocContentResource {
} }
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @ApiOperation(value = "字符串模糊查询文档(搜索项为文档标题和标签名称)")
// @RequestMapping(value = "/title/tag", method = RequestMethod.GET)
// public ResponseModel searchForDocs(
// @RequestParam(value = "queryStr", defaultValue = "") String queryStr,
// @RequestParam(value = "current") int current,
// @RequestParam(value = "size") int size) {
// Page page = new Page();
// page.setCurrent(current);
// page.setSize(size);
// return ResponseHelper.buildResponse(docContentService.searchForDoc(page, queryStr));
// }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "文档被点赞/吐槽状态") @ApiOperation(value = "文档被点赞/吐槽状态")
@RequestMapping(value = "/{sequenceNbr}/statistics/likes", method = RequestMethod.GET) @RequestMapping(value = "/{sequenceNbr}/statistics/likes", method = RequestMethod.GET)
...@@ -227,12 +163,5 @@ public class DocContentResource { ...@@ -227,12 +163,5 @@ public class DocContentResource {
@PathVariable(value = "sequenceNbr") Long sequenceNbr) { @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
return ResponseHelper.buildResponse(docContentService.queryLikeOrDis(sequenceNbr)); return ResponseHelper.buildResponse(docContentService.queryLikeOrDis(sequenceNbr));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "获取简单的预案信息")
@RequestMapping(value = "/getSimpleDetail/{sequenceNbr}", method = RequestMethod.GET)
public ResponseModel<List<Map<String, Object>>> getSimpleDetail(
@PathVariable(value = "sequenceNbr") String sequenceNbr) {
return ResponseHelper.buildResponse(docContentService.getSimpleDetail(sequenceNbr));
}
} }
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.service.DocContentService;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService;
import com.yeejoin.amos.knowledgebase.face.service.ESDocService;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelImportConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.XmlException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
...@@ -25,15 +24,13 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest; ...@@ -25,15 +24,13 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
import com.alibaba.fastjson.JSON; import javax.servlet.http.HttpServletRequest;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import javax.servlet.http.HttpServletResponse;
import com.yeejoin.amos.knowledgebase.face.service.DocLibraryService; import javax.xml.parsers.ParserConfigurationException;
import com.yeejoin.amos.knowledgebase.face.service.ESDocService; import javax.xml.transform.TransformerException;
import com.yeejoin.amos.knowledgebase.face.util.Constants; import java.io.IOException;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelImportConfig; import java.util.List;
import java.util.Map;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/** /**
* <p> * <p>
...@@ -51,6 +48,8 @@ public class DocLibraryResource { ...@@ -51,6 +48,8 @@ public class DocLibraryResource {
@Autowired @Autowired
private DocLibraryService docLibraryService; private DocLibraryService docLibraryService;
@Autowired
private DocContentService docContentService;
/** /**
* 下拉式查询文档信息 * 下拉式查询文档信息
...@@ -66,21 +65,35 @@ public class DocLibraryResource { ...@@ -66,21 +65,35 @@ public class DocLibraryResource {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "下拉式查询文档信息") @ApiOperation(value = "下拉式查询文档信息")
@RequestMapping(value = "/page", method = RequestMethod.GET) @RequestMapping(value = "/page", method = RequestMethod.GET)
public ResponseModel<Page> queryDocPageNew(HttpServletRequest request, public ResponseModel<Page> queryDocPageNew(HttpServletRequest request, @RequestParam(value = "offset") Integer offset, @RequestParam(value = "end") Integer end, @RequestParam(value = "filterByCollection") String filterByCollection, @RequestParam(value = "directoryId", required = false) Long directoryId, @RequestParam(value = "docTitle", required = false) String docTitle, @RequestParam(value = "createTimeLeft", required = false) String createTimeLeft, @RequestParam(value = "createTimeRight", required = false) String createTimeRight) {
@RequestParam(value = "offset") Integer offset,
@RequestParam(value = "end") Integer end,
@RequestParam(value = "filterByCollection") String filterByCollection,
@RequestParam(value = "directoryId", required = false) Long directoryId,
@RequestParam(value = "docTitle", required = false) String docTitle,
@RequestParam(value = "createTimeLeft", required = false) String createTimeLeft,
@RequestParam(value = "createTimeRight", required = false) String createTimeRight) {
Map requestMap = request.getParameterMap(); Map requestMap = request.getParameterMap();
Page page = docLibraryService.queryDocList(offset, end, directoryId, docTitle, null, Constants.DOC_STATUS_PUBLISHED, Page page = docLibraryService.queryDocList(offset, end, directoryId, docTitle, null, DocContentService.DOC_STATUS_PUBLISHED, requestMap, createTimeLeft, createTimeRight, Boolean.parseBoolean(filterByCollection), false);
requestMap, createTimeLeft, createTimeRight, Boolean.parseBoolean(filterByCollection), false);
return ResponseHelper.buildResponse(page); return ResponseHelper.buildResponse(page);
} }
/** /**
* 开放接口,根据文档分类查询分类下的列表数据,只查公开的标签文档
*
* @param pageNumber 当前页码
* @param pageSize 每页数量
* @param directoryId 分类ID
* @return Page
*/
@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
@ApiOperation(value = "开放接口,根据文档分类查询分类下的列表数据")
@RequestMapping(value = "/pageByType", method = RequestMethod.GET)
public ResponseModel<IPage<KnowledgeDocContent>> pageByType(
@RequestParam(value = "pageNumber") int pageNumber,
@RequestParam(value = "pageSize") int pageSize,
@RequestParam(value = "directoryId", required = false) Long directoryId,
@RequestParam(value = "tagId", required = false) Long tagId
) {
int current = pageNumber * pageSize;
if (current < 0) current = 0;
return ResponseHelper.buildResponse(docContentService.pageByType(current, pageSize, directoryId, tagId));
}
/**
* 收藏文档 * 收藏文档
* *
* @param id * @param id
...@@ -122,8 +135,7 @@ public class DocLibraryResource { ...@@ -122,8 +135,7 @@ public class DocLibraryResource {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "搜索联想") @ApiOperation(value = "搜索联想")
@RequestMapping(value = "/associate", method = RequestMethod.GET) @RequestMapping(value = "/associate", method = RequestMethod.GET)
public ResponseModel worldAssociate( public ResponseModel worldAssociate(@RequestParam(value = "queryStr") String queryStr) {
@RequestParam(value = "queryStr") String queryStr) {
if (ValidationUtil.isEmpty(queryStr)) { if (ValidationUtil.isEmpty(queryStr)) {
queryStr = ""; queryStr = "";
} }
...@@ -177,57 +189,35 @@ public class DocLibraryResource { ...@@ -177,57 +189,35 @@ public class DocLibraryResource {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "根据文档标题和标签名称查询文档") @ApiOperation(value = "根据文档标题和标签名称查询文档")
@RequestMapping(value = "/es/query", method = RequestMethod.GET) @RequestMapping(value = "/es/query", method = RequestMethod.GET)
public ResponseModel filter(@RequestParam(value = "queryStr", required = false) String queryStr, public ResponseModel filter(@RequestParam(value = "queryStr", required = false) String queryStr, @RequestParam(value = "current", defaultValue = "0") int current, @RequestParam(value = "size", defaultValue = "10") int size) {
@RequestParam(value = "current", defaultValue = "0") int current,
@RequestParam(value = "size", defaultValue = "10") int size) {
return ResponseHelper.buildResponse(eSDocService.queryByKeys(queryStr, current, size)); return ResponseHelper.buildResponse(eSDocService.queryByKeys(queryStr, current, size));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "高级检索") @ApiOperation(value = "高级检索")
@RequestMapping(value = "/query/advanced", method = RequestMethod.POST) @RequestMapping(value = "/query/advanced", method = RequestMethod.POST)
public ResponseModel searchAdvanced(@RequestBody Map<String, Object> condition, public ResponseModel searchAdvanced(@RequestBody Map<String, Object> condition, @RequestParam(value = "current", defaultValue = "0") int current, @RequestParam(value = "size", defaultValue = "10") int size) {
@RequestParam(value = "current", defaultValue = "0") int current,
@RequestParam(value = "size", defaultValue = "10") int size) {
Page page = new Page(current, size); Page page = new Page(current, size);
return ResponseHelper.buildResponse(docLibraryService.searchAdvanced(page,condition)); return ResponseHelper.buildResponse(docLibraryService.searchAdvanced(page, condition));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "根据文档标题和标签名称查询文档-APP") @ApiOperation(value = "根据文档标题和标签名称查询文档-APP")
@RequestMapping(value = "/es/query1", method = RequestMethod.GET) @RequestMapping(value = "/es/query1", method = RequestMethod.GET)
public ResponseModel filter1(@RequestParam(value = "queryStr", required = false) String queryStr, public ResponseModel filter1(@RequestParam(value = "queryStr", required = false) String queryStr, @RequestParam(value = "current", defaultValue = "0") int current, @RequestParam(value = "size", defaultValue = "10") int size) {
@RequestParam(value = "current", defaultValue = "0") int current,
@RequestParam(value = "size", defaultValue = "10") int size) {
return ResponseHelper.buildResponse(eSDocService.queryAndDetail(queryStr, current, size)); return ResponseHelper.buildResponse(eSDocService.queryAndDetail(queryStr, current, size));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "导出为word文档") @ApiOperation(value = "导出为word文档")
@RequestMapping(value = "/export/{id}/{type}", method = RequestMethod.GET) @RequestMapping(value = "/export/{id}/{type}", method = RequestMethod.GET)
public void export(@PathVariable(value = "id") Long id, public void export(@PathVariable(value = "id") Long id, @PathVariable(value = "type") String type, HttpServletResponse response) {
@PathVariable(value = "type") String type,
HttpServletResponse response) {
if (ValidationUtil.isEmpty(type)) { if (ValidationUtil.isEmpty(type)) {
throw new BadRequest("参数有误"); throw new BadRequest("参数有误");
} }
docLibraryService.export(id, type, response); docLibraryService.export(id, type, response);
} }
// @TycloudOperation(ApiLevel = UserType.AGENCY)
// @ApiOperation(value = "导入excel文档")
// @RequestMapping(value = "/import", method = RequestMethod.POST)
// public ResponseModel importExcel(@RequestPart(value = "file") MultipartFile file,
// @RequestPart(value = "module") String moduleStr) {
// ExcelImportConfig excelConfig;
// try {
// excelConfig = JSON.parseObject(moduleStr, ExcelImportConfig.class);
// } catch (Exception e) {
// throw new BadRequest("模板配置信息格式有误");
// }
// return ResponseHelper.buildResponse(docLibraryService.importExcel(file, excelConfig));
// }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "导入excel文档") @ApiOperation(value = "导入excel文档")
@RequestMapping(value = "/import", method = RequestMethod.POST) @RequestMapping(value = "/import", method = RequestMethod.POST)
...@@ -241,4 +231,19 @@ public class DocLibraryResource { ...@@ -241,4 +231,19 @@ public class DocLibraryResource {
return ResponseHelper.buildResponse(docLibraryService.importExcel(file, excelConfigList)); return ResponseHelper.buildResponse(docLibraryService.importExcel(file, excelConfigList));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "导入word文档")
@RequestMapping(value = "/importWord", method = RequestMethod.POST)
public ResponseModel importWordDocuments(@RequestParam("file") MultipartFile file) throws IOException, XmlException, ParserConfigurationException, TransformerException {
return ResponseHelper.buildResponse(docLibraryService.importWordOfSingle(file));
}
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "批量导入word文档")
@RequestMapping(value = "/batch/importWord", method = RequestMethod.POST)
public ResponseModel batchImportWordDocuments(MultipartHttpServletRequest request){
List<MultipartFile> files = request.getFiles("files");
return ResponseHelper.buildResponse(docLibraryService.importWordOfBatch(files));
}
} }
...@@ -9,7 +9,6 @@ import io.swagger.annotations.ApiOperation; ...@@ -9,7 +9,6 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.StringUtil; import org.typroject.tyboot.core.foundation.utils.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
...@@ -51,10 +50,12 @@ public class DocOuterResource { ...@@ -51,10 +50,12 @@ public class DocOuterResource {
public ResponseModel<Page> queryDocPage(@RequestParam(value = "current") Integer current, public ResponseModel<Page> queryDocPage(@RequestParam(value = "current") Integer current,
@RequestParam(value = "size") Integer size, @RequestParam(value = "size") Integer size,
@RequestParam(value = "code", required = false) String code, @RequestParam(value = "code", required = false) String code,
@RequestParam(value = "docTitle", required = false) String docTitle) { @RequestParam(value = "docTitle", required = false) String docTitle,
@RequestParam(value = "directoryId", required = false) Long directoryId,
@RequestParam(value = "orgCode", required = false) String orgCode) {
Page page = new Page(current, size); Page page = new Page(current, size);
return ResponseHelper.buildResponse(docLibraryService.queryDocPage(page, docTitle, code)); return ResponseHelper.buildResponse(docLibraryService.queryDocPage(page, docTitle, code,directoryId,orgCode));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import com.yeejoin.amos.knowledgebase.face.service.StatisticsRecordService; import com.yeejoin.amos.knowledgebase.face.service.StatisticsRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -15,125 +10,86 @@ import org.springframework.web.bind.annotation.RequestParam; ...@@ -15,125 +10,86 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
import java.util.Date;
import java.util.List;
@RestController @RestController
@TycloudResource(module = "knowledgebase", value = "docstatistics") //@TycloudResource(module = "knowledgebase", value = "docstatistics")
@RequestMapping(value = "/v1/doccontent/docstatistics") @RequestMapping(value = "/v1/doccontent/docstatistics")
@Api(tags = "knowledgebase-文档统计报表") //@Api(tags = "knowledgebase-文档统计报表")
public class DocStatisticsResource { public class DocStatisticsResource {
@Autowired @Autowired
private StatisticsRecordService statisticsRecordService; private StatisticsRecordService statisticsRecordService;
/* /*@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
* @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false) @ApiOperation(value = "耗时* 刷新统计数据")
* @RequestMapping(value = "/record/init", method = RequestMethod.PUT)
* @ApiOperation(value = "耗时* 刷新统计数据") public ResponseModel init() {
* return ResponseHelper.buildResponse(statisticsRecordService.init());
* @RequestMapping(value = "/record/init", method = RequestMethod.PUT) public }
* ResponseModel init() { return
* ResponseHelper.buildResponse(statisticsRecordService.init()); }
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @ApiOperation(value = "灾情统计")
* @TycloudOperation(ApiLevel = UserType.AGENCY) @RequestMapping(value = "/count/disaster", method = RequestMethod.GET)
* public ResponseModel selectDisasterCount() {
* @ApiOperation(value = "灾情统计") return ResponseHelper.buildResponse(statisticsRecordService.selectDisasterCount());
* }
* @RequestMapping(value = "/count/disaster", method = RequestMethod.GET) public
* ResponseModel selectDisasterCount() { return @TycloudOperation(ApiLevel = UserType.AGENCY)
* ResponseHelper.buildResponse(statisticsRecordService.selectDisasterCount()); @ApiOperation(value = "燃烧物质统计分类")
* } @RequestMapping(value = "/count/burning", method = RequestMethod.GET)
* public ResponseModel selectBurningCategory() {
* @TycloudOperation(ApiLevel = UserType.AGENCY) return ResponseHelper.buildResponse(statisticsRecordService.selectCategoryByName(StatisticsRecordService.STATISTICS_BURNING_CATEGORY));
* }
* @ApiOperation(value = "燃烧物质统计分类")
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @RequestMapping(value = "/count/burning", method = RequestMethod.GET) public @ApiOperation(value = "到场时间统计分类")
* ResponseModel selectBurningCategory() { return @RequestMapping(value = "/count/present", method = RequestMethod.GET)
* ResponseHelper.buildResponse(statisticsRecordService.selectCategoryByName( public ResponseModel selectPresentCategory() {
* StatisticsRecordService.STATISTICS_BURNING_CATEGORY)); } return ResponseHelper.buildResponse(statisticsRecordService.selectCategoryByName(StatisticsRecordService.STATISTICS_PRESENT_CATEGORY));
* }
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @ApiOperation(value = "到场时间统计分类") @ApiOperation(value = "伤亡人数趋势统计")
* @RequestMapping(value = "/count/casualties", method = RequestMethod.GET)
* @RequestMapping(value = "/count/present", method = RequestMethod.GET) public public ResponseModel selectCasualtiesSum(@RequestParam(value = "dateType") String dateType,
* ResponseModel selectPresentCategory() { return @RequestParam(value = "dateRangeLeft", required = false) String dateRangeLeft,
* ResponseHelper.buildResponse(statisticsRecordService.selectCategoryByName( @RequestParam(value = "dateRangeRight", required = false) String dateRangeRight) {
* StatisticsRecordService.STATISTICS_PRESENT_CATEGORY)); } return ResponseHelper.buildResponse(statisticsRecordService.selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight, StatisticsRecordService.STATISTICS_CASUALTIES_SUM));
* }
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @ApiOperation(value = "伤亡人数趋势统计") @ApiOperation(value = "参战车辆数量统计")
* @RequestMapping(value = "/count/power", method = RequestMethod.GET)
* @RequestMapping(value = "/count/casualties", method = RequestMethod.GET) public ResponseModel selectPowerSum(@RequestParam(value = "dateType") String dateType,
* public ResponseModel selectCasualtiesSum(@RequestParam(value = "dateType") @RequestParam(value = "dateRangeLeft", required = false) String dateRangeLeft,
* String dateType, @RequestParam(value = "dateRangeRight", required = false) String dateRangeRight) {
* return ResponseHelper.buildResponse(statisticsRecordService.selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight, StatisticsRecordService.STATISTICS_POWER_SUM));
* @RequestParam(value = "dateRangeLeft", required = false) String }
* dateRangeLeft,
* @TycloudOperation(ApiLevel = UserType.AGENCY)
* @RequestParam(value = "dateRangeRight", required = false) String @ApiOperation(value = "过火面积统计")
* dateRangeRight) { return @RequestMapping(value = "/count/area", method = RequestMethod.GET)
* ResponseHelper.buildResponse(statisticsRecordService. public ResponseModel selectAreaSum(@RequestParam(value = "dateType") String dateType,
* selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight, @RequestParam(value = "dateRangeLeft", required = false) String dateRangeLeft,
* StatisticsRecordService.STATISTICS_CASUALTIES_SUM)); } @RequestParam(value = "dateRangeRight", required = false) String dateRangeRight) {
* return ResponseHelper.buildResponse(statisticsRecordService.selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight, StatisticsRecordService.STATISTICS_AREA_COUNT));
* @TycloudOperation(ApiLevel = UserType.AGENCY) }
*
* @ApiOperation(value = "参战车辆数量统计")
*
* @RequestMapping(value = "/count/power", method = RequestMethod.GET) public
* ResponseModel selectPowerSum(@RequestParam(value = "dateType") String
* dateType,
*
* @RequestParam(value = "dateRangeLeft", required = false) String
* dateRangeLeft,
*
* @RequestParam(value = "dateRangeRight", required = false) String
* dateRangeRight) { return
* ResponseHelper.buildResponse(statisticsRecordService.
* selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight,
* StatisticsRecordService.STATISTICS_POWER_SUM)); }
*
* @TycloudOperation(ApiLevel = UserType.AGENCY)
*
* @ApiOperation(value = "过火面积统计")
*
* @RequestMapping(value = "/count/area", method = RequestMethod.GET) public
* ResponseModel selectAreaSum(@RequestParam(value = "dateType") String
* dateType,
*
* @RequestParam(value = "dateRangeLeft", required = false) String
* dateRangeLeft,
*
* @RequestParam(value = "dateRangeRight", required = false) String
* dateRangeRight) { return
* ResponseHelper.buildResponse(statisticsRecordService.
* selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight,
* StatisticsRecordService.STATISTICS_AREA_COUNT)); }
*
* @TycloudOperation(ApiLevel = UserType.AGENCY)
*
* @ApiOperation(value = "灭火药剂统计")
*
* @RequestMapping(value = "/count/extinguishing", method = RequestMethod.GET)
* public ResponseModel selectExtinguishingSum(@RequestParam(value = "dateType")
* String dateType,
*
* @RequestParam(value = "dateRangeLeft", required = false) String
* dateRangeLeft,
*
* @RequestParam(value = "dateRangeRight", required = false) String
* dateRangeRight) { return
* ResponseHelper.buildResponse(statisticsRecordService.
* selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight,
* StatisticsRecordService.STATISTICS_EXTINGUISHING_SUM)); }
*/
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "灭火药剂统计")
@RequestMapping(value = "/count/extinguishing", method = RequestMethod.GET)
public ResponseModel selectExtinguishingSum(@RequestParam(value = "dateType") String dateType,
@RequestParam(value = "dateRangeLeft", required = false) String dateRangeLeft,
@RequestParam(value = "dateRangeRight", required = false) String dateRangeRight) {
return ResponseHelper.buildResponse(statisticsRecordService.selectCountByTypeAndDateRange(dateType, dateRangeLeft, dateRangeRight, StatisticsRecordService.STATISTICS_EXTINGUISHING_SUM));
}*/
@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false) @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
@ApiOperation(value = "标签总数统计") @ApiOperation(value = "标签总数统计")
@RequestMapping(value = "/tag/statistics", method = RequestMethod.GET) @RequestMapping(value = "/tag/statistics", method = RequestMethod.GET)
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.service.MessageService; import com.yeejoin.amos.knowledgebase.face.service.MessageService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
...@@ -42,7 +40,7 @@ public class MessageResource { ...@@ -42,7 +40,7 @@ public class MessageResource {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "查询用户的消息列表.") @ApiOperation(value = "查询用户的消息列表.")
@RequestMapping(value = "/list/owner", method = RequestMethod.GET) @RequestMapping(value = "/list/owner", method = RequestMethod.GET)
public ResponseModel list(@RequestParam(value = "messageType", required = false) String messageType) { public ResponseModel listOwner(@RequestParam(value = "messageType", required = false) String messageType) {
if (ValidationUtil.isEmpty(messageType)) { if (ValidationUtil.isEmpty(messageType)) {
messageType = null; messageType = null;
} }
...@@ -129,7 +127,7 @@ public class MessageResource { ...@@ -129,7 +127,7 @@ public class MessageResource {
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "分页查询查询用户的消息列表.") @ApiOperation(value = "分页查询查询用户的消息列表.")
@RequestMapping(value = "/list/page", method = RequestMethod.GET) @RequestMapping(value = "/list/page", method = RequestMethod.GET)
public ResponseModel<Page> list( public ResponseModel<Page> listPage(
@RequestParam(value = "current", required = true) int current, @RequestParam(value = "current", required = true) int current,
@RequestParam(value = "size", required = true) int size, @RequestParam(value = "size", required = true) int size,
@RequestParam(value = "messageType", required = false) String messageType) { @RequestParam(value = "messageType", required = false) String messageType) {
......
...@@ -2,8 +2,6 @@ package com.yeejoin.amos.knowledgebase.controller; ...@@ -2,8 +2,6 @@ package com.yeejoin.amos.knowledgebase.controller;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagGroupModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagGroupModel;
import com.yeejoin.amos.knowledgebase.face.service.TagGroupService; import com.yeejoin.amos.knowledgebase.face.service.TagGroupService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
...@@ -11,10 +9,10 @@ import org.apache.logging.log4j.Logger; ...@@ -11,10 +9,10 @@ import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation; import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource; import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest; import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import java.util.List; import com.yeejoin.amos.knowledgebase.face.service.TagInstanceService;
import io.swagger.annotations.Api;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource; import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagInstance;
import com.yeejoin.amos.knowledgebase.face.service.TagInstanceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/** /**
* <p> * <p>
...@@ -41,25 +27,4 @@ public class TagInstanceResource { ...@@ -41,25 +27,4 @@ public class TagInstanceResource {
private final Logger logger = LogManager.getLogger(TagInstanceResource.class); private final Logger logger = LogManager.getLogger(TagInstanceResource.class);
@Autowired @Autowired
private TagInstanceService tagInstanceService; private TagInstanceService tagInstanceService;
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "根据主键查询实例标签")
@RequestMapping(value = "find/{id}", method = RequestMethod.GET)
public ResponseModel<KnowledgeTagInstance> findById(@PathVariable("id") Long id) {
return ResponseHelper.buildResponse(tagInstanceService.findById(id));
}
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "根据targetSeq查询实例标签")
@RequestMapping(value = "targetSeq/{id}", method = RequestMethod.GET)
public ResponseModel<List<KnowledgeTagInstanceModel>> queryListByTargetSeq(@PathVariable("id") Long id) {
return ResponseHelper.buildResponse(tagInstanceService.queryListByTargetSeq(id));
}
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "根据targetSeq查询实例标签")
@RequestMapping(value = "getTarget/byName", method = RequestMethod.GET)
public ResponseModel<List<KnowledgeTagInstanceModel>> queryListByTagName(@RequestParam String name) {
return ResponseHelper.buildResponse(tagInstanceService.queryListByTagName(name));
}
} }
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagModel;
import com.yeejoin.amos.knowledgebase.face.service.TagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType; import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.StringUtil; import org.typroject.tyboot.core.foundation.utils.StringUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
...@@ -18,13 +17,6 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest; ...@@ -18,13 +17,6 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper; import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel; import org.typroject.tyboot.core.restful.utils.ResponseModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagModel;
import com.yeejoin.amos.knowledgebase.face.service.TagService;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/** /**
* <p> * <p>
* 标签库 前端控制器 * 标签库 前端控制器
...@@ -107,7 +99,7 @@ public class TagResource { ...@@ -107,7 +99,7 @@ public class TagResource {
@ApiOperation(value = "查询TOP15") @ApiOperation(value = "查询TOP15")
@RequestMapping(value = "/list/top", method = RequestMethod.GET) @RequestMapping(value = "/list/top", method = RequestMethod.GET)
public ResponseModel selectForList(@RequestParam(value = "quoteType", required = false) String quoteType) { public ResponseModel selectForList(@RequestParam(value = "quoteType", required = false) String quoteType) {
boolean isAll = ValidationUtil.equalsIgnoreCase(quoteType, Constants.APPKEY_ALL); boolean isAll = ValidationUtil.equalsIgnoreCase(quoteType, TagService.APPKEY_ALL);
return ResponseHelper.buildResponse(tagService.queryTopList(isAll)); return ResponseHelper.buildResponse(tagService.queryTopList(isAll));
} }
...@@ -123,14 +115,14 @@ public class TagResource { ...@@ -123,14 +115,14 @@ public class TagResource {
@ApiOperation(value = "启用标签") @ApiOperation(value = "启用标签")
@RequestMapping(value = "status/activate/{ids}", method = RequestMethod.PUT) @RequestMapping(value = "status/activate/{ids}", method = RequestMethod.PUT)
public ResponseModel batchActivate(@PathVariable(value = "ids") String ids) { public ResponseModel batchActivate(@PathVariable(value = "ids") String ids) {
return ResponseHelper.buildResponse(tagService.updateTagStatus(StringUtil.String2LongList(ids), Constants.TAG_STATUS_ACTIVATE)); return ResponseHelper.buildResponse(tagService.updateTagStatus(StringUtil.String2LongList(ids), TagService.TAG_STATUS_ACTIVATE));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "停用标签") @ApiOperation(value = "停用标签")
@RequestMapping(value = "status/deactivate/{ids}", method = RequestMethod.PUT) @RequestMapping(value = "status/deactivate/{ids}", method = RequestMethod.PUT)
public ResponseModel batchDeactivate(@PathVariable(value = "ids") String ids) { public ResponseModel batchDeactivate(@PathVariable(value = "ids") String ids) {
return ResponseHelper.buildResponse(tagService.updateTagStatus(StringUtil.String2LongList(ids), Constants.TAG_STATUS_DEACTIVATE)); return ResponseHelper.buildResponse(tagService.updateTagStatus(StringUtil.String2LongList(ids), TagService.TAG_STATUS_DEACTIVATE));
} }
@TycloudOperation(ApiLevel = UserType.AGENCY) @TycloudOperation(ApiLevel = UserType.AGENCY)
......
package com.yeejoin.amos.knowledgebase.controller; package com.yeejoin.amos.knowledgebase.controller;
import com.yeejoin.amos.knowledgebase.face.service.TagValueService;
import io.swagger.annotations.Api;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.doc.TycloudResource; import org.typroject.tyboot.core.restful.doc.TycloudResource;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import com.yeejoin.amos.knowledgebase.face.service.TagValueService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/** /**
* <p> * <p>
...@@ -36,17 +27,5 @@ public class TagValueResource { ...@@ -36,17 +27,5 @@ public class TagValueResource {
private final Logger logger = LogManager.getLogger(TagValueResource.class); private final Logger logger = LogManager.getLogger(TagValueResource.class);
@Autowired @Autowired
private TagValueService tagValueService; private TagValueService tagValueService;
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "获取所有当前系统的值标签的实例值")
@RequestMapping(value = "/getAll/tegartValue", method = RequestMethod.GET)
public ResponseModel<Object> getAllTegartValue(@RequestParam String value) {
return ResponseHelper.buildResponse(tagValueService.getAllTegartValue(value));
}
@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(value = "获取所有当前系统的值标签的实例值")
@RequestMapping(value = "/getOne/", method = RequestMethod.GET)
public ResponseModel<Object> queryByInstance(@RequestParam Long id) {
return ResponseHelper.buildResponse(tagValueService.queryByInstance(id));
}
} }
package com.yeejoin.amos.knowledgebase.face.enumeration;
/**
* @author 杨博超
* @ClassName DynamicsFunctional
**/
public enum DynamicsFunctional {
DOC_BASEINFO,//文档基础信息动态字段配置
VALUE_TAG_CONFIG//标签配置信息动态字段
}
package com.yeejoin.amos.knowledgebase.face.enumeration;
import java.util.Comparator;
import java.util.List;
/**
* @author 杨博超
* @ClassName RoleName
* @Deacription
**/
public enum KnowledgeRoleName {
VIEWER("浏览者", 0, 0, 1, 1),
INPUTER("录入者", 0, 1, 1, 1),
AUDITOR("审核者", 0, 2, 1, 1),
TAG_MANAGER("标签管理员", 1, 0, 0, 0);
private String roleName;
private int tagManagerScore;
private int docManagerScore;
private int docGroupManagerScore;
private int searchScore;
KnowledgeRoleName(String roleName, int tagManagerScore, int docManagerScore, int docGroupManagerScore, int searchScore) {
this.roleName = roleName;
this.tagManagerScore = tagManagerScore;
this.docManagerScore = docManagerScore;
this.docGroupManagerScore = docGroupManagerScore;
this.searchScore = searchScore;
}
public String getRoleName() {
return roleName;
}
public int getTagManagerScore() {
return tagManagerScore;
}
public int getDocManagerScore() {
return docManagerScore;
}
public int getDocGroupManagerScore() {
return docGroupManagerScore;
}
public int getSearchScore() {
return searchScore;
}
public static KnowledgeRoleName getInstance(String roleName) {
KnowledgeRoleName knowledgeRoleName = null;
for (KnowledgeRoleName roleNameIns : KnowledgeRoleName.values()) {
if (roleNameIns.getRoleName().equals(roleName))
knowledgeRoleName = roleNameIns;
}
return knowledgeRoleName;
}
public static KnowledgeRoleName getMaxScore(List<String> roleNames, Comparator<KnowledgeRoleName> comparator) {
KnowledgeRoleName maxScore = null;
for (String roleName : roleNames) {
if (maxScore == null) {
maxScore = getInstance(roleName);
continue;
}
KnowledgeRoleName current = getInstance(roleName);
if(comparator.compare(current,maxScore) > 0)
maxScore = current;
}
return maxScore;
}
}
package com.yeejoin.amos.knowledgebase.face.enumeration;
/**
* @author 杨博超
* @ClassName OperateType
* @Deacription 内容操作类型
**/
public enum OperateType {
LIKE, //点赞
DIS_LIKE, //吐槽
COMMENT, //评论
REFERENCE, //引用
COLLECT //收藏
}
package com.yeejoin.amos.knowledgebase.face.enumeration;
/**
* @author 杨博超
* @ClassName DataType
* @Deacription 动态配置的值类型
**/
public enum OptionDataType {
String, Integer,datetime, Enum,Double,Date
}
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.foundation.utils.TreeNode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.foundation.utils.TreeNode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import java.util.Collection; import java.util.Collection;
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import com.baomidou.mybatisplus.annotation.TableField;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
* 知识库系统动态选项配置的实例值 * 知识库系统动态选项配置的实例值
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
* 知识库内容交互计数表 * 知识库内容交互计数表
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
* 知识库内容交互记录 * 知识库内容交互记录
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.foundation.utils.TreeNode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.foundation.utils.TreeNode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import java.util.Collection; import java.util.Collection;
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import java.util.List; import java.util.List;
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
......
package com.yeejoin.amos.knowledgebase.face.model; package com.yeejoin.amos.knowledgebase.face.model;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
/** /**
* <p> * <p>
* 值标签的实例值 * 值标签的实例值
......
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
...@@ -9,7 +10,7 @@ import java.util.Map; ...@@ -9,7 +10,7 @@ import java.util.Map;
/** /**
* <p> * <p>
* 知识库文档存储 Mapper 接口 * 知识库文档存储 Mapper 接口
* </p> * </p>
* *
* @author 子杨 * @author 子杨
...@@ -18,18 +19,24 @@ import java.util.Map; ...@@ -18,18 +19,24 @@ import java.util.Map;
public interface DocContentMapper extends BaseMapper<KnowledgeDocContent> { public interface DocContentMapper extends BaseMapper<KnowledgeDocContent> {
List<Map<String,Long>> searchForDocIds(@Param("agencyCode") String agencyCode, List<Map<String, Long>> searchForDocIds(
@Param("queryStr") String queryStr, @Param("agencyCode") String agencyCode,
@Param("docStatus")String []docStatus, @Param("queryStr") String queryStr,
@Param("auditStatus")String [] auditStatus, @Param("docStatus") String[] docStatus,
@Param("userId")String userId, @Param("auditStatus") String[] auditStatus,
@Param("orgCode")String orgCode, @Param("userId") String userId,
@Param("offset") long offset, @Param("orgCode") String orgCode,
@Param("length") long length); @Param("offset") long offset,
@Param("length") long length);
List<Map<String,Object>> queryDocBaseInfoList(Map<String, Object> paramMap); List<Map<String, Object>> queryDocBaseInfoList(Map<String, Object> paramMap);
int queryDocBaseInfoTotal(Map<String, Object> paramMap); int queryDocBaseInfoTotal(Map<String, Object> paramMap);
List<Long> getAllPublishedDocIds(); List<Long> getAllPublishedDocIds();
IPage<KnowledgeDocContent> pageByType(
IPage<KnowledgeDocContent> page,
@Param("typeId") Long typeId,
@Param("tagId") Long tagId);
} }
\ No newline at end of file
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity; import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchCrudRepository;
public interface ESDocRepository extends ElasticsearchCrudRepository<ESDocEntity, Long> { public interface ESDocRepository extends ElasticsearchCrudRepository<ESDocEntity, Long> {
......
...@@ -2,6 +2,7 @@ package com.yeejoin.amos.knowledgebase.face.orm.dao; ...@@ -2,6 +2,7 @@ package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord;
import org.apache.ibatis.annotations.Param;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
...@@ -9,7 +10,7 @@ import java.util.Map; ...@@ -9,7 +10,7 @@ import java.util.Map;
/** /**
* <p> * <p>
* 标签分组 Mapper 接口 * 标签分组 Mapper 接口
* </p> * </p>
* *
* @author 子杨 * @author 子杨
...@@ -17,43 +18,42 @@ import java.util.Map; ...@@ -17,43 +18,42 @@ import java.util.Map;
*/ */
public interface StatisticsRecordMapper extends BaseMapper<KnowlegeStatisticsRecord> { public interface StatisticsRecordMapper extends BaseMapper<KnowlegeStatisticsRecord> {
/** /**
* 表清空 * 表清空
* * @return
* @return */
*/ void deleteAll();
void deleteAll();
/** /**
* 查询灾情总计 * 查询灾情总计
* * @return
* @return */
*/ Map<String, Object> selectDisasterCount();
Map<String, Object> selectDisasterCount();
/** /**
* 按类型分组查询 * 按类型分组查询
*/ */
List<Map<String, Object>> selectCategoryByName(String recordName); List<Map<String, Object>> selectCategoryByName(String recordName);
/** /**
* 按类型查询/按时间分段总计 * 按类型查询/按时间分段总计
*/ */
List<Map<String, Object>> selectCountByNameAndDateRange(Map<String, Object> queryMap); List<Map<String, Object>> selectCountByNameAndDateRange(Map<String, Object> queryMap);
List<Map<String, Object>> tagStatisticsMonth(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> tagStatisticsMonth(String tag, Date startDate, Date endDate); List<Map<String, Object>> tagStatisticsYear(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> tagStatisticsYear(String tag, Date startDate, Date endDate); List<Map<String, Object>> docStatisticsMonth(@Param("categoryName")String categoryName, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docStatisticsMonth(String categoryName, Date startDate, Date endDate); List<Map<String, Object>> docStatisticsYear(@Param("categoryName")String categoryName, @Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docStatisticsYear(String categoryName, Date startDate, Date endDate);
List<Map<String, Object>> tagChartStatistics(String tag, Date startDate, Date endDate,String splitSQL); List<Map<String, Object>> tagChartStatistics(@Param("tag")String tag, @Param("startDate")Date startDate, @Param("endDate")Date endDate,@Param("splitSQL")String splitSQL);
List<Map<String, Object>> tagTimeChartStatistics(Date startDate, Date endDate,String splitSQL); List<Map<String, Object>> tagTimeChartStatistics(@Param("startDate")Date startDate, @Param("endDate")Date endDate,@Param("splitSQL")String splitSQL);
List<Map<String, Object>> docChartStatistics(Date startDate, Date endDate); List<Map<String, Object>> docChartStatistics(@Param("startDate")Date startDate, @Param("endDate")Date endDate);
List<Map<String, Object>> docBurnChartStatistics(Date startDate, Date endDate); List<Map<String, Object>> docBurnChartStatistics(@Param("startDate")Date startDate,@Param("endDate") Date endDate);
} }
\ No newline at end of file
package com.yeejoin.amos.knowledgebase.face.orm.dao; package com.yeejoin.amos.knowledgebase.face.orm.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
......
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.Date;
import java.util.List;
@Data
@Accessors(chain = true)
@Document(indexName = "knowledgebase", type = "doc", shards = 1, replicas = 0)
public class ESDocEntity {
/** 主键 */
@Id
private Long sequenceNbr;
/** 文档标题 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_max_word", analyzer = "ik_max_word")
private String docTitle;
/** 主键 */
private Long directoryId;
/** 分类 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
private String directoryName;
/** 作者 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
private String author;
/** 发布时间 */
@Field(type = FieldType.Date, format = DateFormat.basic_date_time)
private Date lastUpdateTime;
/** 正文文字 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_max_word", analyzer = "ik_max_word")
private String textContent;
/** 基本信息 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_max_word")
private String docInfo;
/** 文档正文HTML */
private String htmlContent;
/** 文档摘要 */
private String summary;
/** 文档标签 */
@Field(type = FieldType.Nested, includeInParent = true)
private List<ESTagEntity> docTags;
/** 文档内容标签 */
@Field(type = FieldType.Nested, includeInParent = true)
private List<ESTagEntity> contentTags;
private String docJson;
@Field(type = FieldType.Keyword)
private String sortStr;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.data.elasticsearch.annotations.Parent;
@Data
@Accessors(chain = true)
@Document(indexName = "knowledgebase",type = "tag", shards = 1, replicas = 0)
public class ESTagEntity {
/** 主键 */
@Id
private Long sequenceNbr;
private Long tagSeq;
/** 标签名称 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_max_word", analyzer = "ik_max_word")
private String tagName;
/** 标签值信息 */
@Field(type = FieldType.Text, searchAnalyzer = "ik_smart", analyzer = "ik_smart")
private String tagInfo;
/**原生数据*/
private String tagJson;
/** 绑定外键 */
@Parent(type = "doc")
private String docId;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import java.util.Date;
/**
* <p>
* 知识库文档注释
* </p>
*
* @author ningtianqing
* @since 2020-09-16
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_doc_annotate")
public class KnowledgeDocAnnotate extends BaseEntity {
/**
* 文档id
*/
@TableField("DOC_SEQ")
private Long docSeq;
/**
* 添加注释的用户id
*/
@TableField("USER_ID")
private String userId;
/**
* 注释内容
*/
@TableField("ANNOTATE_CONTENT")
private String annotateContent;
/**
* 注释位置信息(前端定义和使用的内容)
*/
@TableField("POSITION_INFO")
private String positionInfo;
/**
* 创建时间
*/
@TableField("CREATE_TIME")
private Date createTime;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库文档分类
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_doc_category")
public class KnowledgeDocCategory extends BaseEntity {
/**
* 分组名称
*/
@TableField("CATEGORY_NAME")
private String categoryName;
@TableField("PARENT_ID")
private Long parentId;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库评论信息
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_doc_comments")
public class KnowledgeDocComments extends BaseEntity {
/**
* 文档id
*/
@TableField("DOC_SEQ")
private Long docSeq;
/**
* 发表评论的用户id
*/
@TableField("USER_ID")
private String userId;
/**
* 评论内容
*/
@TableField("COMMENTS_CONTENT")
private String commentsContent;
/**
* 父级评论id
*/
@TableField("PARENT_ID")
private Long parentId;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import java.util.Date;
/**
* <p>
* 知识库文档存储
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_doc_content")
public class KnowledgeDocContent extends BaseEntity {
/**
* 富文本内容存储
*/
@TableField("HTML_CONTENT")
private String htmlContent;
/**
* 文档状态:发布,未发布
*/
@TableField("DOC_STATUS")
private String docStatus;
/**
* 发布者
*/
@TableField("USER_ID")
private String userId;
/**
* 创建时间
*/
@TableField("CREATE_TIME")
private Date createTime;
/**
* 是否有附件
*/
@TableField("HAVE_ATTACHMENT")
private Boolean haveAttachment;
/**
* 摘要
*/
@TableField("SUMMARY")
private String summary;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
/**
* 审核状态:通过,驳回,待审核,待提交
**/
@TableField("AUDIT_STATUS")
private String auditStatus;
/**
* 驳回意见
**/
@TableField("REJECTION_COMMENT")
private String rejectionComment;
/**
* 审核人id
**/
@TableField("AUDITOR_USER_ID")
private String auditorUserId;
@TableField("ORG_CODE")
private String orgCode;
/**
* 纯文本内容
*/
@TableField("TEXT_CONTENT")
private String textContent;
/**
* 排序内容
*/
@TableField("SORT_STR")
private String sortStr;
/**
* 所属目录
*/
@TableField("DIRECTORY_ID")
private Long directoryId;
/**
* 文档标题
*/
@TableField("DOC_TITLE")
private String docTitle;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库系统动态选项配置的分组,用于区分不同功能的字段列表
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_dynamics_group")
public class KnowledgeDynamicsGroup extends BaseEntity {
/**
* 分组名称
*/
@TableField("GROUP_NAME")
private String groupName;
/**
* 前端配置
*/
@TableField("FRONT_END_CONFIG")
private String frontEndConfig;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
/**
* 功能标识
*/
@TableField("FUNCTIONAL")
private String functional;
/**
* 业务项目标识
*/
@TableField("APP_KEY")
private String appKey;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库系统动态选项配置,多用于动态字段配置
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_dynamics_option")
public class KnowledgeDynamicsOption extends BaseEntity {
/**
* 字段名
*/
@TableField("FIELD_NAME")
private String fieldName;
/**
* 中文名
*/
@TableField("FIELD_LABEL")
private String fieldLabel;
/**
* 数据类型:文本,数字,枚举,日期
*/
@TableField("DATA_TYPE")
private String dataType;
/**
* 功能标识
*/
@TableField("FUNCTIONAL")
private String functional;
/**
* 业务项目标识
*/
@TableField("APP_KEY")
private String appKey;
@TableField("FRONT_END_CONFIG")
private String frontEndConfig;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
/**
* 分组主键
*/
@TableField("GROUP_SEQ")
private Long groupSeq;
/**
* 查询策略
*/
@TableField("QUERY_STRATEGY")
private String queryStrategy;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库系统动态选项配置的实例值
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_dynamics_value")
public class KnowledgeDynamicsValue extends BaseEntity {
/**
* 字段名
*/
@TableField("FIELD_NAME")
private String fieldName;
/**
* 中文名
*/
@TableField("FIELD_LABEL")
private String fieldLabel;
/**
* 数据类型:文本,数字,枚举,日期
*/
@TableField("DATA_TYPE")
private String dataType;
/**
* 字段分组id
*/
@TableField("GROUP_SEQ")
private Long groupSeq;
/**
* 动态配置字段的值
*/
@TableField("FIELD_VALUE")
private String fieldValue;
/**
* 关联的对象id,即文档id
*/
@TableField("INSTANCE_ID")
private Long instanceId;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
@TableField("OPTION_SEQ")
private Long optionSeq;
@TableField("QUERY_STRATEGY")
private String queryStrategy;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库内容交互计数表
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_interaction_count")
public class KnowledgeInteractionCount extends BaseEntity {
/**
* 操作类型(标签所有情况引用,标签被已审核/已发布文档引用,文档引用)
*/
@TableField("OPERATE_TYPE")
private String operateType;
/**
* 关联对象类型
*/
@TableField("ENTITY_TYPE")
private String entityType;
/**
* 关联对象id
*/
@TableField("ENTITY_ID")
private String entityId;
/**
* 计数
*/
@TableField("OPERATE_COUNT")
private Integer operateCount;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 知识库内容交互记录
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_interaction_record")
public class KnowledgeInteractionRecord extends BaseEntity {
/**
* 用户id
*/
@TableField("USER_ID")
private String userId;
/**
* 操作类型(点赞,吐槽,收藏)
*/
@TableField("OPERATE_TYPE")
private String operateType;
/**
* 关联对象类型
*/
@TableField("ENTITY_TYPE")
private String entityType;
/**
* 关联对象id
*/
@TableField("ENTITY_ID")
private String entityId;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 消息
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_message")
public class KnowledgeMessage extends BaseEntity {
/**
* 消息类型
*/
@TableField("MESSAGE_TYPE")
private String messageType;
/**
* 消息标题
*/
@TableField("MESSAGE_TITLE")
private String messageTitle;
/**
* 消息内容
*/
@TableField("MESSAGE_CONTENT")
private String messageContent;
/**
* 相关文档ID
*/
@TableField("TARGET_SEQ")
private Long targetSeq;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 个人消息
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_message_personal")
public class KnowledgeMessagePersonal extends BaseEntity {
/**
* 接收人
*/
@TableField("MESSAGE_OWNER")
private String messageOwner;
/**
* 消息ID
*/
@TableField("MESSAGE_SEQ")
private Long messageSeq;
/**
* 消息状态
*/
@TableField("MESSAGE_STATUS")
private Integer messageStatus;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 标签库
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_tag")
public class KnowledgeTag extends BaseEntity {
/**
* 标签名称
*/
@TableField("TAG_NAME")
private String tagName;
/**
* 标签编码
*/
@TableField("TAG_CODE")
private String tagCode;
/**
* 标签分类:文本标签,值标签,
*/
@TableField("TAG_TYPE")
private String tagType;
/**
* 标签状态:启用,禁用
*/
@TableField("TAG_STATUS")
private String tagStatus;
/**
* 标签备注
*/
@TableField("TAG_REMARK")
private String tagRemark;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
/**
* 创建人姓名
*/
@TableField("CREATOR")
private String creator;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 标签分组
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_tag_group")
public class KnowledgeTagGroup extends BaseEntity {
/**
* 标签名称
*/
@TableField("GROUP_NAME")
private String groupName;
/**
* 父级分类id
*/
@TableField("PARENT_ID")
private Long parentId;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 标签分组
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_tag_group_ref")
public class KnowledgeTagGroupRef extends BaseEntity {
/**
* 标签分组id
*/
@TableField("GROUP_SEQ")
private Long groupSeq;
/**
* 标签id
*/
@TableField("TAG_SEQ")
private Long tagSeq;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 标签实例
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_tag_instance")
public class KnowledgeTagInstance extends BaseEntity {
/**
* 标签id
*/
@TableField("TAG_SEQ")
private Long tagSeq;
/**
* 标签标记的目标id
*/
@TableField("TARGET_SEQ")
private Long targetSeq;
/**
* 标签名称
*/
@TableField("TAG_NAME")
private String tagName;
/**
* 标记方式:文档,内容
*/
@TableField("MARKING_TYPE")
private String markingType;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
/**
* 标签类型
*/
@TableField("TAG_TYPE")
private String tagType;
@TableField("FRONT_END_CONFIG")
private String frontEndConfig;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
/**
* <p>
* 值标签的实例值
* </p>
*
* @author 子杨
* @since 2020-08-05
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowledge_tag_value")
public class KnowledgeTagValue extends BaseEntity {
/**
* 标签实例id
*/
@TableField("INSTANCE_SEQ")
private Long instanceSeq;
/**
* 值标签的扩展字段名,内容标签文本位置,值标签文本内容/单值/日期,值标签范围最大值-最小值
*/
@TableField("FIELD_NAME")
private String fieldName;
/**
* 值标签扩展字段的值
*/
@TableField("TAG_VALUE")
private String tagValue;
/**
* 机构编号
*/
@TableField("AGENCY_CODE")
private String agencyCode;
@TableField("UNIT")
private String unit;
}
package com.yeejoin.amos.knowledgebase.face.orm.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import java.util.Date;
/**
* <p>
* 标签分组
* </p>
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("knowlege_statistics_record")
public class KnowlegeStatisticsRecord extends BaseEntity {
/**
* 文档ID
*/
@TableField("DOC_SEQ")
private Long docSeq;
/**
* 警情发生时间
*/
@TableField("DISASTER_TIME")
private Date disasterTime;
/**
* 记录类型
*/
@TableField("RECORD_NAME")
private String recordName;
/**
* 分类字段值
*/
@TableField("CATEGORY_VALUE")
private String categoryValue;
/**
* 统计数值
*/
@TableField("COUNT_VALUE")
private Long countValue;
/**
* 值放大倍数
*/
@TableField("VALUE_WEIGHT")
private Integer valueWeight;
/**
* 数值单位
*/
@TableField("UNIT")
private Long unit;
}
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.Date; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocAnnotateModel;
import java.util.List; import com.yeejoin.amos.knowledgebase.face.orm.dao.DocAnnotateMapper;
import java.util.Map; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocAnnotate;
import java.util.Set; import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -16,10 +14,11 @@ import org.typroject.tyboot.core.foundation.utils.Bean; ...@@ -16,10 +14,11 @@ import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData; import java.util.Date;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocAnnotateModel; import java.util.List;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocAnnotateMapper; import java.util.Map;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocAnnotate; import java.util.Set;
import java.util.stream.Collectors;
/** /**
...@@ -88,13 +87,12 @@ public class DocAnnotateService extends BaseService<KnowledgeDocAnnotateModel, K ...@@ -88,13 +87,12 @@ public class DocAnnotateService extends BaseService<KnowledgeDocAnnotateModel, K
**/ **/
public List<KnowledgeDocAnnotateModel> queryForAnnotateList(String docSeq) { public List<KnowledgeDocAnnotateModel> queryForAnnotateList(String docSeq) {
List<KnowledgeDocAnnotateModel> list = this.queryForList("CREATE_TIME",true, docSeq); List<KnowledgeDocAnnotateModel> list = this.queryForList("CREATE_TIME",true, docSeq);
Set<String> userIds = list.stream().filter(item -> !ValidationUtil.isEmpty(item)).map(arg0 -> arg0.getUserId()).collect(Collectors.toSet()); Set<String> userIds = list.stream().filter(item -> !ValidationUtil.isEmpty(item)).map(KnowledgeDocAnnotateModel::getUserId).collect(Collectors.toSet());
Map<String, String> userMap = RemoteData.getUserMap(userIds); Map<String, String> userMap = RemoteData.getUserMap(userIds);
list.forEach(item -> { list.forEach(item -> {
item.setUsername(userMap.get(item.getUserId())); item.setUsername(userMap.get(item.getUserId()));
item.setIsCurrentUser(ValidationUtil.equals(item.getUserId(),RequestContext.getExeUserId())); item.setIsCurrentUser(ValidationUtil.equals(item.getUserId(),RequestContext.getExeUserId()));
}); });
return list; return list;
} }
} }
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.ArrayList; import com.alibaba.fastjson.JSON;
import java.util.Collection; import com.alibaba.fastjson.JSONObject;
import java.util.Iterator; import com.yeejoin.amos.component.rule.action.Topic;
import java.util.List; import com.yeejoin.amos.component.rule.config.ClazzUtils;
import java.util.concurrent.atomic.AtomicBoolean; import com.yeejoin.amos.component.rule.config.RuleConfig;
import java.util.concurrent.atomic.AtomicReference; import com.yeejoin.amos.component.rule.model.ConstantCategoryModel;
import com.yeejoin.amos.component.rule.model.ConstantModel;
import com.yeejoin.amos.component.rule.model.DefinitionModel;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsOptionModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsValue;
import com.yeejoin.amos.knowledgebase.face.util.BaseUtil;
import com.yeejoin.amos.knowledgebase.face.util.ConfigLoader;
import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -15,7 +25,6 @@ import org.springframework.cloud.client.ServiceInstance; ...@@ -15,7 +25,6 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.component.emq.EmqKeeper; import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException; import org.typroject.tyboot.core.foundation.exception.BaseException;
...@@ -24,21 +33,13 @@ import org.typroject.tyboot.core.foundation.utils.ValidationUtil; ...@@ -24,21 +33,13 @@ import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound; import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;
import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden; import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden;
import com.alibaba.fastjson.JSON; import java.util.ArrayList;
import com.alibaba.fastjson.JSONObject; import java.util.Collection;
import com.yeejoin.amos.component.rule.action.Topic; import java.util.Iterator;
import com.yeejoin.amos.component.rule.config.ClazzUtils; import java.util.List;
import com.yeejoin.amos.component.rule.config.RuleConfig; import java.util.concurrent.atomic.AtomicBoolean;
import com.yeejoin.amos.component.rule.model.ConstantCategoryModel; import java.util.concurrent.atomic.AtomicReference;
import com.yeejoin.amos.component.rule.model.ConstantModel; import java.util.stream.Collectors;
import com.yeejoin.amos.component.rule.model.DefinitionModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.util.BaseUtil;
import com.yeejoin.amos.knowledgebase.face.util.ConfigLoader;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming;
/** /**
...@@ -52,12 +53,32 @@ import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming; ...@@ -52,12 +53,32 @@ import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming;
@Component @Component
public class DocAuditService { public class DocAuditService {
/**
* 审核状态--待提交
*/
public static final String DOC_AUDIT_STATUS_SAVED = "SAVED";
/**
* 审核状态--待审核
*/
public static final String DOC_AUDIT_STATUS_SUBMITTED = "SUBMITTED";
/**
* 审核状态--通过
*/
public static final String DOC_AUDIT_STATUS_PASSED = "PASSED";
/**
* 审核状态--驳回
*/
public static final String DOC_AUDIT_STATUS_REJECTED = "REJECTED";
private static final String TAG_INSTANCE_LABEL = "label";
private static String DELETE_SYNC_PLAN_TOPIC = "DELETE_SYNC_PLAN_DOC";
@Autowired @Autowired
private DocContentService service; private DocContentService service;
@Autowired @Autowired
private ESDocService eSDocService; private ESDocService eSDocService;
// @Autowired // @Autowired
// private StatisticsRecordService statisticsRecordService; // private StatisticsRecordService statisticsRecordService;
@Autowired @Autowired
private DocLibraryService docLibraryService; private DocLibraryService docLibraryService;
...@@ -65,6 +86,10 @@ public class DocAuditService { ...@@ -65,6 +86,10 @@ public class DocAuditService {
private LoadBalancerClient loadBalancerClient; private LoadBalancerClient loadBalancerClient;
@Autowired @Autowired
private EmqKeeper emqKeeper; private EmqKeeper emqKeeper;
@Autowired
private DynamicsValueService dynamicsValueService;
@Autowired
private DynamicsOptionService dynamicsOptionService;
@Autowired @Autowired
private ConfigLoader configLoader; private ConfigLoader configLoader;
...@@ -83,11 +108,49 @@ public class DocAuditService { ...@@ -83,11 +108,49 @@ public class DocAuditService {
if (ValidationUtil.isEmpty(resList)) { if (ValidationUtil.isEmpty(resList)) {
throw new DataNotFound("数据不存在"); throw new DataNotFound("数据不存在");
} }
for (KnowledgeDocContentModel doc : resList) {
if (ValidationUtil.isEmpty(doc.getDirectoryId())) {
throw new DataNotFound("【" + doc.getDocTitle() + "】,文档所属分类为空");
}
}
int requiredNum = 0;
//查询必填项数量
List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
requiredNum = optionModels.stream().filter(x -> x.getFrontEndConfig().contains("\"required\":true")).collect(Collectors.toList()).size();
//查询文档必填项是否填写
List<KnowledgeDynamicsValue> requiredByFile = dynamicsValueService.isRequiredByFile(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name(), docSeqList);
if (ValidationUtil.isEmpty(requiredByFile)) {
throw new DataNotFound("【" + resList.get(0).getDocTitle() + "】,信息填写不完整,请完善后发布!");
} else {
List<Long> filterDocs = null;
//筛选出没有记录的
List<Long> valueInsIds = requiredByFile.stream().map(KnowledgeDynamicsValue::getInstanceId).collect(Collectors.toList());
if (requiredByFile.size() != docSeqList.size() * requiredNum) {
filterDocs = docSeqList.stream().filter(x -> {
return !valueInsIds.contains(x);
}).distinct().collect(Collectors.toList());
} else {
//筛选出FieldValue为空的
List<KnowledgeDynamicsValue> fieldValueByNull = requiredByFile.stream().filter(x -> {
return ValidationUtil.isEmpty(x.getFieldValue());
}).collect(Collectors.toList());
filterDocs = fieldValueByNull.stream().map(KnowledgeDynamicsValue::getInstanceId).distinct().collect(Collectors.toList());
}
List<Long> finalFilterDocs = filterDocs;
if (!ValidationUtil.isEmpty(finalFilterDocs)) {
List<KnowledgeDocContentModel> filterFiles = resList.stream().filter(x -> {
return x.getSequenceNbr().equals(finalFilterDocs.get(0));
}).collect(Collectors.toList());
throw new DataNotFound("【" + filterFiles.get(0).getDocTitle() + "】,信息填写不完整,请完善后发布!");
}
}
//更新状态 //更新状态
for (KnowledgeDocContentModel oldDoc : resList) { for (KnowledgeDocContentModel oldDoc : resList) {
if (ValidationUtil.equals(oldDoc.getDocStatus(), Constants.DOC_STATUS_UNPUBLISHED)) { if (ValidationUtil.equals(oldDoc.getDocStatus(), DocContentService.DOC_STATUS_UNPUBLISHED)) {
oldDoc.setDocStatus(Constants.DOC_STATUS_PUBLISHED); oldDoc.setDocStatus(DocContentService.DOC_STATUS_PUBLISHED);
oldDoc.setAuditStatus(Constants.DOC_AUDIT_STATUS_PASSED); oldDoc.setAuditStatus(DOC_AUDIT_STATUS_PASSED);
oldDoc.setAuditorUserId(RequestContext.getExeUserId()); oldDoc.setAuditorUserId(RequestContext.getExeUserId());
service.updateWithModel(oldDoc); service.updateWithModel(oldDoc);
} else { } else {
...@@ -118,13 +181,13 @@ public class DocAuditService { ...@@ -118,13 +181,13 @@ public class DocAuditService {
throw new DataNotFound("数据不存在"); throw new DataNotFound("数据不存在");
} }
for (KnowledgeDocContentModel oldDoc : resList) { for (KnowledgeDocContentModel oldDoc : resList) {
if (ValidationUtil.equals(oldDoc.getDocStatus(), Constants.DOC_STATUS_PUBLISHED)) { if (ValidationUtil.equals(oldDoc.getDocStatus(), DocContentService.DOC_STATUS_PUBLISHED)) {
//判断文档是否被引用 //判断文档是否被引用
if (service.getReference(oldDoc.getSequenceNbr()) > 0) { if (service.getReference(oldDoc.getSequenceNbr()) > 0) {
throw new RequestForbidden("含被引用文档,不能取消发布"); throw new RequestForbidden("含被引用文档,不能取消发布");
} }
oldDoc.setDocStatus(Constants.DOC_STATUS_UNPUBLISHED); oldDoc.setDocStatus(DocContentService.DOC_STATUS_UNPUBLISHED);
oldDoc.setAuditStatus(Constants.DOC_AUDIT_STATUS_SAVED); oldDoc.setAuditStatus(DOC_AUDIT_STATUS_SAVED);
oldDoc.setAuditorUserId(RequestContext.getExeUserId()); oldDoc.setAuditorUserId(RequestContext.getExeUserId());
service.updateWithModel(oldDoc); service.updateWithModel(oldDoc);
} else { } else {
...@@ -155,9 +218,9 @@ public class DocAuditService { ...@@ -155,9 +218,9 @@ public class DocAuditService {
throw new DataNotFound("数据不存在"); throw new DataNotFound("数据不存在");
} }
for (KnowledgeDocContentModel oldDoc : resList) { for (KnowledgeDocContentModel oldDoc : resList) {
if (ValidationUtil.equals(oldDoc.getAuditStatus(), Constants.DOC_AUDIT_STATUS_SAVED)) { if (ValidationUtil.equals(oldDoc.getAuditStatus(), DOC_AUDIT_STATUS_SAVED)) {
//更新审核状态 //更新审核状态
oldDoc.setAuditStatus(Constants.DOC_AUDIT_STATUS_SUBMITTED); oldDoc.setAuditStatus(DOC_AUDIT_STATUS_SUBMITTED);
service.updateWithModel(oldDoc); service.updateWithModel(oldDoc);
} else { } else {
throw new RequestForbidden("只允许对待提交状态的文档执行此操作"); throw new RequestForbidden("只允许对待提交状态的文档执行此操作");
...@@ -179,12 +242,12 @@ public class DocAuditService { ...@@ -179,12 +242,12 @@ public class DocAuditService {
throw new DataNotFound("数据不存在"); throw new DataNotFound("数据不存在");
} }
for (KnowledgeDocContentModel oldDoc : resList) { for (KnowledgeDocContentModel oldDoc : resList) {
if (ValidationUtil.equals(oldDoc.getAuditStatus(), Constants.DOC_AUDIT_STATUS_SUBMITTED)) { if (ValidationUtil.equals(oldDoc.getAuditStatus(), DOC_AUDIT_STATUS_SUBMITTED)) {
//更新审核状态 //更新审核状态
oldDoc.setAuditStatus(Constants.DOC_AUDIT_STATUS_PASSED); oldDoc.setAuditStatus(DOC_AUDIT_STATUS_PASSED);
oldDoc.setAuditorUserId(RequestContext.getExeUserId()); oldDoc.setAuditorUserId(RequestContext.getExeUserId());
//更新文档发布状态 //更新文档发布状态
oldDoc.setDocStatus(Constants.DOC_STATUS_PUBLISHED); oldDoc.setDocStatus(DocContentService.DOC_STATUS_PUBLISHED);
service.updateWithModel(oldDoc); service.updateWithModel(oldDoc);
} else { } else {
throw new RequestForbidden("只允许对待审核状态的文档执行此操作"); throw new RequestForbidden("只允许对待审核状态的文档执行此操作");
...@@ -213,12 +276,12 @@ public class DocAuditService { ...@@ -213,12 +276,12 @@ public class DocAuditService {
if (ValidationUtil.isEmpty(oldDoc)) { if (ValidationUtil.isEmpty(oldDoc)) {
throw new DataNotFound("数据不存在"); throw new DataNotFound("数据不存在");
} }
if (ValidationUtil.equals(oldDoc.getAuditStatus(), Constants.DOC_AUDIT_STATUS_SUBMITTED)) { if (ValidationUtil.equals(oldDoc.getAuditStatus(), DOC_AUDIT_STATUS_SUBMITTED)) {
//更新审核状态&文档状态 //更新审核状态&文档状态
oldDoc.setAuditStatus(Constants.DOC_AUDIT_STATUS_REJECTED); oldDoc.setAuditStatus(DOC_AUDIT_STATUS_REJECTED);
oldDoc.setRejectionComment(rejectionComment); oldDoc.setRejectionComment(rejectionComment);
oldDoc.setAuditorUserId(RequestContext.getExeUserId()); oldDoc.setAuditorUserId(RequestContext.getExeUserId());
oldDoc.setDocStatus(Constants.DOC_STATUS_UNPUBLISHED); oldDoc.setDocStatus(DocContentService.DOC_STATUS_UNPUBLISHED);
return service.updateWithModel(oldDoc); return service.updateWithModel(oldDoc);
} else { } else {
throw new RequestForbidden("只允许对待审核状态的文档执行此操作"); throw new RequestForbidden("只允许对待审核状态的文档执行此操作");
...@@ -233,7 +296,7 @@ public class DocAuditService { ...@@ -233,7 +296,7 @@ public class DocAuditService {
public void pushDeletedDocs2DigitalPlanByMQ(List<KnowledgeDocContentModel> resList) { public void pushDeletedDocs2DigitalPlanByMQ(List<KnowledgeDocContentModel> resList) {
List<Long> ids = BaseUtil.getModelIds(resList); List<Long> ids = BaseUtil.getModelIds(resList);
try { try {
emqKeeper.getMqttClient().publish(Constants.DELETE_SYNC_PLAN_TOPIC, ClazzUtils.serializableObject(ids), RuleConfig.DEFAULT_QOS, false); emqKeeper.getMqttClient().publish(DELETE_SYNC_PLAN_TOPIC, ClazzUtils.serializableObject(ids), RuleConfig.DEFAULT_QOS, false);
logger.info("文档" + ids.toString() + "取消发布,已推送消息至数字预案服务"); logger.info("文档" + ids.toString() + "取消发布,已推送消息至数字预案服务");
} catch (Exception e) { } catch (Exception e) {
logger.fatal("文档" + ids.toString() + "取消发布未能成功推送至数字预案服务", e); logger.fatal("文档" + ids.toString() + "取消发布未能成功推送至数字预案服务", e);
...@@ -344,15 +407,15 @@ public class DocAuditService { ...@@ -344,15 +407,15 @@ public class DocAuditService {
AtomicBoolean isRange = new AtomicBoolean(false); AtomicBoolean isRange = new AtomicBoolean(false);
AtomicReference<String> resRight = new AtomicReference<>(""); AtomicReference<String> resRight = new AtomicReference<>("");
AtomicReference<String> unit = new AtomicReference<>(""); AtomicReference<String> unit = new AtomicReference<>("");
if (!ObjectUtils.isEmpty(values)) { if (!ValidationUtil.isEmpty(values.isEmpty())) {
values.forEach(value -> { values.forEach(value -> {
if (Constants.VALUE_TAG_FIELD_RANGE_MAX.equals(value.getFieldName())) { if (TagValueService.VALUE_TAG_FIELD_RANGE_MAX.equals(value.getFieldName())) {
resRight.set(value.getTagValue()); resRight.set(value.getTagValue());
} else { } else {
resLeft.set(value.getTagValue()); resLeft.set(value.getTagValue());
} }
if (Constants.VALUE_TAG_FIELD_RANGE_MAX.equals(value.getFieldName()) if (TagValueService.VALUE_TAG_FIELD_RANGE_MAX.equals(value.getFieldName())
|| Constants.VALUE_TAG_FIELD_RANGE_MIN.equals(value.getFieldName())) { || TagValueService.VALUE_TAG_FIELD_RANGE_MIN.equals(value.getFieldName())) {
isRange.set(true); isRange.set(true);
} }
unit.set(ValidationUtil.isEmpty(value.getUnit()) || "null".equals(value.getUnit()) ? "" : value.getUnit()); unit.set(ValidationUtil.isEmpty(value.getUnit()) || "null".equals(value.getUnit()) ? "" : value.getUnit());
...@@ -375,7 +438,7 @@ public class DocAuditService { ...@@ -375,7 +438,7 @@ public class DocAuditService {
if (!ValidationUtil.isEmpty(frontEndConfig)) { if (!ValidationUtil.isEmpty(frontEndConfig)) {
try { try {
JSONObject configObject = JSON.parseObject(frontEndConfig); JSONObject configObject = JSON.parseObject(frontEndConfig);
return (String) configObject.get(Constants.TAG_INSTANCE_LABEL); return (String) configObject.get(TAG_INSTANCE_LABEL);
} catch (Exception e) { } catch (Exception e) {
} }
} }
......
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.*; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCategoryModel;
import com.yeejoin.amos.knowledgebase.face.model.MultipleNodeModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocCategoryMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocCategory;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTag;
import com.yeejoin.amos.knowledgebase.face.util.BaseUtil;
import com.yeejoin.amos.knowledgebase.face.util.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -17,16 +24,7 @@ import org.typroject.tyboot.core.rdbms.service.BaseService; ...@@ -17,16 +24,7 @@ import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest; import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden; import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import java.util.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCategoryModel;
import com.yeejoin.amos.knowledgebase.face.model.MultipleNodeModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocCategoryMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocCategory;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTag;
import com.yeejoin.amos.knowledgebase.face.util.BaseUtil;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import com.yeejoin.amos.knowledgebase.face.util.TreeUtil;
/** /**
* <p> * <p>
...@@ -173,6 +171,16 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K ...@@ -173,6 +171,16 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K
return sequenceList; return sequenceList;
} }
public Map<String, Long> getGroupNameValue(List<Long> ids) {
List<KnowledgeDocCategoryModel> list = this.queryBatchSeq(ids);
Map<String, Long> result = new HashMap<>();
for(KnowledgeDocCategoryModel knowledgeDocCategoryModel: list) {
result.put(knowledgeDocCategoryModel.getCategoryName(), knowledgeDocCategoryModel.getSequenceNbr());
}
return result;
}
private void getAllChildList(KnowledgeDocCategoryModel currentTagGroupModel, List<KnowledgeDocCategoryModel> resList) { private void getAllChildList(KnowledgeDocCategoryModel currentTagGroupModel, List<KnowledgeDocCategoryModel> resList) {
if (null == currentTagGroupModel) { if (null == currentTagGroupModel) {
return; return;
...@@ -205,7 +213,7 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K ...@@ -205,7 +213,7 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K
List<KnowledgeDocCategoryModel> allChildren = TreeUtil.getAllChildren(categoryTree); List<KnowledgeDocCategoryModel> allChildren = TreeUtil.getAllChildren(categoryTree);
if (!allChildren.isEmpty()) { if (!allChildren.isEmpty()) {
List<Long> directoryIds = BaseUtil.getModelIds(allChildren); List<Long> directoryIds = BaseUtil.getModelIds(allChildren);
List<MultipleNodeModel> multipleNodeModels = this.baseMapper.queryDocAndCategoryTree(directoryIds, onlyPublish ? Constants.DOC_STATUS_PUBLISHED : null); List<MultipleNodeModel> multipleNodeModels = this.baseMapper.queryDocAndCategoryTree(directoryIds, onlyPublish ? DocContentService.DOC_STATUS_PUBLISHED : null);
return TreeBuilder.buildByRecursive(multipleNodeModels, null == rootCategory ? root : rootCategory.getParentId()); return TreeBuilder.buildByRecursive(multipleNodeModels, null == rootCategory ? root : rootCategory.getParentId());
} }
} }
...@@ -250,13 +258,4 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K ...@@ -250,13 +258,4 @@ public class DocCategoryService extends BaseService<KnowledgeDocCategoryModel, K
List<KnowledgeDocCategoryModel> categoryModelList = this.queryForList(null, true, categoryName, parentId); List<KnowledgeDocCategoryModel> categoryModelList = this.queryForList(null, true, categoryName, parentId);
return categoryModelList.isEmpty() ? null : categoryModelList.get(0); return categoryModelList.isEmpty() ? null : categoryModelList.get(0);
} }
public Map<String, Long> getGroupNameValue(List<Long> ids) {
List<KnowledgeDocCategoryModel> list = this.queryBatchSeq(ids);
Map<String, Long> result = new HashMap<>();
for(KnowledgeDocCategoryModel knowledgeDocCategoryModel: list) {
result.put(knowledgeDocCategoryModel.getCategoryName(), knowledgeDocCategoryModel.getSequenceNbr());
}
return result;
}
} }
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType; import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCommentsModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocCommentsModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeInteractionRecordModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeInteractionRecordModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocCommentsMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.DocCommentsMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocComments; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocComments;
import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import java.util.Date;
import java.util.List;
/** /**
......
...@@ -2,6 +2,7 @@ package com.yeejoin.amos.knowledgebase.face.service; ...@@ -2,6 +2,7 @@ package com.yeejoin.amos.knowledgebase.face.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence; import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.component.feign.model.FeignClientResult; import com.yeejoin.amos.component.feign.model.FeignClientResult;
...@@ -11,15 +12,13 @@ import com.yeejoin.amos.feign.systemctl.model.FileInfoModel; ...@@ -11,15 +12,13 @@ import com.yeejoin.amos.feign.systemctl.model.FileInfoModel;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional; import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName; import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName;
import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType; import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType;
import com.yeejoin.amos.knowledgebase.face.feign.DataFillter;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.*; import com.yeejoin.amos.knowledgebase.face.model.*;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DocContentMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.DocContentMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue; import com.yeejoin.amos.knowledgebase.face.util.DataFillter;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
import com.yeejoin.amos.knowledgebase.face.util.DocSortUtil; import com.yeejoin.amos.knowledgebase.face.util.DocSortUtil;
import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming; import com.yeejoin.amos.knowledgebase.face.util.QuoteCountFlushTiming;
import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -48,11 +47,10 @@ import java.util.*; ...@@ -48,11 +47,10 @@ import java.util.*;
@Component @Component
public class DocContentService extends BaseService<KnowledgeDocContentModel, KnowledgeDocContent, DocContentMapper> implements DataFillter { public class DocContentService extends BaseService<KnowledgeDocContentModel, KnowledgeDocContent, DocContentMapper> implements DataFillter {
public static final String DOC_STATUS_UNPUBLISHED = "UNPUBLISHED";//文档发布状态--未发布
public static final String DOC_STATUS_PUBLISHED = "PUBLISHED"; //文档发布状态--已发布
private final String orderBy = new StringBuilder().append("ORDER BY FIELD(audit_status, '").append(DocAuditService.DOC_AUDIT_STATUS_SAVED).append("', '").append(DocAuditService.DOC_AUDIT_STATUS_SUBMITTED).append("', '").append(DocAuditService.DOC_AUDIT_STATUS_REJECTED).append("', '").append(DocAuditService.DOC_AUDIT_STATUS_PASSED).append("') ASC, create_time DESC").toString();
private final String orderBy = new StringBuilder().append("ORDER BY FIELD(audit_status, '").append(Constants.DOC_AUDIT_STATUS_SAVED).append("', '")
.append(Constants.DOC_AUDIT_STATUS_SUBMITTED).append("', '").append(Constants.DOC_AUDIT_STATUS_REJECTED).append("', '")
.append(Constants.DOC_AUDIT_STATUS_PASSED).append("') ASC, create_time DESC").toString();
@Autowired @Autowired
private DynamicsValueService dynamicsValueService; private DynamicsValueService dynamicsValueService;
...@@ -69,13 +67,11 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -69,13 +67,11 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
@Autowired @Autowired
private TagValueService tagValueService; private TagValueService tagValueService;
@Autowired @Autowired
private private DocLibraryService docLibraryService;
DocLibraryService docLibraryService;
@Autowired @Autowired
private Sequence sequence; private Sequence sequence;
public Page queryDocPage(int offset, int end, Map<String, String[]> paramMap, String[] auditStatus, String[] docStatus, public Page queryDocPage(int offset, int end, Map<String, String[]> paramMap, String[] auditStatus, String[] docStatus, Date createTimeLeft, Date createTimeRight) {
Date createTimeLeft, Date createTimeRight) {
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
if (!ValidationUtil.isEmpty(auditStatus)) { if (!ValidationUtil.isEmpty(auditStatus)) {
wrapper.in("audit_status", Arrays.asList(auditStatus)); wrapper.in("audit_status", Arrays.asList(auditStatus));
...@@ -128,8 +124,8 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -128,8 +124,8 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
docContentModel.setAgencyCode(RequestContext.getAgencyCode()); docContentModel.setAgencyCode(RequestContext.getAgencyCode());
docContentModel.setUserId(RequestContext.getExeUserId()); docContentModel.setUserId(RequestContext.getExeUserId());
docContentModel.setCreateTime(new Date()); docContentModel.setCreateTime(new Date());
docContentModel.setDocStatus(Constants.DOC_STATUS_UNPUBLISHED); docContentModel.setDocStatus(DOC_STATUS_UNPUBLISHED);
docContentModel.setAuditStatus(Constants.DOC_AUDIT_STATUS_SAVED); docContentModel.setAuditStatus(DocAuditService.DOC_AUDIT_STATUS_SAVED);
docContentModel.setSequenceNbr(sequenceNbr); docContentModel.setSequenceNbr(sequenceNbr);
String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName()); String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
if (ValidationUtil.isEmpty(inputerOrg)) { if (ValidationUtil.isEmpty(inputerOrg)) {
...@@ -137,7 +133,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -137,7 +133,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
} }
docContentModel.setOrgCode(inputerOrg); docContentModel.setOrgCode(inputerOrg);
String textContent = String.valueOf(docContentModel.getTextContent()); String textContent = String.valueOf(docContentModel.getTextContent());
docContentModel.setSummary(textContent.substring(0,Math.min(300, textContent.length()))); docContentModel.setSummary(textContent.substring(0, Math.min(300, textContent.length())));
if (ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) { if (ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) {
docContentModel.setHaveAttachment(false); docContentModel.setHaveAttachment(false);
} }
...@@ -146,14 +142,14 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -146,14 +142,14 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), sequenceNbr, DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey()); dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), sequenceNbr, DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey());
// 保存标签实例 // 保存标签实例
List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), sequenceNbr, Constants.MARKING_TYPE_DOC); List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), sequenceNbr, TagInstanceService.MARKING_TYPE_DOC);
tagInstanceService.saveInstance(docContentModel.getDocContentTags(), sequenceNbr, Constants.MARKING_TYPE_CONTENT); tagInstanceService.saveInstance(docContentModel.getDocContentTags(), sequenceNbr, TagInstanceService.MARKING_TYPE_CONTENT);
QuoteCountFlushTiming.needFlushTag(); QuoteCountFlushTiming.needFlushTag();
//保存附件信息 //保存附件信息
saveAttachments(docContentModel.getAttachments(), sequenceNbr); saveAttachments(docContentModel.getAttachments(), sequenceNbr);
//生成排序字段信息 //生成排序字段信息
docContentModel.setSortStr(DocSortUtil.getSortStr(docTags)); docContentModel.setSortStr(DocSortUtil.getSortStr(docTags));
docLibraryService.fillDirectoryName(Arrays.asList(docContentModel)); docLibraryService.fillDirectoryName(Collections.singletonList(docContentModel));
return this.createWithModel(docContentModel); return this.createWithModel(docContentModel);
} }
...@@ -185,44 +181,38 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -185,44 +181,38 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
} }
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException("删除文件出错."); throw new RuntimeException("删除文件出错." + e.getMessage());
} }
return true; return true;
} }
private KnowledgeDocContentModel fillAttachments(KnowledgeDocContentModel docContentModel) { private KnowledgeDocContentModel fillAttachments(KnowledgeDocContentModel docContentModel) {
try { List<FileInfoModel> fileInfoModels = FeignUtil.remoteCall(() -> Systemctl.fileInfoClient.queryByEntity(RequestContext.getAgencyCode(), KnowledgeDocContentModel.class.getSimpleName(), String.valueOf(docContentModel.getSequenceNbr())));
List<FileInfoModel> fileInfoModels = FeignUtil.remoteCall(() -> Systemctl.fileInfoClient.queryByEntity(RequestContext.getAgencyCode(), KnowledgeDocContentModel.class.getSimpleName(), String.valueOf(docContentModel.getSequenceNbr()))); if (!ValidationUtil.isEmpty(fileInfoModels)) {
List<AttachmentModel> attachments = new ArrayList<>();
if (!ValidationUtil.isEmpty(fileInfoModels)) { for (FileInfoModel fileInfoModel : fileInfoModels) {
List<AttachmentModel> attachments = new ArrayList<>(); AttachmentModel attachmentModel = new AttachmentModel();
for (FileInfoModel fileInfoModel : fileInfoModels) { attachmentModel.setFilename(fileInfoModel.getFilename());
AttachmentModel attachmentModel = new AttachmentModel(); attachmentModel.setFileType(fileInfoModel.getFileType());
attachmentModel.setFilename(fileInfoModel.getFilename()); attachmentModel.setOriginalFileName(fileInfoModel.getOriginalFileName());
attachmentModel.setFileType(fileInfoModel.getFileType()); attachmentModel.setFileUrl(fileInfoModel.getFileUrl());
attachmentModel.setOriginalFileName(fileInfoModel.getOriginalFileName()); attachments.add(attachmentModel);
attachmentModel.setFileUrl(fileInfoModel.getFileUrl());
attachments.add(attachmentModel);
}
docContentModel.setAttachments(attachments);
} }
} catch (Exception e) { docContentModel.setAttachments(attachments);
e.printStackTrace();
} }
return docContentModel; return docContentModel;
} }
private String seperotorStrCollection(Collection<Long> stringCollection) { private String seperotorStrCollection(Collection<Long> stringCollection) {
String returnStr = ""; StringBuilder returnStr = new StringBuilder();
if (!ValidationUtil.isEmpty(stringCollection)) { if (!ValidationUtil.isEmpty(stringCollection)) {
for (Long seq : stringCollection) { for (Long seq : stringCollection) {
returnStr += String.valueOf(seq) + ","; returnStr.append(seq).append(",");
} }
returnStr = returnStr.substring(0, returnStr.length() - 1); returnStr = new StringBuilder(returnStr.substring(0, returnStr.length() - 1));
} }
return returnStr; return returnStr.toString();
} }
...@@ -235,39 +225,37 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -235,39 +225,37 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
throw new DataNotFound("找不到指定的文档."); throw new DataNotFound("找不到指定的文档.");
} }
//判断文档的可编辑状态。 //判断文档的可编辑状态。
if (Constants.DOC_STATUS_PUBLISHED.equals(oldModel.getDocStatus()) if (DOC_STATUS_PUBLISHED.equals(oldModel.getDocStatus()) || DocAuditService.DOC_AUDIT_STATUS_PASSED.equals(oldModel.getAuditStatus()) || DocAuditService.DOC_AUDIT_STATUS_SUBMITTED.equals(oldModel.getAuditStatus())) {
|| Constants.DOC_AUDIT_STATUS_PASSED.equals(oldModel.getAuditStatus())
|| Constants.DOC_AUDIT_STATUS_SUBMITTED.equals(oldModel.getAuditStatus())) {
throw new BadRequest("当前文档状态不可编辑."); throw new BadRequest("当前文档状态不可编辑.");
} }
//如果文档为驳回状态,更改为待提交 //如果文档为驳回状态,更改为待提交
if (ValidationUtil.equals(Constants.DOC_AUDIT_STATUS_REJECTED, oldModel.getAuditStatus())) { if (ValidationUtil.equals(DocAuditService.DOC_AUDIT_STATUS_REJECTED, oldModel.getAuditStatus())) {
oldModel.setAuditStatus(Constants.DOC_AUDIT_STATUS_SAVED); oldModel.setAuditStatus(DocAuditService.DOC_AUDIT_STATUS_SAVED);
} }
if (!ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) { if (!ValidationUtil.isEmpty(docContentModel.getHaveAttachment())) {
oldModel.setHaveAttachment(docContentModel.getHaveAttachment()); oldModel.setHaveAttachment(docContentModel.getHaveAttachment());
} }
String textContent = String.valueOf(docContentModel.getTextContent()); String textContent = String.valueOf(docContentModel.getTextContent());
docContentModel.setSummary(textContent.substring(0,Math.min(300, textContent.length()))); docContentModel.setSummary(textContent.substring(0, Math.min(300, textContent.length())));
//保存基础信息 //保存基础信息
dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), docContentModel.getSequenceNbr(), DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey()); dynamicsValueService.saveValueList(docContentModel.getDocBaseInfo(), docContentModel.getSequenceNbr(), DynamicsFunctional.DOC_BASEINFO, RequestContext.getAppKey());
// 保存标签实例 // 保存标签实例
tagInstanceService.deleteByTargetSeq(oldModel.getSequenceNbr());//删除已有的标签 tagInstanceService.deleteByTargetSeq(oldModel.getSequenceNbr());//删除已有的标签
List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), oldModel.getSequenceNbr(), Constants.MARKING_TYPE_DOC); List<KnowledgeTagInstanceModel> docTags = tagInstanceService.saveInstance(docContentModel.getDocTags(), oldModel.getSequenceNbr(), TagInstanceService.MARKING_TYPE_DOC);
tagInstanceService.saveInstance(docContentModel.getDocContentTags(), oldModel.getSequenceNbr(), Constants.MARKING_TYPE_CONTENT); tagInstanceService.saveInstance(docContentModel.getDocContentTags(), oldModel.getSequenceNbr(), TagInstanceService.MARKING_TYPE_CONTENT);
// 重新保存附件信息 // 重新保存附件信息
deleteAttachments(oldModel.getSequenceNbr());//删除已有的文件信息 deleteAttachments(oldModel.getSequenceNbr());//删除已有的文件信息
saveAttachments(docContentModel.getAttachments(), oldModel.getSequenceNbr());//保存新的文件信息. saveAttachments(docContentModel.getAttachments(), oldModel.getSequenceNbr());//保存新的文件信息.
oldModel.setDocTitle(docContentModel.getDocTitle()); oldModel.setDocTitle(docContentModel.getDocTitle());
oldModel.setDirectoryId(docContentModel.getDirectoryId()); oldModel.setDirectoryId(docContentModel.getDirectoryId());
docLibraryService.fillDirectoryName(Arrays.asList(oldModel)); docLibraryService.fillDirectoryName(Collections.singletonList(oldModel));
oldModel.setHtmlContent(docContentModel.getHtmlContent()); oldModel.setHtmlContent(docContentModel.getHtmlContent());
//生成排序字段信息 //生成排序字段信息
oldModel.setSortStr(DocSortUtil.getSortStr(docTags)); oldModel.setSortStr(DocSortUtil.getSortStr(docTags));
docLibraryService.fillDirectoryName(Arrays.asList(oldModel)); docLibraryService.fillDirectoryName(Collections.singletonList(oldModel));
this.updateWithModel(oldModel); this.updateWithModel(oldModel);
return Bean.copyExistPropertis(oldModel, docContentModel); return Bean.copyExistPropertis(oldModel, docContentModel);
} }
...@@ -279,9 +267,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -279,9 +267,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
if (ValidationUtil.isEmpty(docContentModel)) { if (ValidationUtil.isEmpty(docContentModel)) {
throw new BadRequest("指定的文档不存在."); throw new BadRequest("指定的文档不存在.");
} }
if (Constants.DOC_STATUS_PUBLISHED.equals(docContentModel.getDocStatus()) if (DOC_STATUS_PUBLISHED.equals(docContentModel.getDocStatus()) || DocAuditService.DOC_AUDIT_STATUS_PASSED.equals(docContentModel.getAuditStatus()) || DocAuditService.DOC_AUDIT_STATUS_SUBMITTED.equals(docContentModel.getAuditStatus())) {
|| Constants.DOC_AUDIT_STATUS_PASSED.equals(docContentModel.getAuditStatus())
|| Constants.DOC_AUDIT_STATUS_SUBMITTED.equals(docContentModel.getAuditStatus())) {
throw new BadRequest("当前文档状态不可删除."); throw new BadRequest("当前文档状态不可删除.");
} }
this.dynamicsValueService.deleteByInstanceId(docContentModel.getSequenceNbr()); this.dynamicsValueService.deleteByInstanceId(docContentModel.getSequenceNbr());
...@@ -324,24 +310,24 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -324,24 +310,24 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
} }
}); });
tagInstanceModelList.forEach(instanceModel -> { tagInstanceModelList.forEach(instanceModel -> {
switch (instanceModel.getMarkingType()) { if (TagInstanceService.MARKING_TYPE_DOC.equals(instanceModel.getMarkingType())) {
case Constants.MARKING_TYPE_DOC: docTags.add(instanceModel);
docTags.add(instanceModel); } else {
break; docContentTags.add(instanceModel);
default:
docContentTags.add(instanceModel);
} }
}); });
} }
KnowledgeInteractionRecordModel recordModel = interactionRecordService.queryUniqueModel(RequestContext.getExeUserId(), KnowledgeDocContentModel.class.getSimpleName(), //开放接口不需要验证
String.valueOf(docContentModel.getSequenceNbr()), OperateType.COLLECT.name()); try {
KnowledgeInteractionRecordModel recordModel = interactionRecordService.queryUniqueModel(RequestContext.getExeUserId(), KnowledgeDocContentModel.class.getSimpleName(), String.valueOf(docContentModel.getSequenceNbr()), OperateType.COLLECT.name());
fillAttachments(docContentModel); fillAttachments(docContentModel);
docContentModel.setDocTags(docTags); docContentModel.setDocTags(docTags);
docContentModel.setDocContentTags(docContentTags); docContentModel.setDocContentTags(docContentTags);
docContentModel.setCollected(!ValidationUtil.isEmpty(recordModel)); docContentModel.setCollected(!ValidationUtil.isEmpty(recordModel));
docContentModel.setUserName(RemoteData.getUserRealNamById(docContentModel.getUserId())); docContentModel.setUserName(RemoteData.getUserRealNamById(docContentModel.getUserId()));
docLibraryService.fillDirectoryName(Arrays.asList(docContentModel)); } catch (Exception ignored) {
}
docLibraryService.fillDirectoryName(Collections.singletonList(docContentModel));
} }
return docContentModel; return docContentModel;
} }
...@@ -535,8 +521,8 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -535,8 +521,8 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
case AUDITOR: case AUDITOR:
case INPUTER: case INPUTER:
case VIEWER: case VIEWER:
auditStatusSet.add(Constants.DOC_AUDIT_STATUS_PASSED); auditStatusSet.add(DocAuditService.DOC_AUDIT_STATUS_PASSED);
docStatusSet.add(Constants.DOC_STATUS_PUBLISHED); docStatusSet.add(DocContentService.DOC_STATUS_PUBLISHED);
dataPrivilegemap.put(docStatus, docStatusSet.toArray(new String[docStatusSet.size()])); dataPrivilegemap.put(docStatus, docStatusSet.toArray(new String[docStatusSet.size()]));
dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()])); dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()]));
break; break;
...@@ -616,7 +602,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -616,7 +602,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
} }
} }
if (!ValidationUtil.isEmpty(auditorOrg)) { if (!ValidationUtil.isEmpty(auditorOrg)) {
String[] auditStatus = {Constants.DOC_AUDIT_STATUS_PASSED, Constants.DOC_AUDIT_STATUS_SUBMITTED}; String[] auditStatus = {DocAuditService.DOC_AUDIT_STATUS_PASSED, DocAuditService.DOC_AUDIT_STATUS_SUBMITTED};
w.likeRight("org_code", auditorOrg).in("audit_status", Arrays.asList(auditStatus)); w.likeRight("org_code", auditorOrg).in("audit_status", Arrays.asList(auditStatus));
} }
}); });
...@@ -644,7 +630,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -644,7 +630,7 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
return wrapper; return wrapper;
} }
public List<Long> getAllPublishedDocIds(){ public List<Long> getAllPublishedDocIds() {
return this.baseMapper.getAllPublishedDocIds(); return this.baseMapper.getAllPublishedDocIds();
} }
...@@ -654,23 +640,16 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno ...@@ -654,23 +640,16 @@ public class DocContentService extends BaseService<KnowledgeDocContentModel, Kno
Set<Object> docCotentId = Bean.listToMap(refModelList, "sequenceNbr", KnowledgeDocContentModel.class).keySet(); Set<Object> docCotentId = Bean.listToMap(refModelList, "sequenceNbr", KnowledgeDocContentModel.class).keySet();
return new ArrayList(docCotentId); return new ArrayList(docCotentId);
} }
//根据分组id列表查询所有的关系 //根据分组id列表查询所有的关系
private List<KnowledgeDocContentModel> queryListByCategorySeqList(@Condition(Operator.in) List<Long> directoryId) { private List<KnowledgeDocContentModel> queryListByCategorySeqList(@Condition(Operator.in) List<Long> directoryId) {
return this.queryForList(null, false, directoryId); return this.queryForList(null, false, directoryId);
} }
public List<Map<String, Object>> getSimpleDetail(String sequenceNbrs) { /**
String[] idStrings= sequenceNbrs.split(","); * 开放接口,根据文档分类查询分类下的列表数据,只查公开的标签文档
List<String> idListString= Arrays.asList(idStrings); */
List<Long> idList= new ArrayList<Long>(); public IPage<KnowledgeDocContent> pageByType(int offset, int size, Long typeId, Long tagId) {
idListString.stream().forEach(i->{ return baseMapper.pageByType(new Page<>(offset, size), typeId, tagId);
idList.add(Long.parseLong(i)); }
});
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<KnowledgeDocContent>();
wrapper.eq("DOC_STATUS", "PUBLISHED");
wrapper.in("SEQUENCE_NBR",idList);
wrapper.select("SEQUENCE_NBR","DOC_TITLE","REC_DATE");
return this.baseMapper.selectMaps(wrapper);
}
} }
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Sequence; import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel; import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional; import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName; import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName;
import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType; import com.yeejoin.amos.knowledgebase.face.enumeration.OperateType;
import com.yeejoin.amos.knowledgebase.face.enumeration.OptionDataType; import com.yeejoin.amos.knowledgebase.face.enumeration.OptionDataType;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.*; import com.yeejoin.amos.knowledgebase.face.model.*;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity; import com.yeejoin.amos.knowledgebase.face.orm.entity.*;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESTagEntity;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTag;
import com.yeejoin.amos.knowledgebase.face.util.*; import com.yeejoin.amos.knowledgebase.face.util.*;
import com.yeejoin.amos.knowledgebase.face.util.FileExporter.FileType; import com.yeejoin.amos.knowledgebase.face.util.FileExporter.FileType;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelImportConfig; import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelImportConfig;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelParser; import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelParser;
import com.yeejoin.amos.knowledgebase.face.util.excel.ExcelParserOld;
import com.yeejoin.amos.knowledgebase.face.util.pdf.PdfBuilder; import com.yeejoin.amos.knowledgebase.face.util.pdf.PdfBuilder;
import com.yeejoin.amos.knowledgebase.face.util.sql.BaseSqlCondition; import com.yeejoin.amos.knowledgebase.face.util.sql.BaseSqlCondition;
import com.yeejoin.amos.knowledgebase.face.util.word.DocxBuilder; import com.yeejoin.amos.knowledgebase.face.util.word.DocxBuilder;
import com.yeejoin.amos.knowledgebase.face.util.word.wordToHtml;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.XmlException;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
...@@ -47,11 +46,10 @@ import org.typroject.tyboot.core.restful.exception.instance.DataNotFound; ...@@ -47,11 +46,10 @@ import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;
import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden; import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.text.ParseException;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
...@@ -78,7 +76,7 @@ public class DocLibraryService { ...@@ -78,7 +76,7 @@ public class DocLibraryService {
private DynamicsValueService dynamicsValueService; private DynamicsValueService dynamicsValueService;
@Autowired @Autowired
private InteractionCountService interactionCountService; private InteractionCountService interactionCountService;
// @Autowired // @Autowired
// private DynamicsGroupService dynamicsGroupService; // private DynamicsGroupService dynamicsGroupService;
@Autowired @Autowired
private DynamicsOptionService dynamicsOptionService; private DynamicsOptionService dynamicsOptionService;
...@@ -100,10 +98,15 @@ public class DocLibraryService { ...@@ -100,10 +98,15 @@ public class DocLibraryService {
private static final Integer BATCH_IMPORT_ONCE_NUM = 200; private static final Integer BATCH_IMPORT_ONCE_NUM = 200;
private static final List auditStatusList; private static final List auditStatusList;
@Value("${admin.all}")
boolean adminAll = false;
@Value("${admin.all.role}")
String adminAllRole;
static { static {
List<String> list = new ArrayList<>(); List<String> list = new ArrayList<>();
list.add(Constants.DOC_AUDIT_STATUS_SUBMITTED); list.add(DocAuditService.DOC_AUDIT_STATUS_SUBMITTED);
list.add(Constants.DOC_AUDIT_STATUS_PASSED); list.add(DocAuditService.DOC_AUDIT_STATUS_PASSED);
auditStatusList = Collections.unmodifiableList(list); auditStatusList = Collections.unmodifiableList(list);
} }
...@@ -124,7 +127,8 @@ public class DocLibraryService { ...@@ -124,7 +127,8 @@ public class DocLibraryService {
recordModel.setUserId(RequestContext.getExeUserId()); recordModel.setUserId(RequestContext.getExeUserId());
recordModel.setEntityType(KnowledgeDocContentModel.class.getSimpleName()); recordModel.setEntityType(KnowledgeDocContentModel.class.getSimpleName());
recordModel.setEntityId(String.valueOf(id)); recordModel.setEntityId(String.valueOf(id));
KnowledgeInteractionRecordModel oldModel = interactionRecordService.queryUniqueModel(recordModel.getUserId(), recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType()); KnowledgeInteractionRecordModel oldModel = interactionRecordService.queryUniqueModel(recordModel.getUserId(),
recordModel.getEntityType(), recordModel.getEntityId(), recordModel.getOperateType());
if (favor) { if (favor) {
if (ValidationUtil.isEmpty(oldModel)) { if (ValidationUtil.isEmpty(oldModel)) {
recordModel.setAgencyCode(RequestContext.getAgencyCode()); recordModel.setAgencyCode(RequestContext.getAgencyCode());
...@@ -138,10 +142,18 @@ public class DocLibraryService { ...@@ -138,10 +142,18 @@ public class DocLibraryService {
return true; return true;
} }
public Page queryDocList(int offset, int end, Long directoryId, String docTitle, String[] auditStatus, String docStatus, public Page queryDocList(int offset, int end, Long directoryId, String docTitle, String[] auditStatus,
Map<String, String[]> requestMap, String createTimeLeft, String createTimeRight, boolean favor, boolean permission) { String docStatus, Map<String, String[]> requestMap, String createTimeLeft, String createTimeRight,
boolean favor, boolean permission) {
Map<String, Object> paramsMap = new HashMap<>(); Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("userId", RequestContext.getExeUserId()); if (RemoteData.isAdmin(adminAllRole)) {
if (!adminAll) {
paramsMap.put("userId", RequestContext.getExeUserId());
}
} else {
paramsMap.put("userId", RequestContext.getExeUserId());
}
paramsMap.put("start", offset); paramsMap.put("start", offset);
paramsMap.put("limit", end > offset ? end - offset + 1 : 50); paramsMap.put("limit", end > offset ? end - offset + 1 : 50);
// 封装权限过滤条件 // 封装权限过滤条件
...@@ -150,11 +162,12 @@ public class DocLibraryService { ...@@ -150,11 +162,12 @@ public class DocLibraryService {
} }
List<Long> directoryIdList = new ArrayList<>(); List<Long> directoryIdList = new ArrayList<>();
if (directoryId != null) { if (directoryId != null) {
Collection<KnowledgeDocCategoryModel> childCategoryModels = docCategoryService.queryDocCategoryTree(RequestContext.getAgencyCode(), directoryId); Collection<KnowledgeDocCategoryModel> childCategoryModels = docCategoryService
.queryDocCategoryTree(RequestContext.getAgencyCode(), directoryId);
if (!childCategoryModels.isEmpty()) { if (!childCategoryModels.isEmpty()) {
directoryIdList.addAll(BaseUtil.getModelIds(TreeUtil.getAllChildren(childCategoryModels))); directoryIdList.addAll(BaseUtil.getModelIds(TreeUtil.getAllChildren(childCategoryModels)));
} }
//获取所有子分类ID // 获取所有子分类ID
directoryIdList.add(directoryId); directoryIdList.add(directoryId);
} }
...@@ -171,18 +184,14 @@ public class DocLibraryService { ...@@ -171,18 +184,14 @@ public class DocLibraryService {
page.setTotal(total); page.setTotal(total);
if (total > 0 && total > offset) { if (total > 0 && total > offset) {
List<Map<String, Object>> list = docContentService.getBaseMapper().queryDocBaseInfoList(paramsMap); List<Map<String, Object>> list = docContentService.getBaseMapper().queryDocBaseInfoList(paramsMap);
list.stream().map(x -> {
x.put("createTime", x.get("createTime").toString().replace("T", " "));
x.put("recDate", x.get("recDate").toString().replace("T", " "));
return x;
}).collect(Collectors.toList());
page.setRecords(list); page.setRecords(list);
} }
return page; return page;
} }
private void addExtraFieldsAndFilters(Map<String, Object> paramsMap, Map<String, String[]> requestMap) { private void addExtraFieldsAndFilters(Map<String, Object> paramsMap, Map<String, String[]> requestMap) {
List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name()); List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService
.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
if (ValidationUtil.isEmpty(optionModels)) { if (ValidationUtil.isEmpty(optionModels)) {
return; return;
} }
...@@ -194,7 +203,8 @@ public class DocLibraryService { ...@@ -194,7 +203,8 @@ public class DocLibraryService {
String fieldName = optionModel.getFieldName(); String fieldName = optionModel.getFieldName();
extraFields.add(fieldName); extraFields.add(fieldName);
if (requestMap.containsKey(fieldName)) { if (requestMap.containsKey(fieldName)) {
String filterStr = buildFilterStr(fieldName, requestMap.get(fieldName), optionModel.getDataType(), optionModel.getQueryStrategy()); String filterStr = buildFilterStr(fieldName, requestMap.get(fieldName), optionModel.getDataType(),
optionModel.getQueryStrategy());
if (!ValidationUtil.isEmpty(filterStr)) { if (!ValidationUtil.isEmpty(filterStr)) {
extraStrFilters.add(filterStr); extraStrFilters.add(filterStr);
} }
...@@ -233,11 +243,11 @@ public class DocLibraryService { ...@@ -233,11 +243,11 @@ public class DocLibraryService {
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
if (!ValidationUtil.isEmpty(values[0])) { if (!ValidationUtil.isEmpty(values[0])) {
builder.append(fieldName).append(" >= \"").append(values[0]).append("\""); builder.append(fieldName).append(" >= \"").append(values[0]).append("\"");
if (values.length>1 && !ValidationUtil.isEmpty(values[1])) { if (values.length > 1 && !ValidationUtil.isEmpty(values[1])) {
builder.append(" AND "); builder.append(" AND ");
} }
} }
if (values.length>1 && !ValidationUtil.isEmpty(values[1])) { if (values.length > 1 && !ValidationUtil.isEmpty(values[1])) {
builder.append(fieldName).append(" <= \"").append(values[1]).append("\""); builder.append(fieldName).append(" <= \"").append(values[1]).append("\"");
} }
return builder.toString(); return builder.toString();
...@@ -251,19 +261,34 @@ public class DocLibraryService { ...@@ -251,19 +261,34 @@ public class DocLibraryService {
paramsMap.put("permissionFilters", permissionFiltersMap); paramsMap.put("permissionFilters", permissionFiltersMap);
String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName()); String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
String auditorOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.AUDITOR.getRoleName()); String auditorOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.AUDITOR.getRoleName());
boolean isAdmin = RemoteData.isAdmin(adminAllRole);
if (ValidationUtil.isEmpty(inputerOrg) && ValidationUtil.isEmpty(auditorOrg)) { if (ValidationUtil.isEmpty(inputerOrg) && ValidationUtil.isEmpty(auditorOrg)) {
throw new RequestForbidden("用户角色错误"); throw new RequestForbidden("用户角色错误");
} }
if (!ValidationUtil.isEmpty(inputerOrg)) { if (!ValidationUtil.isEmpty(inputerOrg)) {
permissionFiltersMap.put("userId", RequestContext.getExeUserId()); if (RemoteData.isAdmin(adminAllRole)) {
if (!adminAll) {
permissionFiltersMap.put("userId", RequestContext.getExeUserId());
}
} else {
permissionFiltersMap.put("userId", RequestContext.getExeUserId());
}
} }
if (!ValidationUtil.isEmpty(auditorOrg)) { if (!ValidationUtil.isEmpty(auditorOrg)) {
permissionFiltersMap.put("orgCode", auditorOrg); if (RemoteData.isAdmin(adminAllRole)) {
if (!adminAll) {
permissionFiltersMap.put("orgCode", auditorOrg);
}
} else {
permissionFiltersMap.put("orgCode", auditorOrg);
}
permissionFiltersMap.put("auditStatusList", auditStatusList); permissionFiltersMap.put("auditStatusList", auditStatusList);
} }
} }
private void addCommonFilters(Map<String, Object> paramsMap, List<Long> directoryIdList, String docTitle, String docStatus, String[] auditStatus, String createTimeLeft, String createTimeRight) { private void addCommonFilters(Map<String, Object> paramsMap, List<Long> directoryIdList, String docTitle,
String docStatus, String[] auditStatus, String createTimeLeft, String createTimeRight) {
Map<String, Object> commonFiltersMap = new HashMap<>(16); Map<String, Object> commonFiltersMap = new HashMap<>(16);
paramsMap.put("commonFilters", commonFiltersMap); paramsMap.put("commonFilters", commonFiltersMap);
if (!ValidationUtil.isEmpty(directoryIdList)) { if (!ValidationUtil.isEmpty(directoryIdList)) {
...@@ -299,9 +324,7 @@ public class DocLibraryService { ...@@ -299,9 +324,7 @@ public class DocLibraryService {
*/ */
public Page searchAdvanced(Page page, Map<String, Object> queryParams) { public Page searchAdvanced(Page page, Map<String, Object> queryParams) {
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
wrapper.select("SEQUENCE_NBR") wrapper.select("SEQUENCE_NBR").eq("DOC_STATUS", DocContentService.DOC_STATUS_PUBLISHED).orderByAsc("SORT_STR");
.eq("DOC_STATUS", Constants.DOC_STATUS_PUBLISHED)
.orderByAsc("SORT_STR");
BaseSqlCondition sqlCondition = BaseSqlCondition.getInstance(queryParams); BaseSqlCondition sqlCondition = BaseSqlCondition.getInstance(queryParams);
if (sqlCondition.getTotalStatement() > 0) { if (sqlCondition.getTotalStatement() > 0) {
...@@ -320,7 +343,8 @@ public class DocLibraryService { ...@@ -320,7 +343,8 @@ public class DocLibraryService {
} }
}); });
fillDirectoryName(esList); fillDirectoryName(esList);
return page.setRecords(esList).setCurrent(iPage.getCurrent()).setSize(iPage.getSize()).setTotal(iPage.getTotal()); return page.setRecords(esList).setCurrent(iPage.getCurrent()).setSize(iPage.getSize())
.setTotal(iPage.getTotal());
} }
/** /**
...@@ -432,9 +456,11 @@ public class DocLibraryService { ...@@ -432,9 +456,11 @@ public class DocLibraryService {
return res; return res;
} }
//获取我的文档收藏列表 // 获取我的文档收藏列表
private List<Long> getMyFavoriteDocIdList() { private List<Long> getMyFavoriteDocIdList() {
List<KnowledgeInteractionRecordModel> recordModelList = interactionRecordService.queryListByUser(RequestContext.getExeUserId(), OperateType.COLLECT.name(), KnowledgeDocContentModel.class.getSimpleName(), RequestContext.getAgencyCode()); List<KnowledgeInteractionRecordModel> recordModelList = interactionRecordService.queryListByUser(
RequestContext.getExeUserId(), OperateType.COLLECT.name(),
KnowledgeDocContentModel.class.getSimpleName(), RequestContext.getAgencyCode());
List<Long> idList = new ArrayList<>(); List<Long> idList = new ArrayList<>();
for (KnowledgeInteractionRecordModel recordModel : recordModelList) { for (KnowledgeInteractionRecordModel recordModel : recordModelList) {
idList.add(Long.valueOf(recordModel.getEntityId())); idList.add(Long.valueOf(recordModel.getEntityId()));
...@@ -442,14 +468,16 @@ public class DocLibraryService { ...@@ -442,14 +468,16 @@ public class DocLibraryService {
return idList; return idList;
} }
//获取文档被收藏总数 // 获取文档被收藏总数
public int getCollectionCount(Long sequenceNbr) { public int getCollectionCount(Long sequenceNbr) {
return interactionRecordService.countByInstance(OperateType.COLLECT.name(), KnowledgeDocContentModel.class.getSimpleName(), sequenceNbr.toString()); return interactionRecordService.countByInstance(OperateType.COLLECT.name(),
KnowledgeDocContentModel.class.getSimpleName(), sequenceNbr.toString());
} }
//获取文档被引用总数 // 获取文档被引用总数
public int getReferenceCount(Long sequenceNbr) { public int getReferenceCount(Long sequenceNbr) {
return interactionCountService.getOperateCount(InteractionCountService.QUOTE_TYPE_PUBLISH, InteractionCountService.QUOTE_ENTITY_DOCUMENT, sequenceNbr.toString()); return interactionCountService.getOperateCount(InteractionCountService.QUOTE_TYPE_PUBLISH,
InteractionCountService.QUOTE_ENTITY_DOCUMENT, sequenceNbr.toString());
} }
/** /**
...@@ -462,8 +490,8 @@ public class DocLibraryService { ...@@ -462,8 +490,8 @@ public class DocLibraryService {
List resList = new ArrayList<>(); List resList = new ArrayList<>();
List<KnowledgeTag> tagList = tagService.getBaseMapper().queryTagByNameInPublishedDoc(queryStr); List<KnowledgeTag> tagList = tagService.getBaseMapper().queryTagByNameInPublishedDoc(queryStr);
resList.addAll(Bean.listToMap(tagList, "tagName", KnowledgeTag.class).keySet()); resList.addAll(Bean.listToMap(tagList, "tagName", KnowledgeTag.class).keySet());
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<KnowledgeDocContent>() QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<KnowledgeDocContent>().select("DOC_TITLE")
.select("DOC_TITLE").eq("DOC_STATUS", Constants.DOC_STATUS_PUBLISHED).like("DOC_TITLE", queryStr); .eq("DOC_STATUS", DocContentService.DOC_STATUS_PUBLISHED).like("DOC_TITLE", queryStr);
List<KnowledgeDocContent> docContentList = docContentService.list(wrapper); List<KnowledgeDocContent> docContentList = docContentService.list(wrapper);
docContentList.forEach(doc -> { docContentList.forEach(doc -> {
if (!resList.contains(doc.getDocTitle())) { if (!resList.contains(doc.getDocTitle())) {
...@@ -481,7 +509,7 @@ public class DocLibraryService { ...@@ -481,7 +509,7 @@ public class DocLibraryService {
public Map<String, Integer> count(int days) { public Map<String, Integer> count(int days) {
Map<String, Integer> res = new HashMap<>(); Map<String, Integer> res = new HashMap<>();
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
wrapper.eq("doc_status", Constants.DOC_STATUS_PUBLISHED); wrapper.eq("doc_status", DocContentService.DOC_STATUS_PUBLISHED);
res.put("totalAll", docContentService.count(wrapper)); res.put("totalAll", docContentService.count(wrapper));
Date rightRange = new Date(); Date rightRange = new Date();
Date leftRange = getDateBeforeDays(rightRange, days - 1); Date leftRange = getDateBeforeDays(rightRange, days - 1);
...@@ -497,7 +525,8 @@ public class DocLibraryService { ...@@ -497,7 +525,8 @@ public class DocLibraryService {
* @return * @return
*/ */
public List queryNewDocs(int top) { public List queryNewDocs(int top) {
List<KnowledgeDocContentModel> list = docContentService.queryNewDocsWithStatus(top, Constants.DOC_STATUS_PUBLISHED); List<KnowledgeDocContentModel> list = docContentService.queryNewDocsWithStatus(top,
DocContentService.DOC_STATUS_PUBLISHED);
fillDirectoryName(list); fillDirectoryName(list);
return fillDynamics(list, false); return fillDynamics(list, false);
} }
...@@ -537,8 +566,10 @@ public class DocLibraryService { ...@@ -537,8 +566,10 @@ public class DocLibraryService {
} }
contentModel.setHtmlContent(null); contentModel.setHtmlContent(null);
Map contentMap = Bean.BeantoMap(contentModel); Map contentMap = Bean.BeantoMap(contentModel);
List<KnowledgeDynamicsValueModel> listByInstance = dynamicsValueService.queryByInstanceId(contentModel.getSequenceNbr()); List<KnowledgeDynamicsValueModel> listByInstance = dynamicsValueService
Map<Object, Object> returnMap = Bean.listToMap(listByInstance, "fieldName", "fieldValue", KnowledgeDynamicsValueModel.class); .queryByInstanceId(contentModel.getSequenceNbr());
Map<Object, Object> returnMap = Bean.listToMap(listByInstance, "fieldName", "fieldValue",
KnowledgeDynamicsValueModel.class);
if (!simple) { if (!simple) {
returnMap.put("referenceNum", getReferenceCount(contentModel.getSequenceNbr())); returnMap.put("referenceNum", getReferenceCount(contentModel.getSequenceNbr()));
returnMap.put("collectionNum", getCollectionCount(contentModel.getSequenceNbr())); returnMap.put("collectionNum", getCollectionCount(contentModel.getSequenceNbr()));
...@@ -583,188 +614,7 @@ public class DocLibraryService { ...@@ -583,188 +614,7 @@ public class DocLibraryService {
FileExporter.exportFile(fileType, docTitle, bytes, response); FileExporter.exportFile(fileType, docTitle, bytes, response);
} }
// @Transactional(rollbackFor = { Exception.class, BaseException.class }) @Transactional(rollbackFor = {Exception.class, BaseException.class})
// public List importExcel(MultipartFile file, List<ExcelImportConfig> excelConfigList) {
// String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
// if (ValidationUtil.isEmpty(inputerOrg)) {
// throw new RequestForbidden("非录入者角色用户无权录入");
// }
// int finishedNum = 0;
//
// Set<Long> involvedTagIds = new HashSet<>();
// Set<String> enumNameList = new HashSet<>();
// Map<String, ExcelImportConfig> excelConfigMap = new HashMap();
// List<Long> directoryList = new ArrayList<>();
// for (ExcelImportConfig excelConfig : excelConfigList) {
// if (!excelConfig.check()) {
// throw new BadRequest("模板配置数据有误");
// }
// excelConfigMap.put(excelConfig.getDirectoryColumn(), excelConfig);
// Set<Long> involvedTags = excelConfig.getTagColumns().keySet();
// involvedTagIds.addAll(involvedTags);
// Set<String> enumNames = new HashSet<>(excelConfig.getEnumMap().values());
// enumNameList.addAll(enumNames);
// directoryList.add(Long.parseLong(excelConfig.getDirectoryColumn()));
// }
// Map<String, Long> directoryMap = docCategoryService.getGroupNameValue(directoryList);
// Workbook workbook = getBookWithFile(file);
// Sheet sheet = workbook.getSheetAt(0);
// if (sheet == null) {
// throw new BadRequest("文档sheet页为空");
// }
// int rowNumber = getRowNumber(sheet, excelConfigList.get(0));
// if (rowNumber <= 0) {
// throw new BadRequest("数据条目为零");
// }
//
// // 组装标签信息Map
// Map<Long, KnowledgeTagModel> tagMap = new HashMap();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeTagModel> tagModelList = tagService.queryByIds(involvedTagIds);
// for (KnowledgeTagModel tagModel : tagModelList) {
// tagMap.put(tagModel.getSequenceNbr(), tagModel);
// }
// }
// // 组装文档动态字段数据类型Map
// Map<String, KnowledgeDynamicsOptionModel> fieldTypeMap = new HashMap<>();
// List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService
// .queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
// for (KnowledgeDynamicsOptionModel optionModel : optionModels) {
// fieldTypeMap.put(optionModel.getFieldName(), optionModel);
// }
//
// // 组装标签值类型Map
// Map<Long, String> tagValueTypeMap = new HashMap<>();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeDynamicsValueModel> dynamicsValueList = dynamicsValueService.queryFieldValueByIds(new ArrayList(involvedTagIds), "valueType");
// for (KnowledgeDynamicsValueModel dynamicsValueModel : dynamicsValueList) {
// tagValueTypeMap.put(dynamicsValueModel.getInstanceId(), dynamicsValueModel.getFieldValue());
// }
// }
// // 组装字典中英文Map
// Map<String, Map<String, String>> enumCnEnMap = new HashMap<>();
// for (String enumName : enumNameList) {
// try {
// List<DictionarieValueModel> dictList = RemoteData.queryDict(enumName);
// Map<String, String> cnEnMap = new HashMap<>();
// for (DictionarieValueModel dictionarieValueModel : dictList) {
// cnEnMap.put(dictionarieValueModel.getDictDataValue(), dictionarieValueModel.getDictDataKey());
// }
// enumCnEnMap.put(enumName, cnEnMap);
// } catch (Exception e) {
// throw new RequestForbidden("获取字典数据出错,解析无法进行");
// }
// }
// // 组装标签单位Map
// Map<Long, String> tagUnitMap = new HashMap<>();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeDynamicsValueModel> dynamicsValueList = dynamicsValueService.queryFieldValueByIds(new ArrayList(involvedTagIds), "unit");
// for (KnowledgeDynamicsValueModel dynamicsValueModel : dynamicsValueList) {
// tagUnitMap.put(dynamicsValueModel.getInstanceId(), dynamicsValueModel.getFieldValue());
// }
// }
//
// ExcelParser excelParser = new ExcelParser(tagMap, excelConfigMap, fieldTypeMap, tagValueTypeMap, enumCnEnMap,
// tagUnitMap, this.sequence, inputerOrg);
// // 逐行解析
// while (finishedNum < rowNumber) {
// for (int i = 0; i < BATCH_IMPORT_ONCE_NUM && finishedNum < rowNumber; i++, finishedNum++) {
// Row row = sheet.getRow(excelConfigList.get(0).getStartRowIndex() + finishedNum);
// excelParser.parseRow(row, directoryMap);
// if (i % 500 == 0) {
// batchInsertDocDataAll(excelParser.getAndFlushDatas());
// }
// }
// QuoteCountFlushTiming.needFlushTag();
// }
// return excelParser.getImportResults();
// }
// @Transactional(rollbackFor = {Exception.class, BaseException.class})
// public List importExcel(MultipartFile file, List<ExcelImportConfig> excelConfigList) {
// String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
// if (ValidationUtil.isEmpty(inputerOrg)) {
// throw new RequestForbidden("非录入者角色用户无权录入");
// }
// int finishedNum = 0;
// List<Object> list = new ArrayList<>();
// for (ExcelImportConfig excelConfig : excelConfigList) {
// if (!excelConfig.check()) {
// throw new BadRequest("模板配置数据有误");
// }
// Workbook workbook = getBookWithFile(file);
// Sheet sheet = workbook.getSheetAt(0);
// if (sheet == null) {
// throw new BadRequest("文档sheet页为空");
// }
// int rowNumber = getRowNumber(sheet, excelConfig);
// if (rowNumber <= 0) {
// throw new BadRequest("数据条目为零");
// }
// Set<Long> involvedTagIds = excelConfig.getTagColumns().keySet();
// // 组装标签信息Map
// Map<Long, KnowledgeTagModel> tagMap = new HashMap();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeTagModel> tagModelList = tagService.queryByIds(involvedTagIds);
// for (KnowledgeTagModel tagModel : tagModelList) {
// tagMap.put(tagModel.getSequenceNbr(), tagModel);
// }
// }
// // 组装文档动态字段数据类型Map
// Map<String, KnowledgeDynamicsOptionModel> fieldTypeMap = new HashMap<>();
// List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
// for (KnowledgeDynamicsOptionModel optionModel : optionModels) {
// fieldTypeMap.put(optionModel.getFieldName(), optionModel);
// }
//
// // 组装标签值类型Map
// Map<Long, String> tagValueTypeMap = new HashMap<>();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeDynamicsValueModel> dynamicsValueList = dynamicsValueService.queryFieldValueByIds(new ArrayList(involvedTagIds), "valueType");
// for (KnowledgeDynamicsValueModel dynamicsValueModel : dynamicsValueList) {
// tagValueTypeMap.put(dynamicsValueModel.getInstanceId(), dynamicsValueModel.getFieldValue());
// }
// }
// // 组装字典中英文Map
// Map<String, Map<String, String>> enumCnEnMap = new HashMap<>();
// Set<String> enumNameList = new HashSet<>(excelConfig.getEnumMap().values());
// for (String enumName : enumNameList) {
// try {
// List<DictionarieValueModel> dictList = RemoteData.queryDict(enumName);
// Map<String, String> cnEnMap = new HashMap<>();
// for (DictionarieValueModel dictionarieValueModel : dictList) {
// cnEnMap.put(dictionarieValueModel.getDictDataValue(), dictionarieValueModel.getDictDataKey());
// }
// enumCnEnMap.put(enumName, cnEnMap);
// } catch (Exception e) {
// throw new RequestForbidden("获取字典数据出错,解析无法进行");
// }
// }
// // 组装标签单位Map
// Map<Long, String> tagUnitMap = new HashMap<>();
// if (!ValidationUtil.isEmpty(involvedTagIds)) {
// List<KnowledgeDynamicsValueModel> dynamicsValueList = dynamicsValueService.queryFieldValueByIds(new ArrayList(involvedTagIds), "unit");
// for (KnowledgeDynamicsValueModel dynamicsValueModel : dynamicsValueList) {
// tagUnitMap.put(dynamicsValueModel.getInstanceId(), dynamicsValueModel.getFieldValue());
// }
// }
//
// ExcelParser excelParser = new ExcelParser(tagMap, excelConfig, fieldTypeMap, tagValueTypeMap, enumCnEnMap, tagUnitMap, this.sequence, inputerOrg);
// // 逐行解析
// while (finishedNum <= rowNumber) {
// for (int i = 0; i < BATCH_IMPORT_ONCE_NUM && finishedNum < rowNumber; i++, finishedNum++) {
// Row row = sheet.getRow(excelConfig.getStartRowIndex() + finishedNum);
// excelParser.parseRow(row);
// }
// batchInsertDocDataAll(excelParser.getAndFlushDatas());
// QuoteCountFlushTiming.needFlushTag();
// }
// list.add(excelParser.getImportResults());
// }
// return list;
// }
@Transactional(rollbackFor = { Exception.class, BaseException.class })
public List importExcel(MultipartFile file, List<ExcelImportConfig> excelConfigList) { public List importExcel(MultipartFile file, List<ExcelImportConfig> excelConfigList) {
String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName()); String inputerOrg = RemoteData.getOrgWithCurUserAndRole(KnowledgeRoleName.INPUTER.getRoleName());
if (ValidationUtil.isEmpty(inputerOrg)) { if (ValidationUtil.isEmpty(inputerOrg)) {
...@@ -847,24 +697,56 @@ public class DocLibraryService { ...@@ -847,24 +697,56 @@ public class DocLibraryService {
} }
} }
ExcelParserOld excelParser = new ExcelParserOld(tagMap, excelConfigMap, fieldTypeMap, tagValueTypeMap, enumCnEnMap, ExcelParser excelParser = new ExcelParser(tagMap, excelConfigMap, fieldTypeMap, tagValueTypeMap, enumCnEnMap,
tagUnitMap, this.sequence, inputerOrg); tagUnitMap, this.sequence, inputerOrg);
// 逐行解析 // 逐行解析
while (finishedNum < rowNumber) { while (finishedNum < rowNumber) {
for (int i = 1; i <= BATCH_IMPORT_ONCE_NUM && finishedNum < rowNumber; i++, finishedNum++) { for (int i = 0; i < BATCH_IMPORT_ONCE_NUM && finishedNum < rowNumber; i++, finishedNum++) {
Row row = sheet.getRow(excelConfigList.get(0).getStartRowIndex() + finishedNum); Row row = sheet.getRow(excelConfigList.get(0).getStartRowIndex() + finishedNum);
excelParser.parseRow(row, directoryMap); excelParser.parseRow(row, directoryMap);
if (i % 500 == 0) { if (i % 500 == 0) {
batchInsertDocDataAll(excelParser.getAndFlushDatas()); batchInsertDocDataAll(excelParser.getAndFlushDatas());
} }
} }
batchInsertDocDataAll(excelParser.getAndFlushDatas());
QuoteCountFlushTiming.needFlushTag(); QuoteCountFlushTiming.needFlushTag();
} }
return excelParser.getImportResults(); return excelParser.getImportResults();
} }
void batchInsertDocDataAll(ExcelParserOld.TablesDataList datas) { @Transactional(rollbackFor = {Exception.class, BaseException.class})
public String importWordOfSingle(MultipartFile file) throws IOException, XmlException, ParserConfigurationException, TransformerException {
String htmlString = wordToHtml.wordParase(file);
String resultHtml = wordToHtml.wordReplaceTag(htmlString, file.getOriginalFilename());
return resultHtml;
}
@Transactional(rollbackFor = {Exception.class, BaseException.class})
public boolean importWordOfBatch(List<MultipartFile> files) {
if (files.size() <= 0) {
throw new DataNotFound("文件为空!");
}
for (MultipartFile file : files) {
try {
String htmlString = wordToHtml.wordParase(file);
String resultHtml = wordToHtml.wordReplaceTag(htmlString, file.getOriginalFilename());
String wordText = Jsoup.parse(resultHtml).body().text();
KnowledgeDocContentModel knowledgeDocContentModel = new KnowledgeDocContentModel();
knowledgeDocContentModel.setHtmlContent(resultHtml);
knowledgeDocContentModel.setDocTitle(file.getOriginalFilename());
knowledgeDocContentModel.setTextContent(wordText);
docContentService.createDoc(knowledgeDocContentModel);
} catch (IOException | XmlException | ParserConfigurationException | TransformerException e) {
e.printStackTrace();
throw new DataNotFound("上传失败!");
}
}
return true;
}
void batchInsertDocDataAll(ExcelParser.TablesDataList datas) {
docContentService.saveBatch(datas.getDocContentList()); docContentService.saveBatch(datas.getDocContentList());
dynamicsValueService.saveBatch(datas.getDynamicsValueList()); dynamicsValueService.saveBatch(datas.getDynamicsValueList());
tagInstanceService.saveBatch(datas.getTagInstanceList()); tagInstanceService.saveBatch(datas.getTagInstanceList());
...@@ -877,12 +759,15 @@ public class DocLibraryService { ...@@ -877,12 +759,15 @@ public class DocLibraryService {
} }
List<KnowledgeDocContentModel> contentModelList = docContentService.queryByIds(docSeqList); List<KnowledgeDocContentModel> contentModelList = docContentService.queryByIds(docSeqList);
fillDirectoryName(contentModelList); fillDirectoryName(contentModelList);
Map<Object, KnowledgeDocContentModel> docContentModelMap = Bean.listToMap(contentModelList, "sequenceNbr", KnowledgeDocContentModel.class); Map<Object, KnowledgeDocContentModel> docContentModelMap = Bean.listToMap(contentModelList, "sequenceNbr",
KnowledgeDocContentModel.class);
if (!contentModelList.isEmpty()) { if (!contentModelList.isEmpty()) {
List<KnowledgeTagInstanceModel> tagInstanceModelList = tagInstanceService.queryListByTargetSeqs(docSeqList); List<KnowledgeTagInstanceModel> tagInstanceModelList = tagInstanceService.queryListByTargetSeqs(docSeqList);
Map<Object, KnowledgeTagInstanceModel> tagInstanceModelMap = Bean.listToMap(tagInstanceModelList, "sequenceNbr", KnowledgeTagInstanceModel.class); Map<Object, KnowledgeTagInstanceModel> tagInstanceModelMap = Bean.listToMap(tagInstanceModelList,
"sequenceNbr", KnowledgeTagInstanceModel.class);
List<KnowledgeTagValueModel> tagValueModelList = tagValueService.queryTagValuesByDocIds(docSeqList); List<KnowledgeTagValueModel> tagValueModelList = tagValueService.queryTagValuesByDocIds(docSeqList);
List<KnowledgeDynamicsValueModel> dynamicsValueModelList = dynamicsValueService.queryByInstanceIds(docSeqList); List<KnowledgeDynamicsValueModel> dynamicsValueModelList = dynamicsValueService
.queryByInstanceIds(docSeqList);
// 标签值组装到标签实例 // 标签值组装到标签实例
tagValueModelList.forEach(tagValueModel -> { tagValueModelList.forEach(tagValueModel -> {
KnowledgeTagInstanceModel instanceModel = tagInstanceModelMap.get(tagValueModel.getInstanceSeq()); KnowledgeTagInstanceModel instanceModel = tagInstanceModelMap.get(tagValueModel.getInstanceSeq());
...@@ -899,8 +784,9 @@ public class DocLibraryService { ...@@ -899,8 +784,9 @@ public class DocLibraryService {
tagInstanceModelList.forEach(tagInstanceModel -> { tagInstanceModelList.forEach(tagInstanceModel -> {
KnowledgeDocContentModel docContentModel = docContentModelMap.get(tagInstanceModel.getTargetSeq()); KnowledgeDocContentModel docContentModel = docContentModelMap.get(tagInstanceModel.getTargetSeq());
if (null != docContentModel) { if (null != docContentModel) {
boolean isDoc = Constants.MARKING_TYPE_DOC.equals(tagInstanceModel.getMarkingType()); boolean isDoc = TagInstanceService.MARKING_TYPE_DOC.equals(tagInstanceModel.getMarkingType());
List<KnowledgeTagInstanceModel> tagList = isDoc ? docContentModel.getDocTags() : docContentModel.getDocContentTags(); List<KnowledgeTagInstanceModel> tagList = isDoc ? docContentModel.getDocTags()
: docContentModel.getDocContentTags();
if (null == tagList) { if (null == tagList) {
tagList = new ArrayList<>(); tagList = new ArrayList<>();
if (isDoc) { if (isDoc) {
...@@ -979,7 +865,8 @@ public class DocLibraryService { ...@@ -979,7 +865,8 @@ public class DocLibraryService {
*/ */
public Map<String, Map<String, String>> getBaseEnumMap() { public Map<String, Map<String, String>> getBaseEnumMap() {
Map<String, Map<String, String>> resMap = new HashMap<>(); Map<String, Map<String, String>> resMap = new HashMap<>();
List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name()); List<KnowledgeDynamicsOptionModel> optionModels = dynamicsOptionService
.queryByFunctional(RequestContext.getAppKey(), DynamicsFunctional.DOC_BASEINFO.name());
for (KnowledgeDynamicsOptionModel optionModel : optionModels) { for (KnowledgeDynamicsOptionModel optionModel : optionModels) {
if ("Enum".equals(optionModel.getDataType())) { if ("Enum".equals(optionModel.getDataType())) {
String fieldName = optionModel.getFieldName(); String fieldName = optionModel.getFieldName();
...@@ -1013,13 +900,15 @@ public class DocLibraryService { ...@@ -1013,13 +900,15 @@ public class DocLibraryService {
int finishNmu = 0; int finishNmu = 0;
int current = 0; int current = 0;
while (count > finishNmu) { while (count > finishNmu) {
com.baomidou.mybatisplus.extension.plugins.pagination.Page page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(current++, 30); Page page = new Page(
current++, 30);
IPage resPage = docContentService.page(page); IPage resPage = docContentService.page(page);
List<KnowledgeDocContent> records = resPage.getRecords(); List<KnowledgeDocContent> records = resPage.getRecords();
records.forEach(doc -> { records.forEach(doc -> {
if (ValidationUtil.isEmpty(doc.getTextContent()) && ValidationUtil.isEmpty(doc.getSortStr())) { if (ValidationUtil.isEmpty(doc.getTextContent()) && ValidationUtil.isEmpty(doc.getSortStr())) {
doc.setTextContent(htmlContent2Text(doc.getHtmlContent())); doc.setTextContent(htmlContent2Text(doc.getHtmlContent()));
doc.setSortStr(DocSortUtil.getSortStr(tagInstanceService.queryByTargetAndType(null, doc.getSequenceNbr(), Constants.MARKING_TYPE_DOC))); doc.setSortStr(DocSortUtil.getSortStr(tagInstanceService.queryByTargetAndType(null,
doc.getSequenceNbr(), TagInstanceService.MARKING_TYPE_DOC)));
} }
}); });
docContentService.updateBatchById(records); docContentService.updateBatchById(records);
...@@ -1042,7 +931,8 @@ public class DocLibraryService { ...@@ -1042,7 +931,8 @@ public class DocLibraryService {
if (ValidationUtil.isEmpty(categoryModelList)) { if (ValidationUtil.isEmpty(categoryModelList)) {
return; return;
} }
Map<Object, KnowledgeDocCategoryModel> categoryModelMap = Bean.listToMap(categoryModelList, "sequenceNbr", KnowledgeDocCategoryModel.class); Map<Object, KnowledgeDocCategoryModel> categoryModelMap = Bean.listToMap(categoryModelList, "sequenceNbr",
KnowledgeDocCategoryModel.class);
docList.forEach(doc -> { docList.forEach(doc -> {
if (doc instanceof KnowledgeDocContentModel) { if (doc instanceof KnowledgeDocContentModel) {
KnowledgeDocContentModel doc1 = (KnowledgeDocContentModel) doc; KnowledgeDocContentModel doc1 = (KnowledgeDocContentModel) doc;
...@@ -1056,15 +946,34 @@ public class DocLibraryService { ...@@ -1056,15 +946,34 @@ public class DocLibraryService {
}); });
} }
public Page queryDocPage(Page page, String docTitle, String code) { public Page queryDocPage(Page page, String docTitle, String code, Long directoryId, String orgCode) {
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
wrapper.eq("DOC_STATUS", Constants.DOC_STATUS_PUBLISHED); wrapper.eq("DOC_STATUS", DocContentService.DOC_STATUS_PUBLISHED);
if (!ValidationUtil.isEmpty(docTitle)) { if (!ValidationUtil.isEmpty(docTitle)) {
wrapper.like("DOC_TITLE", docTitle); wrapper.like("DOC_TITLE", docTitle);
} }
if (!ValidationUtil.isEmpty(orgCode)) {
wrapper.like("ORG_CODE", orgCode);
}
if (!ValidationUtil.isEmpty(code)) { if (!ValidationUtil.isEmpty(code)) {
wrapper.inSql("SEQUENCE_NBR", "SELECT INSTANCE_ID FROM KNOWLEDGE_DYNAMICS_VALUE kdv WHERE kdv.FIELD_NAME = 'code' AND kdv.FIELD_VALUE LIKE '%" + code.replace("'", "''") + "%'"); wrapper.inSql("SEQUENCE_NBR",
"SELECT INSTANCE_ID FROM KNOWLEDGE_DYNAMICS_VALUE kdv WHERE kdv.FIELD_NAME = 'code' AND kdv.FIELD_VALUE LIKE '%"
+ code.replace("'", "''") + "%'");
}
if (!ValidationUtil.isEmpty(directoryId)) {
wrapper.and(e -> {
e.eq("DIRECTORY_ID", directoryId);
List<KnowledgeDocCategory> cList = docCategoryService
.list(new LambdaQueryWrapper<KnowledgeDocCategory>().eq(KnowledgeDocCategory::getParentId,
directoryId));
List<Long> ids = cList.stream().map(i -> i.getSequenceNbr()).collect(Collectors.toList());
if (ids.size() > 0) {
e.or().in("DIRECTORY_ID", ids);
}
});
} }
wrapper.orderByDesc("REC_DATE");
page = (Page) docContentService.page(page, wrapper); page = (Page) docContentService.page(page, wrapper);
if (!page.getRecords().isEmpty()) { if (!page.getRecords().isEmpty()) {
ArrayList list = Bean.toModels(page.getRecords(), KnowledgeDocContentModel.class); ArrayList list = Bean.toModels(page.getRecords(), KnowledgeDocContentModel.class);
...@@ -1076,20 +985,19 @@ public class DocLibraryService { ...@@ -1076,20 +985,19 @@ public class DocLibraryService {
public List selectByDirsRand(List<Long> directoryList, Integer total) { public List selectByDirsRand(List<Long> directoryList, Integer total) {
Set<Long> directoryIdSet = new HashSet<>(); Set<Long> directoryIdSet = new HashSet<>();
List<KnowledgeDocCategoryModel> categoryList = Bean.toModels(docCategoryService.list(), KnowledgeDocCategoryModel.class); List<KnowledgeDocCategoryModel> categoryList = Bean.toModels(docCategoryService.list(),
directoryList.forEach( KnowledgeDocCategoryModel.class);
directoryId -> { directoryList.forEach(directoryId -> {
directoryIdSet.addAll(BaseUtil.getModelIds(TreeUtil.getAllChildren(TreeBuilder.bulid(categoryList, directoryId)))); directoryIdSet.addAll(
if (!directoryId.equals(DocCategoryService.ROOT)) { BaseUtil.getModelIds(TreeUtil.getAllChildren(TreeBuilder.bulid(categoryList, directoryId))));
directoryIdSet.add(directoryId); if (!directoryId.equals(DocCategoryService.ROOT)) {
} directoryIdSet.add(directoryId);
} }
); });
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
wrapper.eq("DOC_STATUS", Constants.DOC_STATUS_PUBLISHED) wrapper.eq("DOC_STATUS", DocContentService.DOC_STATUS_PUBLISHED).in("DIRECTORY_ID", directoryIdSet);
.in("DIRECTORY_ID", directoryIdSet);
if (total != null) { if (total != null) {
wrapper.last("ORDER BY RAND() LIMIT "+ total); wrapper.last("ORDER BY RAND() LIMIT " + total);
} }
List<KnowledgeDocContent> contentList = docContentService.list(wrapper); List<KnowledgeDocContent> contentList = docContentService.list(wrapper);
List<KnowledgeDocContentModel> list = Bean.toModels(contentList, KnowledgeDocContentModel.class); List<KnowledgeDocContentModel> list = Bean.toModels(contentList, KnowledgeDocContentModel.class);
......
...@@ -4,7 +4,6 @@ package com.yeejoin.amos.knowledgebase.face.service; ...@@ -4,7 +4,6 @@ package com.yeejoin.amos.knowledgebase.face.service;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsGroupModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsGroupModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DynamicsGroupMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.DynamicsGroupMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsGroup; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
......
...@@ -5,13 +5,11 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; ...@@ -5,13 +5,11 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional; import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName; import com.yeejoin.amos.knowledgebase.face.enumeration.KnowledgeRoleName;
import com.yeejoin.amos.knowledgebase.face.enumeration.OptionDataType; import com.yeejoin.amos.knowledgebase.face.enumeration.OptionDataType;
import com.yeejoin.amos.knowledgebase.face.feign.DataFillter;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsOptionModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsOptionModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.DynamicsValueMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.DynamicsValueMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsValue; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsValue;
import com.yeejoin.amos.knowledgebase.face.util.Constants; import com.yeejoin.amos.knowledgebase.face.util.DataFillter;
import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -26,6 +24,7 @@ import org.typroject.tyboot.core.rdbms.service.BaseService; ...@@ -26,6 +24,7 @@ import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest; import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
...@@ -148,8 +147,8 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode ...@@ -148,8 +147,8 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode
} }
switch (knowledgeRoleName) { switch (knowledgeRoleName) {
case AUDITOR: case AUDITOR:
auditStatusSet.add(Constants.DOC_AUDIT_STATUS_PASSED); auditStatusSet.add(DocAuditService.DOC_AUDIT_STATUS_PASSED);
auditStatusSet.add(Constants.DOC_AUDIT_STATUS_SUBMITTED); auditStatusSet.add(DocAuditService.DOC_AUDIT_STATUS_SUBMITTED);
dataPrivilegemap.put(DataFillter.orgCode, orgCode); dataPrivilegemap.put(DataFillter.orgCode, orgCode);
dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()])); dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()]));
break; break;
...@@ -160,8 +159,8 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode ...@@ -160,8 +159,8 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode
dataPrivilegemap.put(DataFillter.noData, true); dataPrivilegemap.put(DataFillter.noData, true);
break; break;
case VIEWER: case VIEWER:
auditStatusSet.add(Constants.DOC_AUDIT_STATUS_PASSED); auditStatusSet.add(DocAuditService.DOC_AUDIT_STATUS_PASSED);
docStatusSet.add(Constants.DOC_STATUS_PUBLISHED); docStatusSet.add(DocContentService.DOC_STATUS_PUBLISHED);
dataPrivilegemap.put(docStatus, docStatusSet.toArray(new String[docStatusSet.size()])); dataPrivilegemap.put(docStatus, docStatusSet.toArray(new String[docStatusSet.size()]));
dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()])); dataPrivilegemap.put(auditStatus, auditStatusSet.toArray(new String[auditStatusSet.size()]));
break; break;
...@@ -370,4 +369,15 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode ...@@ -370,4 +369,15 @@ public class DynamicsValueService extends BaseService<KnowledgeDynamicsValueMode
public List<KnowledgeDynamicsValueModel> queryByInstanceIds(@Condition(Operator.in) Collection<Long> instanceId) { public List<KnowledgeDynamicsValueModel> queryByInstanceIds(@Condition(Operator.in) Collection<Long> instanceId) {
return this.queryForList("", false, instanceId); return this.queryForList("", false, instanceId);
} }
//查询文档发布时间是否为空
public List<KnowledgeDynamicsValue> isRequiredByFile(String appKey, String name, List<Long> docSeqList) {
String fineSeqs = docSeqList.stream().map(String::valueOf).collect(Collectors.joining(","));
QueryWrapper<KnowledgeDynamicsValue> wrapper = new QueryWrapper<>();
wrapper.inSql("OPTION_SEQ",
"SELECT kdo.SEQUENCE_NBR FROM `knowledge_dynamics_option` kdo WHERE kdo.FUNCTIONAL = '" + name + "' AND kdo.APP_KEY = '" + appKey + "' AND kdo.FRONT_END_CONFIG LIKE '%\"required\":true%'");
wrapper.and(wq -> wq.inSql("INSTANCE_ID", fineSeqs));
return this.list(wrapper);
}
} }
...@@ -3,7 +3,6 @@ package com.yeejoin.amos.knowledgebase.face.service; ...@@ -3,7 +3,6 @@ package com.yeejoin.amos.knowledgebase.face.service;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
...@@ -12,8 +11,7 @@ import com.yeejoin.amos.knowledgebase.face.orm.dao.ESDocRepository; ...@@ -12,8 +11,7 @@ import com.yeejoin.amos.knowledgebase.face.orm.dao.ESDocRepository;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity; import com.yeejoin.amos.knowledgebase.face.orm.entity.ESDocEntity;
import com.yeejoin.amos.knowledgebase.face.orm.entity.ESTagEntity; import com.yeejoin.amos.knowledgebase.face.orm.entity.ESTagEntity;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.util.Constants; import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
...@@ -73,7 +71,7 @@ public class ESDocService { ...@@ -73,7 +71,7 @@ public class ESDocService {
* @return Page对象 * @return Page对象
*/ */
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public Page<ESDocEntity> findAll(int current, int size) { public Page<ESDocEntity> findAll(int current, int size) {
// 创建查询构造器 // 创建查询构造器
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder() NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
// 分页 // 分页
...@@ -82,22 +80,18 @@ public class ESDocService { ...@@ -82,22 +80,18 @@ public class ESDocService {
.withSort(SortBuilders.fieldSort("sortStr.keyword").order(SortOrder.DESC)); .withSort(SortBuilders.fieldSort("sortStr.keyword").order(SortOrder.DESC));
List<ESDocEntity> list = new LinkedList<>(); List<ESDocEntity> list = new LinkedList<>();
try try {
{ SearchHits<ESDocEntity> searchHits = elasticsearchTemplate.search(queryBuilder.build(), ESDocEntity.class);
SearchHits<ESDocEntity> searchHits =elasticsearchTemplate.search(queryBuilder.build(), ESDocEntity.class);
for (SearchHit searchHit : searchHits.getSearchHits()) {
for (SearchHit searchHit : searchHits.getSearchHits()) ESDocEntity docEntity = (ESDocEntity) searchHit.getContent();
{ list.add(docEntity);
ESDocEntity docEntity = (ESDocEntity)searchHit.getContent(); }
list.add(docEntity);
} return new AggregatedPageImpl<>(list, PageRequest.of(current, size), searchHits.getTotalHits());
} catch (Exception e) {
return new AggregatedPageImpl<>(list, PageRequest.of(current, size), searchHits.getTotalHits()); e.printStackTrace();
} }
catch (Exception e)
{
e.printStackTrace();
}
return new AggregatedPageImpl<>(list, PageRequest.of(current, size), 0); return new AggregatedPageImpl<>(list, PageRequest.of(current, size), 0);
} }
...@@ -119,8 +113,8 @@ public class ESDocService { ...@@ -119,8 +113,8 @@ public class ESDocService {
* @param size 页面大小 * @param size 页面大小
* @return * @return
*/ */
@SuppressWarnings({ "rawtypes", "unchecked" }) @SuppressWarnings({"rawtypes", "unchecked"})
public Page<ESDocEntity> queryByKeys(String queryStr, int current, int size) { public Page<ESDocEntity> queryByKeys(String queryStr, int current, int size) {
List<String> keys = queryStr2List(queryStr); List<String> keys = queryStr2List(queryStr);
if (ValidationUtil.isEmpty(keys)) { if (ValidationUtil.isEmpty(keys)) {
return findAll(current, size); return findAll(current, size);
...@@ -128,88 +122,83 @@ public class ESDocService { ...@@ -128,88 +122,83 @@ public class ESDocService {
// 条件构造,多条件循环匹配 // 条件构造,多条件循环匹配
BoolQueryBuilder boolMust = QueryBuilders.boolQuery(); BoolQueryBuilder boolMust = QueryBuilders.boolQuery();
for (String key : keys) { for (String key : keys) {
boolMust.must( boolMust.must(QueryBuilders.boolQuery().minimumShouldMatch(1)
QueryBuilders.boolQuery().minimumShouldMatch(1) .should(QueryBuilders.matchQuery("docTitle", key).boost(1f))
.should(QueryBuilders.matchPhraseQuery("docTitle", key)) .should(QueryBuilders.matchQuery("docInfo", key).boost(0.3f))
.should(QueryBuilders.matchPhraseQuery("docInfo", key)) .should(QueryBuilders.matchQuery("author", key).boost(0.3f))
.should(QueryBuilders.matchPhraseQuery("author", key)) .should(QueryBuilders.matchQuery("textContent", key).boost(0.5f))
.should(QueryBuilders.matchPhraseQuery("textContent", key)) .should(QueryBuilders.matchQuery("docTags.tagInfo", key).boost(0.8f))
.should(QueryBuilders.matchPhraseQuery("docTags.tagInfo", key)) .should(QueryBuilders.matchQuery("contentTags.tagInfo", key).boost(0.8f))
.should(QueryBuilders.matchPhraseQuery("contentTags.tagInfo", key))
); );
} }
// 创建查询构造器 // 创建查询构造器
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder() NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder()
// 高亮字段 // 高亮字段
.withHighlightFields( .withHighlightFields(
new HighlightBuilder.Field("docTitle").preTags("").postTags("").numOfFragments(0), new HighlightBuilder.Field("docTitle").preTags("<em>").postTags("</em>").numOfFragments(0),
new HighlightBuilder.Field("textContent").preTags("").postTags("").numOfFragments(1).fragmentSize(200).noMatchSize(100).order("score"), new HighlightBuilder.Field("textContent").preTags("<em>").postTags("</em>").numOfFragments(1).fragmentSize(200).noMatchSize(100).order("score"),
new HighlightBuilder.Field("docTags.tagInfo").preTags("").postTags("").numOfFragments(0), new HighlightBuilder.Field("docTags.tagInfo").preTags("").postTags("").numOfFragments(0),
new HighlightBuilder.Field("contentTags.tagInfo").preTags("").postTags("").numOfFragments(0) new HighlightBuilder.Field("contentTags.tagInfo").preTags("").postTags("").numOfFragments(0)
) )
// 分页 // 分页
.withPageable(PageRequest.of(current, size)) .withPageable(PageRequest.of(current, size))
// 排序
.withSort(SortBuilders.fieldSort("sortStr.keyword").order(SortOrder.ASC))
//过滤条件 //过滤条件
.withQuery(boolMust); .withQuery(boolMust);
// 对高亮词条进行操作 // 对高亮词条进行操作
List<ESDocEntity> list = new ArrayList<>(); List<ESDocEntity> list = new ArrayList<>();
try try {
{ SearchHits<ESDocEntity> searchHits = elasticsearchTemplate.search(queryBuilder.build(), ESDocEntity.class);
SearchHits<ESDocEntity> searchHits = elasticsearchTemplate.search(queryBuilder.build(), ESDocEntity.class);
for (SearchHit searchHit : searchHits.getSearchHits()) {
for (SearchHit searchHit : searchHits.getSearchHits()) {
ESDocEntity docEntity = (ESDocEntity) searchHit.getContent();
ESDocEntity docEntity = (ESDocEntity)searchHit.getContent(); searchHit.getHighlightFields();
searchHit.getHighlightFields(); // 文档标题
// 文档标题 List<String> docTitle = searchHit.getHighlightField("docTitle");
List<String> docTitle = searchHit.getHighlightField("docTitle"); if (!ValidationUtil.isEmpty(docTitle)) {
if (!ValidationUtil.isEmpty(docTitle)) { StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(); for (String fragment : docTitle) {
for (String fragment : docTitle) { sb.append(fragment);
sb.append(fragment); }
} docEntity.setDocTitle(sb.toString());
docEntity.setDocTitle(sb.toString()); }
} // 文档内容
// 文档内容 List<String> textContent = searchHit.getHighlightField("textContent");
List<String> textContent = searchHit.getHighlightField("textContent"); if (!ValidationUtil.isEmpty(textContent)) {
if (!ValidationUtil.isEmpty(textContent)) { StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(); for (String fragment : textContent) {
for (String fragment : textContent) { sb.append(fragment);
sb.append(fragment); }
} docEntity.setSummary(sb.toString());
docEntity.setSummary(sb.toString()); }
} Set<String> tagInfoSet = new HashSet<>();
Set<String> tagInfoSet = new HashSet<>(); // 文档标签
// 文档标签 List<String> docTagsInfo = searchHit.getHighlightField("docTags.tagInfo");
List<String> docTagsInfo = searchHit.getHighlightField("docTags.tagInfo"); if (!ValidationUtil.isEmpty(docTagsInfo)) {
if (!ValidationUtil.isEmpty(docTagsInfo)) { for (String fragment : docTagsInfo) {
for (String fragment : docTagsInfo) { tagInfoSet.add(fragment);
tagInfoSet.add(fragment); }
} }
} List<String> contentTagsInfo = searchHit.getHighlightField("contentTags.tagInfo");
List<String> contentTagsInfo = searchHit.getHighlightField("contentTags.tagInfo"); if (!ValidationUtil.isEmpty(contentTagsInfo)) {
if (!ValidationUtil.isEmpty(contentTagsInfo)) { for (String fragment : contentTagsInfo) {
for (String fragment : contentTagsInfo) { tagInfoSet.add(fragment);
tagInfoSet.add(fragment); }
} }
} // 删除不匹配的和重复的标签
// 删除不匹配的和重复的标签 deleteRepeatedTags(docEntity.getDocTags(), tagInfoSet);
deleteRepeatedTags(docEntity.getDocTags(), tagInfoSet); deleteRepeatedTags(docEntity.getContentTags(), tagInfoSet);
deleteRepeatedTags(docEntity.getContentTags(), tagInfoSet);
list.add(docEntity);
list.add(docEntity); }
}
return new AggregatedPageImpl<>(list, PageRequest.of(current, size), searchHits.getTotalHits());
return new AggregatedPageImpl<>(list, PageRequest.of(current, size), searchHits.getTotalHits()); } catch (Exception e) {
} return new AggregatedPageImpl<>(list, PageRequest.of(current, size), 0);
catch (Exception e) }
{
return new AggregatedPageImpl<>(list, PageRequest.of(current, size), 0);
}
} }
/** /**
...@@ -238,14 +227,16 @@ public class ESDocService { ...@@ -238,14 +227,16 @@ public class ESDocService {
* @param tagInfoSet 命中的tagInfo * @param tagInfoSet 命中的tagInfo
*/ */
private static void deleteRepeatedTags(List<ESTagEntity> list, Set<String> tagInfoSet) { private static void deleteRepeatedTags(List<ESTagEntity> list, Set<String> tagInfoSet) {
Iterator<ESTagEntity> tagIterator = list.iterator(); if (!ValidationUtil.isEmpty(tagInfoSet)) {
while (tagIterator.hasNext()) { Iterator<ESTagEntity> tagIterator = list.iterator();
ESTagEntity tag = tagIterator.next(); while (tagIterator.hasNext()) {
if (tagInfoSet.contains(tag.getTagInfo())) { ESTagEntity tag = tagIterator.next();
tagInfoSet.remove(tag.getTagInfo()); if (tagInfoSet.contains(tag.getTagInfo())) {
tag.setTagInfo(null); tagInfoSet.remove(tag.getTagInfo());
} else { tag.setTagInfo(null);
tagIterator.remove(); } else {
tagIterator.remove();
}
} }
} }
} }
...@@ -307,7 +298,7 @@ public class ESDocService { ...@@ -307,7 +298,7 @@ public class ESDocService {
Map<String, Map<String, String>> enumCnEnMap = docLibraryService.getBaseEnumMap(); Map<String, Map<String, String>> enumCnEnMap = docLibraryService.getBaseEnumMap();
List<ESDocEntity> esDocs = new ArrayList<>(); List<ESDocEntity> esDocs = new ArrayList<>();
for (KnowledgeDocContentModel docDetail : docs) { for (KnowledgeDocContentModel docDetail : docs) {
if (ValidationUtil.equals(docDetail.getDocStatus(), Constants.DOC_STATUS_PUBLISHED)) { if (ValidationUtil.equals(docDetail.getDocStatus(), DocContentService.DOC_STATUS_PUBLISHED)) {
List<ESTagEntity> docTags = buildESTagsByInstanceList(docDetail.getDocTags()); List<ESTagEntity> docTags = buildESTagsByInstanceList(docDetail.getDocTags());
List<ESTagEntity> contentTags = buildESTagsByInstanceList(docDetail.getDocContentTags()); List<ESTagEntity> contentTags = buildESTagsByInstanceList(docDetail.getDocContentTags());
ESDocEntity esDocEntity = new ESDocEntity() ESDocEntity esDocEntity = new ESDocEntity()
...@@ -387,7 +378,7 @@ public class ESDocService { ...@@ -387,7 +378,7 @@ public class ESDocService {
private String getTagInfoStr(KnowledgeTagInstanceModel instanceModel) { private String getTagInfoStr(KnowledgeTagInstanceModel instanceModel) {
StringBuilder infoStr = new StringBuilder(); StringBuilder infoStr = new StringBuilder();
infoStr.append(instanceModel.getTagName()).append(" "); infoStr.append(instanceModel.getTagName()).append(" ");
if (Constants.TAG_TYPE_TEXT.equals(instanceModel.getTagType()) if (TagService.TAG_TYPE_TEXT.equals(instanceModel.getTagType())
|| ValidationUtil.isEmpty(instanceModel.getTagValues())) { || ValidationUtil.isEmpty(instanceModel.getTagValues())) {
return infoStr.toString().trim(); return infoStr.toString().trim();
} }
...@@ -395,7 +386,7 @@ public class ESDocService { ...@@ -395,7 +386,7 @@ public class ESDocService {
String fieldName = valueModel.getFieldName(); String fieldName = valueModel.getFieldName();
String tagValue = valueModel.getTagValue(); String tagValue = valueModel.getTagValue();
switch (fieldName) { switch (fieldName) {
case Constants.VALUE_TAG_FIELD_DATE_H: case TagValueService.VALUE_TAG_FIELD_DATE_H:
infoStr.append(tagValue).append(" "); infoStr.append(tagValue).append(" ");
try { try {
Date date = DateUtil.formatStringToDate(tagValue, null); Date date = DateUtil.formatStringToDate(tagValue, null);
...@@ -445,7 +436,7 @@ public class ESDocService { ...@@ -445,7 +436,7 @@ public class ESDocService {
esDocRepository.deleteAll(); esDocRepository.deleteAll();
//保存所有已发布文档 //保存所有已发布文档
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
wrapper.eq("doc_status", Constants.DOC_STATUS_PUBLISHED); wrapper.eq("doc_status", DocContentService.DOC_STATUS_PUBLISHED);
int count = docContentService.count(wrapper); int count = docContentService.count(wrapper);
int finishNmu = 0; int finishNmu = 0;
int current = 0; int current = 0;
......
...@@ -6,19 +6,16 @@ import com.yeejoin.amos.knowledgebase.face.model.KnowledgeInteractionCountModel; ...@@ -6,19 +6,16 @@ import com.yeejoin.amos.knowledgebase.face.model.KnowledgeInteractionCountModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.InteractionCountMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.InteractionCountMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeInteractionCount; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeInteractionCount;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException; import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
......
...@@ -4,12 +4,11 @@ package com.yeejoin.amos.knowledgebase.face.service; ...@@ -4,12 +4,11 @@ package com.yeejoin.amos.knowledgebase.face.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence; import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeMessageModel; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeMessageModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.MessageMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.MessageMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeMessage; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeMessage;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeMessagePersonal; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeMessagePersonal;
import com.yeejoin.amos.knowledgebase.face.util.Constants; import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
...@@ -36,7 +35,20 @@ import java.util.*; ...@@ -36,7 +35,20 @@ import java.util.*;
@Component @Component
public class MessageService extends BaseService<KnowledgeMessageModel, KnowledgeMessage, MessageMapper> { public class MessageService extends BaseService<KnowledgeMessageModel, KnowledgeMessage, MessageMapper> {
/**
* 消息类型-要点推送
*/
public static final String MESSAGE_TYPE_PUSH = "ESSENTIAL_PUSH";
/**
* 消息类型-战例分享
*/
public static final String MESSAGE_TYPE_SHARE = "DOC_SHARE";
/**
* 消息主题前缀
*/
public static final String TOPIC_PREFIX = "knowledge_message_";
public static final String SHARE_WAY_APP = "app";
private final String userTypeUser = "user"; private final String userTypeUser = "user";
private final String userTypeGroup = "group"; private final String userTypeGroup = "group";
...@@ -95,14 +107,14 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge ...@@ -95,14 +107,14 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge
*/ */
@Transactional(rollbackFor = {BaseException.class, Exception.class}) @Transactional(rollbackFor = {BaseException.class, Exception.class})
public boolean shareDoc(List<Map<String, Object>> users, List<Map<String, Object>> docs, String way) { public boolean shareDoc(List<Map<String, Object>> users, List<Map<String, Object>> docs, String way) {
if (ValidationUtil.equalsIgnoreCase(way, Constants.SHARE_WAY_APP)) { if (ValidationUtil.equalsIgnoreCase(way, SHARE_WAY_APP)) {
for (Map<String, Object> doc : docs) { for (Map<String, Object> doc : docs) {
//创建消息 //创建消息
if (ValidationUtil.isEmpty(doc) || ValidationUtil.isEmpty(doc.get("sequenceNbr"))) { if (ValidationUtil.isEmpty(doc) || ValidationUtil.isEmpty(doc.get("sequenceNbr"))) {
throw new BadRequest("分享内容缺失"); throw new BadRequest("分享内容缺失");
} }
String messageTitle = String.valueOf(doc.get("docTitle")); String messageTitle = String.valueOf(doc.get("docTitle"));
KnowledgeMessageModel message = createMessage(Constants.MESSAGE_TYPE_SHARE, Long.valueOf(doc.get("sequenceNbr").toString()), messageTitle, String.valueOf(doc.get("summary"))); KnowledgeMessageModel message = createMessage(MESSAGE_TYPE_SHARE, Long.valueOf(doc.get("sequenceNbr").toString()), messageTitle, String.valueOf(doc.get("summary")));
Set<String> userIdSet = new HashSet<>(); Set<String> userIdSet = new HashSet<>();
userIdSet = parseUserMapToIdList(users, userIdSet); userIdSet = parseUserMapToIdList(users, userIdSet);
//创建个人消息 //创建个人消息
...@@ -122,7 +134,7 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge ...@@ -122,7 +134,7 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge
@Transactional(rollbackFor = {BaseException.class, Exception.class}) @Transactional(rollbackFor = {BaseException.class, Exception.class})
public boolean pushEssential(List<Map<String, Object>> users, String messageTitle, String content, Long docSeq) { public boolean pushEssential(List<Map<String, Object>> users, String messageTitle, String content, Long docSeq) {
//创建消息 //创建消息
KnowledgeMessageModel message = createMessage(Constants.MESSAGE_TYPE_PUSH, docSeq, messageTitle, content); KnowledgeMessageModel message = createMessage(MESSAGE_TYPE_PUSH, docSeq, messageTitle, content);
Set<String> userIdSet = new HashSet<>(); Set<String> userIdSet = new HashSet<>();
userIdSet = parseUserMapToIdList(users, userIdSet); userIdSet = parseUserMapToIdList(users, userIdSet);
//创建个人消息 //创建个人消息
...@@ -239,7 +251,7 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge ...@@ -239,7 +251,7 @@ public class MessageService extends BaseService<KnowledgeMessageModel, Knowledge
* 获取用户的主题 * 获取用户的主题
*/ */
private String getTopic(String userId) { private String getTopic(String userId) {
return Constants.TOPIC_PREFIX + String.valueOf(userId); return TOPIC_PREFIX + String.valueOf(userId);
} }
/** /**
......
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ctc.wstx.util.StringUtil;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDocContentModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowlegeStatisticsRecordModel; import com.yeejoin.amos.knowledgebase.face.model.KnowlegeStatisticsRecordModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.StatisticsRecordMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.StatisticsRecordMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowlegeStatisticsRecord;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
/** /**
* <p> * <p>
* 标签分组 服务类 * 标签分组 服务类
...@@ -37,219 +20,280 @@ import java.util.*; ...@@ -37,219 +20,280 @@ import java.util.*;
* @since 2020-08-05 * @since 2020-08-05
*/ */
@Component @Component
public class StatisticsRecordService public class StatisticsRecordService extends BaseService<KnowlegeStatisticsRecordModel, KnowlegeStatisticsRecord, StatisticsRecordMapper> {
extends BaseService<KnowlegeStatisticsRecordModel, KnowlegeStatisticsRecord, StatisticsRecordMapper> {
/*@Autowired
/* private DocContentService docContentService;
* @Autowired private DocContentService docContentService;
* private final Logger logger = LogManager.getLogger(StatisticsRecordService.class);
* private final Logger logger =
* LogManager.getLogger(StatisticsRecordService.class); *//**
* * 灾情标记
*//** *//*
* 灾情标记 public static final String TAG_NAME_TIME = "时间";
*/ public static final String STATISTICS_DISASTER_COUNT = "DISASTER_RECORD";
/*
* public static final String TAG_NAME_TIME = "时间"; public static final String *//**
* STATISTICS_DISASTER_COUNT = "DISASTER_RECORD"; * 燃烧物质分类
* *//*
*//** public static final String TAG_NAME_BURNING = "燃烧物质";
* 燃烧物质分类 public static final String STATISTICS_BURNING_CATEGORY = "BURNING_RECORD";
*/
/* *//**
* public static final String TAG_NAME_BURNING = "燃烧物质"; public static final * 参战车辆统计
* String STATISTICS_BURNING_CATEGORY = "BURNING_RECORD"; *//*
* public static final String TAG_NAME_POWER = "参战车辆";
*//** public static final String STATISTICS_POWER_SUM = "POWER_RECORD";
* 参战车辆统计
*/ *//**
/* * 伤亡人数统计
* public static final String TAG_NAME_POWER = "参战车辆"; public static final *//*
* String STATISTICS_POWER_SUM = "POWER_RECORD"; public static final String TAG_NAME_CASUALTIES = "人员伤亡情况 含亡人";
* public static final String STATISTICS_CASUALTIES_SUM = "CASUALTIES_RECORD";
*//**
* 伤亡人数统计 *//**
*/ * 灭火药剂统计
/* *//*
* public static final String TAG_NAME_CASUALTIES = "人员伤亡情况 含亡人"; public static public static final String TAG_NAME_EXTINGUISHING = "使用的灭火药剂数量";
* final String STATISTICS_CASUALTIES_SUM = "CASUALTIES_RECORD"; public static final String STATISTICS_EXTINGUISHING_SUM = "EXTINGUISHING_RECORD";
*
*//** *//**
* 灭火药剂统计 * 过火面积统计
*/ *//*
/* public static final String TAG_NAME_AREA = "过火面积";
* public static final String TAG_NAME_EXTINGUISHING = "使用的灭火药剂数量"; public public static final String STATISTICS_AREA_COUNT = "FIRE_AREA_RECORD";
* static final String STATISTICS_EXTINGUISHING_SUM = "EXTINGUISHING_RECORD";
* *//**
*//** * 到场时间分类
* 过火面积统计 *//*
*/ public static final String TAG_NAME_PICKUP = "接警时间";
/* public static final String TAG_NAME_PRESENT = "到场时间";
* public static final String TAG_NAME_AREA = "过火面积"; public static final String public static final String STATISTICS_PRESENT_CATEGORY = "PRESENT_TIME_RECORD";
* STATISTICS_AREA_COUNT = "FIRE_AREA_RECORD";
*
*//** public static final String DATE_GROUP_BY_DAY = "day";
* 到场时间分类 public static final String DATE_GROUP_BY_MONTH = "month";
*/
/* @Value("${diy-config.report.record-data}")
* public static final String TAG_NAME_PICKUP = "接警时间"; public static final private boolean needRecord;
* String TAG_NAME_PRESENT = "到场时间"; public static final String
* STATISTICS_PRESENT_CATEGORY = "PRESENT_TIME_RECORD"; *//** 根据文档标签添加对应的记录 *//*
* private void addRecordWithDocValueTag(List<KnowledgeTagInstanceModel> docTags, Long docSeq) {
* //找出预定义的所有标签
* public static final String DATE_GROUP_BY_DAY = "day"; public static final Map<Object, KnowledgeTagInstanceModel> tagMap = Bean.listToMap(docTags, "tagName", KnowledgeTagInstanceModel.class);
* String DATE_GROUP_BY_MONTH = "month"; KnowledgeTagInstanceModel tagTime = tagMap.get(TAG_NAME_TIME);
* if (ValidationUtil.isEmpty(tagTime)) {
* @Value("${diy-config.report.record-data}") private boolean needRecord; return;
* }
*//** 根据文档标签添加对应的记录 */ Object timeObj = getValueFromTag(tagTime);
/* if (ValidationUtil.isEmpty(timeObj) || !(timeObj instanceof Date)) {
* private void addRecordWithDocValueTag(List<KnowledgeTagInstanceModel> return;
* docTags, Long docSeq) { //找出预定义的所有标签 Map<Object, KnowledgeTagInstanceModel> }
* tagMap = Bean.listToMap(docTags, "tagName", KnowledgeTagInstanceModel.class); Date disasterTime = (Date) timeObj;
* KnowledgeTagInstanceModel tagTime = tagMap.get(TAG_NAME_TIME); if //记录灾情
* (ValidationUtil.isEmpty(tagTime)) { return; } Object timeObj = insertSumTypeRecord(docSeq, disasterTime, STATISTICS_DISASTER_COUNT, 1.0, 1);
* getValueFromTag(tagTime); if (ValidationUtil.isEmpty(timeObj) || !(timeObj //记录燃烧物质
* instanceof Date)) { return; } Date disasterTime = (Date) timeObj; //记录灾情 KnowledgeTagInstanceModel tagBurning = tagMap.get(TAG_NAME_BURNING);
* insertSumTypeRecord(docSeq, disasterTime, STATISTICS_DISASTER_COUNT, 1.0, 1); if (!ValidationUtil.isEmpty(tagBurning)) {
* //记录燃烧物质 KnowledgeTagInstanceModel tagBurning = tagMap.get(TAG_NAME_BURNING); insertCategoryTypeRecord(docSeq, disasterTime, STATISTICS_BURNING_CATEGORY, getValueFromTag(tagBurning));
* if (!ValidationUtil.isEmpty(tagBurning)) { insertCategoryTypeRecord(docSeq, }
* disasterTime, STATISTICS_BURNING_CATEGORY, getValueFromTag(tagBurning)); } //记录参战车辆
* //记录参战车辆 KnowledgeTagInstanceModel tagPower = tagMap.get(TAG_NAME_POWER); if KnowledgeTagInstanceModel tagPower = tagMap.get(TAG_NAME_POWER);
* (!ValidationUtil.isEmpty(tagPower)) { insertSumTypeRecord(docSeq, if (!ValidationUtil.isEmpty(tagPower)) {
* disasterTime, STATISTICS_POWER_SUM, getValueFromTag(tagPower), 1); } //记录伤亡人数 insertSumTypeRecord(docSeq, disasterTime, STATISTICS_POWER_SUM, getValueFromTag(tagPower), 1);
* KnowledgeTagInstanceModel tagCasualties = tagMap.get(TAG_NAME_CASUALTIES); if }
* (!ValidationUtil.isEmpty(tagCasualties)) { insertSumTypeRecord(docSeq, //记录伤亡人数
* disasterTime, STATISTICS_CASUALTIES_SUM, getValueFromTag(tagCasualties), 1); KnowledgeTagInstanceModel tagCasualties = tagMap.get(TAG_NAME_CASUALTIES);
* } //记录灭火药剂数量 KnowledgeTagInstanceModel tagExtinguishing = if (!ValidationUtil.isEmpty(tagCasualties)) {
* tagMap.get(TAG_NAME_EXTINGUISHING); if insertSumTypeRecord(docSeq, disasterTime, STATISTICS_CASUALTIES_SUM, getValueFromTag(tagCasualties), 1);
* (!ValidationUtil.isEmpty(tagExtinguishing)) { insertSumTypeRecord(docSeq, }
* disasterTime, STATISTICS_EXTINGUISHING_SUM, //记录灭火药剂数量
* getValueFromTag(tagExtinguishing), 1); } //记录过火面积 KnowledgeTagInstanceModel KnowledgeTagInstanceModel tagExtinguishing = tagMap.get(TAG_NAME_EXTINGUISHING);
* tagArea = tagMap.get(TAG_NAME_AREA); if (!ValidationUtil.isEmpty(tagArea)) { if (!ValidationUtil.isEmpty(tagExtinguishing)) {
* insertSumTypeRecord(docSeq, disasterTime, STATISTICS_AREA_COUNT, insertSumTypeRecord(docSeq, disasterTime, STATISTICS_EXTINGUISHING_SUM, getValueFromTag(tagExtinguishing), 1);
* getValueFromTag(tagArea), 1); } //记录到场时间 KnowledgeTagInstanceModel tagPickup }
* = tagMap.get(TAG_NAME_PICKUP); KnowledgeTagInstanceModel tagPresent = //记录过火面积
* tagMap.get(TAG_NAME_PRESENT); if (!ValidationUtil.isEmpty(tagPickup) && KnowledgeTagInstanceModel tagArea = tagMap.get(TAG_NAME_AREA);
* !ValidationUtil.isEmpty(tagPresent)) { Object pickTimeObj = if (!ValidationUtil.isEmpty(tagArea)) {
* getValueFromTag(tagPickup); Object presentTimeObj = insertSumTypeRecord(docSeq, disasterTime, STATISTICS_AREA_COUNT, getValueFromTag(tagArea), 1);
* getValueFromTag(tagPresent); if (!ValidationUtil.isEmpty(pickTimeObj) && }
* pickTimeObj instanceof Date && !ValidationUtil.isEmpty(presentTimeObj) && //记录到场时间
* presentTimeObj instanceof Date) { long presentTimeByMinute = (long) KnowledgeTagInstanceModel tagPickup = tagMap.get(TAG_NAME_PICKUP);
* Math.ceil((((Date) presentTimeObj).getTime() - ((Date) KnowledgeTagInstanceModel tagPresent = tagMap.get(TAG_NAME_PRESENT);
* pickTimeObj).getTime()) / 1000.0 / 60.0); insertCategoryTypeRecord(docSeq, if (!ValidationUtil.isEmpty(tagPickup) && !ValidationUtil.isEmpty(tagPresent)) {
* disasterTime, STATISTICS_PRESENT_CATEGORY, presentTimeByMinute); } } } Object pickTimeObj = getValueFromTag(tagPickup);
* Object presentTimeObj = getValueFromTag(tagPresent);
*//** 获取标签值 */ if (!ValidationUtil.isEmpty(pickTimeObj) && pickTimeObj instanceof Date
/* && !ValidationUtil.isEmpty(presentTimeObj) && presentTimeObj instanceof Date) {
* private Object getValueFromTag(KnowledgeTagInstanceModel tag) { if long presentTimeByMinute = (long) Math.ceil((((Date) presentTimeObj).getTime() - ((Date) pickTimeObj).getTime()) / 1000.0 / 60.0);
* (ValidationUtil.isEmpty(tag) || !ValidationUtil.equals(tag.getTagType(), insertCategoryTypeRecord(docSeq, disasterTime, STATISTICS_PRESENT_CATEGORY, presentTimeByMinute);
* TagService.TAG_TYPE_VALUE) || ValidationUtil.isEmpty(tag.getTagValues())) { }
* return null; } String fieldName = tag.getTagValues().get(0).getFieldName(); }
* String tagValue = tag.getTagValues().get(0).getTagValue(); if }
* (ValidationUtil.isEmpty(fieldName) || ValidationUtil.isEmpty(tagValue)) {
* return null; } switch (fieldName) { case *//** 获取标签值 *//*
* TagValueService.VALUE_TAG_FIELD_DATE_H: try { return private Object getValueFromTag(KnowledgeTagInstanceModel tag) {
* DateUtil.formatStringToDate(tagValue, null); } catch (Exception e) { if (ValidationUtil.isEmpty(tag)
* logger.error("报表统计:时间格式标签值解析出错"); return null; } case || !ValidationUtil.equals(tag.getTagType(), TagService.TAG_TYPE_VALUE)
* TagValueService.VALUE_TAG_FIELD_SINGLEVALUE: try { return || ValidationUtil.isEmpty(tag.getTagValues())) {
* Double.parseDouble(tagValue); } catch (Exception e) { return null;
* logger.error("报表统计:数字格式标签值解析出错"); return null; } case }
* TagValueService.VALUE_TAG_FIELD_TEXT: return tagValue; default: return null; String fieldName = tag.getTagValues().get(0).getFieldName();
* } } String tagValue = tag.getTagValues().get(0).getTagValue();
* if (ValidationUtil.isEmpty(fieldName)
*//** 插入分类统计记录 */ || ValidationUtil.isEmpty(tagValue)) {
/* return null;
* private void insertCategoryTypeRecord(Long docSeq, Date disasterTime, String }
* recordName, Object category) { KnowlegeStatisticsRecordModel recordModel = switch (fieldName) {
* new KnowlegeStatisticsRecordModel(); recordModel.setDocSeq(docSeq); case TagValueService.VALUE_TAG_FIELD_DATE_H:
* recordModel.setDisasterTime(disasterTime); try {
* recordModel.setRecordName(recordName); return DateUtil.formatStringToDate(tagValue, null);
* recordModel.setCategoryValue(String.valueOf(category)); } catch (Exception e) {
* recordModel.setValueWeight(1); recordModel.setCountValue(1L); logger.error("报表统计:时间格式标签值解析出错");
* this.createWithModel(recordModel); } return null;
* }
* case TagValueService.VALUE_TAG_FIELD_SINGLEVALUE:
*//** 插入数量统计记录 */ try {
/* return Double.parseDouble(tagValue);
* private void insertSumTypeRecord(Long docSeq, Date disasterTime, String } catch (Exception e) {
* recordName, Object numObj, Integer weight) { if logger.error("报表统计:数字格式标签值解析出错");
* (!ValidationUtil.isEmpty(numObj) && numObj instanceof Double) { Long num = return null;
* ((Double) numObj).longValue(); KnowlegeStatisticsRecordModel recordModel = }
* new KnowlegeStatisticsRecordModel(); recordModel.setDocSeq(docSeq); case TagValueService.VALUE_TAG_FIELD_TEXT:
* recordModel.setDisasterTime(disasterTime); return tagValue;
* recordModel.setRecordName(recordName); recordModel.setCountValue(num); default:
* recordModel.setValueWeight(weight); this.createWithModel(recordModel); } } return null;
* }
*//** }
* 根据文档id删除相关记录
*/ *//** 插入分类统计记录 *//*
/* private void insertCategoryTypeRecord(Long docSeq, Date disasterTime, String recordName, Object category) {
* public void deleteRecordsByDocIds(List<KnowledgeDocContentModel> docs) { if KnowlegeStatisticsRecordModel recordModel = new KnowlegeStatisticsRecordModel();
* (!ValidationUtil.isEmpty(docs)) { Set ids = Bean.listToMap(docs, recordModel.setDocSeq(docSeq);
* "sequenceNbr", KnowledgeDocContentModel.class).keySet(); recordModel.setDisasterTime(disasterTime);
* QueryWrapper<KnowlegeStatisticsRecord> wrapper = new QueryWrapper<>(); recordModel.setRecordName(recordName);
* wrapper.in("doc_seq", ids); this.getBaseMapper().delete(wrapper); } } recordModel.setCategoryValue(String.valueOf(category));
* recordModel.setValueWeight(1);
*//** recordModel.setCountValue(1L);
* 初始化统计数据记录 this.createWithModel(recordModel);
* }
* @return
*/
/* *//** 插入数量统计记录 *//*
* @Transactional(rollbackFor = {Exception.class, BaseException.class}) public private void insertSumTypeRecord(Long docSeq, Date disasterTime, String recordName, Object numObj, Integer weight) {
* boolean init() { this.getBaseMapper().deleteAll(); //扫描所有已发布文档相关的统计型标签 if (!ValidationUtil.isEmpty(numObj) && numObj instanceof Double) {
* QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>(); Long num = ((Double) numObj).longValue();
* wrapper.eq("doc_status", DocContentService.DOC_STATUS_PUBLISHED); int count = KnowlegeStatisticsRecordModel recordModel = new KnowlegeStatisticsRecordModel();
* docContentService.count(wrapper); int finishNmu = 0; int current = 0; while recordModel.setDocSeq(docSeq);
* (count > finishNmu) { Page page = new Page(current++, 30); IPage resPage = recordModel.setDisasterTime(disasterTime);
* docContentService.page(page, wrapper); List<KnowledgeDocContent> records = recordModel.setRecordName(recordName);
* resPage.getRecords(); Set ids = Bean.listToMap(records, "sequenceNbr", recordModel.setCountValue(num);
* KnowledgeDocContent.class).keySet(); saveRecordsByDocIds(ids); finishNmu += recordModel.setValueWeight(weight);
* records.size(); } return true; } this.createWithModel(recordModel);
* }
* public boolean addDocRecords(List<KnowledgeDocContentModel> docs) { if }
* (!ValidationUtil.isEmpty(docs)) { Set ids = Bean.listToMap(docs,
* "sequenceNbr", KnowledgeDocContentModel.class).keySet(); *//**
* saveRecordsByDocIds(ids); } return true; } * 根据文档id删除相关记录
* *//*
* private void saveRecordsByDocIds(Collection ids) { if (!needRecord) { return; public void deleteRecordsByDocIds(List<KnowledgeDocContentModel> docs) {
* } for (Object id : ids) { KnowledgeDocContentModel docContentModel = if (!ValidationUtil.isEmpty(docs)) {
* docContentService.queryOneDocDetail((Long) id); if Set ids = Bean.listToMap(docs, "sequenceNbr", KnowledgeDocContentModel.class).keySet();
* (ValidationUtil.isEmpty(docContentModel)) { continue; } QueryWrapper<KnowlegeStatisticsRecord> wrapper = new QueryWrapper<>();
* addRecordWithDocValueTag(docContentModel.getDocTags(), wrapper.in("doc_seq", ids);
* docContentModel.getSequenceNbr()); } } this.getBaseMapper().delete(wrapper);
* }
*//** }
* 查询灾情统计/同比/环比
* *//**
* @return * 初始化统计数据记录
*/ *
/* * @return
* public Map<String, Object> selectDisasterCount() { return *//*
* this.getBaseMapper().selectDisasterCount(); } @Transactional(rollbackFor = {Exception.class, BaseException.class})
* public boolean init() {
* public List<Map<String, Object>> selectCategoryByName(String recordName) { this.getBaseMapper().deleteAll();
* return this.getBaseMapper().selectCategoryByName(recordName); } //扫描所有已发布文档相关的统计型标签
* QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<>();
*//** wrapper.eq("doc_status", DocContentService.DOC_STATUS_PUBLISHED);
* 分类汇总 int count = docContentService.count(wrapper);
*//* int finishNmu = 0;
* public List<Map<String, Object>> selectCountByTypeAndDateRange(String int current = 0;
* dateType, String dateRangeLeft, String dateRangeRight, String recordName) { while (count > finishNmu) {
* Map<String, Object> queryMap = new HashMap<>(); switch (dateType) { case Page page = new Page(current++, 30);
* DATE_GROUP_BY_MONTH: queryMap.put("format", "%Y-%m"); break; default: IPage resPage = docContentService.page(page, wrapper);
* queryMap.put("format", "%Y-%m-%d"); break; } List<KnowledgeDocContent> records = resPage.getRecords();
* if(!ValidationUtil.isEmpty(dateRangeLeft)){ try { Set ids = Bean.listToMap(records, "sequenceNbr", KnowledgeDocContent.class).keySet();
* queryMap.put("dateRangeLeft", DateUtil.formatStringToDate(dateRangeLeft, saveRecordsByDocIds(ids);
* null)); } catch (Exception e) { throw new BadRequest("时间参数格式有误"); } } finishNmu += records.size();
* if(!ValidationUtil.isEmpty(dateRangeRight)){ try { }
* queryMap.put("dateRangeRight", DateUtil.formatStringToDate(dateRangeRight, return true;
* null)); } catch (Exception e) { throw new BadRequest("时间参数格式有误"); } } }
* queryMap.put("recordName", recordName); return
* this.getBaseMapper().selectCountByNameAndDateRange(queryMap); } public boolean addDocRecords(List<KnowledgeDocContentModel> docs) {
*/ if (!ValidationUtil.isEmpty(docs)) {
Set ids = Bean.listToMap(docs, "sequenceNbr", KnowledgeDocContentModel.class).keySet();
saveRecordsByDocIds(ids);
}
return true;
}
private void saveRecordsByDocIds(Collection ids) {
if (!needRecord) {
return;
}
for (Object id : ids) {
KnowledgeDocContentModel docContentModel = docContentService.queryOneDocDetail((Long) id);
if (ValidationUtil.isEmpty(docContentModel)) {
continue;
}
addRecordWithDocValueTag(docContentModel.getDocTags(), docContentModel.getSequenceNbr());
}
}
*//**
* 查询灾情统计/同比/环比
*
* @return
*//*
public Map<String, Object> selectDisasterCount() {
return this.getBaseMapper().selectDisasterCount();
}
public List<Map<String, Object>> selectCategoryByName(String recordName) {
return this.getBaseMapper().selectCategoryByName(recordName);
}
*//**
* 分类汇总
*//*
public List<Map<String, Object>> selectCountByTypeAndDateRange(String dateType, String dateRangeLeft, String dateRangeRight, String recordName) {
Map<String, Object> queryMap = new HashMap<>();
switch (dateType) {
case DATE_GROUP_BY_MONTH:
queryMap.put("format", "%Y-%m");
break;
default:
queryMap.put("format", "%Y-%m-%d");
break;
}
if(!ValidationUtil.isEmpty(dateRangeLeft)){
try {
queryMap.put("dateRangeLeft", DateUtil.formatStringToDate(dateRangeLeft, null));
} catch (Exception e) {
throw new BadRequest("时间参数格式有误");
}
}
if(!ValidationUtil.isEmpty(dateRangeRight)){
try {
queryMap.put("dateRangeRight", DateUtil.formatStringToDate(dateRangeRight, null));
} catch (Exception e) {
throw new BadRequest("时间参数格式有误");
}
}
queryMap.put("recordName", recordName);
return this.getBaseMapper().selectCountByNameAndDateRange(queryMap);
}*/
public Map<String, Object> tagStatistics(String tag, Date startDate, Date endDate, String mode) { public Map<String, Object> tagStatistics(String tag, Date startDate, Date endDate, String mode) {
endDate = getLastDayOfMonth(endDate); endDate = getLastDayOfMonth(endDate);
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
......
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.ArrayList; import com.baomidou.mybatisplus.core.toolkit.Sequence;
import java.util.Collection; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel;
import java.util.List; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import java.util.Map; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.TagInstanceMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagInstance;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
...@@ -15,14 +17,10 @@ import org.typroject.tyboot.core.rdbms.annotation.Condition; ...@@ -15,14 +17,10 @@ import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator; import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
import com.baomidou.mybatisplus.core.toolkit.Sequence; import java.util.ArrayList;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsValueModel; import java.util.Collection;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel; import java.util.List;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagModel; import java.util.Map;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.TagInstanceMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagInstance;
import com.yeejoin.amos.knowledgebase.face.util.Constants;
/** /**
...@@ -36,6 +34,10 @@ import com.yeejoin.amos.knowledgebase.face.util.Constants; ...@@ -36,6 +34,10 @@ import com.yeejoin.amos.knowledgebase.face.util.Constants;
@Component @Component
public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, KnowledgeTagInstance, TagInstanceMapper> { public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, KnowledgeTagInstance, TagInstanceMapper> {
public static final String MARKING_TYPE_DOC = "DOC"; // 标记类型--文档标签
public static final String MARKING_TYPE_CONTENT = "CONTENT";// 标记类型--内容标签
@Autowired @Autowired
private TagValueService tagValueService; private TagValueService tagValueService;
...@@ -72,11 +74,11 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K ...@@ -72,11 +74,11 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K
instanceModel.setTagType(tagModel.getTagType()); instanceModel.setTagType(tagModel.getTagType());
//值标签保存标签的具体值 //值标签保存标签的具体值
List<KnowledgeTagValueModel> valueModels = instanceModel.getTagValues(); List<KnowledgeTagValueModel> valueModels = instanceModel.getTagValues();
if (Constants.TAG_TYPE_VALUE.equals(tagModel.getTagType()) && !ValidationUtil.isEmpty(valueModels)) { if (TagService.TAG_TYPE_VALUE.equals(tagModel.getTagType()) && !ValidationUtil.isEmpty(valueModels)) {
List<KnowledgeDynamicsValueModel> valueTagConfigs = dynamicsValueService.queryByInstanceId(tagModel.getSequenceNbr()); List<KnowledgeDynamicsValueModel> valueTagConfigs = dynamicsValueService.queryByInstanceId(tagModel.getSequenceNbr());
Map<String,Object> valueTagConfigMap = Bean.listToMap(valueTagConfigs,"fieldName","fieldValue",KnowledgeDynamicsValueModel.class); Map<String, Object> valueTagConfigMap = Bean.listToMap(valueTagConfigs, "fieldName", "fieldValue", KnowledgeDynamicsValueModel.class);
String unit = String.valueOf(valueTagConfigMap.get("unit")); String unit = String.valueOf(valueTagConfigMap.get("unit"));
List<KnowledgeTagValueModel> savedValues = this.tagValueService.saveInstanceValue(instanceSeq, valueModels,unit); List<KnowledgeTagValueModel> savedValues = this.tagValueService.saveInstanceValue(instanceSeq, valueModels, unit);
instanceModel.setTagValues(savedValues); instanceModel.setTagValues(savedValues);
} }
this.createWithModel(instanceModel); this.createWithModel(instanceModel);
...@@ -111,7 +113,9 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K ...@@ -111,7 +113,9 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K
// return this.queryCount(tagSeq, targetSeq); // return this.queryCount(tagSeq, targetSeq);
// } // }
/** 根据标签ID统计标签实例数量 */ /**
* 根据标签ID统计标签实例数量
*/
public int queryCountByTagSeq(Long tagSeq) { public int queryCountByTagSeq(Long tagSeq) {
return this.queryCount(tagSeq); return this.queryCount(tagSeq);
} }
...@@ -136,10 +140,10 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K ...@@ -136,10 +140,10 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K
public List<KnowledgeTagInstanceModel> queryByTargetAndType(String agencyCode, Long targetSeq, String markingType) { public List<KnowledgeTagInstanceModel> queryByTargetAndType(String agencyCode, Long targetSeq, String markingType) {
List<KnowledgeTagInstanceModel> instanceModels = this.queryForList(null, false, agencyCode, targetSeq,markingType); List<KnowledgeTagInstanceModel> instanceModels = this.queryForList(null, false, agencyCode, targetSeq, markingType);
if (!ValidationUtil.isEmpty(instanceModels)) { if (!ValidationUtil.isEmpty(instanceModels)) {
for (KnowledgeTagInstanceModel instanceModel : instanceModels) { for (KnowledgeTagInstanceModel instanceModel : instanceModels) {
if (Constants.TAG_TYPE_VALUE.equals(instanceModel.getTagType())) { if (TagService.TAG_TYPE_VALUE.equals(instanceModel.getTagType())) {
List<KnowledgeTagValueModel> list = this.tagValueService.queryByInstance(instanceModel.getSequenceNbr()); List<KnowledgeTagValueModel> list = this.tagValueService.queryByInstance(instanceModel.getSequenceNbr());
instanceModel.setTagValues(list); instanceModel.setTagValues(list);
} }
...@@ -156,15 +160,7 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K ...@@ -156,15 +160,7 @@ public class TagInstanceService extends BaseService<KnowledgeTagInstanceModel, K
return this.queryForList(null, false, targetSeq); return this.queryForList(null, false, targetSeq);
} }
public List<KnowledgeTagInstanceModel> queryTopTagListByUser(String recUserId) {
public KnowledgeTagInstance findById(Long id) { return this.queryForList("REC_DATE", true, recUserId);
return this.baseMapper.selectById(id); }
}
public List<KnowledgeTagInstanceModel> queryListByTagName(String tagName) {
// TODO Auto-generated method stub
return this.queryForList(null, false, tagName);
}
} }
...@@ -3,15 +3,14 @@ package com.yeejoin.amos.knowledgebase.face.service; ...@@ -3,15 +3,14 @@ package com.yeejoin.amos.knowledgebase.face.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Sequence; import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional; import com.yeejoin.amos.knowledgebase.face.enumeration.DynamicsFunctional;
import com.yeejoin.amos.knowledgebase.face.feign.RemoteData;
import com.yeejoin.amos.knowledgebase.face.model.*; import com.yeejoin.amos.knowledgebase.face.model.*;
import com.yeejoin.amos.knowledgebase.face.orm.dao.TagMapper; import com.yeejoin.amos.knowledgebase.face.orm.dao.TagMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTag; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTag;
import com.yeejoin.amos.knowledgebase.face.util.ConfigLoader; import com.yeejoin.amos.knowledgebase.face.util.ConfigLoader;
import com.yeejoin.amos.knowledgebase.face.util.Constants; import com.yeejoin.amos.knowledgebase.face.util.RemoteData;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
...@@ -27,7 +26,10 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest; ...@@ -27,7 +26,10 @@ import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound; import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;
import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden; import org.typroject.tyboot.core.restful.exception.instance.RequestForbidden;
import java.io.Serializable;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** /**
...@@ -41,6 +43,27 @@ import java.util.*; ...@@ -41,6 +43,27 @@ import java.util.*;
@Component @Component
public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, TagMapper> { public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, TagMapper> {
/**
* 标签状态-激活
*/
public static final String TAG_STATUS_ACTIVATE = "ACTIVATED";
/**
* 标签状态-禁用
*/
public static final String TAG_STATUS_DEACTIVATE = "DEACTIVATED";
/**
* 标签类型-文本标签
*/
public static final String TAG_TYPE_TEXT = "TEXT_TAG";
/**
* 标签类型-值标签
*/
public static final String TAG_TYPE_VALUE = "VALUE_TAG";
public static final String APPKEY_ALL = "ALL";
@Autowired @Autowired
private TagGroupService tagGroupService; private TagGroupService tagGroupService;
@Autowired @Autowired
...@@ -73,7 +96,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -73,7 +96,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
} }
Long sequenceNbr = sequence.nextId(); Long sequenceNbr = sequence.nextId();
model.setSequenceNbr(sequenceNbr); model.setSequenceNbr(sequenceNbr);
model.setTagStatus(Constants.TAG_STATUS_ACTIVATE); model.setTagStatus(TAG_STATUS_DEACTIVATE);
model.setAgencyCode(RequestContext.getAgencyCode()); model.setAgencyCode(RequestContext.getAgencyCode());
model.setCreator(RequestContext.getExeUserId()); model.setCreator(RequestContext.getExeUserId());
//创建标签-分组关联关系 //创建标签-分组关联关系
...@@ -101,7 +124,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -101,7 +124,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
throw new BadRequest("标签名称不可重复"); throw new BadRequest("标签名称不可重复");
} }
//判断标签状态 //判断标签状态
if (ValidationUtil.equals(oldTagModel.getTagStatus(), Constants.TAG_STATUS_ACTIVATE)) { if (ValidationUtil.equals(oldTagModel.getTagStatus(), TAG_STATUS_ACTIVATE)) {
throw new BadRequest("启用状态的标签不允许编辑"); throw new BadRequest("启用状态的标签不允许编辑");
} }
Long sequenceNbr = oldTagModel.getSequenceNbr(); Long sequenceNbr = oldTagModel.getSequenceNbr();
...@@ -115,12 +138,12 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -115,12 +138,12 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
} }
private void restoreDynamicsValues(Long sequenceNbr, KnowledgeTagModel model) { private void restoreDynamicsValues(Long sequenceNbr, KnowledgeTagModel model) {
if (ValidationUtil.equals(Constants.TAG_TYPE_VALUE, model.getTagType())) { if (ValidationUtil.equals(TAG_TYPE_VALUE, model.getTagType())) {
Map<String, Object> tagValues = model.getTagValues(); Map<String, Object> tagValues = model.getTagValues();
if (!ValidationUtil.isEmpty(tagValues)) { if (!ValidationUtil.isEmpty(tagValues)) {
dynamicsValueService.saveValueList(tagValues, sequenceNbr, dynamicsValueService.saveValueList(tagValues, sequenceNbr,
DynamicsFunctional.VALUE_TAG_CONFIG, DynamicsFunctional.VALUE_TAG_CONFIG,
Constants.APPKEY_ALL); APPKEY_ALL);
} }
} }
} }
...@@ -161,7 +184,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -161,7 +184,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
* @param tagName 标签名称 * @param tagName 标签名称
* @param tagCode 标签代码 * @param tagCode 标签代码
* @param tagStatus 标签状态 * @param tagStatus 标签状态
* @return Map<首字母String , 列表List> * @return Map<首字母String, 列表List>
*/ */
public Map<String, List<KnowledgeTagModel>> queryTagMap(Long groupSeq, String tagName, String tagCode, String tagStatus) { public Map<String, List<KnowledgeTagModel>> queryTagMap(Long groupSeq, String tagName, String tagCode, String tagStatus) {
Map<String, List<KnowledgeTagModel>> resMap = new TreeMap<>(); Map<String, List<KnowledgeTagModel>> resMap = new TreeMap<>();
...@@ -240,7 +263,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -240,7 +263,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
tagIdList = StringUtil.String2LongList(tags); tagIdList = StringUtil.String2LongList(tags);
} }
for (KnowledgeTagModel tagModel : tagModels) { for (KnowledgeTagModel tagModel : tagModels) {
if (ValidationUtil.equals(tagModel.getTagStatus(), Constants.TAG_STATUS_ACTIVATE)) { if (ValidationUtil.equals(tagModel.getTagStatus(), TAG_STATUS_ACTIVATE)) {
throw new RequestForbidden("包含启用状态的标签,不允许删除"); throw new RequestForbidden("包含启用状态的标签,不允许删除");
} }
if (tagIsQuoted(tagModel.getSequenceNbr())) { if (tagIsQuoted(tagModel.getSequenceNbr())) {
...@@ -360,26 +383,41 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -360,26 +383,41 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
*/ */
public List<KnowledgeTagModel> queryTopList(boolean isAll) { public List<KnowledgeTagModel> queryTopList(boolean isAll) {
List<KnowledgeTagModel> res = new LinkedList<>(); List<KnowledgeTagModel> res = new LinkedList<>();
String operateType = isAll ? InteractionCountService.QUOTE_TYPE_ALL : InteractionCountService.QUOTE_TYPE_PUBLISH; List<? extends Serializable> tagSeqsCollect = new ArrayList<>();
List<KnowledgeInteractionCountModel> countModels = interactionCountService.queryTop(15, operateType, InteractionCountService.QUOTE_ENTITY_TAG, RequestContext.getAgencyCode()); List<KnowledgeTagModel> knowledgeTagTopList = new ArrayList<>();
for (KnowledgeInteractionCountModel countModel : countModels) { //查询标签实例表,查询当前用户常用的标签
if (countModel.getOperateCount() > 0) { List<KnowledgeTagInstanceModel> knowledgeTagInstanceModels = tagInstanceService.queryTopTagListByUser(RequestContext.getExeUserId());
KnowledgeTagModel tagModel = this.queryBySeq(Long.valueOf(countModel.getEntityId())); List<Long> tagSeqsByInstance = knowledgeTagInstanceModels.stream().map(KnowledgeTagInstanceModel::getTagSeq).collect(Collectors.toList());
if (!ValidationUtil.isEmpty(tagModel)) { if (ValidationUtil.isEmpty(tagSeqsByInstance) || tagSeqsByInstance.size() < 15) {
res.add(tagModel); //查询标签使用统计表,查询当前机构常用的标签
} String operateType = isAll ? InteractionCountService.QUOTE_TYPE_ALL : InteractionCountService.QUOTE_TYPE_PUBLISH;
} else { List<KnowledgeInteractionCountModel> countModels = interactionCountService.queryTop(15, operateType, InteractionCountService.QUOTE_ENTITY_TAG, RequestContext.getAgencyCode());
break; countModels = countModels.stream().filter(x -> x.getOperateCount() > 0).collect(Collectors.toList());
} List<String> tagSeqsByCount = countModels.stream().map(KnowledgeInteractionCountModel::getEntityId).collect(Collectors.toList());
tagSeqsCollect = Stream.of(tagSeqsByInstance, tagSeqsByCount).flatMap(Collection::stream).distinct().collect(Collectors.toList());
} }
for (KnowledgeTagModel tagModel : res) { if (!ValidationUtil.isEmpty(tagSeqsCollect)) {
tagAddDynamicsValues(tagModel); knowledgeTagTopList = this.queryByIds((Collection<Long>) tagSeqsCollect);
}
if (knowledgeTagTopList.size() < 15) {
//查询标签表
List<KnowledgeTagModel> knowledgeTagList = this.queryForPage(new Page(0, 15 - tagSeqsCollect.size()), "", false).getRecords();
knowledgeTagTopList.addAll(knowledgeTagList);
//去重
res = knowledgeTagTopList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(KnowledgeTagModel::getSequenceNbr))), ArrayList::new));
} }
if (!ValidationUtil.isEmpty(res)) {
res = res.size() < 15 ? res : res.subList(0, 15);
for (KnowledgeTagModel tagModel : res) {
tagAddDynamicsValues(tagModel);
}
}
return res; return res;
} }
public List<KnowledgeTagModel> queryTagDetailList(String tagName) { public List<KnowledgeTagModel> queryTagDetailList(String tagName) {
List<KnowledgeTag> tagList = queryTagListWithGroup(null, tagName, null, Constants.TAG_STATUS_ACTIVATE); List<KnowledgeTag> tagList = queryTagListWithGroup(null, tagName, null, TAG_STATUS_ACTIVATE);
List<KnowledgeTagModel> res = new ArrayList<>(); List<KnowledgeTagModel> res = new ArrayList<>();
for (KnowledgeTag tag : tagList) { for (KnowledgeTag tag : tagList) {
KnowledgeTagModel tagModel = new KnowledgeTagModel(); KnowledgeTagModel tagModel = new KnowledgeTagModel();
...@@ -393,7 +431,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -393,7 +431,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
} }
private void tagAddDynamicsValues(KnowledgeTagModel tagModel) { private void tagAddDynamicsValues(KnowledgeTagModel tagModel) {
if (ValidationUtil.equals(Constants.TAG_TYPE_VALUE, tagModel.getTagType())) { if (ValidationUtil.equals(TAG_TYPE_VALUE, tagModel.getTagType())) {
List<KnowledgeDynamicsValueModel> valueModels = dynamicsValueService.queryByInstanceId(tagModel.getSequenceNbr()); List<KnowledgeDynamicsValueModel> valueModels = dynamicsValueService.queryByInstanceId(tagModel.getSequenceNbr());
if (!ValidationUtil.isEmpty(valueModels)) { if (!ValidationUtil.isEmpty(valueModels)) {
Map fieldsMap = Bean.listToMap(valueModels, "fieldName", KnowledgeDynamicsValueModel.class); Map fieldsMap = Bean.listToMap(valueModels, "fieldName", KnowledgeDynamicsValueModel.class);
...@@ -417,7 +455,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag ...@@ -417,7 +455,7 @@ public class TagService extends BaseService<KnowledgeTagModel, KnowledgeTag, Tag
throw new BadRequest("参数有误"); throw new BadRequest("参数有误");
} }
QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<KnowledgeDocContent>() QueryWrapper<KnowledgeDocContent> wrapper = new QueryWrapper<KnowledgeDocContent>()
.eq("DOC_STATUS", Constants.DOC_STATUS_PUBLISHED) .eq("DOC_STATUS", DocContentService.DOC_STATUS_PUBLISHED)
.inSql("SEQUENCE_NBR", "SELECT DISTINCT TARGET_SEQ FROM knowledge_tag_instance WHERE TAG_SEQ = " + sequenceNbr); .inSql("SEQUENCE_NBR", "SELECT DISTINCT TARGET_SEQ FROM knowledge_tag_instance WHERE TAG_SEQ = " + sequenceNbr);
return docContentService.list(wrapper); return docContentService.list(wrapper);
} }
......
package com.yeejoin.amos.knowledgebase.face.service; package com.yeejoin.amos.knowledgebase.face.service;
import java.util.Arrays; import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import java.util.Collection; import com.yeejoin.amos.knowledgebase.face.orm.dao.TagValueMapper;
import java.util.List; import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext; import org.typroject.tyboot.core.foundation.context.RequestContext;
...@@ -13,13 +12,8 @@ import org.typroject.tyboot.core.foundation.utils.Bean; ...@@ -13,13 +12,8 @@ import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil; import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService; import org.typroject.tyboot.core.rdbms.service.BaseService;
import com.baomidou.mybatisplus.core.conditions.Wrapper; import java.util.Collection;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import java.util.List;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.dao.TagValueMapper;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue;
import net.bytebuddy.asm.Advice.This;
/** /**
...@@ -33,6 +27,15 @@ import net.bytebuddy.asm.Advice.This; ...@@ -33,6 +27,15 @@ import net.bytebuddy.asm.Advice.This;
@Component @Component
public class TagValueService extends BaseService<KnowledgeTagValueModel, KnowledgeTagValue, TagValueMapper> { public class TagValueService extends BaseService<KnowledgeTagValueModel, KnowledgeTagValue, TagValueMapper> {
public static final String VALUE_TAG_FIELD_SINGLEVALUE = "singleValue";//单值字段名
public static final String VALUE_TAG_FIELD_RANGE_MAX = "rangeMax";//范围值 上界
public static final String VALUE_TAG_FIELD_RANGE_MIN = "rangeMin";//范围值 下界
public static final String VALUE_TAG_FIELD_TEXT = "text";//文本值
public static final String VALUE_TAG_FIELD_DATE_H = "dateH";//时间,年月日时分秒
public static final String VALUE_TAG_FIELD_ENUM_NAME = "enumName";// 枚举类型字段名
@Transactional(rollbackFor = {Exception.class, BaseException.class}) @Transactional(rollbackFor = {Exception.class, BaseException.class})
public List<KnowledgeTagValueModel> saveInstanceValue(Long instanceSeq, List<KnowledgeTagValueModel> valueModels, String unit) { public List<KnowledgeTagValueModel> saveInstanceValue(Long instanceSeq, List<KnowledgeTagValueModel> valueModels, String unit) {
...@@ -71,13 +74,4 @@ public class TagValueService extends BaseService<KnowledgeTagValueModel, Knowled ...@@ -71,13 +74,4 @@ public class TagValueService extends BaseService<KnowledgeTagValueModel, Knowled
public List<KnowledgeTagValueModel> queryTagValuesByDocIds(Collection<Long> docSeqList) { public List<KnowledgeTagValueModel> queryTagValuesByDocIds(Collection<Long> docSeqList) {
return Bean.toModels(this.getBaseMapper().queryTagValuesByDocIds(docSeqList), KnowledgeTagValueModel.class); return Bean.toModels(this.getBaseMapper().queryTagValuesByDocIds(docSeqList), KnowledgeTagValueModel.class);
} }
public List<KnowledgeTagValue> getAllTegartValue(String value) {
String[] strings = value.split(",");
QueryWrapper<KnowledgeTagValue> wrapper = new QueryWrapper<KnowledgeTagValue>();
wrapper.eq("AGENCY_CODE", RequestContext.getAgencyCode());
wrapper.in("TAG_VALUE", Arrays.asList(strings));
return this.baseMapper.selectList(wrapper);
}
} }
package com.yeejoin.amos.knowledgebase.face.util;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.model.BaseModel;
import org.typroject.tyboot.core.rdbms.orm.entity.BaseEntity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* <h1><h1>
*
* @author tiantao
* @date 2020/12/7 11:47
*/
public class BaseUtil {
public static List<Long> getEntityIds(Collection<? extends BaseEntity> entityList){
List<Long> idList = new ArrayList<>();
if (!ValidationUtil.isEmpty(entityList)) {
entityList.forEach(entity -> idList.add(entity.getSequenceNbr()));
}
return idList;
}
public static List<Long> getModelIds(Collection<? extends BaseModel> entityList){
List<Long> idList = new ArrayList<>();
if (!ValidationUtil.isEmpty(entityList)) {
entityList.forEach(entity -> idList.add(entity.getSequenceNbr()));
}
return idList;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* <h1>定制化配置信息加载器<h1>
*
* @author tiantao
* @date 2021/1/7 9:33
*/
@Getter
@Component
@PropertySource(value = "classpath:customization.properties", encoding = "UTF-8")
public class ConfigLoader {
private boolean sync;
private String tags;
private String projects;
private boolean tagWithName;
private String agencyCode;
@Value("${system-conf.rule.sync}")
public void setSync(boolean sync) {
this.sync = sync;
}
@Value("${system-conf.rule.source.tags}")
public void setTags(String tags) {
this.tags = tags;
}
@Value("${system-conf.rule.target.projects}")
public void setProjects(String projects) {
this.projects = projects;
}
@Value("${system-conf.rule.source.tag-with-name}")
public void setTagWithName(boolean tagWithName) {
this.tagWithName = tagWithName;
}
@Value("${system-conf.rule.target.agency-code}")
public void setAgencyCode(String agencyCode) {
this.agencyCode = agencyCode;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import java.util.*;
/**
* @author 杨博超
* @ClassName DataFillter
* @Deacription 文档数据过参数组装
**/
public interface DataFillter {
String auditStatus = "auditStatus";
String docStatus = "docStatus";
String orgCode = "orgCode";
String noData = "noData";
String userId = "userId";
Map<String, Object> assembleParams(List<String> roleNameList, String orgCode);
/**
* @return java.util.Map<java.lang.String, java.lang.String>
* @author 杨博超
* @description 根据角色过滤数据
* @Param [auditStatus, docStatus]
**/
static Map<String, Object> dataFillterByRoleName(DataFillter dataFillter) {
Map<String, Object> dataPrivilegemap = new HashMap<>();
try {
AgencyUserModel agencyUserModel = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryByUserId(RequestContext.getExeUserId()));
Map<Long, List<RoleModel>> map = agencyUserModel.getOrgRoles();
Collection<List<RoleModel>> roleCollection = map.values();
List<String> roleNameList = new ArrayList<>();
for (List<RoleModel> list : roleCollection)
for (RoleModel roleModel : list)
roleNameList.add(roleModel.getRoleName());
String orgCodce = null;
if (!ValidationUtil.isEmpty(agencyUserModel.getCompanyDepartments())
&& !ValidationUtil.isEmpty(agencyUserModel.getCompanyDepartments().values())
&& agencyUserModel.getCompanyDepartments().values().size() > 0
&& !ValidationUtil.isEmpty(agencyUserModel.getCompanyDepartments().values().iterator().next().iterator().next())) { //TODO 多部门多公司处理
orgCodce = agencyUserModel.getCompanyDepartments().values().iterator().next().iterator().next().getOrgCode();
} else if (!ValidationUtil.isEmpty(agencyUserModel.getCompanys())) {
orgCodce = agencyUserModel.getCompanys().iterator().next().getOrgCode();
}
if(ValidationUtil.isEmpty(orgCodce))
throw new RuntimeException("用户部门信息有误.");
dataPrivilegemap.put(DataFillter.orgCode, orgCodce);
if (!ValidationUtil.isEmpty(dataFillter))
dataPrivilegemap = dataFillter.assembleParams(roleNameList, orgCodce);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("获取数据用户角色信息失败.");
}
return dataPrivilegemap;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class DataTransformator {
/**
* 多个集合合并成一个
*
* @param list
* @return
*/
public static Set<Long> objSet2LongSet(List<Set> list) {
Set<Long> res = new HashSet<>();
for (Set set : list) {
for (Object o : set) {
if (o instanceof Long) {
res.add((Long) o);
} else {
res.add(Long.parseLong(o.toString()));
}
}
}
return res;
}
/**
* html内容转text
*
* @param htmlContent html文本
* @return 文本
*/
public static String htmlContent2Text(String htmlContent) {
String res = "";
try {
Element body = Jsoup.parseBodyFragment(htmlContent, "UTF-8").body();
body.getElementsByTag("h1").remove();
res = body.text();
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 文件对象转字节数组
*
* @throws IOException
*/
public static byte[] file2Bytes(File file) throws IOException {
try (FileInputStream fis = new FileInputStream(file)) {
return inputStream2Bytes(fis);
}
}
public static byte[] inputStream2Bytes(InputStream is) throws IOException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
// 10M
byte[] bytes = new byte[1024 * 1024 * 10];
int len;
while ((len = is.read(bytes)) > 0) {
bos.write(bytes, 0, len);
}
return bos.toByteArray();
}
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.service.TagValueService;
import lombok.Data;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* 文档根据标签定制化排序
*
* @author tiantao
*/
public class DocSortUtil {
public static List<DocTagConfig> tagConfigList;
/**
* 正数恒定大于负数,1开头表正数,0开头表负数
*/
private static final String POSITIVE = "1";
private static final String NEGATIVE = "0";
private static final DecimalFormat LONG_FORMAT = new DecimalFormat("0000000000000000000");
static {
loadConfig();
}
public static void loadConfig() {
Object configObj = JSON.parse("{\n" +
" \"docTag\": [\n" +
" {\n" +
" \"sort\": 1,\n" +
" \"name\": \"死亡/失踪人数总和\",\n" +
" \"desc\": true,\n" +
" \"formula\": \"1319951584694317058+1319952328386359297+1319951672883752961+1319952397084864513\"\n" +
" },\n" +
" {\n" +
" \"sort\": 2,\n" +
" \"name\": \"受伤人数总和\",\n" +
" \"desc\": true,\n" +
" \"formula\": \"1319951506357301249+1319952269997453314+1319951885195227138+1319952474897592321\"\n" +
" },\n" +
" {\n" +
" \"sort\": 3,\n" +
" \"name\": \"参战总人数\",\n" +
" \"desc\": true,\n" +
" \"formula\": \"1319953830182072322\"\n" +
" },\n" +
" {\n" +
" \"sort\": 4,\n" +
" \"name\": \"处置时间\",\n" +
" \"desc\": true,\n" +
" \"formula\": \"1320181702299004930-1320181277285986305\"\n" +
" }\n" +
" ]\n" +
"}");
tagConfigList = new ArrayList<>();
if (configObj instanceof Map) {
Object docTag = ((Map) configObj).get("docTag");
if (docTag instanceof List) {
((List) docTag).forEach(tag -> {
try {
DocTagConfig docTagConfig = JSON.parseObject(JSON.toJSONString(tag), DocTagConfig.class);
tagConfigList.add(docTagConfig);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
tagConfigList.sort(Comparator.comparingInt(o -> o.sort));
}
public static String getSortStr(List<KnowledgeTagInstanceModel> docTags) {
Map<Object, KnowledgeTagInstanceModel> docTagsMap = Bean.listToMap(docTags, "tagSeq", KnowledgeTagInstanceModel.class);
StringBuilder res = new StringBuilder();
final boolean[] flag = {false};
tagConfigList.forEach(docTagConfig -> {
String formula = docTagConfig.formula;
List<String> tagSeqs = trimArray(formula.split("\\D"));
long sortValue = 0L;
for (int i = 0; i < tagSeqs.size(); i++) {
Long tagValue = getTagLongValue(tagSeqs.get(i), docTagsMap);
if (i > 0) {
String operator = formula.substring(formula.indexOf(tagSeqs.get(i - 1)) + tagSeqs.get(i - 1).length(), formula.indexOf(tagSeqs.get(i)));
switch (operator.trim()) {
case "+":
sortValue += tagValue;
break;
case "-":
sortValue -= tagValue;
break;
default:
throw new BadRequest("排序规则错误,无法识别的运算符");
}
} else {
sortValue = tagValue;
}
}
if (flag[0]) {
res.append("_");
}else {
flag[0] = true;
}
res.append(formatLong2SortStr(sortValue, docTagConfig.desc));
});
return res.toString();
}
/**
* 依据正负数/正倒序转换数值为字符串正整数
* @param sortValue 数值
* @param desc 是否倒序排列
* @return 字符串
*/
private static String formatLong2SortStr(long sortValue, boolean desc) {
if (desc) {
if (sortValue < 0) {
sortValue = 0 - sortValue;
return POSITIVE + LONG_FORMAT.format(sortValue);
} else {
sortValue = Long.MAX_VALUE - sortValue;
return NEGATIVE + LONG_FORMAT.format(sortValue);
}
} else {
if (sortValue < 0) {
sortValue = Long.MAX_VALUE - (0 - sortValue);
return NEGATIVE + LONG_FORMAT.format(sortValue);
} else {
return POSITIVE + LONG_FORMAT.format(sortValue);
}
}
}
/**
* 获取不同数据格式转化的long数值
* @param ts 标签实例id
* @param docTagsMap 标签实例map
* @return long值
*/
private static Long getTagLongValue(String ts, Map<Object, KnowledgeTagInstanceModel> docTagsMap) {
Long res = 0L;
try {
Long tagSeq = Long.valueOf(ts.trim());
KnowledgeTagInstanceModel instanceModel = docTagsMap.get(tagSeq);
if (null == instanceModel) {
return res;
}
List<KnowledgeTagValueModel> tagValues = instanceModel.getTagValues();
if (tagValues != null && tagValues.size() > 0) {
String fieldName = tagValues.get(0).getFieldName();
String tagValue = tagValues.get(0).getTagValue();
switch (fieldName) {
case TagValueService.VALUE_TAG_FIELD_DATE_H:
res = DateUtil.formatStringToDate(tagValue, null).getTime();
break;
case TagValueService.VALUE_TAG_FIELD_SINGLEVALUE:
res = Long.valueOf(tagValue);
break;
default:
throw new BadRequest("排序规则错误,不支持的数据类型");
}
}
} catch (BaseException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 去除数组中的空值
* @param arr 数组
* @param <T> 泛型
* @return List
*/
private static <T> List<T> trimArray(T[] arr) {
List<T> res = new ArrayList<>();
for (T t : arr) {
if (!ValidationUtil.isEmpty(t)) {
res.add(t);
}
}
return res;
}
@Data
private static class DocTagConfig {
// 排序优先级
private int sort;
// 排序名称,方便读懂json与逻辑无关
private String name;
// 是否倒序
private boolean desc;
// 算法公式,格式为标签id用数学运算符连接,目前仅支持加减
private String formula;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
public class FileExporter {
public static void exportFile(FileType fileType, String fileName, byte[] data, HttpServletResponse response) {
try {
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType(fileType.getContentType());
fileName = fileName.replaceAll("\\.", "·");
fileName = URLEncoder.encode(fileName + fileType.getFileSufix(), "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + "");
response.getOutputStream().write(data);
response.getOutputStream().flush();
} catch (Exception e) {
throw new BadRequest("导出文档出错");
} finally {
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 文件类型
*/
public enum FileType {
// word文档
docx(".docx", "application/msword"),
// pdf文档
pdf(".pdf", "application/pdf");
private String fileSufix;
private String contentType;
private FileType(String fileSufix, String contentType) {
this.fileSufix = fileSufix;
this.contentType = contentType;
}
public String getFileSufix() {
return fileSufix;
}
public String getContentType() {
return contentType;
}
public static FileType getInstance(String fileSufix) {
FileType knowledgeRoleName = null;
for (FileType fileType : FileType.values()) {
if (fileType.getFileSufix().equals(fileSufix)) {
knowledgeRoleName = fileType;
}
}
return knowledgeRoleName;
}
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.wml.Numbering;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* 导入导出配置
* @author tiantao
*/
public class IOConfig {
/**
* 列表样式与前端匹配
*/
public static final Map<String, Long> NUM_MAP;
public static final Map<String, Long> ILV1_MAP;
/**
* 列表样式
*/
public static final NumberingDefinitionsPart INIT_NUMBERING_DEFINITION;
/**
* 图片服务器路径
*/
public static String PIC_URI = "http://39.98.246.31:8888/";
/**
* 图片服务器路由
*/
public static String PIC_ROUTER = "/fileURI/";
static {
Map<String, Long> tmp1 = new HashMap<>();
tmp1.put("ul", 1L);
tmp1.put("ol", 2L);
NUM_MAP = Collections.unmodifiableMap(tmp1);
Map<String, Long> tmp2 = new HashMap<>();
tmp2.put("square", 1L);
tmp2.put("disc", 2L);
tmp2.put("circle", 3L);
tmp2.put("lower-alpha", 1L);
tmp2.put("lower-roman", 2L);
tmp2.put("upper-alpha", 3L);
tmp2.put("upper-roman", 4L);
tmp2.put("lower-greek", 1L);
ILV1_MAP = Collections.unmodifiableMap(tmp2);
NumberingDefinitionsPart numberingDefinitionsPart = null;
try {
numberingDefinitionsPart = new NumberingDefinitionsPart();
InputStream is = IOConfig.class.getClassLoader().getResourceAsStream("office/listStyle.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder builder = new StringBuilder();
String str;
while ((str = reader.readLine()) != null) {
builder.append(str);
}
Numbering numbering = (Numbering) XmlUtils.unmarshalString(builder.toString());
numberingDefinitionsPart.setJaxbElement(numbering);
} catch (Exception e) {
e.printStackTrace();
}
INIT_NUMBERING_DEFINITION = numberingDefinitionsPart;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class PropertiesLoader {
/**
* 图片服务器地址
*/
@Value("${pic-server.uri}")
private String picUri;
/**
* 图片服务器路由标识
*/
@Value("${pic-server.router}")
private String picRouter;
@PostConstruct
public void savePropertiesData(){
IOConfig.PIC_URI = picUri;
IOConfig.PIC_ROUTER = picRouter;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import com.google.common.base.Joiner;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.DictionarieValueModel;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.DataNotFound;
import java.util.*;
import java.util.stream.Collectors;
public class RemoteData {
/**
* 根据用户id Set集合查询对应的用户姓名
*
* @param userIds
* @return Map
*/
public static Map<String, String> getUserMap(Set<String> userIds) {
String join = Joiner.on(",").join(userIds);
try {
List<AgencyUserModel> agencyUserModelList = FeignUtil
.remoteCall(() -> Privilege.agencyUserClient.queryByIds(join, false));
Map<String, String> userMap = agencyUserModelList.stream().collect(
Collectors.toMap(AgencyUserModel::getUserId, AgencyUserModel::getRealName, (k1, k2) -> k2));
return userMap;
} catch (Exception e) {
}
return Collections.emptyMap();
}
/**
* 根据用户id查询对应的用户姓名
*
* @param userId
* @return Map
*/
public static String getUserRealNamById(String userId) {
if (ValidationUtil.isEmpty(userId)) {
return null;
}
try {
AgencyUserModel user = FeignUtil.remoteCall(() -> Privilege.agencyUserClient.queryByUserId(userId));
if (!ValidationUtil.isEmpty(user)) {
return user.getRealName();
}
} catch (Exception ignored) {
}
return null;
}
public static List<DictionarieValueModel> queryDict(String enumName) {
return FeignUtil.remoteCall(() -> Systemctl.dictionarieClient.dictValues(enumName));
}
/**
* 获取当前操作者对应角色下的部门信息
*
* @param roleName 角色名
* @return 部门
*/
public static String getOrgWithCurUserAndRole(String roleName) {
Map<String, String> roleOrgMap = getCurUserOrgRoleMap();
return roleOrgMap.get(roleName);
}
private static Map<String, String> getCurUserOrgRoleMap() {
Map<String, String> resMap = new HashMap<>();
try {
AgencyUserModel agencyUserModel = FeignUtil
.remoteCall(() -> Privilege.agencyUserClient.queryByUserId(RequestContext.getExeUserId()));
Map<Long, List<RoleModel>> rolesMap = agencyUserModel.getOrgRoles();
// 组装部门信息为Map
Map<Long, DepartmentModel> departmentMap = new HashMap<>();
for (List<DepartmentModel> departments : agencyUserModel.getCompanyDepartments().values()) {
if (ValidationUtil.isEmpty(departments)) {
continue;
}
Iterator<DepartmentModel> iterator = departments.iterator();
while (iterator.hasNext()) {
DepartmentModel next = iterator.next();
if (!ValidationUtil.isEmpty(next)) {
departmentMap.put(next.getSequenceNbr(), next);
}
}
}
// 组装单位信息为Map
Map<Long, CompanyModel> companyMap = new HashMap(
Bean.listToMap(agencyUserModel.getCompanys(), "sequenceNbr", CompanyModel.class));
Map<Long, List<Long>> orgRoleMap = agencyUserModel.getOrgRoleSeqs();
for (Long orgKey : orgRoleMap.keySet()) {
List<RoleModel> roleModels = rolesMap.get(orgKey);
for (RoleModel roleModel : roleModels) {
String orgCode = null;
if (departmentMap.containsKey(orgKey)) {
orgCode = departmentMap.get(orgKey).getOrgCode();
} else if (companyMap.containsKey(orgKey)) {
orgCode = companyMap.get(orgKey).getOrgCode();
} else {
throw new DataNotFound("用户角色数据丢失");
}
resMap.put(roleModel.getRoleName(), orgCode);
}
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
return resMap;
}
/**
* 是否包含admin
*
* @param roleName
* @return
*/
public static boolean isAdmin(String adminAllRole) {
Map<String, String> roleOrgMap = getCurUserOrgRoleMap();
if (adminAllRole != null&&!adminAllRole.isEmpty()) {
String[] roles = adminAllRole.split(",");
for (String role : roles) {
if (roleOrgMap.containsKey(role)) {
return true;
}
}
}
return false;
}
}
package com.yeejoin.amos.knowledgebase.face.util;
import org.typroject.tyboot.core.foundation.utils.TreeNode;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* <h1><h1>
*
* @author tiantao
* @date 2020/12/7 14:23
*/
public class TreeUtil {
public static<T extends TreeNode> List<T> getAllChildren(Collection<T> trees) {
List<T> childrenNodes = new ArrayList<>();
if (!ValidationUtil.isEmpty(trees)) {
trees.forEach(node->{
childrenNodes.add(node);
if (!ValidationUtil.isEmpty(node.getChildren())) {
childrenNodes.addAll(getAllChildren(node.getChildren()));
}
});
}
return childrenNodes;
}
}
package com.yeejoin.amos.knowledgebase.face.util.excel;
import lombok.Data;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import java.util.List;
import java.util.Map;
@Data
public class ExcelImportConfig {
/**
* 终止行号
*/
private Integer stopColIndex;
/**
* 起始行
*/
private Integer startRowIndex;
/**
* 标签与列对应关系
*/
private Map<Long, List<Integer>> tagColumns;
/**
* 基本信息与列对应关系
*/
private Map<String, Integer> basicColumns;
/**
* 列数据格式化方式
*/
private Map<Integer, String> formatMap;
/**
* 列数据对应枚举
*/
private Map<Integer, String> enumMap;
/**
* 文档正文模板
*/
private String htmlModule;
/**
* 文档摘要模板
*/
private String summaryModule;
/**
* 文档标题列
*/
private Integer titleColumn;
/**
* 文档分类列
*/
private String directoryColumn;
/**
* 完整性检查
*
* @return 是否完整
*/
public boolean check() {
if (ValidationUtil.isEmpty(startRowIndex)
|| null == tagColumns
|| null == basicColumns
|| null == formatMap
|| null == enumMap
|| null == titleColumn
|| null == directoryColumn
|| ValidationUtil.isEmpty(htmlModule)) {
return false;
}
for (List<Integer> colIndexList : tagColumns.values()) {
if (ValidationUtil.isEmpty(colIndexList)
|| ValidationUtil.isEmpty(colIndexList.get(0))) {
return false;
}
for (Integer colIndex : colIndexList) {
if (ValidationUtil.isEmpty(colIndex)) {
return false;
}
}
}
for (Integer value : basicColumns.values()) {
if (ValidationUtil.isEmpty(value)) {
return false;
}
}
return true;
}
}
package com.yeejoin.amos.knowledgebase.face.util.excel;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeDynamicsOptionModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagInstanceModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagModel;
import com.yeejoin.amos.knowledgebase.face.model.KnowledgeTagValueModel;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDocContent;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeDynamicsValue;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagInstance;
import com.yeejoin.amos.knowledgebase.face.orm.entity.KnowledgeTagValue;
import com.yeejoin.amos.knowledgebase.face.service.DocAuditService;
import com.yeejoin.amos.knowledgebase.face.service.DocContentService;
import com.yeejoin.amos.knowledgebase.face.service.TagInstanceService;
import com.yeejoin.amos.knowledgebase.face.service.TagValueService;
import com.yeejoin.amos.knowledgebase.face.util.DocSortUtil;
import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.DateUtil;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Pattern;
/**
* excel格式的战例解析--定制化
*
* @author tiantao
*/
public class ExcelParser {
private static final Pattern NUMBER_STRING_PATTEN = Pattern.compile("^[-\\+]?[\\d]*$");
private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final String DATE_FORMAT4_HTML = "yyyy-MM-dd HH:mm";
private static String getHolderRegex(Integer index) {
return "#\\{knowledge-" + index + "\\}";
}
private static String getHolderAllRegex() {
return "#\\{knowledge-\\d+\\}";
}
private static String removeAllHolder(String str) {
return str.replaceAll(getHolderAllRegex(), "");
}
private static String replaceHolder(String str, Integer index, String text) {
if (text == null) {
text = "";
}
return str.replaceAll(getHolderRegex(index), text);
}
/**
* 配置信息中涉及的标签列表以id为key
*/
private final Map<Long, KnowledgeTagModel> tagMap;
/**
* 导入配置
*/
private final Map<String, ExcelImportConfig> excelConfigMap;
/**
* 文档动态字段数据类型Map
*/
private final Map<String, KnowledgeDynamicsOptionModel> fieldTypeMap;
/**
* 标签的值类型
*/
private final Map<Long, String> tagValueTypeMap;
/**
* 涉及的枚举信息,以分组为外层key,中文值为内层key,英文值为value
*/
private final Map<String, Map<String, String>> enumCnEnMap;
/**
* 标签的单位
*/
private final Map<Long, String> tagUnitMap;
/**
* 解析的数据及返回结果数据
*/
private List<ImportResult> ImportResults = new ArrayList<>();
private TablesDataList tablesDataList = new TablesDataList();
private Sequence sequence;
public List<ImportResult> getImportResults() {
return ImportResults;
}
private Date now = new Date();
private final String orgCode;
public ExcelParser(@NonNull Map<Long, KnowledgeTagModel> tagMap, @NonNull Map<String, ExcelImportConfig> excelConfigMap,
Map<String, KnowledgeDynamicsOptionModel> fieldTypeMap, @NonNull Map<Long, String> tagValueTypeMap,
@NonNull Map<String, Map<String, String>> enumCnEnMap, @NonNull Map<Long, String> tagUnitMap,
@NonNull Sequence sequence, String orgCode) {
this.tagMap = Collections.unmodifiableMap(tagMap);
this.excelConfigMap = excelConfigMap;
this.fieldTypeMap = Collections.unmodifiableMap(fieldTypeMap);
this.tagValueTypeMap = Collections.unmodifiableMap(tagValueTypeMap);
this.enumCnEnMap = Collections.unmodifiableMap(enumCnEnMap);
this.tagUnitMap = Collections.unmodifiableMap(tagUnitMap);
this.sequence = sequence;
this.orgCode = orgCode;
}
/**
* 解析表格行
*
* @param row 表格行对象
*/
public void parseRow(Row row, Map<String, Long> typeValueMap) {
try {
String typeValue = convertCellValueToString(row.getCell(1));
if (ValidationUtil.isEmpty(typeValue) || ValidationUtil.isEmpty(typeValueMap.get(typeValue))) {
throw new BadRequest("缺少基本信息");
}
ExcelImportConfig excelConfig = this.excelConfigMap.get(String.valueOf(typeValueMap.get(typeValue)));
String docTitle = convertCellValueToString(row.getCell(excelConfig.getTitleColumn()));
// String docDirectory = convertCellValueToString(row.getCell(excelConfig.getDirectoryColumn()));
String docDirectory = excelConfig.getDirectoryColumn();
if (ValidationUtil.isEmpty(docTitle) || ValidationUtil.isEmpty(docDirectory)) {
throw new BadRequest("缺少基本信息");
}
Long directoryId = Long.parseLong(docDirectory);
// 创建文档
KnowledgeDocContent docContent = getNewDoc(excelConfig);
// 设置文档分类
docContent.setDocTitle(docTitle);
docContent.setDirectoryId(directoryId);
// 创建动态字段
List<KnowledgeDynamicsValue> dynamicsValues = getDynamicsValueList(excelConfig, row, docContent);
// 创建标签实例
List<KnowledgeTagInstance> tagInstances = new ArrayList<>();
// 以及标签值实例
List<KnowledgeTagValue> tagValues = new ArrayList<>();
Map<Long, List<Integer>> tagColumns = excelConfig.getTagColumns();
Map<Integer, String> formatMap = excelConfig.getFormatMap();
for (Long tagSeq : tagColumns.keySet()) {
if (!tagMap.containsKey(tagSeq) || !tagValueTypeMap.containsKey(tagSeq)) {
continue;
}
String valueType = tagValueTypeMap.get(tagSeq);
KnowledgeTagInstance tagInstance = getTagInstance(tagMap.get(tagSeq), docContent.getSequenceNbr());
switch (valueType) {
case "single": {
Integer valueColIndex = tagColumns.get(tagSeq).get(0);
String cellValue = convertCellValueToString(row.getCell(valueColIndex));
if (ValidationUtil.isEmpty(cellValue) || !NUMBER_STRING_PATTEN.matcher(cellValue).matches()) {
continue;
}
tagValues.add(getTagValue(tagInstance, TagValueService.VALUE_TAG_FIELD_SINGLEVALUE, cellValue));
replaceHtmlHolder(docContent, valueColIndex, cellValue, cellValue);
break;
}
case "date": {
Integer valueColIndex = tagColumns.get(tagSeq).get(0);
String cellValue = convertCellValueToString(row.getCell(valueColIndex));
if (ValidationUtil.isEmpty(cellValue) || !formatMap.containsKey(valueColIndex)) {
continue;
}
try {
Date date = DateUtil.formatStringToDate(cellValue, formatMap.get(valueColIndex));
cellValue = DateUtil.formatDate(date, DATE_FORMAT);
String htmlDateStr = DateUtil.formatDate(date, DATE_FORMAT4_HTML);
tagValues.add(getTagValue(tagInstance, TagValueService.VALUE_TAG_FIELD_DATE_H, cellValue));
replaceHtmlHolder(docContent, valueColIndex, htmlDateStr, cellValue);
} catch (Exception e) {
continue;
}
break;
}
case "text": {
Integer valueColIndex = tagColumns.get(tagSeq).get(0);
String cellValue = convertCellValueToString(row.getCell(valueColIndex));
if (ValidationUtil.isEmpty(cellValue)) {
continue;
}
tagValues.add(getTagValue(tagInstance, TagValueService.VALUE_TAG_FIELD_TEXT, cellValue));
replaceHtmlHolder(docContent, valueColIndex, cellValue, cellValue);
break;
}
case "range":
if (tagColumns.get(tagSeq).size() > 1) {
Integer valueColIndex1 = tagColumns.get(tagSeq).get(0);
String cellValue1 = convertCellValueToString(row.getCell(valueColIndex1));
Integer valueColIndex2 = tagColumns.get(tagSeq).get(1);
String cellValue2 = convertCellValueToString(row.getCell(valueColIndex2));
if (ValidationUtil.isEmpty(cellValue1) && ValidationUtil.isEmpty(cellValue2)
|| !NUMBER_STRING_PATTEN.matcher(cellValue1).matches() || !NUMBER_STRING_PATTEN.matcher(cellValue2).matches()) {
continue;
}
if (!ValidationUtil.isEmpty(cellValue1)) {
tagValues.add(getTagValue(tagInstance, TagValueService.VALUE_TAG_FIELD_RANGE_MIN, cellValue1));
replaceHtmlHolder(docContent, valueColIndex1, cellValue1, cellValue1);
}
if (!ValidationUtil.isEmpty(cellValue2)) {
tagValues.add(getTagValue(tagInstance, TagValueService.VALUE_TAG_FIELD_RANGE_MAX, cellValue2));
replaceHtmlHolder(docContent, valueColIndex2, cellValue2, cellValue2);
}
} else {
continue;
}
break;
default:
break;
}
tagInstances.add(tagInstance);
}
if(ValidationUtil.isEmpty(excelConfig.getTitleColumn())) {
throw new BadRequest("缺少标题所在的索引信息");
}
replaceHtmlHolder(docContent, excelConfig.getTitleColumn(), docTitle, docTitle);
docContent.setHtmlContent(removeAllHolder(docContent.getHtmlContent()));
docContent.setTextContent(removeAllHolder(docContent.getTextContent()));
String textContent = String.valueOf(docContent.getTextContent());
docContent.setSummary(textContent.substring(0,Math.min(300, textContent.length())));
List<KnowledgeTagInstanceModel> docTags = stuffTagValues(tagInstances, tagValues);
docContent.setSortStr(DocSortUtil.getSortStr(docTags));
this.tablesDataList.getDocContentList().add(docContent);
this.tablesDataList.getDynamicsValueList().addAll(dynamicsValues);
this.tablesDataList.getTagInstanceList().addAll(tagInstances);
this.tablesDataList.getTagValueList().addAll(tagValues);
this.ImportResults.add(new ImportResult(row.getRowNum()));
} catch (BaseException e) {
this.ImportResults.add(new ImportResult(row.getRowNum(), e.getMessage()));
} catch (Exception e) {
this.ImportResults.add(new ImportResult(row.getRowNum(), e.getStackTrace()[0].getMethodName()));
}
}
private List<KnowledgeTagInstanceModel> stuffTagValues(List<KnowledgeTagInstance> tagInstances, List<KnowledgeTagValue> tagValues) {
if (ValidationUtil.isEmpty(tagInstances)) {
return Collections.emptyList();
}
ArrayList<KnowledgeTagInstanceModel> resList = Bean.toModels(tagInstances, KnowledgeTagInstanceModel.class);
Map<Object, KnowledgeTagInstanceModel> instanceModelMap = Bean.listToMap(resList, "sequenceNbr", KnowledgeTagInstanceModel.class);
if (!ValidationUtil.isEmpty(tagValues)) {
tagValues.forEach(tagValue->{
KnowledgeTagInstanceModel instanceModel = instanceModelMap.get(tagValue.getInstanceSeq());
List<KnowledgeTagValueModel> tagValueModels = instanceModel.getTagValues();
if (null == tagValueModels) {
tagValueModels = new ArrayList<>();
instanceModel.setTagValues(tagValueModels);
}
tagValueModels.add(Bean.toModel(tagValue, new KnowledgeTagValueModel()));
});
}
return resList;
}
private void replaceHtmlHolder(KnowledgeDocContent docContent, Integer colIndex, String contentValue, String textValue) {
docContent.setHtmlContent(replaceHolder(docContent.getHtmlContent(), colIndex, contentValue));
docContent.setTextContent(replaceHolder(docContent.getTextContent(), colIndex, textValue));
}
/**
* 获取解析到的数据列表,并刷新以备下一波解析
*
* @return 数据列表合集
*/
public TablesDataList getAndFlushDatas() {
TablesDataList res = this.tablesDataList;
this.tablesDataList = new TablesDataList();
return res;
}
/**
* 创建一个新的文档
*
* @return
*/
private KnowledgeDocContent getNewDoc(ExcelImportConfig excelConfig) {
KnowledgeDocContent docContent = new KnowledgeDocContent();
docContent.setSequenceNbr(sequence.nextId());
docContent.setRecDate(now);
docContent.setRecUserId(RequestContext.getExeUserId());
docContent.setUserId(RequestContext.getExeUserId());
docContent.setCreateTime(now);
docContent.setAgencyCode(RequestContext.getAgencyCode());
docContent.setOrgCode(this.orgCode);
docContent.setHtmlContent(excelConfig.getHtmlModule());
docContent.setTextContent(excelConfig.getSummaryModule());
docContent.setDocStatus(DocContentService.DOC_STATUS_UNPUBLISHED);
docContent.setAuditStatus(DocAuditService.DOC_AUDIT_STATUS_SAVED);
docContent.setHaveAttachment(false);
return docContent;
}
private List<KnowledgeDynamicsValue> getDynamicsValueList(ExcelImportConfig excelConfig, Row row, KnowledgeDocContent docContent) {
List<KnowledgeDynamicsValue> dynamicsValues = new ArrayList<>();
Map<String, Integer> basicColumns = excelConfig.getBasicColumns();
Map<Integer, String> enumMap = excelConfig.getEnumMap();
for (String fieldName : basicColumns.keySet()) {
Integer colIndex = basicColumns.get(fieldName);
Cell cell = row.getCell(colIndex);
KnowledgeDynamicsOptionModel optionModel = fieldTypeMap.get(fieldName);
if (null == optionModel) {
throw new BadRequest("无法识别的字段名:" + fieldName);
}
String type = fieldTypeMap.get(fieldName).getDataType();
String cellValue = convertCellValueToString(cell);
if (type.toUpperCase().equals("ENUM")) {
if (!enumMap.containsKey(colIndex)) {
throw new BadRequest("缺少枚举字段的配置信息:" + fieldName);
}
String enumName = enumMap.get(colIndex);
cellValue = enumCnEnMap.get(enumName).get(cellValue);
}
dynamicsValues.add(getNewDynamicsField(optionModel, cellValue, docContent.getSequenceNbr()));
// 替换模板占位字符
replaceHtmlHolder(docContent, colIndex, cellValue, cellValue);
}
return dynamicsValues;
}
private KnowledgeDynamicsValue getNewDynamicsField(KnowledgeDynamicsOptionModel optionModel, String cellValue, Long docSequenceNbr) {
KnowledgeDynamicsValue dynamicsValue = new KnowledgeDynamicsValue();
dynamicsValue.setSequenceNbr(sequence.nextId());
dynamicsValue.setRecDate(now);
dynamicsValue.setRecUserId(RequestContext.getExeUserId());
dynamicsValue.setFieldName(optionModel.getFieldName());
dynamicsValue.setFieldValue(ValidationUtil.isEmpty(cellValue) ? "" : cellValue);
dynamicsValue.setDataType(optionModel.getDataType());
dynamicsValue.setAgencyCode(RequestContext.getAgencyCode());
dynamicsValue.setFieldLabel(optionModel.getFieldLabel());
dynamicsValue.setGroupSeq(optionModel.getGroupSeq());
dynamicsValue.setQueryStrategy(optionModel.getQueryStrategy());
dynamicsValue.setInstanceId(docSequenceNbr);
dynamicsValue.setOptionSeq(optionModel.getSequenceNbr());
return dynamicsValue;
}
KnowledgeTagInstance getTagInstance(KnowledgeTagModel tagModel, Long docSequenceNbr) {
KnowledgeTagInstance tagInstance = new KnowledgeTagInstance();
tagInstance.setSequenceNbr(sequence.nextId());
tagInstance.setRecDate(now);
tagInstance.setRecUserId(RequestContext.getExeUserId());
tagInstance.setAgencyCode(RequestContext.getAgencyCode());
tagInstance.setTagSeq(tagModel.getSequenceNbr());
tagInstance.setTargetSeq(docSequenceNbr);
tagInstance.setTagType(tagModel.getTagType());
tagInstance.setTagName(tagModel.getTagName());
tagInstance.setMarkingType(TagInstanceService.MARKING_TYPE_DOC);
return tagInstance;
}
/**
* 创建一个新的标签值实例
*
* @param tagInstance 实例对象
* @param value 值
* @return Model
*/
private KnowledgeTagValue getTagValue(KnowledgeTagInstance tagInstance, String fieldName, String value) {
KnowledgeTagValue tagValue = new KnowledgeTagValue();
tagValue.setSequenceNbr(sequence.nextId());
tagValue.setRecDate(now);
tagValue.setRecUserId(RequestContext.getExeUserId());
tagValue.setAgencyCode(RequestContext.getAgencyCode());
tagValue.setInstanceSeq(tagInstance.getSequenceNbr());
tagValue.setFieldName(fieldName);
tagValue.setTagValue(value);
tagValue.setUnit(tagUnitMap.get(tagInstance.getTagSeq()));
return tagValue;
}
/**
* 获取单元格的文本内容
*
* @param cell
* @return
*/
public static String convertCellValueToString(Cell cell) {
if (cell == null) {
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
//数字
case NUMERIC:
Double doubleValue = cell.getNumericCellValue();
// 格式化科学计数法,取一位整数
DecimalFormat df = new DecimalFormat("0");
returnValue = df.format(doubleValue);
break;
//字符串
case STRING:
returnValue = cell.getStringCellValue().trim();
break;
//布尔
case BOOLEAN:
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
// 空值
case BLANK:
break;
// 公式
case FORMULA:
returnValue = cell.getCellFormula();
break;
// 故障
case ERROR:
break;
default:
}
return returnValue;
}
/**
* 数据涉及对象列表缓存
*/
@Getter
public class TablesDataList {
private List<KnowledgeDocContent> docContentList = new ArrayList<>();
private List<KnowledgeTagInstance> tagInstanceList = new ArrayList<>();
private List<KnowledgeTagValue> tagValueList = new ArrayList<>();
private List<KnowledgeDynamicsValue> dynamicsValueList = new ArrayList<>();
}
@Data
class ImportResult {
// 行号
private Integer rowIndex;
// 是否导入成功
private boolean success;
// 错误信息
private String errorMessege;
ImportResult(Integer rowIndex, String errorMessege) {
this.rowIndex = rowIndex;
this.success = false;
this.errorMessege = errorMessege;
}
ImportResult(Integer rowIndex) {
this.rowIndex = rowIndex;
this.success = true;
}
}
}
package com.yeejoin.amos.knowledgebase.face.util.pdf;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.IBlockElement;
import com.itextpdf.layout.element.IElement;
import com.itextpdf.layout.font.FontProvider;
import com.yeejoin.amos.knowledgebase.face.util.IOConfig;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static com.yeejoin.amos.knowledgebase.face.util.DataTransformator.inputStream2Bytes;
/**
* pdf导出工具
*
* @author tiantao
*/
public class PdfBuilder {
private static final ConverterProperties CP;
static {
CP = new ConverterProperties();
// 设置字体
FontProvider fontProvider = new DefaultFontProvider(false, false, false);
boolean success = false;
try(InputStream font = PdfBuilder.class.getClassLoader().getResourceAsStream("fonts/msyh.ttf")) {
fontProvider.addFont(inputStream2Bytes(font));
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (!success) {
fontProvider.addStandardPdfFonts();
}
CP.setFontProvider(fontProvider);
CP.setCharset("utf-8");
}
public static byte[] html2Pdf(String html, String docTitle) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
org.jsoup.nodes.Document htmlDocument = Jsoup.parseBodyFragment(html, "UTF-8");
for (Element imgDocument : htmlDocument.getElementsByTag("img")) {
String src = imgDocument.attr("src");
if (null != src && src.length() > 0 && src.startsWith(IOConfig.PIC_ROUTER)) {
imgDocument.attr("src", src.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI));
}
}
replaceElement(htmlDocument);
String htmlStr = htmlDocument.html();
PdfDocument pd = new PdfDocument(new PdfWriter(os));
pd.getDocumentInfo().setTitle(docTitle);
Document document = new Document(pd, PageSize.A4);
try {
// 设置页面边距 必须先设置边距,再添加内容,否则页边距无效
document.setMargins(20, 32, 20, 32);
List<IElement> list = HtmlConverter.convertToElements(htmlStr, CP);
for (IElement ie : list) {
document.add((IBlockElement) ie);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
document.close();
}
return os.toByteArray();
}
/**
* 替换显示效果不好的页面元素
*
* @param element body
*/
static void replaceElement(Element element) {
Elements inputs = element.getElementsByTag("input");
inputs.forEach(input -> {
String type = input.attr("type");
String value = input.attr("value");
if (type != null) {
switch (type.trim()) {
case "datetime-local":
input.removeAttr("type");
if (value != null && value.trim().length() > 0) {
input.attr("value", value.trim().replaceAll("/", "-").replaceAll("T", " "));
}
break;
case "text":
break;
default:
}
}
});
Elements textareas = element.getElementsByTag("textarea");
textareas.forEach(textarea -> {
String value = textarea.attr("value");
textarea.tagName("div").clearAttributes().attr("style", "font-size: 14px; line-height: 30px; padding: 0 7px; border-radius: 4px; border: solid 1px #dedede;");
String text = "";
if (value != null) {
text += text + value;
}
textarea.appendChild(new TextNode(text));
});
}
}
package com.yeejoin.amos.knowledgebase.face.util.sql;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Getter;
import java.util.Map;
import java.util.Set;
/**
* 自定义查询体
* @author tiantao
*/
@Getter
abstract public class BaseSqlCondition {
/**
* 条件类型
*/
private static final String CONDITION_TYPE = "conditionType";
private static final String BLOCK = "block";
private static final String CONDITION = "condition";
/**
* 逻辑关系
*/
private String logic;
BaseSqlCondition(Map<String, Object> resourceMap) {
this.logic = (String) resourceMap.get("logic");
}
public static BaseSqlCondition getInstance(Map<String, Object> resourceMap) {
String type = (String) resourceMap.get(CONDITION_TYPE);
BaseSqlCondition sqlCondition;
if (BLOCK.equals(type)) {
sqlCondition = new SqlBlock(resourceMap);
} else if (CONDITION.equals(type)) {
sqlCondition = new SqlStatement(resourceMap);
} else {
throw new RuntimeException("条件格式错误");
}
if (!sqlCondition.validate()) {
throw new RuntimeException("条件格式错误");
}
return sqlCondition;
}
public <T> void compose(QueryWrapper<T> queryWrapper) {
composeWrapper(queryWrapper, "and");
}
/**
* 组装条件到QueryWrapper
*
* @param queryWrapper 查询语句
* @param logic 与上个条件的逻辑关系
* @param <T> 泛型
*/
abstract <T> void composeWrapper(QueryWrapper<T> queryWrapper, String logic);
/**
* 检查数据格式及完整性
* @return 是否合格
*/
abstract boolean validate();
public abstract Set<String> getTagSeqs();
public abstract int getTotalStatement();
}
package com.yeejoin.amos.knowledgebase.face.util.sql;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.*;
/**
* 查询条件块
*/
class SqlBlock extends BaseSqlCondition {
private List<BaseSqlCondition> conditions;
SqlBlock(Map<String, Object> resourceMap) {
super(resourceMap);
this.conditions = new ArrayList<>();
Object children = resourceMap.get("children");
if (children instanceof List) {
try {
((List<Map<String, Object>>) children).forEach(map -> this.conditions.add(BaseSqlCondition.getInstance(map)));
} catch (ClassCastException e) {
throw new RuntimeException("条件格式错误");
}
} else {
throw new RuntimeException("条件格式错误");
}
}
@Override
<T> void composeWrapper(QueryWrapper<T> queryWrapper, String logic) {
switch (logic) {
case "or":
queryWrapper.or(this::composeChild);
break;
case "and":
default:
queryWrapper.and(this::composeChild);
break;
}
}
@Override
boolean validate() {
return conditions != null && !conditions.isEmpty();
}
@Override
public Set<String> getTagSeqs() {
Set<String> set = new HashSet<>();
conditions.forEach(condition -> set.addAll(condition.getTagSeqs()));
return set;
}
@Override
public int getTotalStatement() {
return conditions.stream().mapToInt(BaseSqlCondition::getTotalStatement).sum();
}
private <T> void composeChild(QueryWrapper<T> wrapper) {
final String[] nextLogic = {"and"};
conditions.forEach(condition -> {
condition.composeWrapper(wrapper, nextLogic[0]);
nextLogic[0] = condition.getLogic();
});
}
}
package com.yeejoin.amos.knowledgebase.face.util.sql;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
/**
* 查询条件语句
*
* @author tiantao
*/
@Setter
@Accessors(chain = true)
class SqlStatement extends BaseSqlCondition {
static {
Map<String, String[]> map = new HashMap<>();
map.put(ValueType.date.name(), str2array("dateH"));
map.put(ValueType.text.name(), str2array("text"));
map.put(ValueType.single.name(), str2array("singleValue"));
map.put(ValueType.range.name(), str2array("rangeMin", "rangeMax"));
valueTypeFieldMap = Collections.unmodifiableMap(map);
map = new HashMap<>();
map.put(ValueType.date.name(), str2array(", MAX(CASE `tv`.`FIELD_NAME` WHEN 'dateH' THEN `tv`.`TAG_VALUE` ELSE NULL END) AS `dateH`"));
map.put(ValueType.text.name(), str2array(", MAX(CASE `tv`.`FIELD_NAME` WHEN 'text' THEN `tv`.`TAG_VALUE` ELSE NULL END) AS `text`"));
map.put(ValueType.single.name(), str2array(", MAX(CASE `tv`.`FIELD_NAME` WHEN 'singleValue' THEN `tv`.`TAG_VALUE` ELSE NULL END) AS `singleValue`"));
map.put(ValueType.range.name(), str2array(", MAX(CASE `tv`.`FIELD_NAME` WHEN 'rangeMin' THEN `tv`.`TAG_VALUE` ELSE NULL END) AS `rangeMin`",
", MAX(CASE `tv`.`FIELD_NAME` WHEN 'rangeMax' THEN `tv`.`TAG_VALUE` ELSE NULL END) AS `rangeMax`"));
valueTagFieldSqlMap = Collections.unmodifiableMap(map);
}
private static final Map<String, String[]> valueTypeFieldMap;
private static final Map<String, String[]> valueTagFieldSqlMap;
private static final Pattern numberPattern = Pattern.compile("^[-\\+]?[\\d]+[.]?[\\d]*$");
private static final Pattern datePattern = Pattern.compile("^[\\d]{4}-[\\d]{2}-[\\d]{2} [\\d]{2}:[\\d]{2}:[\\d]{2}$");
private static final Pattern datePattern16 = Pattern.compile("^[\\d]{4}/[\\d]{2}/[\\d]{2} [\\d]{2}:[\\d]{2}$");
/**
* 字段类型
*/
private FieldType fieldType;
/**
* 字段名/标签id
*/
private String expandField;
/**
* 值类型
*/
private ValueType valueType;
/**
* 值
*/
private List<String> values;
/**
* 模糊匹配
*/
private boolean fuzzy;
private static String[] str2array(String... str) {
return str;
}
SqlStatement(Map<String, Object> resourceMap) {
super(resourceMap);
this.setFieldType(FieldType.valueOf((String) resourceMap.get("fieldType")))
.setExpandField((String) resourceMap.get("expandFiled"))
.setValues((List<String>) resourceMap.get("values"))
.setFuzzy(Boolean.parseBoolean(String.valueOf(resourceMap.get("fuzzy"))));
if (this.fieldType != FieldType.textTag) {
this.setValueType(ValueType.valueOf((String) resourceMap.get("valueType")));
}
}
@Override
<T> void composeWrapper(QueryWrapper<T> queryWrapper, String logic) {
switch (logic) {
case "or":
queryWrapper.or();
case "and":
default:
composeThis(queryWrapper);
break;
}
}
@Override
boolean validate() {
if (fieldType == null || expandField == null || values == null) {
return false;
}
if (fieldType != FieldType.textTag && valueType == null) {
return false;
}
boolean emptyVal = ValidationUtil.isEmpty(values);
if (fieldType != FieldType.textTag && values.size() > 0) {
String val1 = values.get(0);
String val2 = "";
switch (valueType) {
case text:
//格式化
if (!emptyVal && !ValidationUtil.isEmpty(val1)) {
values.add(0, stringParamFormat(val1));
values.remove(1);
}
break;
case date:
// 校验并格式化
if (!emptyVal && !ValidationUtil.isEmpty(val1)) {
if (val1.contains("/") && val1.length() == 16) {
paramValidate(datePattern16, val1);
} else {
paramValidate(datePattern, val1);
}
values.add(0, stringParamFormat(val1));
values.remove(1);
}
val2 = values.get(1);
if (!emptyVal && !ValidationUtil.isEmpty(val2)) {
if (val2.contains("/") && val1.length() == 16) {
paramValidate(datePattern16, val2);
} else {
paramValidate(datePattern, val2);
}
values.add(1, stringParamFormat(val2));
values.remove(2);
}
break;
case range:
case single:
// 校验
if (!emptyVal && !ValidationUtil.isEmpty(val1)) {
paramValidate(numberPattern, val1);
}
val2 = values.get(1);
if (!emptyVal && !ValidationUtil.isEmpty(val2)) {
paramValidate(numberPattern, val2);
}
break;
default:
}
}
if (valuesIsEmpty(true)) {
switch (this.fieldType) {
case valueTag:
this.fieldType = FieldType.textTag;
break;
case textTag:
break;
case content:
case baseInfo:
throw new BadRequest("条件搜索值为空");
default:
}
}
return true;
}
@Override
public Set<String> getTagSeqs() {
Set<String> set = new HashSet<>();
if (fieldType == FieldType.textTag || fieldType == FieldType.valueTag) {
set.add(expandField);
}
return set;
}
@Override
public int getTotalStatement() {
return 1;
}
/**
* value判空
*
* @param all 全空
* @return
*/
private boolean valuesIsEmpty(boolean all) {
if (all) {
if (ValidationUtil.isEmpty(values)) {
return true;
} else {
boolean empty0 = ValidationUtil.isEmpty(values.get(0));
if (values.size() > 1) {
return empty0 && ValidationUtil.isEmpty(values.get(1));
}
return empty0;
}
} else {
if (ValidationUtil.isEmpty(values)) {
return true;
} else {
boolean empty0 = ValidationUtil.isEmpty(values.get(0));
if (values.size() > 1) {
return !(empty0 || ValidationUtil.isEmpty(values.get(1)));
}
return empty0;
}
}
}
private <T> void composeThis(QueryWrapper<T> queryWrapper) {
switch (fieldType) {
case content:
composeContentCondition(queryWrapper);
break;
case baseInfo:
queryWrapper.inSql("SEQUENCE_NBR", buildBaseInfoSql());
break;
case textTag:
queryWrapper.inSql("SEQUENCE_NBR", buildTagExistSql());
break;
case valueTag:
queryWrapper.inSql("SEQUENCE_NBR", buildTagValueSql());
break;
default:
}
}
private <T> void composeContentCondition(QueryWrapper<T> wrapper) {
switch (valueType) {
case text: {
String text = "";
if (values != null && values.get(0) != null) {
text = values.get(0);
}
if (fuzzy) {
wrapper.like(expandField, text);
} else {
wrapper.eq(expandField, text);
}
break;
}
case date: {
String min = values.get(0);
String max = values.get(1);
paramValidate(datePattern, min, max);
if (min != null) {
wrapper.ge(expandField, min);
}
if (max != null) {
wrapper.le(expandField, max);
}
break;
}
default:
}
}
private String buildBaseInfoSql() {
StringBuilder builder = new StringBuilder("SELECT INSTANCE_ID FROM `knowledge_dynamics_value` WHERE FIELD_NAME = '")
.append(expandField).append("'");
getChildCondition("FIELD_VALUE").forEach(child -> builder.append(" AND ").append(child));
return builder.toString();
}
private String buildTagValueSql() {
StringBuilder builder = new StringBuilder("SELECT TARGET_SEQ FROM (SELECT `ti`.`SEQUENCE_NBR` AS `SEQUENCE_NBR`, `ti`.`TAG_SEQ` AS `TAG_SEQ`, `ti`.`TARGET_SEQ` AS `TARGET_SEQ`");
Arrays.asList(valueTagFieldSqlMap.get(valueType.name())).forEach(fieldSql -> builder.append(fieldSql));
builder.append(" FROM `knowledge_tag_instance` `ti` INNER JOIN `knowledge_tag_value` `tv` ON `ti`.`SEQUENCE_NBR` = `tv`.`INSTANCE_SEQ` WHERE `ti`.`MARKING_TYPE` = 'DOC' AND `ti`.`TAG_SEQ` = ")
.append(expandField).append(" AND (");
AtomicBoolean needOr = new AtomicBoolean(false);
Arrays.asList(valueTypeFieldMap.get(valueType.name())).forEach(fieldName -> {
if (needOr.get()) {
builder.append(" OR");
} else {
needOr.set(true);
}
builder.append(" `tv`.FIELD_NAME = '").append(fieldName).append("'");
});
builder.append(")").append(" GROUP BY `ti`.`SEQUENCE_NBR`) AS tmp").append(" WHERE");
AtomicBoolean needAnd = new AtomicBoolean(false);
getChildCondition(valueTypeFieldMap.get(valueType.name())).forEach(child -> {
if (needAnd.get()) {
builder.append(" AND");
} else {
needAnd.set(true);
}
builder.append(" ").append(child);
});
return builder.toString();
}
private String buildTagExistSql() {
return "SELECT TARGET_SEQ FROM `knowledge_tag_instance` WHERE TAG_SEQ = " + expandField;
}
private List<String> getChildCondition(String... fields) {
List<String> res = new ArrayList<>();
switch (valueType) {
case text: {
if (fuzzy) {
res.add(fields[0] + " like '%" + stringParamFormat(values.get(0)) + "%'");
} else {
res.add(fields[0] + " = '" + stringParamFormat(values.get(0)) + "'");
}
break;
}
case single: {
String min = values.get(0);
String max = values.get(1);
if (min != null && min.length() > 0) {
res.add("CONVERT(" + fields[0] + ",DECIMAL)" + " >= " + min);
}
if (max != null && max.length() > 0) {
res.add("CONVERT(" + fields[0] + ",DECIMAL)" + " <= " + max);
}
break;
}
case date: {
String min = values.get(0);
if (fuzzy) {
if (min != null && min.length() > 0) {
res.add(fields[0] + " >= '" + min + "'");
}
if (values.size() > 1) {
String max = values.get(1);
if (max != null && max.length() > 0) {
res.add(fields[0] + " <= '" + max + "'");
}
}
} else {
if (min != null && min.length() > 0) {
res.add(fields[0] + " = '" + min + "'");
}
if (values.size() > 1) {
String max = values.get(1);
if (max != null && max.length() > 0) {
res.add(fields[0] + " = '" + max + "'");
}
}
}
break;
}
case range: {
String min = values.get(0);
String max = values.get(1);
if (fuzzy) {
if (min != null && min.length() > 0) {
res.add(fields[1] + " >= " + min);
}
if (max != null && max.length() > 0) {
res.add(fields[0] + " <= " + max);
}
} else {
if (min != null && min.length() > 0) {
res.add(fields[0] + " <= " + min);
}
if (max != null && max.length() > 0) {
res.add(fields[1] + " >= " + max);
}
}
break;
}
default:
}
return res;
}
/**
* sql参数防注入格式化
*/
private static String stringParamFormat(String str) {
if (null != str) {
return str.replace("'", "''");
} else {
return "null";
}
}
// 参数格式校验
private static void paramValidate(Pattern pattern, String... numbers) {
for (String number : numbers) {
if (number == null || number.length() == 0) {
continue;
}
if (!pattern.matcher(number).matches()) {
throw new RuntimeException("数值格式有误");
}
}
}
enum FieldType {
/**
* 文档表字段
*/
content,
/**
* 动态字段
*/
baseInfo,
/**
* 文本标签
*/
textTag,
/**
* 标签值
*/
valueTag
}
enum ValueType {
text, date, single, range
}
}
package com.yeejoin.amos.knowledgebase.face.util.word;
import com.yeejoin.amos.knowledgebase.face.util.IOConfig;
import lombok.Data;
import lombok.experimental.Accessors;
import org.docx4j.XmlUtils;
import org.docx4j.dml.wordprocessingDrawing.Inline;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.relationships.Relationship;
import org.docx4j.wml.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import javax.xml.bind.JAXBException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
/**
* word导出工具
* @author tiantao
*/
public class DocxBuilder {
private WordprocessingMLPackage wordMLPackage;
private ObjectFactory factory;
private int docPrId = 1;
private int cNvPrId = 2;
public DocxBuilder(String html) {
Document document = Jsoup.parseBodyFragment(html, "UTF-8");
try {
wordMLPackage = WordprocessingMLPackage.createPackage();
factory = Context.getWmlObjectFactory();
wordMLPackage.getMainDocumentPart().addTargetPart(IOConfig.INIT_NUMBERING_DEFINITION);
addElement(wordMLPackage.getMainDocumentPart(), null, document.body(), new TextStyle(), new ParagraphStyle());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成word字节数据
*
* @return 字节数组
*/
public byte[] build() {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
wordMLPackage.save(outputStream);
} catch (Docx4JException e) {
e.printStackTrace();
}
return outputStream.toByteArray();
}
/**
* 递归解析html元素,根据不同的标签名插入不同数据到word中
*
* @param parent word区域
* @param current 当前操作行
* @param node html元素节点
* @param textStyle 当前文本样式
* @param paragraphStyle 当前段落样式
*/
private void addElement(ContentAccessor parent, ContentAccessor current, Node node, TextStyle textStyle, ParagraphStyle paragraphStyle) {
if (node instanceof TextNode) {
addText(current, ((TextNode) node).text().trim(), textStyle);
} else {
switch (node.nodeName()) {
case "body":
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "div":
if (!(parent instanceof Tc)) {
paragraphStyle = getDivParagraphStyle(node.attr("data-level"), node.attr("style"));
}
if (isTableDiv(node)) {
addChildElement(parent, current, node, textStyle, paragraphStyle);
} else {
textStyle = getDivTextStyle(node.attr("data-level"));
current = factory.createP();
((P) current).setPPr(paragraphStyle.getPPr());
addChildElement(parent, current, node, textStyle, paragraphStyle);
parent.getContent().add(current);
}
break;
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
case "h7":
case "h8":
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "em":
textStyle = new TextStyle(textStyle).setItalic(true);
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "span":
textStyle = getSpanTextStyle(textStyle, node.attr("style"));
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "strong":
textStyle = new TextStyle(textStyle).setBold(true);
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "sup":
textStyle = new TextStyle(textStyle).setTextScript("superscript");
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "sub":
textStyle = new TextStyle(textStyle).setTextScript("subscript");
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "label":
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "ul":
case "ol":
paragraphStyle = getListParagraphStyle(node.nodeName(), node.attr("style"));
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "li":
current = factory.createP();
((P) current).setPPr(paragraphStyle.getPPr());
addChildElement(parent, current, node, textStyle, paragraphStyle);
parent.getContent().add(current);
break;
case "table":
addChildElement(parent, current, node, textStyle, paragraphStyle);
break;
case "caption":
paragraphStyle = getTableCaptionParagraphStyle();
textStyle = new TextStyle().setFontSize("14").setAsciiFont("黑体").setBold(true).setUnderscore(true);
current = factory.createP();
((P) current).setPPr(paragraphStyle.getPPr());
addChildElement(parent, current, node, textStyle, paragraphStyle);
parent.getContent().add(current);
break;
case "tbody":
addTable(parent, node);
break;
case "img":
addImg(parent, current, node.attr("src"), node.attr("alt"));
break;
case "a":
addA(current, node.attr("href"), ((Element) node).text());
break;
default:
System.err.println(node.nodeName());
}
}
}
private void addChildElement(ContentAccessor parent, ContentAccessor current, Node node, TextStyle textStyle, ParagraphStyle paragraphStyle) {
for (Node child : node.childNodes()) {
addElement(parent, current, child, textStyle, paragraphStyle);
}
}
/**
* 加入文字
*
* @param current 当前行
* @param text 文本
* @param textStyle 文字样式
*/
private void addText(ContentAccessor current, String text, TextStyle textStyle) {
if (text.length() > 0) {
R r = getR(text, textStyle);
if (current instanceof P) {
P p = (P) current;
p.getContent().add(r);
}
}
}
/**
* 加入表格
*
* @param parent word区域
* @param node table元素
*/
private void addTable(ContentAccessor parent, Node node) {
// 二维元素列表
List<LinkedList<Element>> elementCollection = new ArrayList<>();
// 二维Tc列表
List<List<Tc>> tcCollection = new ArrayList<>();
// 元素坐标-偏移量
Map<TcPosition, Integer> positionOffsetMap = new HashMap<>();
// 待合并单元格
Map<TcPosition, List<TcPosition>> mergeMap = new HashMap<>();
// 拆解表格数据并分析表格合并项
disassembleAndMergeAnalysis(node, elementCollection, positionOffsetMap, mergeMap);
// TODO-表格样式解析
Tbl table = factory.createTbl();
// 采用默认表格样式
setTableStyle(table, !(parent instanceof Tc));
parent.getContent().add(table);
// 解析二维元素列表
parseTdList2Table(table, elementCollection, tcCollection);
// 单元格合并
mergeTc(mergeMap, tcCollection);
}
/**
* 拆解表格数据并分析表格合并项
*
* @param node html表格元素
* @param elementCollection 二维元素列表
* @param positionOffsetMap 元素坐标-偏移量
* @param mergeMap 待合并单元格
*/
private void disassembleAndMergeAnalysis(Node node, List<LinkedList<Element>> elementCollection, Map<TcPosition, Integer> positionOffsetMap, Map<TcPosition, List<TcPosition>> mergeMap) {
// 最大列数
int maxColNum = 0;
Elements trs = ((Element) node).getElementsByTag("tr");
List<Element> trList = new ArrayList<>();
for (Element tr : trs) {
if (tr.parent() == node) {
trList.add(tr);
}
}
for (int row = 0; row < trList.size(); row++) {
LinkedList<Element> nodeList = new LinkedList<>();
elementCollection.add(nodeList);
Element tr = trList.get(row);
Elements tds = tr.getElementsByTag("td");
List<Element> tdList = new ArrayList<>();
Iterator<Element> tdIterator = tds.iterator();
while (tdIterator.hasNext()) {
Element td = tdIterator.next();
if (td.parent() == tr) {
tdList.add(td);
}
}
maxColNum = Math.max(maxColNum, tdList.size());
for (int col = 0; col <= maxColNum; col++) {
TcPosition position = new TcPosition(row, col);
if (positionOffsetMap.containsKey(position)) {
Integer count = positionOffsetMap.get(position);
for (int i = 0; i < count; i++) {
nodeList.add(null);
}
}
if (col >= tdList.size()) {
continue;
}
Element td = tdList.get(col);
nodeList.add(td);
int rowspan = 1;
int colspan = 1;
if (td.attributes().hasKey("rowspan")) {
rowspan = Integer.parseInt(td.attributes().get("rowspan"));
}
if (td.attributes().hasKey("colspan")) {
colspan = Integer.parseInt(td.attributes().get("colspan"));
}
if (rowspan > 1 || colspan > 1) {
List<TcPosition> voidTcPositionList = new ArrayList<>();
for (int i = 0; i < rowspan; i++) {
for (int j = 0; j < colspan; j++) {
TcPosition newPosition = new TcPosition(row + i, col + j);
if (!newPosition.equals(position)) {
voidTcPositionList.add(newPosition);
}
if (i == 0 && j == 1) {
positionOffsetMap.put(newPosition, colspan - 1);
}
if (j == 0 && i > 0) {
positionOffsetMap.put(newPosition, colspan);
}
}
}
mergeMap.put(position, voidTcPositionList);
}
}
}
}
/**
* 解析二维td元素列表
*
* @param table word表格对象
* @param elementCollection 二维td元素列表
* @param tcCollection Tc对象存储
*/
private void parseTdList2Table(Tbl table, List<LinkedList<Element>> elementCollection, List<List<Tc>> tcCollection) {
for (LinkedList<Element> elementList : elementCollection) {
Tr tr = factory.createTr();
table.getContent().add(tr);
List<Tc> tcList = new ArrayList<>();
tcCollection.add(tcList);
for (Element element : elementList) {
// TODO-单元格样式解析
Tc tc = factory.createTc();
// 默认单元格样式
setTcStyle(tc);
tr.getContent().add(tc);
tcList.add(tc);
ParagraphStyle paragraphStyle = new ParagraphStyle().setLineIndentation(0L).setTcLine(true).setLineAlign("center");
if (isTableDiv(element)) {
addChildElement(tc, null, element, new TextStyle(), paragraphStyle);
// 必须增加空行,否则文件打开报错
tc.getContent().add(factory.createP());
} else if (isDivParent(element)) {
addChildElement(tc, null, element, new TextStyle(), paragraphStyle);
} else {
P p = factory.createP();
p.setPPr(paragraphStyle.getPPr());
tc.getContent().add(p);
if (null != element) {
addChildElement(tc, p, element, new TextStyle(), paragraphStyle);
}
}
}
}
}
// 表格单元格合并
private void mergeTc(Map<TcPosition, List<TcPosition>> mergeMap, List<List<Tc>> tcCollection) {
for (TcPosition startPosition : mergeMap.keySet()) {
TcPr tcpr = getTcPr(tcCollection.get(startPosition.row).get(startPosition.col));
TcPrInner.VMerge vMerge = factory.createTcPrInnerVMerge();
vMerge.setVal("restart");
tcpr.setVMerge(vMerge);
TcPrInner.HMerge hMerge = factory.createTcPrInnerHMerge();
hMerge.setVal("restart");
tcpr.setHMerge(hMerge);
List<TcPosition> continuesPositions = mergeMap.get(startPosition);
for (TcPosition continuePosition : continuesPositions) {
tcpr = getTcPr(tcCollection.get(continuePosition.row).get(continuePosition.col));
if (continuePosition.col.equals(startPosition.col)) {
vMerge = factory.createTcPrInnerVMerge();
vMerge.setVal("continue");
tcpr.setVMerge(vMerge);
hMerge = factory.createTcPrInnerHMerge();
hMerge.setVal("restart");
tcpr.setHMerge(hMerge);
} else {
hMerge = factory.createTcPrInnerHMerge();
hMerge.setVal("continue");
tcpr.setHMerge(hMerge);
}
}
}
}
/**
* 判断元素是否为table父节点
*
* @param node 元素
* @return 是否为table父节点
*/
private boolean isTableDiv(Node node) {
if (null == node) {
return false;
}
for (Node child : node.childNodes()) {
if ("table".equals(child.nodeName())) {
return true;
}
}
return false;
}
/**
* 判断元素是否为div父节点
*
* @param node 元素
* @return 是否为div父节点
*/
private boolean isDivParent(Node node) {
if (null == node) {
return false;
}
for (Node child : node.childNodes()) {
if ("div".equals(child.nodeName())) {
return true;
}
}
return false;
}
/**
* 加入图片
*
* @param parent word区域
* @param current 当前块
* @param src 图片地址
* @param alt 图片名
*/
private void addImg(ContentAccessor parent, ContentAccessor current, String src, String alt) {
if (null != src) {
try {
byte[] bytes = getRemotePic2Bytes(src);
BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordMLPackage, bytes);
Inline inline = imagePart.createImageInline(alt, alt, docPrId++, cNvPrId++, false, 5000);
Drawing drawing = factory.createDrawing();
drawing.getAnchorOrInline().add(inline);
if (current != null) {
if (current instanceof P) {
current.getContent().add(drawing);
} else {
P p = factory.createP();
current.getContent().add(p);
p.getContent().add(drawing);
}
} else {
P p = factory.createP();
parent.getContent().add(p);
p.getContent().add(drawing);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 加入超链接
*
* @param current 当前行
* @param href 链接地址
* @param text 文本
*/
private void addA(ContentAccessor current, String href, String text) {
if (null == current) {
return;
}
Relationship relationship = new org.docx4j.relationships.ObjectFactory().createRelationship();
wordMLPackage.getMainDocumentPart().getRelationshipsPart().addRelationship(relationship);
relationship.setType(Namespaces.HYPERLINK);
relationship.setTarget(href);
relationship.setTargetMode("External");
StringBuilder builder = new StringBuilder();
builder.append("<w:hyperlink r:id=\"");
builder.append(relationship.getId());
builder.append("\" xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" ");
builder.append("xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" >");
builder.append("<w:r><w:rPr><w:rStyle w:val=\"Hyperlink\" />");
builder.append("<w:rFonts w:ascii=\"");
builder.append("Times New Roman");
builder.append("\" w:hAnsi=\"");
builder.append("Times New Roman");
builder.append("\" w:eastAsia=\"");
builder.append("宋体");
builder.append("\" w:hint=\"eastAsia\"/>");
builder.append("<w:sz w:val=\"");
builder.append("24");
builder.append("\"/><w:szCs w:val=\"");
builder.append("24");
builder.append("\"/></w:rPr><w:t>");
builder.append(text);
builder.append("</w:t></w:r></w:hyperlink>");
try {
P.Hyperlink link = (P.Hyperlink) XmlUtils.unmarshalString(builder.toString());
current.getContent().add(link);
} catch (JAXBException e) {
e.printStackTrace();
}
}
private R getR(String textVal, TextStyle textStyle) {
Text text = factory.createText();
text.setValue(textVal);
R r = factory.createR();
r.setRPr(textStyle.getRPr());
r.getContent().add(text);
return r;
}
/**
* 获取远程图片转为字节数组
*
* @param picUrl 图片链接
* @return 包含图片字节数据的字节数组
*/
private static byte[] getRemotePic2Bytes(String picUrl) {
byte[] picBytes = {};
try {
if (picUrl.startsWith(IOConfig.PIC_ROUTER)) {
picUrl = picUrl.replaceFirst(IOConfig.PIC_ROUTER, IOConfig.PIC_URI);
}
URL url = new URL(picUrl);
URLConnection con = url.openConnection();
// 设置请求超时为5s
con.setConnectTimeout(5 * 1000);
// 输入流
InputStream is = con.getInputStream();
// 1K的数据缓冲
byte[] current = new byte[1024];
// 读取到的数据长度
int len;
while ((len = is.read(current)) != -1) {
picBytes = Arrays.copyOf(picBytes, picBytes.length + len);
System.arraycopy(current, 0, picBytes, picBytes.length - len, len);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return picBytes;
}
private ParagraphStyle getDivParagraphStyle(String level, String style) {
ParagraphStyle paragraphStyle = new ParagraphStyle();
if (null != level && level.trim().length() > 0) {
long lv = Long.parseLong(level.trim());
if (lv == 1L) {
paragraphStyle.setLineAlign("center");
} else {
paragraphStyle.setLineLv(lv - 2L);
}
if (lv < 4) {
paragraphStyle.setLineIndentation(0L);
}
return paragraphStyle;
} else {
Map<String, String> styleMap = styleStr2Map(style);
if (styleMap.containsKey("text-align")) {
paragraphStyle.setLineAlign(styleMap.get("text-align"));
}
}
return paragraphStyle;
}
private ParagraphStyle getListParagraphStyle(String listType, String style) {
String listStyle = styleStr2Map(style).get("list-style-type");
Long numId =1L;
if (IOConfig.NUM_MAP.containsKey(listType)) {
numId = IOConfig.NUM_MAP.get(listType);
}
Long ilv1Id = 1L;
if (IOConfig.NUM_MAP.containsKey(listStyle)) {
ilv1Id = IOConfig.NUM_MAP.get(listStyle);
}
numId = IOConfig.INIT_NUMBERING_DEFINITION.restart(numId == null ? 1L : numId, ilv1Id == null ? 1L : ilv1Id, 1L);
return new ParagraphStyle()
.setList(true)
.setNumId(numId).setIlv1Id(ilv1Id);
}
private ParagraphStyle getTableCaptionParagraphStyle() {
return new ParagraphStyle().setLineAlign("center").setLineIndentation(0L);
}
private TextStyle getDivTextStyle(String level) {
TextStyle textStyle = new TextStyle();
if (null != level && level.trim().length() > 0) {
switch (level.trim()) {
case "1":
textStyle.setFontSize("24px").setBold(true).setEastAsiaFont("黑体");
break;
case "2":
textStyle.setFontSize("18px").setBold(true).setEastAsiaFont("黑体");
break;
default:
}
}
return textStyle;
}
private TextStyle getSpanTextStyle(TextStyle textStyle, String style) {
textStyle = new TextStyle(textStyle);
Map<String, String> spanStyleMap = styleStr2Map(style);
for (String key : spanStyleMap.keySet()) {
switch (key.trim().toLowerCase()) {
case "text-decoration":
textStyle.setUnderscore(true);
break;
case "color":
textStyle.setFontColor(spanStyleMap.get(key));
break;
case "font-size":
textStyle.setFontSize(spanStyleMap.get(key));
break;
default:
System.err.println(key);
break;
}
}
return textStyle;
}
/**
* 设置表格默认样式
*
* @param table 表格对象
* @param needInd 是否缩进
*/
private void setTableStyle(Tbl table, boolean needInd) {
TblPr tablePr = factory.createTblPr();
table.setTblPr(tablePr);
TblBorders borders = factory.createTblBorders();
tablePr.setTblBorders(borders);
CTBorder border = new CTBorder();
border.setColor("auto");
border.setSz(new BigInteger("4"));
border.setSpace(new BigInteger("0"));
border.setVal(STBorder.SINGLE);
borders.setBottom(border);
borders.setLeft(border);
borders.setRight(border);
borders.setTop(border);
borders.setInsideH(border);
borders.setInsideV(border);
if (needInd) {
TblWidth tblInd = factory.createTblWidth();
tblInd.setW(new BigInteger("600"));
tablePr.setTblInd(tblInd);
}
}
/**
* 设置表格默认样式
*
* @param tc 单元格格对象
*/
private void setTcStyle(Tc tc) {
CTVerticalJc vjc = factory.createCTVerticalJc();
vjc.setVal(STVerticalJc.CENTER);
getTcPr(tc).setVAlign(vjc);
}
private TcPr getTcPr(Tc tc) {
TcPr tcpr = tc.getTcPr();
if (null == tcpr) {
tcpr = factory.createTcPr();
tc.setTcPr(tcpr);
}
return tcpr;
}
/**
* style属性字符串转map
*
* @param style style属性值
* @return Map
*/
private static Map<String, String> styleStr2Map(String style) {
Map<String, String> styleMap = new HashMap<>();
if (null != style) {
String[] styleItems = style.split(";");
for (String styleItem : styleItems) {
String[] styleEntry = styleItem.split(":");
if (styleEntry.length == 2) {
styleMap.put(styleEntry[0].trim(), styleEntry[1].trim());
}
}
}
return styleMap;
}
/**
* 文本样式
*/
@Data
@Accessors(chain = true)
class TextStyle {
// 加粗
private boolean bold;
// 斜体
private boolean italic;
// 下划线
private boolean underscore;
// 角标
private String textScript;
// 中文字体
private String asciiFont = "Times New Roman";
// 英文字体
private String eastAsiaFont = "宋体";
// 字体大小
private String fontSize = "16px";
// 字体颜色
private String fontColor;
TextStyle() {
}
TextStyle(TextStyle old) {
this.setBold(old.bold)
.setFontColor(old.fontColor)
.setFontSize(old.fontSize)
.setItalic(old.italic)
.setUnderscore(old.underscore)
.setTextScript(old.textScript);
}
RPr getRPr() {
RPr rpr = factory.createRPr();
// 字体
RFonts font = new RFonts();
rpr.setRFonts(font);
font.setAscii(asciiFont);
font.setEastAsia(eastAsiaFont);
// 字号
HpsMeasure measure = new HpsMeasure();
rpr.setSzCs(measure);
rpr.setSz(measure);
measure.setVal(BigInteger.valueOf((Long.parseLong(fontSize.toLowerCase().replaceAll("px", "")) - 4) * 2));
// 加粗/斜体/下划线
if (this.bold) {
rpr.setB(new BooleanDefaultTrue());
}
if (this.italic) {
rpr.setI(new BooleanDefaultTrue());
}
if (this.underscore) {
U u = factory.createU();
u.setVal(UnderlineEnumeration.SINGLE);
rpr.setU(u);
}
// 字体颜色
Color color = factory.createColor();
rpr.setColor(color);
color.setVal(this.fontColor);
// 设置角标
if (null != this.textScript) {
CTVerticalAlignRun ctVerticalAlignRun = factory.createCTVerticalAlignRun();
STVerticalAlignRun stVerticalAlignRun = STVerticalAlignRun.fromValue(textScript);
ctVerticalAlignRun.setVal(stVerticalAlignRun);
rpr.setVertAlign(ctVerticalAlignRun);
}
return rpr;
}
}
/**
* 段落样式
*/
@Data
@Accessors(chain = true)
class ParagraphStyle {
// 缩进
private Long lineIndentation = 200L;
// 对齐方式
private String lineAlign = "left";
// 大纲级别
private Long lineLv;
private boolean isTcLine;
// 是否为列表
private boolean list;
// 列表样式
private Long numId;
private Long ilv1Id;
PPr getPPr() {
PPr ppr = factory.createPPr();
// 列表样式
if (this.list) {
PPrBase.NumPr numPr = factory.createPPrBaseNumPr();
ppr.setNumPr(numPr);
// The <w:numId> element
PPrBase.NumPr.NumId numIdElement = factory.createPPrBaseNumPrNumId();
numPr.setNumId(numIdElement);
numIdElement.setVal(BigInteger.valueOf(this.numId));
// The <w:ilv> element
PPrBase.NumPr.Ilvl ilvlElement = factory.createPPrBaseNumPrIlvl();
numPr.setIlvl(ilvlElement);
ilvlElement.setVal(BigInteger.valueOf(this.ilv1Id));
}
// 文本对齐
Jc jc = factory.createJc();
ppr.setJc(jc);
switch (lineAlign) {
case "center":
jc.setVal(JcEnumeration.CENTER);
break;
case "right":
jc.setVal(JcEnumeration.RIGHT);
break;
default:
jc.setVal(JcEnumeration.LEFT);
}
// 首行缩进
PPrBase.Ind ind = factory.createPPrBaseInd();
ppr.setInd(ind);
ind.setFirstLineChars(BigInteger.valueOf(lineIndentation));
// 大纲级别
if (null != lineLv) {
PPrBase.OutlineLvl outlineLvl = factory.createPPrBaseOutlineLvl();
ppr.setOutlineLvl(outlineLvl);
outlineLvl.setVal(BigInteger.valueOf(this.lineLv));
}
PPrBase.Spacing spacing = factory.createPPrBaseSpacing();
// 行间距 [自动auto] [最小atLeast] [固定exact 1磅=20 1行=100 单倍行距=240]
spacing.setLineRule(STLineSpacingRule.AUTO);
if (isTcLine) {
spacing.setBefore(BigInteger.valueOf(100L));
spacing.setAfter(BigInteger.valueOf(100L));
}
ppr.setSpacing(spacing);
return ppr;
}
}
/**
* 表格单元格坐标
*/
class TcPosition {
private Integer row;
private Integer col;
public TcPosition(Integer row, Integer col) {
this.row = row;
this.col = col;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TcPosition)) {
return false;
}
TcPosition that = (TcPosition) o;
return Objects.equals(row, that.row) &&
Objects.equals(col, that.col);
}
@Override
public int hashCode() {
return Objects.hash(row, col);
}
}
}
package com.yeejoin.amos.knowledgebase.face.util.word;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.xmlbeans.XmlException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class wordToHtml {
private static List<Integer> titleList = new ArrayList<>();
public static String wordParase(MultipartFile file) throws IOException, XmlException, ParserConfigurationException, TransformerException {
String filesuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
if (".docx".equals(filesuffix) || ".DOCX".equals(filesuffix)) {
return uploadDocXFile(file);
} else {
return uploadDocFile(file);
}
}
public static String wordReplaceTag(String htmlString, String fileName) {
String filename = fileName.substring(0, fileName.lastIndexOf("."));
String filesuffix = fileName.substring(fileName.lastIndexOf("."));
if (".docx".equals(filesuffix) || ".DOCX".equals(filesuffix)) {
return docXReplaceTag(htmlString, filename);
} else {
return docReplaceTag(htmlString, filename);
}
}
//docx上传并转html
private static String uploadDocXFile(MultipartFile file) throws IOException {
InputStream inputStream = file.getInputStream();
XWPFDocument wordDocument = new XWPFDocument(inputStream);
List<XWPFParagraph> paragraphs = wordDocument.getParagraphs();
titleList = new ArrayList<>();
for (XWPFParagraph para : paragraphs) {
String titlelevel = para.getStyleID();
if (!ValidationUtil.isEmpty(titlelevel) && isInteger(titlelevel) && Integer.parseInt(titlelevel) < 6) {
titleList.add(Integer.parseInt(titlelevel));
}
}
//上传图片
XHTMLOptions options = XHTMLOptions.create();
// 设置图片存储路径
String path = System.getProperty("java.io.tmpdir");
String firstImagePathStr = path + System.currentTimeMillis();
options.setExtractor(new FileImageExtractor(new File(firstImagePathStr)));
options.URIResolver(new BasicURIResolver(firstImagePathStr));
// 将Word文档转换为HTML文档
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XHTMLConverter.getInstance().convert(wordDocument, outputStream, options);
String html = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
// 将image文件转换为base64并替换到html字符串里
String middleImageDirStr = "/word/media";
String imageDirStr = firstImagePathStr + middleImageDirStr;
File imageDir = new File(imageDirStr);
String[] imageList = imageDir.list();
if (imageList != null) {
for (int i = 0; i < imageList.length; i++) {
String oneImagePathStr = imageDirStr + "/" + imageList[i];
MultipartFile multipartFile = getMulFileByPath(oneImagePathStr);
Map<String, String> imgResult = Systemctl.fileStorageClient.updateCommonFile(multipartFile).getResult();
String imageUrl = "";
if (!ValidationUtil.isEmpty(imgResult) && imgResult.keySet().iterator().hasNext()) {
imageUrl = imgResult.keySet().iterator().next();
}
//修改文档中的图片信息
html = html.replace(oneImagePathStr, imageUrl);
}
}
//删除图片路径
File firstImagePath = new File(firstImagePathStr);
FileUtils.deleteDirectory(firstImagePath);
// 关闭流
outputStream.close();
wordDocument.close();
return html;
}
//doc上传并转html
private static String uploadDocFile(MultipartFile file) throws IOException, ParserConfigurationException, TransformerException {
HWPFDocument wordDocument = new HWPFDocument(file.getInputStream());
Range range = wordDocument.getRange();
titleList = new ArrayList<>();
for (int i = 0; i < range.numParagraphs(); i++) {
Paragraph para = range.getParagraph(i);
int level = para.getStyleIndex();
String text = para.text();
if (!ValidationUtil.isEmpty(level) && level > 0 && level <= 6) {
// 如果该段落为标题,获取标题信息
para.replaceText(text+"#标题" + level + "#", true);
titleList.add(para.getLvl() + 1);
}
}
WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
//将读取到的图片上传并添加链接地址
wordToHtmlConverter.setPicturesManager((imageStream, pictureType, name, width, height) -> {
String imageUrl = "";
try {
Map<String, String> imgResult = Systemctl.fileStorageClient.updateCommonFile(encodeToMultipartFile(imageStream)).getResult();
if (!ValidationUtil.isEmpty(imgResult) && imgResult.keySet().iterator().hasNext()) {
imageUrl = imgResult.keySet().iterator().next();
}
} catch (Exception e) {
e.printStackTrace();
}
return imageUrl;
});
wordToHtmlConverter.processDocument(wordDocument);
org.w3c.dom.Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(out);
//通过TransformerFactory创造出Transformer ,并设置Transformer的属性
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "html");
//开始转换,结果数据在ByteArrayOutputStream里
transformer.transform(domSource, streamResult);
String html = new String(out.toByteArray(), StandardCharsets.UTF_8);
// 关闭流
out.close();
wordDocument.close();
return html;
}
private static Elements findTitels(Document doc, String className) {
//找到标题所在的标签
return doc.body().select("p." + className);
}
//docX转html后,标题的节点标签转换
public static String docXReplaceTag(String htmlString, String fileName) {
// 使用jsoup解析HTML文档
Document docx = Jsoup.parse(htmlString);
Collections.sort(titleList);
Boolean isAddTitle = false;
int start = 1;
if (!ValidationUtil.isEmpty(titleList)) {
Elements firstTitle = findTitels(docx, "X" + titleList.get(0));
if (!ValidationUtil.isEmpty(firstTitle)) {
Element firstEle = docx.body().children().get(0).children().first();
if (!firstTitle.equals(firstEle)) {
isAddTitle = true;
}
}
if (!ValidationUtil.isEmpty(titleList)) {
start = titleList.get(0);
if (titleList.get(0).equals(titleList.get(1))) {
isAddTitle = true;
}
}
} else {
isAddTitle = true;
}
if (!ValidationUtil.isEmpty(titleList)) {
for (int i = start; i < start + 10; i++) {
Elements titelsSingle = findTitels(docx, "X" + i);
for (Element heading : titelsSingle) {
heading.tagName("div");
if (!ValidationUtil.isEmpty(heading.children())) {
int level = isAddTitle ? i - start + 2 : i - start + 1;
heading.attr("class", "clib-writefile-tag-text title-h" + level);
heading.attr("data-level", String.valueOf(level));
String eleId = level == 1 ? "1" : String.valueOf(UUID.randomUUID()).replace("-", "").toLowerCase();
heading.attr("id", eleId);
heading.removeAttr("style");
Element titelH = new Element("h" + level).attr("id", eleId);
titelH.text(heading.children().text());
heading.html("").appendChild(titelH);
}
}
}
}
//添加根节点
if (isAddTitle) {
Element root = new Element("div")
.attr("class", "clib-writefile-tag-text title-h1")
.attr("data-level", "1")
.attr("id", "1");
Element titelH = new Element("h1").attr("id", "1").text(fileName);
root.appendChild(titelH);
docx.body().children().get(0).children().get(0).before(root);
}
return docx.body().children().html().replaceAll("\n", "");
}
//doc转html后,标题的节点标签转换
private static String docReplaceTag(String htmlString, String fileName) {
// 使用jsoup解析HTML文档
Document doc = Jsoup.parse(htmlString);
//内部样式转行内样式
doc = formatHtmlRowCss(doc);
Collections.sort(titleList);
Boolean isAddTitle = false;
int start = 1;
if (!ValidationUtil.isEmpty(titleList)) {
Elements firstTitle = findTitels(doc, "p" + titleList.get(0));
if (!ValidationUtil.isEmpty(firstTitle)) {
Element firstEle = doc.body().children().first();
if (!firstTitle.get(0).equals(firstEle)) {
isAddTitle = true;
}
}
if (!ValidationUtil.isEmpty(titleList)) {
start = titleList.get(0);
if (titleList.get(0).equals(titleList.get(1))) {
isAddTitle = true;
}
}
} else {
isAddTitle = true;
}
if (!ValidationUtil.isEmpty(titleList)) {
for (int i = start; i < start + 10; i++) {
Elements titelsSingle = doc.body().select("span:contains(#标题" + i + "#)");
for (Element heading : titelsSingle) {
int level = isAddTitle ? i - start + 2 : i - start + 1;
String eleId = level == 1 ? "1" : String.valueOf(UUID.randomUUID()).replace("-", "").toLowerCase();
Element parentElement = heading.parent().tag().getName().equals("p") ? heading.parent() : heading.parent().parent();
if (!ValidationUtil.isEmpty(parentElement)) {
Element parent = parentElement;
parent.tagName("div");
parent.attr("class", "clib-writefile-tag-text title-h" + level);
parent.attr("data-level", String.valueOf(level));
parent.attr("id", eleId);
parent.removeAttr("style");
Element titelH = new Element("h" + level).attr("id", eleId);
titelH.text(parent.children().text().replaceFirst("#标题" + i + "#", ""));
parent.html("").appendChild(titelH);
}
}
}
}
//添加根节点
if (isAddTitle) {
Element root = new Element("div")
.attr("class", "clib-writefile-tag-text title-h1")
.attr("data-level", "1")
.attr("id", "1");
Element titelH = new Element("h1").attr("id", "1").text(fileName);
root.appendChild(titelH);
doc.body().children().get(0).before(root);
}
return doc.body().html().replaceAll("\n", "");
}
/**
* 获取MultipartFile文件
*
* @param picPath
* @return
*/
private static MultipartFile getMulFileByPath(String picPath) {
FileItem fileItem = createFileItem(picPath);
MultipartFile mfile = new CommonsMultipartFile(fileItem);
return mfile;
}
private static FileItem createFileItem(String filePath) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName" + extFile);
File newfile = new File(filePath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
/**
* byte 转换为 MultipartFile
*
* @param bytes
* @return
*/
private static MultipartFile encodeToMultipartFile(byte[] bytes) {
MultipartFile multipartFile = null;
InputStream input = null;
OutputStream outputStream = null;
File tempFile = null;
try {
String path = System.getProperty("java.io.tmpdir");
String firstImagePathStr = path + System.currentTimeMillis();
File file = new File(firstImagePathStr);
file.mkdirs();
firstImagePathStr = firstImagePathStr + System.currentTimeMillis() + ".png";
tempFile = new File(firstImagePathStr);
tempFile.createNewFile();
// 把 byte 转换为 File 文件
getFileByBytes(bytes, firstImagePathStr);
// 第一个参数 fieldName 就是文件上传的 name
FileItem fileItem = new DiskFileItem("uploadFile", Files.probeContentType(tempFile.toPath()), false, tempFile.getName(), (int) tempFile.length(), tempFile.getParentFile());
input = new FileInputStream(tempFile);
outputStream = fileItem.getOutputStream();
IOUtils.copy(input, outputStream);
multipartFile = new CommonsMultipartFile(fileItem);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
input.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 删除这个 File
if (tempFile.exists()) {
tempFile.delete();
}
return multipartFile;
}
/**
* byte [] 转换为 File
*
* @param bytes
* @param filePath
*/
private static void getFileByBytes(byte[] bytes, String filePath) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
// 判断文件目录是否存在
if (!dir.exists() && dir.isDirectory()) {
dir.mkdirs();
}
file = new File(filePath);
//输出流
fos = new FileOutputStream(file);
//缓冲流
bos = new BufferedOutputStream(fos);
//将字节数组写出
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static Document formatHtmlRowCss(Document doc) {
String allcss = doc.getElementsByTag("style").html();
Map<String, String> styleMap = new HashMap<>();
Pattern pattern = Pattern.compile("\\.(\\w+)\\{(?s)(.+?)\\}");
Matcher matcher = pattern.matcher(allcss);
while (matcher.find()) {
styleMap.put(matcher.group(1), matcher.group(2));
}
return replaceClass(styleMap, doc);
}
private static Document replaceClass(Map<String, String> styMap, Document doc) {
Elements anyClass = doc.getElementsByAttribute("class");
for (Element element : anyClass) {
String aClass = element.attr("class");
System.out.println(aClass);
String[] classStrs = (aClass.split(" "));
for (String classStr : classStrs) {
element.attr("style", element.attr("style") + styMap.get(classStr));
}
element.removeAttr("class");
}
return doc;
}
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
}
...@@ -21,6 +21,29 @@ ...@@ -21,6 +21,29 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- 解析excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 针对2007以上版本的库 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<!-- 针对2003版本的库 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment