Commit 11aa2cb8 by 林永健

feat(financial): 添加财资标签与汇总报表功能

- 新增 NbCbAccDetailTagSummaryRemote 远程接口及其实现
- 新增财资标签管理相关控制器、请求响应类和数据传输对象
- 在财资明细相关页面添加标签路径和财务报表口径字段
- 实现财资明细打标签、标签树查询和汇总报表生成功能
- 添加多sheet动态Excel导出工具方法
- 在财资明细查询中增加标签和财务口径筛选条件
- 实现财务报表口径汇总统计功能
1 parent 130c17d3
Showing 26 changed files with 2569 additions and 17 deletions
...@@ -2,8 +2,11 @@ package cn.com.glsx.dj.financial.dto; ...@@ -2,8 +2,11 @@ package cn.com.glsx.dj.financial.dto;
import cn.com.glsx.dj.financial.model.NbCbAccDetail; import cn.com.glsx.dj.financial.model.NbCbAccDetail;
import cn.com.glsx.dj.financial.model.NbCbDetailLog; import cn.com.glsx.dj.financial.model.NbCbDetailLog;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.List; import java.util.List;
...@@ -16,6 +19,9 @@ import java.util.List; ...@@ -16,6 +19,9 @@ import java.util.List;
*/ */
@Data @Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@ApiModel(value = "NbCbAccDetailDTO", description = "财资明细查询与响应DTO")
public class NbCbAccDetailDTO extends NbCbAccDetail { public class NbCbAccDetailDTO extends NbCbAccDetail {
/** /**
...@@ -107,4 +113,34 @@ public class NbCbAccDetailDTO extends NbCbAccDetail { ...@@ -107,4 +113,34 @@ public class NbCbAccDetailDTO extends NbCbAccDetail {
@ApiModelProperty(name = "custType", notes = "主体类型:1-广联 2-优加", dataType = "Integer") @ApiModelProperty(name = "custType", notes = "主体类型:1-广联 2-优加", dataType = "Integer")
private Integer custType; private Integer custType;
/**
* 财资标签路径名称
*/
@ApiModelProperty(value = "财资标签路径名称")
private String accDetailTagPathName;
/**
* 财务报表口径
*/
@ApiModelProperty(value = "财务报表口径")
private String financialReportCaliber;
/**
* 财资标签名称
*/
@ApiModelProperty(value = "财资标签名称")
private String accDetailTagName;
/**
* 财资标签可选项
*/
@ApiModelProperty(value = "财资标签可选项")
private List<NbCbAccDetailTagDTO> accDetailTagOptions;
/**
* 财务报表口径可选项
*/
@ApiModelProperty(value = "财务报表口径可选项")
private List<String> financialReportCaliberOptions;
} }
package cn.com.glsx.dj.financial.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 财资汇总报表数据
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailSummaryReportDTO", description = "财资明细汇总报表数据")
public class NbCbAccDetailSummaryReportDTO implements Serializable {
private static final long serialVersionUID = 689839078122878619L;
@ApiModelProperty(value = "sheet集合")
private List<NbCbAccDetailSummarySheetDTO> sheets;
}
package cn.com.glsx.dj.financial.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* 财资汇总报表查询DTO
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailSummaryReportQueryDTO", description = "财资明细汇总报表查询DTO")
public class NbCbAccDetailSummaryReportQueryDTO implements Serializable {
private static final long serialVersionUID = -4446227866762693837L;
@ApiModelProperty(value = "开始日期")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date startDate;
@ApiModelProperty(value = "结束日期")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date endDate;
@ApiModelProperty(value = "操作人")
private String operator;
}
package cn.com.glsx.dj.financial.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 财资汇总报表单个Sheet数据
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailSummarySheetDTO", description = "财资明细汇总报表单个Sheet数据")
public class NbCbAccDetailSummarySheetDTO implements Serializable {
private static final long serialVersionUID = -3203482997334312780L;
@ApiModelProperty(value = "sheet名称")
private String sheetName;
@ApiModelProperty(value = "表头列")
private List<String> columns;
@ApiModelProperty(value = "表格数据")
private List<List<Object>> rows;
}
package cn.com.glsx.dj.financial.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* 财资明细打标签请求 DTO。
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailTagBindDTO", description = "财资明细打标签请求DTO")
public class NbCbAccDetailTagBindDTO implements Serializable {
private static final long serialVersionUID = -1352164927777449325L;
@ApiModelProperty(value = "明细ID集合,单条传一个元素,批量传多个元素", required = true)
private List<Long> detailIds;
@ApiModelProperty(value = "三级标签ID,传空表示解绑")
private Integer accDetailTagId;
@ApiModelProperty(value = "操作人")
private String operator;
}
package cn.com.glsx.dj.financial.dto;
import cn.com.glsx.dj.financial.model.NbCbAccDetailTag;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.List;
/**
* 财资标签 DTO。
*
*
*/
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@ApiModel(value = "NbCbAccDetailTagDTO", description = "财资标签DTO")
public class NbCbAccDetailTagDTO extends NbCbAccDetailTag {
private static final long serialVersionUID = 1879806618653593395L;
@ApiModelProperty(value = "子节点列表")
private List<NbCbAccDetailTagDTO> children;
}
package cn.com.glsx.dj.financial.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 财资标签操作预检查结果。
*
* 用于保存前确认、删除前确认等前置交互场景。
*/
@Data
@ApiModel(value = "NbCbAccDetailTagOperationPreviewDTO", description = "财资标签操作预检查结果DTO")
public class NbCbAccDetailTagOperationPreviewDTO implements Serializable {
private static final long serialVersionUID = -1971499528885768320L;
@ApiModelProperty(value = "是否需要前端弹出确认提示")
private Boolean confirmRequired;
@ApiModelProperty(value = "确认或提示文案")
private String message;
}
package cn.com.glsx.dj.financial.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 财资标签树查询 DTO。
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailTagQueryDTO", description = "财资标签树查询DTO")
public class NbCbAccDetailTagQueryDTO implements Serializable {
private static final long serialVersionUID = 7263672632754205678L;
@ApiModelProperty(value = "节点ID")
private Integer id;
@ApiModelProperty(value = "父节点ID")
private Integer parentId;
@ApiModelProperty(value = "层级")
private Integer level;
@ApiModelProperty(value = "名称模糊查询")
private String nameLike;
@ApiModelProperty(value = "路径查询条件,查询当前路径节点及全部子孙节点")
private String path;
@ApiModelProperty(value = "是否按节点ID查询当前节点及全部子孙节点,需配合id使用")
private Boolean descendantOfId;
@ApiModelProperty(value = "是否为结果补齐全部祖先节点")
private Boolean appendAncestors;
@ApiModelProperty(value = "是否仅返回完整三级标签")
private Boolean onlyComplete;
}
...@@ -14,6 +14,7 @@ public enum AccDetailOperationTypeEnum { ...@@ -14,6 +14,7 @@ public enum AccDetailOperationTypeEnum {
PUSH_RECEIPT((byte)7,"推送回单"), PUSH_RECEIPT((byte)7,"推送回单"),
REPUSH_DETAIL((byte)8,"重推流水明细"), REPUSH_DETAIL((byte)8,"重推流水明细"),
REPUSH_RECEIPT((byte)9,"重推回单"), REPUSH_RECEIPT((byte)9,"重推回单"),
EDIT_CUSTOM_TAG((byte)10,"编辑自定义标签"),
; ;
private byte value; private byte value;
......
...@@ -251,6 +251,12 @@ public class NbCbAccDetail implements Serializable { ...@@ -251,6 +251,12 @@ public class NbCbAccDetail implements Serializable {
private String labelValue4; private String labelValue4;
/** /**
* 财资自定义标签ID
*/
@Column(name = "acc_detail_tag_id")
private Integer accDetailTagId;
/**
* 排序规则 * 排序规则
*/ */
@Column(name = "sort_rule") @Column(name = "sort_rule")
......
package cn.com.glsx.dj.financial.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
* 财资标签目录。
*
*
*/
@Data
@ApiModel(value = "NbCbAccDetailTag", description = "财资标签目录")
@Table(name = "nb_cb_acc_detail_tag")
public class NbCbAccDetailTag implements Serializable {
private static final long serialVersionUID = 8253168219092092100L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ApiModelProperty(value = "主键ID")
private Integer id;
@ApiModelProperty(value = "标签名称")
private String name;
@Column(name = "parent_id")
@ApiModelProperty(value = "父节点ID")
private Integer parentId;
@ApiModelProperty(value = "标签层级")
private Integer level;
@ApiModelProperty(value = "ID路径")
private String path;
@Column(name = "path_name")
@ApiModelProperty(value = "名称路径")
private String pathName;
@Column(name = "financial_report_caliber")
@ApiModelProperty(value = "财务报表口径")
private String financialReportCaliber;
@Column(name = "sort_num")
@ApiModelProperty(value = "排序值")
private Integer sortNum;
@ApiModelProperty(value = "状态:1启用,0停用")
private Integer status;
@ApiModelProperty(value = "备注")
private String remark;
@Column(name = "created_date")
@ApiModelProperty(value = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
@Column(name = "created_by")
@ApiModelProperty(value = "创建人")
private String createdBy;
@Column(name = "updated_date")
@ApiModelProperty(value = "更新时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date updatedDate;
@Column(name = "updated_by")
@ApiModelProperty(value = "更新人")
private String updatedBy;
@Column(name = "deleted_flag")
@ApiModelProperty(value = "删除标记")
private String deletedFlag;
}
...@@ -36,9 +36,10 @@ public class NbCbDetailLog implements Serializable { ...@@ -36,9 +36,10 @@ public class NbCbDetailLog implements Serializable {
private Byte logType; private Byte logType;
/** /**
* 操作项 1-重推财资数据 2-推送财资数据 3-获取财资数据 4-获取流水明细 5-获取回单 6-推送流水明细 7-推送回单 8-重推流水明细 9-重推回单 * 操作项 1-重推财资数据 2-推送财资数据 3-获取财资数据 4-获取流水明细 5-获取回单
* 6-推送流水明细 7-推送回单 8-重推流水明细 9-重推回单 10-编辑自定义标签
*/ */
@ApiModelProperty(notes = "操作项 1-重推财资数据 2-推送财资数据 3-获取财资数据 4-获取流水明细 5-获取回单 6-推送流水明细 7-推送回单 8-重推流水明细 9-重推回单") @ApiModelProperty(notes = "操作项 1-重推财资数据 2-推送财资数据 3-获取财资数据 4-获取流水明细 5-获取回单 6-推送流水明细 7-推送回单 8-重推流水明细 9-重推回单 10-编辑自定义标签")
@Column(name = "operation_type") @Column(name = "operation_type")
private Byte operationType; private Byte operationType;
......
package cn.com.glsx.dj.financial.remote;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailSummaryReportDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailSummaryReportQueryDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagBindDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagOperationPreviewDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagQueryDTO;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
import cn.com.glsx.framework.core.annotation.ApiService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* 财资标签与汇总报表远程接口。
*
*
*/
@ApiService(value = "财资标签与汇总报表接口", owner = "lyj", protocol = ApiService.ProtocolEnum.dubbo, version = "1.0.0")
public interface NbCbAccDetailTagSummaryRemote {
@ApiMethod("查询财资标签树")
@ApiParam(name = "queryDTO", notes = "标签树查询条件", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("财资标签树")
RpcResponse<List<NbCbAccDetailTagDTO>> queryTagTree(@NotNull NbCbAccDetailTagQueryDTO queryDTO);
@ApiMethod("保存财资标签")
@ApiParam(name = "tagDTO", notes = "标签信息", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("保存结果")
RpcResponse<Integer> saveTag(@NotNull NbCbAccDetailTagDTO tagDTO);
@ApiMethod("财资标签保存前预检查")
@ApiParam(name = "tagDTO", notes = "标签信息", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("预检查结果")
RpcResponse<NbCbAccDetailTagOperationPreviewDTO> previewSaveTag(@NotNull NbCbAccDetailTagDTO tagDTO);
@ApiMethod("删除财资标签")
@ApiParam(name = "tagDTO", notes = "标签信息", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("删除结果")
RpcResponse<Boolean> deleteTag(@NotNull NbCbAccDetailTagDTO tagDTO);
@ApiMethod("财资标签删除前预检查")
@ApiParam(name = "tagDTO", notes = "标签信息", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("预检查结果")
RpcResponse<NbCbAccDetailTagOperationPreviewDTO> previewDeleteTag(@NotNull NbCbAccDetailTagDTO tagDTO);
@ApiMethod("财资明细打标签")
@ApiParam(name = "bindDTO", notes = "打标签参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("打标签结果")
RpcResponse<Boolean> bindDetailTag(@NotNull NbCbAccDetailTagBindDTO bindDTO);
@ApiMethod("生成财资汇总报表数据")
@ApiParam(name = "queryDTO", notes = "汇总报表查询条件", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("汇总报表数据")
RpcResponse<NbCbAccDetailSummaryReportDTO> buildAccDetailSummaryReport(@NotNull NbCbAccDetailSummaryReportQueryDTO queryDTO);
}
...@@ -3,6 +3,7 @@ package cn.com.glsx.dj.financial.mapper; ...@@ -3,6 +3,7 @@ package cn.com.glsx.dj.financial.mapper;
import cn.com.glsx.dj.financial.dto.NbCbAccAssociationDTO; import cn.com.glsx.dj.financial.dto.NbCbAccAssociationDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailDTO; import cn.com.glsx.dj.financial.dto.NbCbAccDetailDTO;
import cn.com.glsx.dj.financial.model.NbCbAccDetail; import cn.com.glsx.dj.financial.model.NbCbAccDetail;
import cn.com.glsx.dj.financial.service.nb.NbCbAccDetailTagAmountSummary;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.ResultMap;
...@@ -54,6 +55,20 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> { ...@@ -54,6 +55,20 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> {
List<NbCbAccDetail> queryByIds(@Param("ids") List<Long> ids); List<NbCbAccDetail> queryByIds(@Param("ids") List<Long> ids);
/** /**
* 更新明细自定义标签。
*
* @param ids 明细ID
* @param accDetailTagId 自定义标签ID,传空表示解绑
* @param updatedBy 更新人
* @param updatedDate 更新时间
* @return 更新条数
*/
Integer updateAccDetailTagBatch(@Param("ids") List<Long> ids,
@Param("accDetailTagId") Integer accDetailTagId,
@Param("updatedBy") String updatedBy,
@Param("updatedDate") Date updatedDate);
/**
* 查询回单关联的交易明细列表 * 查询回单关联的交易明细列表
* *
* @param receiptIds * @param receiptIds
...@@ -62,6 +77,16 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> { ...@@ -62,6 +77,16 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> {
List<NbCbAccDetail> queryByReceiptIds(@Param("receiptIds") List<Long> receiptIds); List<NbCbAccDetail> queryByReceiptIds(@Param("receiptIds") List<Long> receiptIds);
/** /**
* 查询指定时间范围内的标签月度汇总结果
*
* @param startDateTime 开始时间
* @param endDateTime 结束时间
* @return 汇总结果
*/
List<NbCbAccDetailTagAmountSummary> queryTagAmountSummary(@Param("startDateTime") String startDateTime,
@Param("endDateTime") String endDateTime);
/**
* 查询账号指定日期的余额 * 查询账号指定日期的余额
* *
* @param accList * @param accList
...@@ -81,6 +106,26 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> { ...@@ -81,6 +106,26 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> {
List<NbCbAccDetail> queryRealCustomerTrans(@Param("accList") List<String> accList, @Param("innerAccList") List<String> innerAccList, @Param("beginDate") Date beginDate, @Param("endDate") Date endDate); List<NbCbAccDetail> queryRealCustomerTrans(@Param("accList") List<String> accList, @Param("innerAccList") List<String> innerAccList, @Param("beginDate") Date beginDate, @Param("endDate") Date endDate);
/** /**
* 查询内部往来检验明细
*
* @param accountNos 内部账号范围
* @param startDateTime 开始时间
* @param endDateTime 结束时间
* @return 明细列表
*/
List<NbCbAccDetail> queryInternalTransactions(@Param("accountNos") List<String> accountNos,
@Param("startDateTime") String startDateTime,
@Param("endDateTime") String endDateTime);
/**
* 统计标签已被引用的明细数量
*
* @param tagIds 标签ID列表
* @return 明细数量
*/
Integer countByAccDetailTagIds(@Param("tagIds") List<Integer> tagIds);
/**
* 通过回单id反查交易明细 * 通过回单id反查交易明细
* *
* @param receiptIds * @param receiptIds
...@@ -136,4 +181,4 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> { ...@@ -136,4 +181,4 @@ public interface NbCbAccDetailMapper extends OreMapper<NbCbAccDetail> {
* @return * @return
*/ */
List<NbCbAccDetail> queryNeedToSyncH5FileDetailList(); List<NbCbAccDetail> queryNeedToSyncH5FileDetailList();
}
\ No newline at end of file \ No newline at end of file
}
package cn.com.glsx.dj.financial.mapper;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagQueryDTO;
import cn.com.glsx.dj.financial.model.NbCbAccDetailTag;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
/**
* 财资明细标签 Mapper。
*
*
*/
@Mapper
public interface NbCbAccDetailTagMapper extends OreMapper<NbCbAccDetailTag> {
/**
* 按条件查询标签树节点。
*
* @param queryDTO 标签树查询条件
* @return 标签列表
*/
List<NbCbAccDetailTag> queryTagTreeByCondition(@Param("query") NbCbAccDetailTagQueryDTO queryDTO);
/**
* 查询全部有效标签。
*
* @return 标签列表
*/
List<NbCbAccDetailTag> listAllActiveTags();
/**
* 根据ID集合查询标签
*
* @param ids ID集合
* @return 标签列表
*/
List<NbCbAccDetailTag> listByIds(@Param("ids") List<Integer> ids);
/**
* 统计子标签数量。
*
* @param tagId 标签 ID
* @return 子标签数量
*/
Integer countChildTag(@Param("tagId") Integer tagId);
/**
* 统计当前节点下的全部子孙标签数量
*
* @param pathPrefix 路径前缀
* @return 子孙标签数量
*/
Integer countDescendantTag(@Param("pathPrefix") String pathPrefix);
/**
* 查询当前路径下的全部三级标签ID
*
* @param pathPrefix 路径前缀
* @return 三级标签ID集合
*/
List<Integer> listLeafTagIdsByPathPrefix(@Param("pathPrefix") String pathPrefix);
/**
* 按同父级同层级统计重名标签数
*
* @param currentId 当前标签ID
* @param parentId 父节点ID
* @param level 层级
* @param name 标签名称
* @return 重名数量
*/
Integer countDuplicateByParentAndLevel(@Param("currentId") Integer currentId,
@Param("parentId") Integer parentId,
@Param("level") Integer level,
@Param("name") String name);
/**
* 按路径批量刷新子孙节点路径信息
*
* @param oldPath 原路径
* @param oldPathName 原名称路径
* @param newPath 新路径
* @param newPathName 新名称路径
* @param operator 操作人
* @param now 更新时间
* @return 更新数量
*/
Integer updateDescendantPath(@Param("oldPath") String oldPath,
@Param("oldPathName") String oldPathName,
@Param("newPath") String newPath,
@Param("newPathName") String newPathName,
@Param("operator") String operator,
@Param("now") java.util.Date now);
}
...@@ -4,6 +4,15 @@ import cn.com.glsx.dj.financial.model.NbCbDailyReportAccount; ...@@ -4,6 +4,15 @@ import cn.com.glsx.dj.financial.model.NbCbDailyReportAccount;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper; import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
@Mapper @Mapper
public interface NbCbDailyReportAccountMapper extends OreMapper<NbCbDailyReportAccount> { public interface NbCbDailyReportAccountMapper extends OreMapper<NbCbDailyReportAccount> {
}
\ No newline at end of file \ No newline at end of file
/**
* 查询启用中的内部账号。
*
* @return 内部账号列表
*/
List<String> listEnabledInternalAccounts();
}
package cn.com.glsx.dj.financial.remote;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailSummaryReportDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailSummaryReportQueryDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagBindDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagOperationPreviewDTO;
import cn.com.glsx.dj.financial.dto.NbCbAccDetailTagQueryDTO;
import cn.com.glsx.dj.financial.service.nb.NbCbAccDetailTagSummaryService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
/**
* 财资标签与汇总报表远程服务实现。
*
*
*/
@Slf4j
@DubboService(validation = "true", version = "1.0.0")
public class NbCbAccDetailTagSummaryRemoteImpl implements NbCbAccDetailTagSummaryRemote {
@Autowired
private NbCbAccDetailTagSummaryService nbCbAccDetailTagSummaryService;
@Override
public RpcResponse<List<NbCbAccDetailTagDTO>> queryTagTree(NbCbAccDetailTagQueryDTO queryDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.queryTagTree(queryDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<Integer> saveTag(NbCbAccDetailTagDTO tagDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.saveTag(tagDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<NbCbAccDetailTagOperationPreviewDTO> previewSaveTag(NbCbAccDetailTagDTO tagDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.previewSaveTag(tagDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<Boolean> deleteTag(NbCbAccDetailTagDTO tagDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.deleteTag(tagDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<NbCbAccDetailTagOperationPreviewDTO> previewDeleteTag(NbCbAccDetailTagDTO tagDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.previewDeleteTag(tagDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<Boolean> bindDetailTag(NbCbAccDetailTagBindDTO bindDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.bindDetailTag(bindDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<NbCbAccDetailSummaryReportDTO> buildAccDetailSummaryReport(NbCbAccDetailSummaryReportQueryDTO queryDTO) {
try {
return RpcResponse.success(nbCbAccDetailTagSummaryService.buildAccDetailSummaryReport(queryDTO));
} catch (RpcServiceException e) {
log.error(e.getMessage(), e);
return RpcResponse.error(e);
}
}
}
package cn.com.glsx.dj.financial.service.nb;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 现金流量表汇总行定义。
*
* 用于描述单行的名称、取值标记、取值说明以及计算方式,
* 其中取值标记、取值说明仅作为研发期的内部辅助信息,不作为最终sheet输出列。
* 便于按模板顺序统一组装“现金流量表汇总”sheet。
*
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NbCbAccDetailCashFlowRowDefinition {
/**
* 分组标题行。
*/
public static final String TYPE_SECTION = "SECTION";
/**
* 收入口径行。
*/
public static final String TYPE_INCOME = "INCOME";
/**
* 支出口径行。
*/
public static final String TYPE_EXPENSE = "EXPENSE";
/**
* 手工填写行。
*/
public static final String TYPE_MANUAL = "MANUAL";
/**
* 汇总求和行。
*/
public static final String TYPE_SUM = "SUM";
/**
* 差额计算行。
*/
public static final String TYPE_DIFF = "DIFF";
/**
* 期初余额行。
*/
public static final String TYPE_BEGIN_BALANCE = "BEGIN_BALANCE";
/**
* 行名称。
*/
private String name;
/**
* 模板中的取值标记。
*/
private String marker;
/**
* 模板中的取值说明。
*/
private String description;
/**
* 行类型。
*/
private String type;
/**
* 依赖的来源行名称。
*/
private List<String> refs;
public static NbCbAccDetailCashFlowRowDefinition section(String name) {
return new NbCbAccDetailCashFlowRowDefinition(name, "", "", TYPE_SECTION, Collections.emptyList());
}
public static NbCbAccDetailCashFlowRowDefinition income(String name) {
return new NbCbAccDetailCashFlowRowDefinition(name, "1", "取“报表口径”同名标签金额之和", TYPE_INCOME, Collections.emptyList());
}
public static NbCbAccDetailCashFlowRowDefinition expense(String name) {
return new NbCbAccDetailCashFlowRowDefinition(name, "2", "取“报表口径”同名标签金额之和", TYPE_EXPENSE, Collections.emptyList());
}
public static NbCbAccDetailCashFlowRowDefinition manual(String name) {
return new NbCbAccDetailCashFlowRowDefinition(name, "", "手动填写/无同名财务口径时留空", TYPE_MANUAL, Collections.emptyList());
}
public static NbCbAccDetailCashFlowRowDefinition sum(String name, String... refs) {
return new NbCbAccDetailCashFlowRowDefinition(name, "", "系统汇总计算", TYPE_SUM, Arrays.asList(refs));
}
public static NbCbAccDetailCashFlowRowDefinition diff(String name, String left, String right) {
return new NbCbAccDetailCashFlowRowDefinition(name, "", "系统差额计算", TYPE_DIFF, Arrays.asList(left, right));
}
public static NbCbAccDetailCashFlowRowDefinition beginBalance(String name) {
return new NbCbAccDetailCashFlowRowDefinition(name, "111", "系统获取:统计周期开始日前一日余额", TYPE_BEGIN_BALANCE, Collections.emptyList());
}
}
...@@ -97,6 +97,9 @@ public class NbCbAccDetailService { ...@@ -97,6 +97,9 @@ public class NbCbAccDetailService {
private NbCbReceiptService nbReceiptService; private NbCbReceiptService nbReceiptService;
@Autowired @Autowired
private NbCbAccDetailTagSummaryService nbCbAccDetailTagSummaryService;
@Autowired
private Environment env; private Environment env;
@Autowired @Autowired
private JdInterfaceProxy jdInterfaceProxy; private JdInterfaceProxy jdInterfaceProxy;
...@@ -799,20 +802,27 @@ public class NbCbAccDetailService { ...@@ -799,20 +802,27 @@ public class NbCbAccDetailService {
// String custId = nbCbCustInfoService.getCustIdByType(NbCbCustEnum.GL_CUST.getCustType()); // String custId = nbCbCustInfoService.getCustIdByType(NbCbCustEnum.GL_CUST.getCustType());
String custId = nbCbCustInfoService.getCustIdByType(condition.getCustType()); String custId = nbCbCustInfoService.getCustIdByType(condition.getCustType());
condition.setCustId(custId); condition.setCustId(custId);
NbCbAccDetailDTO nbCbAccDetailDTO = new NbCbAccDetailDTO(); NbCbAccDetailDTO configDTO = new NbCbAccDetailDTO();
nbCbAccDetailDTO.setAccNameList(nbCbAccDetailMapper.selectAccNameList(condition)); configDTO.setAccNameList(nbCbAccDetailMapper.selectAccNameList(condition));
nbCbAccDetailDTO.setBankTypeList(nbCbAccDetailMapper.selectBankTypeList(condition)); configDTO.setBankTypeList(nbCbAccDetailMapper.selectBankTypeList(condition));
nbCbAccDetailDTO.setBankAccList(nbCbAccDetailMapper.selectBankAccList(condition)); configDTO.setBankAccList(nbCbAccDetailMapper.selectBankAccList(condition));
nbCbAccDetailDTO.setBankNameList(nbCbAccDetailMapper.selectBankNameList(condition)); configDTO.setBankNameList(nbCbAccDetailMapper.selectBankNameList(condition));
//nbCbAccDetailDTO.setOppAccNameList(nbCbAccDetailMapper.selectOppAccNameList()); //configDTO.setOppAccNameList(nbCbAccDetailMapper.selectOppAccNameList());
//nbCbAccDetailDTO.setOppAccNoList(nbCbAccDetailMapper.selectOppAccNoList()); //configDTO.setOppAccNoList(nbCbAccDetailMapper.selectOppAccNoList());
List<CurCodeDTO> curCodeDTOList = new ArrayList<>(); List<CurCodeDTO> curCodeDTOList = new ArrayList<>();
for (CurCodeEnum value : CurCodeEnum.values()) { for (CurCodeEnum value : CurCodeEnum.values()) {
curCodeDTOList.add(new CurCodeDTO(value.getValue(), value.getDisplayName())); curCodeDTOList.add(new CurCodeDTO(value.getValue(), value.getDisplayName()));
} }
nbCbAccDetailDTO.setCurCodeList(curCodeDTOList); configDTO.setCurCodeList(curCodeDTOList);
return nbCbAccDetailDTO;
NbCbAccDetailTagQueryDTO tagQueryDTO = new NbCbAccDetailTagQueryDTO();
tagQueryDTO.setOnlyComplete(true);
tagQueryDTO.setAppendAncestors(true);
List<NbCbAccDetailTagDTO> accDetailTagOptions = nbCbAccDetailTagSummaryService.queryTagTree(tagQueryDTO);
configDTO.setAccDetailTagOptions(accDetailTagOptions);
configDTO.setFinancialReportCaliberOptions(extractFinancialReportCaliberOptions(accDetailTagOptions));
return configDTO;
} catch (RpcServiceException e) { } catch (RpcServiceException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {
...@@ -821,6 +831,36 @@ public class NbCbAccDetailService { ...@@ -821,6 +831,36 @@ public class NbCbAccDetailService {
} }
} }
/**
* 提取可选的财务报表口径列表
*
* @param tagOptions 财资标签树
* @return 口径列表
*/
private List<String> extractFinancialReportCaliberOptions(List<NbCbAccDetailTagDTO> tagOptions) {
LinkedHashSet<String> caliberSet = new LinkedHashSet<>();
collectFinancialReportCaliber(tagOptions, caliberSet);
return new ArrayList<>(caliberSet);
}
/**
* 递归提取财务报表口径
*
* @param tagOptions 财资标签列表
* @param caliberSet 口径集合
*/
private void collectFinancialReportCaliber(List<NbCbAccDetailTagDTO> tagOptions, Set<String> caliberSet) {
if (CollectionUtils.isEmpty(tagOptions)) {
return;
}
for (NbCbAccDetailTagDTO tagOption : tagOptions) {
if (StringUtils.isNotBlank(tagOption.getFinancialReportCaliber())) {
caliberSet.add(tagOption.getFinancialReportCaliber());
}
collectFinancialReportCaliber(tagOption.getChildren(), caliberSet);
}
}
/** /**
* 批量同步交易明细到金蝶系统 * 批量同步交易明细到金蝶系统
......
package cn.com.glsx.dj.financial.service.nb;
import cn.com.glsx.dj.financial.model.NbCbAccDetail;
import cn.com.glsx.dj.financial.model.NbCbAccDetailTag;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 财资汇总报表构建上下文。
*
* 用于承载一次报表生成过程中会被多个 sheet 复用的基础数据,
* 包括统计周期、标签树、余额账号范围、内部往来账号范围和预聚合结果等。
*
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NbCbAccDetailSummaryReportContext {
/**
* 统计开始日期。
*/
private Date startDate;
/**
* 统计结束日期。
*/
private Date endDate;
/**
* 统计月份列表,格式 yyyy-MM。
*/
private List<String> monthKeys;
/**
* 全量有效标签。
*/
private List<NbCbAccDetailTag> allTags;
/**
* 标签 ID 到标签实体的映射。
*/
private Map<Integer, NbCbAccDetailTag> tagMap;
/**
* 任意标签节点对应的完整三级叶子标签 ID 集合。
*/
private Map<Integer, List<Integer>> leafIdsByTag;
/**
* 纳入余额统计的账号列表,来源于 nb_cb_account。
*/
private List<String> balanceAccountNos;
/**
* 内部往来检验使用的内部交易明细。
*/
private List<NbCbAccDetail> internalTransactions;
/**
* 纳入内部往来检验的内部账号列表。
*/
private List<String> internalAccountNos;
/**
* 统计开始日前一日余额。
*/
private BigDecimal beginBalance;
/**
* 各月份月末余额,key 为 yyyy-MM。
*/
private Map<String, BigDecimal> monthEndBalances;
/**
* 各月份叶子标签金额汇总,第一层 key 为 yyyy-MM。
*/
private Map<String, Map<Integer, BigDecimal>> monthLeafAmountMap;
/**
* 收入口径金额汇总。
*/
private Map<String, BigDecimal> incomeByCaliber;
/**
* 支出口径金额汇总。
*/
private Map<String, BigDecimal> expenseByCaliber;
}
package cn.com.glsx.dj.financial.service.nb;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.math.BigDecimal;
/**
* 财资明细标签月度汇总结果。
*
* 用于承载数据库按“月份 + 三级标签”预聚合后的金额结果,
* 避免在报表生成时一次性把大量明细记录加载到内存再做二次统计。
*
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class NbCbAccDetailTagAmountSummary {
/**
* 月份键,格式 yyyy-MM。
*/
private String monthKey;
/**
* 三级标签 ID。
*/
private Integer accDetailTagId;
/**
* 收入金额汇总。
*/
private BigDecimal incomeAmount;
/**
* 支出金额汇总。
*/
private BigDecimal expenseAmount;
/**
* 带方向金额汇总,收入为正,支出为负。
*/
private BigDecimal signedAmount;
}
package cn.com.glsx.dj.financial.service.nb;
import cn.com.glsx.dj.financial.model.NbCbAccDetailTag;
import lombok.Data;
/**
* 财资标签保存上下文
*/
@Data
public class NbCbAccDetailTagSaveContext {
private NbCbAccDetailTag parent;
private NbCbAccDetailTag current;
private String oldPath;
private String oldPathName;
private int targetLevel;
}
package cn.com.glsx.dj.financial.service.nb;
import cn.com.glsx.dj.financial.dto.*;
import cn.com.glsx.dj.financial.mapper.NbCbAccDetailMapper;
import cn.com.glsx.dj.financial.mapper.NbCbAccDetailTagMapper;
import cn.com.glsx.dj.financial.mapper.NbCbDetailLogMapper;
import cn.com.glsx.dj.financial.mapper.NbCbDailyReportAccountMapper;
import cn.com.glsx.dj.financial.model.NbCbAccDetail;
import cn.com.glsx.dj.financial.model.NbCbAccDetailTag;
import cn.com.glsx.dj.financial.model.NbCbAccount;
import cn.com.glsx.dj.financial.model.NbCbDetailLog;
import cn.com.glsx.framework.core.beans.BaseModel;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.framework.core.util.RpcAssert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import cn.com.glsx.dj.financial.constants.NbCbDetailLogType;
import cn.com.glsx.dj.financial.enums.AccDetailOperationTypeEnum;
import cn.com.glsx.dj.financial.enums.Flag;
/**
* 财资标签与汇总报表服务
*
*
*/
@Slf4j
@Service
@Transactional(propagation = Propagation.SUPPORTS, rollbackFor = RpcServiceException.class)
public class NbCbAccDetailTagSummaryService {
private static final String DATE_PATTERN = "yyyy-MM-dd";
private static final String MONTH_PATTERN = "yyyy-MM";
private static final List<String> FUND_SUMMARY_FIXED_ROWS = Arrays.asList(
"月末余额",
"银盛余额",
"月度变动净额",
"融资类收支净额",
"(1)银行贷款余额",
"新增借款",
"还借款",
"贷款变动净额",
"贷款利息支出",
"(2)承兑票据余额",
"2-1增量业务票据余额",
"增量业务出票",
"增量票据到期",
"2-2经营业务票据余额",
"经营业务出票",
"经营票据到期"
);
private static final List<NbCbAccDetailCashFlowRowDefinition> CASH_FLOW_ROW_DEFINITIONS = Arrays.asList(
NbCbAccDetailCashFlowRowDefinition.section("一、经营活动产生的现金流量:"),
NbCbAccDetailCashFlowRowDefinition.income("销售商品、提供劳务收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("收到的税费返还"),
NbCbAccDetailCashFlowRowDefinition.income("收到其他与经营活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("经营活动现金流入小计", "销售商品、提供劳务收到的现金", "收到的税费返还", "收到其他与经营活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("购买商品、接受劳务支付的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("支付给职工以及为职工支付的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("支付的各项税费"),
NbCbAccDetailCashFlowRowDefinition.expense("支付其他与经营活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("经营活动现金流出小计", "购买商品、接受劳务支付的现金", "支付给职工以及为职工支付的现金", "支付的各项税费", "支付其他与经营活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.diff("经营活动产生的现金流量净额", "经营活动现金流入小计", "经营活动现金流出小计"),
NbCbAccDetailCashFlowRowDefinition.section("二、投资活动产生的现金流量:"),
NbCbAccDetailCashFlowRowDefinition.income("收回投资收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("取得投资收益收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("处置固定资产、无形资产和其他长期资产收回的现金净额"),
NbCbAccDetailCashFlowRowDefinition.income("处置子公司及其他营业单位收到的现金净额"),
NbCbAccDetailCashFlowRowDefinition.income("收到其他与投资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("投资活动现金流入小计", "收回投资收到的现金", "取得投资收益收到的现金",
"处置固定资产、无形资产和其他长期资产收回的现金净额", "处置子公司及其他营业单位收到的现金净额", "收到其他与投资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("购建固定资产、无形资产和其他长期资产支付的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("投资支付的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("取得子公司及其他营业单位支付的现金净额"),
NbCbAccDetailCashFlowRowDefinition.expense("支付其他与投资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("投资活动现金流出小计", "购建固定资产、无形资产和其他长期资产支付的现金", "投资支付的现金",
"取得子公司及其他营业单位支付的现金净额", "支付其他与投资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.diff("投资活动产生的现金流量净额", "投资活动现金流入小计", "投资活动现金流出小计"),
NbCbAccDetailCashFlowRowDefinition.section("三、筹资活动产生的现金流量:"),
NbCbAccDetailCashFlowRowDefinition.income("吸收投资收到的现金"),
NbCbAccDetailCashFlowRowDefinition.manual("其中:子公司吸收少数股东投资收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("取得借款收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("发行债券收到的现金"),
NbCbAccDetailCashFlowRowDefinition.income("收到其他与筹资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("筹资活动现金流入小计", "吸收投资收到的现金", "取得借款收到的现金", "发行债券收到的现金", "收到其他与筹资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("偿还债务支付的现金"),
NbCbAccDetailCashFlowRowDefinition.expense("分配股利、利润或偿付利息支付的现金"),
NbCbAccDetailCashFlowRowDefinition.manual("其中:子公司支付给少数股东的股利、利润"),
NbCbAccDetailCashFlowRowDefinition.expense("支付其他与筹资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.sum("筹资活动现金流出小计", "偿还债务支付的现金", "分配股利、利润或偿付利息支付的现金", "支付其他与筹资活动有关的现金"),
NbCbAccDetailCashFlowRowDefinition.diff("筹资活动产生的现金流量净额", "筹资活动现金流入小计", "筹资活动现金流出小计"),
NbCbAccDetailCashFlowRowDefinition.manual("四、汇率变动对现金及现金等价物的影响"),
NbCbAccDetailCashFlowRowDefinition.sum("五、现金及现金等价物净增加额", "经营活动产生的现金流量净额", "投资活动产生的现金流量净额", "筹资活动产生的现金流量净额"),
NbCbAccDetailCashFlowRowDefinition.beginBalance("加:期初现金及现金等价物余额"),
NbCbAccDetailCashFlowRowDefinition.sum("六、期末现金及现金等价物余额", "四、汇率变动对现金及现金等价物的影响", "五、现金及现金等价物净增加额", "加:期初现金及现金等价物余额")
);
@Autowired
private NbCbAccDetailTagMapper nbCbAccDetailTagMapper;
@Autowired
private NbCbAccDetailMapper nbCbAccDetailMapper;
@Autowired
private NbCbDetailLogMapper nbCbDetailLogMapper;
@Autowired
private NbCbDailyReportAccountMapper nbCbDailyReportAccountMapper;
@Autowired
private NbCbAccountService nbCbAccountService;
/**
* 查询财资标签树
*
* @param queryDTO 查询条件
* @return 标签树
*/
public List<NbCbAccDetailTagDTO> queryTagTree(NbCbAccDetailTagQueryDTO queryDTO) {
log.info("查询财资标签树入参:{}", queryDTO);
List<NbCbAccDetailTag> filtered = queryTagsByCondition(queryDTO);
if (CollectionUtils.isEmpty(filtered)) {
log.info("查询财资标签树结果为空");
return Collections.emptyList();
}
if (shouldAppendAncestors(queryDTO)) {
filtered = appendAncestorTags(filtered);
}
List<NbCbAccDetailTagDTO> tree = buildTagTree(filtered);
log.info("查询财资标签树完成, 匹配节点数:{}, 根节点数:{}", filtered.size(), tree.size());
return tree;
}
/**
* 按条件查询标签节点
*
* 优先通过 SQL 完成大部分过滤,避免每次树查询都先拉取全量标签再在内存中做筛选。
* 仅在需要给树结构补祖先节点时,才回查一次全量标签做树组装。
*
* @param queryDTO 查询条件
* @return 过滤后的标签节点
*/
private List<NbCbAccDetailTag> queryTagsByCondition(NbCbAccDetailTagQueryDTO queryDTO) {
if (queryDTO == null) {
return listAllActiveTags();
}
String descendantPath = validateAndQueryTagPath(queryDTO);
if (StringUtils.isNotBlank(descendantPath)) {
queryDTO.setPath(descendantPath);
}
List<NbCbAccDetailTag> tags = nbCbAccDetailTagMapper.queryTagTreeByCondition(queryDTO);
log.info("标签树SQL过滤完成, id:{}, parentId:{}, path:{}, descendantOfId:{}, appendAncestors:{}, level:{}, onlyComplete:{}, resultCount:{}",
queryDTO.getId(), queryDTO.getParentId(), queryDTO.getPath(), queryDTO.getDescendantOfId(),
queryDTO.getAppendAncestors(), queryDTO.getLevel(), queryDTO.getOnlyComplete(), tags.size());
return tags;
}
/**
* 保存财资标签
*
* @param tagDTO 标签信息
* @return 主键ID
*/
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RpcServiceException.class)
public Integer saveTag(NbCbAccDetailTagDTO tagDTO) {
log.info("保存财资标签入参:{}", tagDTO);
NbCbAccDetailTagSaveContext context = prepareSaveTagContext(tagDTO);
NbCbAccDetailTag parent = context.getParent();
NbCbAccDetailTag current = context.getCurrent();
String oldPath = context.getOldPath();
String oldPathName = context.getOldPathName();
int targetLevel = context.getTargetLevel();
Date now = new Date();
NbCbAccDetailTag entity = current == null ? new NbCbAccDetailTag() : current;
entity.setName(StringUtils.trim(tagDTO.getName()));
entity.setParentId(tagDTO.getParentId());
entity.setLevel(targetLevel);
entity.setFinancialReportCaliber(targetLevel == 3 ? StringUtils.trimToNull(tagDTO.getFinancialReportCaliber()) : null);
entity.setSortNum(tagDTO.getSortNum());
entity.setStatus(tagDTO.getStatus() == null ? 1 : tagDTO.getStatus());
entity.setRemark(tagDTO.getRemark());
entity.setUpdatedDate(now);
entity.setUpdatedBy(StringUtils.defaultIfBlank(tagDTO.getUpdatedBy(), tagDTO.getCreatedBy()));
if (current == null) {
entity.setCreatedDate(now);
entity.setCreatedBy(tagDTO.getCreatedBy());
entity.setDeletedFlag(BaseModel.DeletedFlagEnum.N.name());
nbCbAccDetailTagMapper.insertSelective(entity);
} else {
nbCbAccDetailTagMapper.updateByPrimaryKeySelective(entity);
}
String path = parent == null ? String.valueOf(entity.getId()) : parent.getPath() + "," + entity.getId();
String pathName = parent == null ? entity.getName() : parent.getPathName() + "," + entity.getName();
NbCbAccDetailTag pathUpdate = new NbCbAccDetailTag();
pathUpdate.setId(entity.getId());
pathUpdate.setPath(path);
pathUpdate.setPathName(pathName);
pathUpdate.setUpdatedDate(now);
pathUpdate.setUpdatedBy(entity.getUpdatedBy());
nbCbAccDetailTagMapper.updateByPrimaryKeySelective(pathUpdate);
if (current != null && StringUtils.isNotBlank(oldPath)
&& (!StringUtils.equals(oldPath, path) || !StringUtils.equals(oldPathName, pathName))) {
refreshDescendantPath(oldPath, oldPathName, path, pathName, entity.getUpdatedBy(), now);
}
return entity.getId();
}
/**
* 财资标签保存前预检查
*
* @param tagDTO 标签信息
* @return 预检查结果
*/
public NbCbAccDetailTagOperationPreviewDTO previewSaveTag(NbCbAccDetailTagDTO tagDTO) {
log.info("财资标签保存前预检查入参:{}", tagDTO);
NbCbAccDetailTagSaveContext context = prepareSaveTagContext(tagDTO);
NbCbAccDetailTagOperationPreviewDTO previewDTO = new NbCbAccDetailTagOperationPreviewDTO();
previewDTO.setConfirmRequired(false);
if (context.getCurrent() != null) {
String oldName = StringUtils.defaultString(context.getCurrent().getName());
String newName = StringUtils.defaultString(StringUtils.trim(tagDTO.getName()));
previewDTO.setConfirmRequired(true);
previewDTO.setMessage("您正在执行财务类目修改,确定将原标签类目【" + oldName + "】修改为【" + newName + "】吗?");
}
return previewDTO;
}
/**
* 删除财资标签
*
* @param tagDTO 标签信息
* @return 是否成功
*/
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RpcServiceException.class)
public Boolean deleteTag(NbCbAccDetailTagDTO tagDTO) {
log.info("删除财资标签入参:{}", tagDTO);
NbCbAccDetailTag tag = prepareDeleteTag(tagDTO);
NbCbAccDetailTag deleteEntity = new NbCbAccDetailTag();
deleteEntity.setId(tag.getId());
deleteEntity.setDeletedFlag(BaseModel.DeletedFlagEnum.D.name());
deleteEntity.setUpdatedDate(new Date());
deleteEntity.setUpdatedBy(tagDTO.getUpdatedBy());
nbCbAccDetailTagMapper.updateByPrimaryKeySelective(deleteEntity);
return true;
}
/**
* 财资标签删除前预检查
*
* @param tagDTO 标签信息
* @return 预检查结果
*/
public NbCbAccDetailTagOperationPreviewDTO previewDeleteTag(NbCbAccDetailTagDTO tagDTO) {
log.info("财资标签删除前预检查入参:{}", tagDTO);
NbCbAccDetailTag tag = prepareDeleteTag(tagDTO);
NbCbAccDetailTagOperationPreviewDTO previewDTO = new NbCbAccDetailTagOperationPreviewDTO();
previewDTO.setConfirmRequired(true);
previewDTO.setMessage("您正在执行财务类目删除,确定彻底注销闲置标签类目【" + tag.getName() + "】吗?");
return previewDTO;
}
/**
* 单条或批量明细打标签
*
* @param bindDTO 打标签参数
* @return 是否成功
*/
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = RpcServiceException.class)
public Boolean bindDetailTag(NbCbAccDetailTagBindDTO bindDTO) {
log.info("财资明细打标签入参:{}", bindDTO);
RpcAssert.assertNotNull(bindDTO, DefaultErrorEnum.DATA_NULL, "打标签参数不能为空");
List<Long> detailIds = bindDTO.getDetailIds();
if (CollectionUtils.isEmpty(detailIds)) {
throw new RpcServiceException(DefaultErrorEnum.PARAMETER_NULL, "明细ID不能为空");
}
if (bindDTO.getAccDetailTagId() != null) {
NbCbAccDetailTag tag = loadTag(bindDTO.getAccDetailTagId());
if (!Objects.equals(tag.getLevel(), 3) || StringUtils.isBlank(tag.getFinancialReportCaliber())) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
"批量标签操作仅可选择完整的三级标签(含财务报表口径),不支持选择不完整标签。");
}
}
List<NbCbAccDetail> details = nbCbAccDetailMapper.queryByIds(detailIds);
if (CollectionUtils.isEmpty(details)) {
log.warn("未查询到可更新的财资明细, detailIds:{}", detailIds);
return true;
}
Date now = new Date();
List<Long> changedDetailIds = new ArrayList<>();
List<NbCbDetailLog> detailLogs = new ArrayList<>();
for (NbCbAccDetail detail : details) {
if (Objects.equals(detail.getAccDetailTagId(), bindDTO.getAccDetailTagId())) {
log.info("财资明细【{}】已打过标签【{}】,无需重复打标签", detail.getId(), detail.getAccDetailTagId());
continue;
}
changedDetailIds.add(detail.getId());
detailLogs.add(buildDetailTagLog(detail.getId(), bindDTO.getOperator(), now));
}
if (CollectionUtils.isEmpty(changedDetailIds)) {
log.info("财资明细打标签无实际变更, detailIds:{}, accDetailTagId:{}", detailIds, bindDTO.getAccDetailTagId());
return true;
}
nbCbAccDetailMapper.updateAccDetailTagBatch(changedDetailIds, bindDTO.getAccDetailTagId(), bindDTO.getOperator(), now);
log.info("财资明细打标签批量更新完成, changedCount:{}, accDetailTagId:{}", changedDetailIds.size(), bindDTO.getAccDetailTagId());
if (CollectionUtils.isNotEmpty(detailLogs)) {
nbCbDetailLogMapper.insertList(detailLogs);
log.info("财资明细打标签日志写入完成, detailCount:{}, logCount:{}", details.size(), detailLogs.size());
}
return true;
}
/**
* 构建明细标签变更操作日志。
*
* @param detailId 明细ID
* @param operator 操作人
* @param now 操作时间
* @return 明细日志
*/
private NbCbDetailLog buildDetailTagLog(Long detailId, String operator, Date now) {
NbCbDetailLog detailLog = new NbCbDetailLog();
detailLog.setAccDetailId(detailId);
detailLog.setLogType(NbCbDetailLogType.LOG_TYPE_DETAIL);
detailLog.setOperationType(AccDetailOperationTypeEnum.EDIT_CUSTOM_TAG.getValue());
detailLog.setOperationResult(Flag.Y.name());
detailLog.setCreatedBy(operator);
detailLog.setUpdatedBy(operator);
detailLog.setCreatedDate(now);
detailLog.setUpdatedDate(now);
detailLog.setDeletedFlag(BaseModel.DeletedFlagEnum.N.name());
return detailLog;
}
/**
* 生成财资汇总报表数据
*
* @param queryDTO 报表查询条件
* @return 报表结构
*/
public NbCbAccDetailSummaryReportDTO buildAccDetailSummaryReport(NbCbAccDetailSummaryReportQueryDTO queryDTO) {
log.info("生成财资汇总报表数据入参:{}", queryDTO);
// 先统一准备统计周期、标签树、余额、明细和口径汇总等公共上下文,
// 再分别生成三个 sheet,避免在单个 sheet 构建过程中重复查库和重复聚合。
NbCbAccDetailSummaryReportContext context = buildReportContext(queryDTO);
NbCbAccDetailSummaryReportDTO reportDTO = new NbCbAccDetailSummaryReportDTO();
List<NbCbAccDetailSummarySheetDTO> sheets = new ArrayList<>();
log.info("开始构建资金汇总sheet");
sheets.add(buildFundSummarySheet(context));
log.info("开始构建现金流量表汇总sheet");
sheets.add(buildCashFlowSummarySheet(context));
log.info("开始构建内部往来检验sheet");
sheets.add(buildInternalReconciliationSheet(context));
reportDTO.setSheets(sheets);
log.info("生成财资汇总报表数据完成, sheetCount:{}", sheets.size());
return reportDTO;
}
/**
* 构建报表上下文
*
* @param queryDTO 查询条件
* @return 报表上下文
*/
private NbCbAccDetailSummaryReportContext buildReportContext(NbCbAccDetailSummaryReportQueryDTO queryDTO) {
Date defaultEndDate = DateUtil.endOfMonth(DateUtil.offsetMonth(new Date(), -1));
Date defaultStartDate = DateUtil.beginOfYear(defaultEndDate);
Date startDate = resolveDate(queryDTO == null ? null : queryDTO.getStartDate(), defaultStartDate);
Date endDate = resolveDate(queryDTO == null ? null : queryDTO.getEndDate(), defaultEndDate);
if (startDate.after(endDate)) {
throw new RpcServiceException(DefaultErrorEnum.VALIDATE_FAILED, "开始日期不能晚于结束日期");
}
// 内部往来检验账号范围直接复用既有日报账号配置,
// 不再单独维护新的母子公司账号表。
List<String> internalAccountNos = listEnabledInternalAccounts();
List<String> balanceAccountNos = listAllBalanceAccountNos();
List<NbCbAccDetailTag> allTags = listAllActiveTags();
Map<Integer, NbCbAccDetailTag> tagMap = allTags.stream()
.collect(Collectors.toMap(NbCbAccDetailTag::getId, item -> item, (left, right) -> left, LinkedHashMap::new));
Map<Integer, List<Integer>> leafIdsByTag = buildLeafIdsByTag(allTags);
List<String> monthKeys = buildMonthKeys(startDate, endDate);
String startDateTime = DateUtil.formatDate(startDate) + " 00:00:00";
String endDateTime = DateUtil.formatDate(endDate) + " 23:59:59";
// 资金汇总和现金流量表汇总的标签金额,不基于内部账号范围过滤,
// 而是基于指定时间范围内全部已打标签明细做数据库预聚合。
List<NbCbAccDetailTagAmountSummary> tagAmountSummaries = nbCbAccDetailMapper.queryTagAmountSummary(startDateTime, endDateTime);
Map<String, Map<Integer, BigDecimal>> monthLeafAmountMap = buildMonthLeafAmountMap(tagAmountSummaries, tagMap);
Map<String, BigDecimal> incomeByCaliber = new LinkedHashMap<>();
Map<String, BigDecimal> expenseByCaliber = new LinkedHashMap<>();
// 现金流量表汇总与资金汇总的标签金额都来自财资明细打标结果,
// 这里直接使用数据库预聚合结果组装口径金额,避免把整年明细一次性加载到内存。
buildCaliberAmountMap(tagAmountSummaries, tagMap, incomeByCaliber, expenseByCaliber);
List<NbCbAccDetail> internalTransactions = loadInternalTransactions(startDate, endDate, internalAccountNos);
BigDecimal beginBalance = loadBalanceForDate(balanceAccountNos, DateUtil.offsetDay(DateUtil.beginOfDay(startDate), -1));
Map<String, BigDecimal> monthEndBalances = new LinkedHashMap<>();
for (String monthKey : monthKeys) {
Date monthDate = DateUtil.parse(monthKey, MONTH_PATTERN);
monthEndBalances.put(monthKey, loadBalanceForDate(balanceAccountNos, DateUtil.endOfMonth(monthDate)));
}
log.info("生成财资汇总报表上下文完成, startDate:{}, endDate:{}, monthCount:{}, tagCount:{}, balanceAccountCount:{}, internalAccountCount:{}, tagSummaryCount:{}, internalDetailCount:{}",
DateUtil.formatDate(startDate), DateUtil.formatDate(endDate), monthKeys.size(), allTags.size(),
balanceAccountNos.size(), internalAccountNos.size(), tagAmountSummaries.size(), internalTransactions.size());
return new NbCbAccDetailSummaryReportContext(startDate, endDate, monthKeys, allTags, tagMap, leafIdsByTag, balanceAccountNos,
internalTransactions, internalAccountNos, beginBalance, monthEndBalances, monthLeafAmountMap, incomeByCaliber, expenseByCaliber);
}
/**
* 构建资金汇总sheet
*
* @param context 报表上下文
* @return sheet数据
*/
private NbCbAccDetailSummarySheetDTO buildFundSummarySheet(NbCbAccDetailSummaryReportContext context) {
NbCbAccDetailSummarySheetDTO sheetDTO = new NbCbAccDetailSummarySheetDTO();
sheetDTO.setSheetName("资金汇总");
List<String> columns = new ArrayList<>();
columns.add("项目");
columns.add("年初余额");
for (String monthKey : context.getMonthKeys()) {
columns.add(formatMonthColumn(monthKey));
}
sheetDTO.setColumns(columns);
List<List<Object>> rows = new ArrayList<>();
// BigDecimal previousBalance = context.getBeginBalance();
for (String fixedRow : FUND_SUMMARY_FIXED_ROWS) {
List<Object> row = initRow(columns.size(), fixedRow);
if (StringUtils.equals(fixedRow, "月末余额")) {
row.set(1, formatDecimal(context.getBeginBalance()));
for (int i = 0; i < context.getMonthKeys().size(); i++) {
row.set(i + 2, formatDecimal(context.getMonthEndBalances().get(context.getMonthKeys().get(i))));
}
}
// if (StringUtils.equals(fixedRow, "月度变动净额")) {
// for (int i = 0; i < context.getMonthKeys().size(); i++) {
// BigDecimal current = context.getMonthEndBalances().get(context.getMonthKeys().get(i));
// row.set(i + 2, formatDecimal(current.subtract(previousBalance)));
// previousBalance = current;
// }
// }
rows.add(row);
}
List<NbCbAccDetailTag> roots = context.getAllTags().stream()
.filter(tag -> tag.getParentId() == null)
.sorted(tagComparator())
.collect(Collectors.toList());
for (NbCbAccDetailTag root : roots) {
appendFundSummaryTagRows(root, rows, columns.size(), context);
}
sheetDTO.setRows(rows);
log.info("资金汇总sheet构建完成, columnCount:{}, rowCount:{}", columns.size(), rows.size());
return sheetDTO;
}
/**
* 构建现金流量表汇总sheet
*
* @param context 报表上下文
* @return sheet数据
*/
private NbCbAccDetailSummarySheetDTO buildCashFlowSummarySheet(NbCbAccDetailSummaryReportContext context) {
NbCbAccDetailSummarySheetDTO sheetDTO = new NbCbAccDetailSummarySheetDTO();
sheetDTO.setSheetName("现金流量表汇总");
// “取值标记”“取值说明”“取值周期”仅用于研发理解模板取数规则,
// 不属于最终导出的业务结果列。
sheetDTO.setColumns(Arrays.asList("项目", "金额"));
Map<String, BigDecimal> calculatedValues = new LinkedHashMap<>();
List<List<Object>> rows = new ArrayList<>();
for (NbCbAccDetailCashFlowRowDefinition definition : CASH_FLOW_ROW_DEFINITIONS) {
BigDecimal amount = calculateCashFlowAmount(definition, calculatedValues, context);
if (amount != null) {
calculatedValues.put(definition.getName(), amount);
}
List<Object> row = new ArrayList<>();
row.add(definition.getName());
row.add(amount == null ? "" : formatDecimal(amount));
rows.add(row);
}
sheetDTO.setRows(rows);
log.info("现金流量表汇总sheet构建完成, rowCount:{}, calculatedValueCount:{}", rows.size(), calculatedValues.size());
return sheetDTO;
}
/**
* 构建内部往来检验sheet
*
* @param context 报表上下文
* @return sheet数据
*/
private NbCbAccDetailSummarySheetDTO buildInternalReconciliationSheet(NbCbAccDetailSummaryReportContext context) {
NbCbAccDetailSummarySheetDTO sheetDTO = new NbCbAccDetailSummarySheetDTO();
sheetDTO.setSheetName("内部往来检验");
sheetDTO.setColumns(Arrays.asList("交易时间", "本方户名", "本方账号", "收入", "支出", "账户余额",
"对方户名", "对方账号", "币种", "交易备注", "交易类型", "用途",
"收支标志", "回单状态", "同步状态(流水明细)", "同步状态(回单)", "同步状态(快照)", "数据来源"));
BigDecimal expenseTotal = BigDecimal.ZERO;
BigDecimal incomeTotal = BigDecimal.ZERO;
List<List<Object>> rows = new ArrayList<>();
for (NbCbAccDetail detail : context.getInternalTransactions()) {
BigDecimal income = isIncome(detail) ? defaultAmount(detail.getAmt()) : BigDecimal.ZERO;
BigDecimal expense = isIncome(detail) ? BigDecimal.ZERO : defaultAmount(detail.getAmt());
incomeTotal = incomeTotal.add(income);
expenseTotal = expenseTotal.add(expense);
}
if (incomeTotal.compareTo(expenseTotal) != 0) {
log.warn("内部往来检验结果异常, incomeTotal:{}, expenseTotal:{}, diff:{}",
incomeTotal, expenseTotal, incomeTotal.subtract(expenseTotal));
}
rows.add(summaryRow("支出汇总", formatDecimal(expenseTotal), sheetDTO.getColumns().size()));
rows.add(summaryRow("收入汇总", formatDecimal(incomeTotal), sheetDTO.getColumns().size()));
rows.add(summaryRow("检验结果", incomeTotal.compareTo(expenseTotal) == 0 ? "正常" : "异常", sheetDTO.getColumns().size()));
for (NbCbAccDetail detail : context.getInternalTransactions()) {
BigDecimal income = isIncome(detail) ? defaultAmount(detail.getAmt()) : BigDecimal.ZERO;
BigDecimal expense = isIncome(detail) ? BigDecimal.ZERO : defaultAmount(detail.getAmt());
List<Object> row = new ArrayList<>();
row.add(detail.getTransTime());
row.add(detail.getAccName());
row.add(detail.getBankAcc());
row.add(income.compareTo(BigDecimal.ZERO) == 0 ? "" : formatDecimal(income));
row.add(expense.compareTo(BigDecimal.ZERO) == 0 ? "" : formatDecimal(expense));
row.add(formatDecimal(detail.getBal()));
row.add(detail.getOppAccName());
row.add(detail.getOppAccNo());
row.add(detail.getCurCode());
row.add(StringUtils.defaultString(detail.getPostScript()));
row.add(StringUtils.defaultString(detail.getAbs()));
row.add(StringUtils.defaultString(detail.getUses()));
row.add(resolveCdSignName(detail));
row.add(resolveReceiptStatus(detail));
row.add(resolveSyncStatus(detail.getJdSync()));
row.add(resolveReceiptSyncStatus(detail));
row.add(resolveSyncStatus(detail.getH5JdSync()));
row.add(resolveDataSource(detail.getDataSource()));
rows.add(row);
}
sheetDTO.setRows(rows);
log.info("内部往来检验sheet构建完成, rowCount:{}, incomeTotal:{}, expenseTotal:{}", rows.size(), incomeTotal, expenseTotal);
return sheetDTO;
}
/**
* 递归追加资金汇总动态标签行
*
* @param tag 标签节点
* @param rows 行数据
* @param columnSize 列数
* @param context 报表上下文
*/
private void appendFundSummaryTagRows(NbCbAccDetailTag tag, List<List<Object>> rows, int columnSize, NbCbAccDetailSummaryReportContext context) {
List<Integer> leafIds = context.getLeafIdsByTag().get(tag.getId());
if (CollectionUtils.isEmpty(leafIds)) {
return;
}
List<Object> row = initRow(columnSize, buildIndentedTagName(tag));
for (int i = 0; i < context.getMonthKeys().size(); i++) {
String monthKey = context.getMonthKeys().get(i);
BigDecimal amount = sumLeafAmount(context.getMonthLeafAmountMap().get(monthKey), leafIds);
row.set(i + 2, amount.compareTo(BigDecimal.ZERO) == 0 ? "" : formatDecimal(amount));
}
rows.add(row);
List<NbCbAccDetailTag> children = context.getAllTags().stream()
.filter(item -> Objects.equals(item.getParentId(), tag.getId()))
.sorted(tagComparator())
.collect(Collectors.toList());
for (NbCbAccDetailTag child : children) {
appendFundSummaryTagRows(child, rows, columnSize, context);
}
}
/**
* 计算现金流sheet单行金额
*
* @param definition 行定义
* @param calculatedValues 已计算金额
* @param context 报表上下文
* @return 金额
*/
private BigDecimal calculateCashFlowAmount(NbCbAccDetailCashFlowRowDefinition definition, Map<String, BigDecimal> calculatedValues,
NbCbAccDetailSummaryReportContext context) {
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_SECTION)
|| Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_MANUAL)) {
return null;
}
// 同名“报表口径”直接取汇总结果;模板中标记为小计/净额/期初余额的行走系统二次计算。
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_INCOME)) {
return context.getIncomeByCaliber().getOrDefault(definition.getName(), BigDecimal.ZERO);
}
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_EXPENSE)) {
return context.getExpenseByCaliber().getOrDefault(definition.getName(), BigDecimal.ZERO);
}
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_BEGIN_BALANCE)) {
return context.getBeginBalance();
}
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_SUM)) {
BigDecimal result = BigDecimal.ZERO;
for (String ref : definition.getRefs()) {
result = result.add(calculatedValues.getOrDefault(ref, BigDecimal.ZERO));
}
return result;
}
if (Objects.equals(definition.getType(), NbCbAccDetailCashFlowRowDefinition.TYPE_DIFF)) {
BigDecimal left = calculatedValues.getOrDefault(definition.getRefs().get(0), BigDecimal.ZERO);
BigDecimal right = calculatedValues.getOrDefault(definition.getRefs().get(1), BigDecimal.ZERO);
return left.subtract(right);
}
return null;
}
/**
* 构建月度叶子标签金额映射
*
* @param summaries 标签月度汇总数据
* @param tagMap 标签映射
* @return 月份-叶子标签金额映射
*/
private Map<String, Map<Integer, BigDecimal>> buildMonthLeafAmountMap(List<NbCbAccDetailTagAmountSummary> summaries,
Map<Integer, NbCbAccDetailTag> tagMap) {
Map<String, Map<Integer, BigDecimal>> monthLeafAmountMap = new LinkedHashMap<>();
for (NbCbAccDetailTagAmountSummary summary : summaries) {
if (summary.getAccDetailTagId() == null) {
continue;
}
NbCbAccDetailTag tag = tagMap.get(summary.getAccDetailTagId());
if (!isCompleteLeafTag(tag)) {
continue;
}
String monthKey = summary.getMonthKey();
if (StringUtils.isBlank(monthKey)) {
continue;
}
monthLeafAmountMap.computeIfAbsent(monthKey, key -> new LinkedHashMap<>());
Map<Integer, BigDecimal> leafAmountMap = monthLeafAmountMap.get(monthKey);
leafAmountMap.put(tag.getId(), leafAmountMap.getOrDefault(tag.getId(), BigDecimal.ZERO).add(defaultAmount(summary.getSignedAmount())));
}
return monthLeafAmountMap;
}
/**
* 构建报表口径金额映射
*
* @param summaries 标签月度汇总数据
* @param tagMap 标签映射
* @param incomeByCaliber 收入口径金额
* @param expenseByCaliber 支出口径金额
*/
private void buildCaliberAmountMap(List<NbCbAccDetailTagAmountSummary> summaries, Map<Integer, NbCbAccDetailTag> tagMap,
Map<String, BigDecimal> incomeByCaliber, Map<String, BigDecimal> expenseByCaliber) {
for (NbCbAccDetailTagAmountSummary summary : summaries) {
if (summary.getAccDetailTagId() == null) {
continue;
}
NbCbAccDetailTag tag = tagMap.get(summary.getAccDetailTagId());
if (!isCompleteLeafTag(tag)) {
continue;
}
String caliber = StringUtils.trimToNull(tag.getFinancialReportCaliber());
if (caliber == null) {
continue;
}
incomeByCaliber.put(caliber, incomeByCaliber.getOrDefault(caliber, BigDecimal.ZERO).add(defaultAmount(summary.getIncomeAmount())));
expenseByCaliber.put(caliber, expenseByCaliber.getOrDefault(caliber, BigDecimal.ZERO).add(defaultAmount(summary.getExpenseAmount())));
}
}
/**
* 加载内部往来检验明细
*
* @param startDate 开始日期
* @param endDate 结束日期
* @param internalAccountNo 内部账号
* @return 明细列表
*/
private List<NbCbAccDetail> loadInternalTransactions(Date startDate, Date endDate, List<String> internalAccountNo) {
if (CollectionUtils.isEmpty(internalAccountNo)) {
log.warn("内部往来检验账号范围为空,直接返回空明细列表, startDate:{}, endDate:{}",
DateUtil.formatDate(startDate), DateUtil.formatDate(endDate));
return Collections.emptyList();
}
List<NbCbAccDetail> details = nbCbAccDetailMapper.queryInternalTransactions(internalAccountNo,
DateUtil.formatDate(startDate) + " 00:00:00", DateUtil.formatDate(endDate) + " 23:59:59");
log.info("加载内部往来检验明细完成, startDate:{}, endDate:{}, internalAccountCount:{}, detailCount:{}",
DateUtil.formatDate(startDate), DateUtil.formatDate(endDate), internalAccountNo.size(), details.size());
return details;
}
/**
* 查询指定日期余额
*
* @param accountNos 账号列表
* @param date 查询日期
* @return 余额
*/
private BigDecimal loadBalanceForDate(List<String> accountNos, Date date) {
if (CollectionUtils.isEmpty(accountNos) || date == null) {
return BigDecimal.ZERO;
}
String queryDate = DateUtil.format(date, DATE_PATTERN);
List<NbCbAccount> nbCbAccounts = nbCbAccountService.queryNbCbAccountList(accountNos, queryDate, queryDate);
BigDecimal sdkBalance = nbCbAccounts.stream()
.map(NbCbAccount::getBal)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
if (sdkBalance.compareTo(BigDecimal.ZERO) != 0 || CollectionUtils.isNotEmpty(nbCbAccounts)) {
log.info("查询宁波余额完成, queryDate:{}, accountCount:{}, sdkBalance:{}", queryDate, accountNos.size(), sdkBalance);
return sdkBalance;
}
log.warn("宁波余额结果为空, 回退使用明细余额汇总, queryDate:{}, accountCount:{}", queryDate, accountNos.size());
List<NbCbAccDetail> detailBalances = nbCbAccDetailMapper.queryAccBalance(accountNos, DateUtil.beginOfDay(date));
BigDecimal detailBalance = detailBalances.stream()
.map(NbCbAccDetail::getBal)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
log.info("明细余额回退汇总完成, queryDate:{}, detailBalance:{}", queryDate, detailBalance);
return detailBalance;
}
/**
* 构建标签到叶子标签ID集合的映射
*
* @param allTags 全量标签
* @return 映射关系
*/
private Map<Integer, List<Integer>> buildLeafIdsByTag(List<NbCbAccDetailTag> allTags) {
Map<Integer, List<Integer>> result = new LinkedHashMap<>();
for (NbCbAccDetailTag tag : allTags) {
List<Integer> leafIds = allTags.stream()
.filter(this::isCompleteLeafTag)
.filter(item -> StringUtils.equals(item.getPath(), tag.getPath()) || StringUtils.startsWith(item.getPath(), tag.getPath() + ","))
.map(NbCbAccDetailTag::getId)
.collect(Collectors.toList());
if (CollectionUtils.isNotEmpty(leafIds)) {
result.put(tag.getId(), leafIds);
}
}
return result;
}
/**
* 查询所有有效标签
*
* @return 标签列表
*/
private List<NbCbAccDetailTag> listAllActiveTags() {
return nbCbAccDetailTagMapper.listAllActiveTags();
}
/**
* 查询启用中的内部账号
*
* @return 账号列表
*/
private List<String> listEnabledInternalAccounts() {
List<String> accountNos = nbCbDailyReportAccountMapper.listEnabledInternalAccounts();
if (CollectionUtils.isEmpty(accountNos)) {
log.warn("未查询到可用于内部往来检验的内部账号配置");
return Collections.emptyList();
}
return accountNos.stream().filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());
}
/**
* 查询余额统计使用的全部账号
*
* @return 账号列表
*/
private List<String> listAllBalanceAccountNos() {
NbCbAccountDTO queryDTO = new NbCbAccountDTO();
return nbCbAccountService.list(queryDTO).stream()
.map(NbCbAccount::getBankAcc)
.filter(StringUtils::isNotBlank)
.distinct()
.collect(Collectors.toList());
}
/**
* 是否需要补齐祖先节点
*
* @param queryDTO 查询条件
* @return 是否补齐
*/
private boolean shouldAppendAncestors(NbCbAccDetailTagQueryDTO queryDTO) {
return queryDTO != null && Boolean.TRUE.equals(queryDTO.getAppendAncestors());
}
/**
* 校验标签树查询参数
*
* @param queryDTO 查询条件
*/
private String validateAndQueryTagPath(NbCbAccDetailTagQueryDTO queryDTO) {
if (!Boolean.TRUE.equals(queryDTO.getDescendantOfId())) {
return null;
}
if (queryDTO.getId() == null) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "按节点ID查询子孙节点时,节点ID不能为空");
}
if (StringUtils.isNotBlank(queryDTO.getPath())) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "path与descendantOfId不能同时使用");
}
NbCbAccDetailTag current = loadActiveTagIfExists(queryDTO.getId());
if (current == null) {
log.info("标签树按节点ID查询子孙节点时,指定节点不存在, id:{}", queryDTO.getId());
return null;
}
return current.getPath();
}
/**
* 为树结果补齐祖先节点
*
* @param filtered 已过滤标签
* @param tagMap 标签映射
* @return 补齐后的标签
*/
private List<NbCbAccDetailTag> appendAncestorTags(List<NbCbAccDetailTag> filtered) {
Set<Integer> ancestorIds = new LinkedHashSet<>();
for (NbCbAccDetailTag tag : filtered) {
ancestorIds.add(tag.getId());
if (StringUtils.isNotBlank(tag.getPath())) {
for (String item : StringUtils.split(tag.getPath(), ",")) {
if (StringUtils.isNotBlank(item)) {
ancestorIds.add(Integer.parseInt(item));
}
}
}
}
if (CollectionUtils.isEmpty(ancestorIds)) {
return filtered;
}
log.info("开始补齐标签树祖先节点, filteredCount:{}, ancestorIdCount:{}", filtered.size(), ancestorIds.size());
return Optional.ofNullable(nbCbAccDetailTagMapper.listByIds(new ArrayList<>(ancestorIds)))
.orElse(Collections.emptyList());
}
/**
* 构建标签树
*
* @param tags 标签列表
* @return 树结构
*/
private List<NbCbAccDetailTagDTO> buildTagTree(List<NbCbAccDetailTag> tags) {
if (CollectionUtils.isEmpty(tags)) {
return Collections.emptyList();
}
Map<Integer, NbCbAccDetailTagDTO> dtoMap = new LinkedHashMap<>();
List<NbCbAccDetailTag> sortedTags = tags.stream()
.sorted(tagComparator())
.collect(Collectors.toList());
for (NbCbAccDetailTag tag : sortedTags) {
NbCbAccDetailTagDTO dto = new NbCbAccDetailTagDTO();
BeanUtils.copyProperties(tag, dto);
dto.setChildren(new ArrayList<>());
dtoMap.put(dto.getId(), dto);
}
List<NbCbAccDetailTagDTO> roots = new ArrayList<>();
for (NbCbAccDetailTagDTO dto : dtoMap.values()) {
if (dto.getParentId() != null && dtoMap.containsKey(dto.getParentId())) {
dtoMap.get(dto.getParentId()).getChildren().add(dto);
} else {
roots.add(dto);
}
}
return roots;
}
/**
* 标签排序规则
*
* @return 排序器
*/
private Comparator<NbCbAccDetailTag> tagComparator() {
return Comparator.comparing(NbCbAccDetailTag::getLevel)
.thenComparing(item -> item.getSortNum() == null ? Integer.MAX_VALUE : item.getSortNum())
.thenComparing(NbCbAccDetailTag::getId);
}
/**
* 校验标签重名
*
* @param currentId 当前ID
* @param parentId 父节点ID
* @param level 层级
* @param name 标签名称
*/
private void validateDuplicateTag(Integer currentId, Integer parentId, Integer level, String name) {
String trimName = StringUtils.trim(name);
if (Optional.ofNullable(nbCbAccDetailTagMapper.countDuplicateByParentAndLevel(currentId, parentId, level, trimName)).orElse(0) > 0) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR, "标签已存在,请修改后重试");
}
}
/**
* 刷新子孙节点路径
*
* @param oldPath 原路径
* @param oldPathName 原名称路径
* @param newPath 新路径
* @param newPathName 新名称路径
* @param operator 操作人
* @param now 更新时间
*/
private void refreshDescendantPath(String oldPath, String oldPathName, String newPath, String newPathName, String operator, Date now) {
if (StringUtils.isBlank(oldPath)) {
return;
}
nbCbAccDetailTagMapper.updateDescendantPath(oldPath, oldPathName, newPath, newPathName, operator, now);
}
/**
* 判断标签或其子孙标签是否已被明细使用
*
* @param tagId 标签ID
* @return 是否使用
*/
private boolean hasUsedTag(Integer tagId) {
NbCbAccDetailTag current = loadActiveTagIfExists(tagId);
if (current == null) {
return false;
}
List<Integer> ids = collectUsedCheckTagIds(current);
if (CollectionUtils.isEmpty(ids)) {
return false;
}
return Optional.ofNullable(nbCbAccDetailMapper.countByAccDetailTagIds(ids)).orElse(0) > 0;
}
/**
* 判断是否存在子标签
*
* @param tagId 标签ID
* @return 是否存在
*/
private boolean hasChildTag(Integer tagId) {
return Optional.ofNullable(nbCbAccDetailTagMapper.countChildTag(tagId)).orElse(0) > 0;
}
/**
* 统计当前标签下全部子孙标签数量
*
* @param current 当前标签
* @return 子孙标签数量
*/
private int countDescendantTag(NbCbAccDetailTag current) {
if (current == null || StringUtils.isBlank(current.getPath())) {
return 0;
}
return Optional.ofNullable(nbCbAccDetailTagMapper.countDescendantTag(current.getPath())).orElse(0);
}
/**
* 收集使用校验需要检查的三级标签ID
*
* @param current 当前标签
* @return 需要校验的三级标签ID
*/
private List<Integer> collectUsedCheckTagIds(NbCbAccDetailTag current) {
if (current == null) {
return Collections.emptyList();
}
if (Objects.equals(current.getLevel(), 3)) {
return Collections.singletonList(current.getId());
}
if (StringUtils.isBlank(current.getPath())) {
return Collections.emptyList();
}
return Optional.ofNullable(nbCbAccDetailTagMapper.listLeafTagIdsByPathPrefix(current.getPath())).orElse(Collections.emptyList());
}
/**
* 预处理标签保存上下文
*
* @param tagDTO 标签信息
* @return 保存上下文
*/
private NbCbAccDetailTagSaveContext prepareSaveTagContext(NbCbAccDetailTagDTO tagDTO) {
RpcAssert.assertNotNull(tagDTO, DefaultErrorEnum.DATA_NULL, "标签信息不能为空");
if (StringUtils.isBlank(tagDTO.getName())) {
throw new RpcServiceException(DefaultErrorEnum.PARAMETER_NULL, "标签名称不能为空");
}
NbCbAccDetailTag parent = null;
int targetLevel = 1;
if (tagDTO.getParentId() != null) {
parent = loadTag(tagDTO.getParentId());
targetLevel = parent.getLevel() + 1;
}
if (targetLevel > 3) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
"系统提醒:最大允许配置 3 级类目标签。当前选中的科目已达第 3 级上限,无法继续添加。");
}
NbCbAccDetailTag current = null;
String oldPath = null;
String oldPathName = null;
if (tagDTO.getId() != null) {
current = loadTag(tagDTO.getId());
oldPath = current.getPath();
oldPathName = current.getPathName();
if (hasUsedTag(tagDTO.getId())) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
"该级账务标签正处于前端流水账目的核对标记状态中,一旦修改将损坏历史标签信息,严禁修改!");
}
}
validateDuplicateTag(tagDTO.getId(), tagDTO.getParentId(), targetLevel, tagDTO.getName());
NbCbAccDetailTagSaveContext context = new NbCbAccDetailTagSaveContext();
context.setParent(parent);
context.setCurrent(current);
context.setOldPath(oldPath);
context.setOldPathName(oldPathName);
context.setTargetLevel(targetLevel);
return context;
}
/**
* 预处理标签删除上下文
*
* @param tagDTO 标签信息
* @return 当前标签
*/
private NbCbAccDetailTag prepareDeleteTag(NbCbAccDetailTagDTO tagDTO) {
RpcAssert.assertNotNull(tagDTO, DefaultErrorEnum.DATA_NULL, "标签信息不能为空");
RpcAssert.assertNotNull(tagDTO.getId(), DefaultErrorEnum.PARAMETER_NULL, "标签ID不能为空");
NbCbAccDetailTag tag = loadTag(tagDTO.getId());
if (hasUsedTag(tag.getId())) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
"该级账务标签正处于前端流水账目的核对标记状态中,一旦移除将损坏历史标签信息,严禁删除!");
}
int childCount = countDescendantTag(tag);
if (childCount > 0) {
throw new RpcServiceException(DefaultErrorEnum.SERVER_ERROR,
"该标签下方仍挂载有 " + childCount + " 个明细子科目。按财务审计合规规范,禁止直接穿透级联删除!请先由最底层向外逐级清理。");
}
return tag;
}
/**
* 加载有效标签
*
* @param id 标签ID
* @return 标签
*/
private NbCbAccDetailTag loadTag(Integer id) {
NbCbAccDetailTag tag = nbCbAccDetailTagMapper.selectByPrimaryKey(id);
if (tag == null || !StringUtils.equals(tag.getDeletedFlag(), BaseModel.DeletedFlagEnum.N.name())) {
throw new RpcServiceException(DefaultErrorEnum.DATA_NOT_EXIST, "标签不存在");
}
return tag;
}
/**
* 按主键加载有效标签
*
* 仅用于查询场景,节点不存在时返回空,避免树查询因无效入参直接抛错。
*
* @param id 标签ID
* @return 有效标签
*/
private NbCbAccDetailTag loadActiveTagIfExists(Integer id) {
if (id == null) {
return null;
}
NbCbAccDetailTag tag = nbCbAccDetailTagMapper.selectByPrimaryKey(id);
if (tag == null || !StringUtils.equals(tag.getDeletedFlag(), BaseModel.DeletedFlagEnum.N.name())) {
return null;
}
return tag;
}
/**
* 判断是否为完整三级叶子标签
*
* @param tag 标签
* @return 是否完整
*/
private boolean isCompleteLeafTag(NbCbAccDetailTag tag) {
return tag != null
&& Objects.equals(tag.getLevel(), 3)
&& StringUtils.isNotBlank(tag.getFinancialReportCaliber())
&& (tag.getStatus() == null || Objects.equals(tag.getStatus(), 1));
}
/**
* 构建月份列表
*
* @param startDate 开始日期
* @param endDate 结束日期
* @return 月份列表
*/
private List<String> buildMonthKeys(Date startDate, Date endDate) {
List<String> monthKeys = new ArrayList<>();
DateTime current = DateUtil.beginOfMonth(startDate);
DateTime endMonth = DateUtil.beginOfMonth(endDate);
while (!current.after(endMonth)) {
monthKeys.add(DateUtil.format(current, MONTH_PATTERN));
current = DateUtil.offsetMonth(current, 1);
}
return monthKeys;
}
/**
* 解析日期,统一归一到当天开始时间。
*
* @param date 查询日期
* @param defaultDate 默认日期
* @return 归一化后的日期
*/
private Date resolveDate(Date date, Date defaultDate) {
Date target = date == null ? defaultDate : date;
return DateUtil.beginOfDay(target);
}
/**
* 判断是否收入
*
* @param detail 明细
* @return 是否收入
*/
private boolean isIncome(NbCbAccDetail detail) {
return detail != null && StringUtils.equals(detail.getCdSign(), "0");
}
/**
* 默认金额
*
* @param amount 金额
* @return 非空金额
*/
private BigDecimal defaultAmount(BigDecimal amount) {
return amount == null ? BigDecimal.ZERO : amount;
}
/**
* 初始化一行数据
*
* @param size 列数
* @param rowTitle 行标题
* @return 行数据
*/
private List<Object> initRow(int size, String rowTitle) {
List<Object> row = new ArrayList<>(Collections.nCopies(size, ""));
row.set(0, rowTitle);
return row;
}
/**
* 构建汇总说明行
*
* @param label 标签
* @param value 值
* @param size 列数
* @return 行数据
*/
private List<Object> summaryRow(String label, String value, int size) {
List<Object> row = new ArrayList<>(Collections.nCopies(size, ""));
row.set(0, label);
if (size > 1) {
row.set(1, value);
}
return row;
}
/**
* 构建带层级缩进的标签名称
*
* @param tag 标签
* @return 展示名称
*/
private String buildIndentedTagName(NbCbAccDetailTag tag) {
if (tag == null) {
return "";
}
if (Objects.equals(tag.getLevel(), 1)) {
return tag.getName();
}
if (Objects.equals(tag.getLevel(), 2)) {
return " " + tag.getName();
}
return " " + tag.getName();
}
/**
* 汇总叶子标签金额
*
* @param monthAmountMap 月份金额映射
* @param leafIds 叶子标签ID
* @return 汇总金额
*/
private BigDecimal sumLeafAmount(Map<Integer, BigDecimal> monthAmountMap, List<Integer> leafIds) {
if (monthAmountMap == null || CollectionUtils.isEmpty(leafIds)) {
return BigDecimal.ZERO;
}
BigDecimal result = BigDecimal.ZERO;
for (Integer leafId : leafIds) {
result = result.add(monthAmountMap.getOrDefault(leafId, BigDecimal.ZERO));
}
return result;
}
/**
* 格式化月份列名
*
* @param month 月份
* @return 列名
*/
private String formatMonthColumn(String monthKey) {
return DateUtil.format(DateUtil.parse(monthKey, MONTH_PATTERN), "yy年M月");
}
/**
* 解析收支标志展示值。
*
* @param detail 明细
* @return 展示值
*/
private String resolveCdSignName(NbCbAccDetail detail) {
if (detail == null) {
return "";
}
if (StringUtils.isNotBlank(detail.getCdSignName())) {
return detail.getCdSignName();
}
if (isIncome(detail)) {
return "收入";
}
return "支出";
}
/**
* 解析回单状态展示值。
*
* @param detail 明细
* @return 展示值
*/
private String resolveReceiptStatus(NbCbAccDetail detail) {
if (detail == null) {
return "";
}
return StringUtils.isNotBlank(detail.getReceiptInfo()) || StringUtils.isNotBlank(detail.getMatchCode()) ? "是" : "否";
}
/**
* 解析同步状态展示值。
*
* @param syncFlag 同步标志
* @return 展示值
*/
private String resolveSyncStatus(Byte syncFlag) {
if (syncFlag == null) {
return "";
}
return Objects.equals(syncFlag, (byte) 1) ? "成功" : "失败";
}
/**
* 解析回单同步状态展示值。
*
* @param detail 明细
* @return 展示值
*/
private String resolveReceiptSyncStatus(NbCbAccDetail detail) {
if (detail == null) {
return "";
}
if (StringUtils.isNotBlank(detail.getReceiptInfo()) || StringUtils.isNotBlank(detail.getMatchCode())) {
return "成功";
}
return "";
}
/**
* 解析数据来源展示值。
*
* @param dataSource 数据来源
* @return 展示值
*/
private String resolveDataSource(Integer dataSource) {
if (Objects.equals(dataSource, 1)) {
return "宁波财资";
}
if (Objects.equals(dataSource, 2)) {
return "人工导入";
}
return "";
}
/**
* 格式化金额
*
* @param amount 金额
* @return 字符串金额
*/
private String formatDecimal(BigDecimal amount) {
if (amount == null) {
return "";
}
return amount.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
}
}
...@@ -42,6 +42,7 @@ ...@@ -42,6 +42,7 @@
<result column="label_value2" property="labelValue2" jdbcType="VARCHAR" /> <result column="label_value2" property="labelValue2" jdbcType="VARCHAR" />
<result column="label_value3" property="labelValue3" jdbcType="VARCHAR" /> <result column="label_value3" property="labelValue3" jdbcType="VARCHAR" />
<result column="label_value4" property="labelValue4" jdbcType="VARCHAR" /> <result column="label_value4" property="labelValue4" jdbcType="VARCHAR" />
<result column="acc_detail_tag_id" property="accDetailTagId" jdbcType="INTEGER" />
<result column="sort_rule" property="sortRule" jdbcType="VARCHAR" /> <result column="sort_rule" property="sortRule" jdbcType="VARCHAR" />
<result column="order_no" property="orderNo" jdbcType="VARCHAR" /> <result column="order_no" property="orderNo" jdbcType="VARCHAR" />
<result column="alipay_trade_name" property="alipayTradeName" jdbcType="VARCHAR" /> <result column="alipay_trade_name" property="alipayTradeName" jdbcType="VARCHAR" />
...@@ -65,6 +66,9 @@ ...@@ -65,6 +66,9 @@
<resultMap id="DTOResultMap" type="cn.com.glsx.dj.financial.dto.NbCbAccDetailDTO" extends="BaseResultMap"> <resultMap id="DTOResultMap" type="cn.com.glsx.dj.financial.dto.NbCbAccDetailDTO" extends="BaseResultMap">
<result column="receipt_jd_sync" property="receiptJdSync" jdbcType="TINYINT" /> <result column="receipt_jd_sync" property="receiptJdSync" jdbcType="TINYINT" />
<result column="acc_detail_tag_path_name" property="accDetailTagPathName" jdbcType="VARCHAR" />
<result column="financial_report_caliber" property="financialReportCaliber" jdbcType="VARCHAR" />
<result column="acc_detail_tag_name" property="accDetailTagName" jdbcType="VARCHAR" />
<collection property="logList" ofType="cn.com.glsx.dj.financial.model.NbCbDetailLog"> <collection property="logList" ofType="cn.com.glsx.dj.financial.model.NbCbDetailLog">
<id column="dl_id" property="id" jdbcType="BIGINT" /> <id column="dl_id" property="id" jdbcType="BIGINT" />
<id column="dl_acc_detail_id" property="accDetailId" jdbcType="BIGINT" /> <id column="dl_acc_detail_id" property="accDetailId" jdbcType="BIGINT" />
...@@ -90,6 +94,14 @@ ...@@ -90,6 +94,14 @@
</association> </association>
</resultMap> </resultMap>
<resultMap id="tagAmountSummaryMap" type="cn.com.glsx.dj.financial.service.nb.NbCbAccDetailTagAmountSummary">
<result column="month_key" property="monthKey" jdbcType="VARCHAR"/>
<result column="acc_detail_tag_id" property="accDetailTagId" jdbcType="INTEGER"/>
<result column="income_amount" property="incomeAmount" jdbcType="DECIMAL"/>
<result column="expense_amount" property="expenseAmount" jdbcType="DECIMAL"/>
<result column="signed_amount" property="signedAmount" jdbcType="DECIMAL"/>
</resultMap>
<sql id="Base_Column_List" > <sql id="Base_Column_List" >
<!-- <!--
WARNING - @mbg.generated WARNING - @mbg.generated
...@@ -99,7 +111,7 @@ ...@@ -99,7 +111,7 @@
voucher_no, bif_code, bank_type, opp_bank_type, is_for_individual, serial_id, bank_serial_id, voucher_no, bif_code, bank_type, opp_bank_type, is_for_individual, serial_id, bank_serial_id,
group_trans, capital_trans, post_script, cash_tfr_flg, pay_bill_code, china_develop_bank_no, group_trans, capital_trans, post_script, cash_tfr_flg, pay_bill_code, china_develop_bank_no,
china_develop_acc_type, alipay_base_order_number, alipay_business_description, label_value1, china_develop_acc_type, alipay_base_order_number, alipay_business_description, label_value1,
label_value2, label_value3, label_value4, sort_rule, order_no, alipay_trade_name, label_value2, label_value3, label_value4, acc_detail_tag_id, sort_rule, order_no, alipay_trade_name,
com_pre_remarks, match_code, receipt_info, bill_num, rec_time, opp_area_code, opp_bank_no, com_pre_remarks, match_code, receipt_info, bill_num, rec_time, opp_area_code, opp_bank_no,
jd_sync, jd_id, h5_jd_sync, created_date, created_by, updated_date, updated_by, deleted_flag jd_sync, jd_id, h5_jd_sync, created_date, created_by, updated_date, updated_by, deleted_flag
</sql> </sql>
...@@ -138,8 +150,12 @@ ...@@ -138,8 +150,12 @@
dl.deleted_flag dl_deleted_flag dl.deleted_flag dl_deleted_flag
from from
( (
select ad.*, ncr.jd_sync as receipt_jd_sync select ad.*, ncr.jd_sync as receipt_jd_sync,
tag.path_name as acc_detail_tag_path_name,
tag.financial_report_caliber as financial_report_caliber,
tag.name as acc_detail_tag_name
from nb_cb_acc_detail ad from nb_cb_acc_detail ad
left join nb_cb_acc_detail_tag tag on ad.acc_detail_tag_id = tag.id and tag.deleted_flag = 'N'
left join nb_cb_receipt ncr on ncr.match_code = ad.match_code and ncr.sub_serial_no = ad.sub_serial_no left join nb_cb_receipt ncr on ncr.match_code = ad.match_code and ncr.sub_serial_no = ad.sub_serial_no
<include refid="conditionForDetailList"/> <include refid="conditionForDetailList"/>
order by ad.trans_time desc order by ad.trans_time desc
...@@ -152,6 +168,7 @@ ...@@ -152,6 +168,7 @@
<select id="list_COUNT" resultType="Long"> <select id="list_COUNT" resultType="Long">
select count(*) select count(*)
from nb_cb_acc_detail ad from nb_cb_acc_detail ad
left join nb_cb_acc_detail_tag tag on ad.acc_detail_tag_id = tag.id and tag.deleted_flag = 'N'
left join nb_cb_receipt ncr on ncr.match_code = ad.match_code and ncr.sub_serial_no = ad.sub_serial_no left join nb_cb_receipt ncr on ncr.match_code = ad.match_code and ncr.sub_serial_no = ad.sub_serial_no
<include refid="conditionForDetailList"/> <include refid="conditionForDetailList"/>
</select> </select>
...@@ -277,6 +294,22 @@ ...@@ -277,6 +294,22 @@
and ad.data_source = #{dataSource} and ad.data_source = #{dataSource}
</if> </if>
<if test="accDetailTagId != null">
and ad.acc_detail_tag_id in (
select child.id
from nb_cb_acc_detail_tag current_tag
inner join nb_cb_acc_detail_tag child
on child.deleted_flag = 'N'
and (child.path = current_tag.path or child.path like CONCAT(current_tag.path, ',%'))
where current_tag.id = #{accDetailTagId}
and current_tag.deleted_flag = 'N'
)
</if>
<if test="financialReportCaliber != null and financialReportCaliber != ''">
and tag.financial_report_caliber like CONCAT('%',#{financialReportCaliber},'%')
</if>
<if test="transTimeStart != null"> <if test="transTimeStart != null">
<![CDATA[ and ad.trans_time >= #{transTimeStart} ]]> <![CDATA[ and ad.trans_time >= #{transTimeStart} ]]>
</if> </if>
...@@ -382,6 +415,22 @@ ...@@ -382,6 +415,22 @@
and ad.data_source = #{dataSource} and ad.data_source = #{dataSource}
</if> </if>
<if test="accDetailTagId != null">
and ad.acc_detail_tag_id in (
select child.id
from nb_cb_acc_detail_tag current_tag
inner join nb_cb_acc_detail_tag child
on child.deleted_flag = 'N'
and (child.path = current_tag.path or child.path like CONCAT(current_tag.path, ',%'))
where current_tag.id = #{accDetailTagId}
and current_tag.deleted_flag = 'N'
)
</if>
<if test="financialReportCaliber != null and financialReportCaliber != ''">
and tag.financial_report_caliber like CONCAT('%',#{financialReportCaliber},'%')
</if>
<if test="transTimeStart != null"> <if test="transTimeStart != null">
<![CDATA[ and ad.trans_time >= #{transTimeStart} ]]> <![CDATA[ and ad.trans_time >= #{transTimeStart} ]]>
</if> </if>
...@@ -418,9 +467,39 @@ ...@@ -418,9 +467,39 @@
#{item} #{item}
</foreach> </foreach>
</select> </select>
<update id="updateAccDetailTagBatch">
update nb_cb_acc_detail
set acc_detail_tag_id = #{accDetailTagId},
updated_by = #{updatedBy},
updated_date = #{updatedDate}
where id in
<foreach collection="ids" item="item" open="(" separator="," close=")">
#{item}
</foreach>
and deleted_flag = 'N'
</update>
<select id="queryTagAmountSummary" resultMap="tagAmountSummaryMap">
select
substring(trans_time, 1, 7) as month_key,
acc_detail_tag_id,
sum(case when cd_sign = '0' then amt else 0 end) as income_amount,
sum(case when cd_sign = '1' then amt else 0 end) as expense_amount,
sum(case when cd_sign = '0' then amt else -amt end) as signed_amount
from nb_cb_acc_detail
where deleted_flag = 'N'
and acc_detail_tag_id is not null
and trans_time <![CDATA[>=]]> #{startDateTime}
and trans_time <![CDATA[<=]]> #{endDateTime}
group by substring(trans_time, 1, 7), acc_detail_tag_id
order by month_key asc, acc_detail_tag_id asc
</select>
<select id="listDistinctBankAcc" resultType="java.lang.String"> <select id="listDistinctBankAcc" resultType="java.lang.String">
select distinct(bank_acc) select distinct(bank_acc)
from nb_cb_acc_detail ad from nb_cb_acc_detail ad
left join nb_cb_acc_detail_tag tag on ad.acc_detail_tag_id = tag.id and tag.deleted_flag = 'N'
<include refid="listCondition"/> <include refid="listCondition"/>
</select> </select>
...@@ -479,6 +558,35 @@ ...@@ -479,6 +558,35 @@
and abs not like '%资金归集%' and abs not like '%资金归集%'
order by cast(trans_time as datetime) desc order by cast(trans_time as datetime) desc
</select> </select>
<select id="queryInternalTransactions" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from nb_cb_acc_detail
where deleted_flag = 'N'
and bank_acc in
<foreach collection="accountNos" item="item" open="(" separator="," close=")">
#{item}
</foreach>
and opp_acc_no in
<foreach collection="accountNos" item="item" open="(" separator="," close=")">
#{item}
</foreach>
and trans_time <![CDATA[>=]]> #{startDateTime}
and trans_time <![CDATA[<=]]> #{endDateTime}
order by trans_time desc, id desc
</select>
<select id="countByAccDetailTagIds" resultType="java.lang.Integer">
select count(1)
from nb_cb_acc_detail
where deleted_flag = 'N'
and acc_detail_tag_id in
<foreach collection="tagIds" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</select>
<select id="selectByReceiptIds" resultMap="BaseResultMap"> <select id="selectByReceiptIds" resultMap="BaseResultMap">
select select
d.* d.*
...@@ -581,4 +689,4 @@ ...@@ -581,4 +689,4 @@
and (d.h5_jd_sync = 0 or d.h5_jd_sync is null) and (d.h5_jd_sync = 0 or d.h5_jd_sync is null)
</select> </select>
</mapper>
\ No newline at end of file \ No newline at end of file
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.financial.mapper.NbCbAccDetailTagMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.financial.model.NbCbAccDetailTag">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="parent_id" property="parentId" jdbcType="INTEGER"/>
<result column="level" property="level" jdbcType="INTEGER"/>
<result column="path" property="path" jdbcType="VARCHAR"/>
<result column="path_name" property="pathName" jdbcType="VARCHAR"/>
<result column="financial_report_caliber" property="financialReportCaliber" jdbcType="VARCHAR"/>
<result column="sort_num" property="sortNum" jdbcType="INTEGER"/>
<result column="status" property="status" jdbcType="INTEGER"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
<result column="created_date" property="createdDate" jdbcType="TIMESTAMP"/>
<result column="created_by" property="createdBy" jdbcType="VARCHAR"/>
<result column="updated_date" property="updatedDate" jdbcType="TIMESTAMP"/>
<result column="updated_by" property="updatedBy" jdbcType="VARCHAR"/>
<result column="deleted_flag" property="deletedFlag" jdbcType="CHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, name, parent_id, level, path, path_name, financial_report_caliber, sort_num,
status, remark, created_date, created_by, updated_date, updated_by, deleted_flag
</sql>
<select id="queryTagTreeByCondition" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from nb_cb_acc_detail_tag
<where>
deleted_flag = 'N'
<if test="query != null and query.id != null and (query.descendantOfId == null or !query.descendantOfId)">
and id = #{query.id}
</if>
<if test="query != null and query.parentId != null">
and parent_id = #{query.parentId}
</if>
<if test="query != null and query.level != null">
and level = #{query.level}
</if>
<if test="query != null and query.nameLike != null and query.nameLike != ''">
and name like concat('%', #{query.nameLike}, '%')
</if>
<if test="query != null and query.onlyComplete != null and query.onlyComplete">
and level = 3
and (status is null or status = 1)
and financial_report_caliber is not null
and financial_report_caliber != ''
</if>
<if test="query != null and query.path != null and query.path != ''">
and (path = #{query.path} or path like concat(#{query.path}, ',%'))
</if>
</where>
order by level asc, sort_num asc, id asc
</select>
<select id="listAllActiveTags" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
order by level asc, sort_num asc, id asc
</select>
<select id="listByIds" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
<if test="ids != null and ids.size() > 0">
and id in
<foreach collection="ids" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
</if>
order by level asc, sort_num asc, id asc
</select>
<select id="countChildTag" resultType="java.lang.Integer">
select count(1)
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
and parent_id = #{tagId}
</select>
<select id="countDescendantTag" resultType="java.lang.Integer">
select count(1)
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
and path like concat(#{pathPrefix}, ',%')
</select>
<select id="listLeafTagIdsByPathPrefix" resultType="java.lang.Integer">
select id
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
and level = 3
and path like concat(#{pathPrefix}, ',%')
order by sort_num asc, id asc
</select>
<select id="countDuplicateByParentAndLevel" resultType="java.lang.Integer">
select count(1)
from nb_cb_acc_detail_tag
where deleted_flag = 'N'
and level = #{level}
and name = #{name}
and
<choose>
<when test="parentId == null">
parent_id is null
</when>
<otherwise>
parent_id = #{parentId}
</otherwise>
</choose>
<if test="currentId != null">
and id != #{currentId}
</if>
</select>
<update id="updateDescendantPath">
update nb_cb_acc_detail_tag
set path = concat(#{newPath}, substring(path, char_length(#{oldPath}) + 1)),
path_name = concat(#{newPathName}, substring(path_name, char_length(#{oldPathName}) + 1)),
updated_by = #{operator},
updated_date = #{now}
where deleted_flag = 'N'
and path like concat(#{oldPath}, ',%')
</update>
</mapper>
...@@ -26,4 +26,12 @@ ...@@ -26,4 +26,12 @@
id, account, company_name, short_name, bank_name, remark, company_level, domestic, id, account, company_name, short_name, bank_name, remark, company_level, domestic,
status, created_by, created_date, updated_by, updated_date status, created_by, created_date, updated_by, updated_date
</sql> </sql>
</mapper>
\ No newline at end of file \ No newline at end of file
<select id="listEnabledInternalAccounts" resultType="java.lang.String">
select distinct account
from nb_cb_daily_report_account
where status = 1
and account is not null
and account != ''
</select>
</mapper>
  • @wangxw1
    commented
    Master

    你好!以下是对你提交的代码的专业审查意见。整体来看,代码结构清晰,DTO 封装规范,Swagger 注释完整,且 Commit Message 质量很高。但在 Dubbo 异常处理、批量操作的边界防护以及参数校验方面存在一些需要优化的隐患。

    一、关键问题与优化建议(Top 3)

    1. Dubbo 服务提供者异常捕获不完整(重要性:高,影响稳定性与契约)

    问题描述:在 NbCbAccDetailTagSummaryRemoteImpl 中,所有的接口方法均只捕获了自定义的 RpcServiceException。 影响分析:如果服务内部抛出了未预期的运行时异常(如 NullPointerException、数据库的 DuplicateKeyException 或 BadSqlGrammarException 等),这些异常将不会被捕获,而是直接抛给 Dubbo 框架。这会导致 RpcResponse 的统一返回契约被破坏,同时可能引发消费者端的反序列化异常(如果消费者端没有该异常类),严重影响系统稳定性。 优化建议:增加对 Exception(或 Throwable)的兜底捕获,确保所有未捕获异常都能被正确包装进 RpcResponse.error() 中。 代码示例:

        @Override
        public RpcResponse<Boolean> bindDetailTag(NbCbAccDetailTagBindDTO bindDTO) {
            try {
                return RpcResponse.success(nbCbAccDetailTagSummaryService.bindDetailTag(bindDTO));
            } catch (RpcServiceException e) {
                log.error("业务异常: {}", e.getMessage(), e);
                return RpcResponse.error(e);
            } catch (Exception e) {
                log.error("系统未知异常: {}", e.getMessage(), e);
                // 建议在 RpcResponse 中定义通用的系统错误码
                return RpcResponse.error("500", "系统内部异常"); 
            }
        }
    

    2. 批量操作缺乏数量上限约束(重要性:中,影响性能与健壮性)

    问题描述:NbCbAccDetailTagBindDTO 中的 detailIds 列表以及 NbCbAccDetailMapper.updateAccDetailTagBatch 方法,没有对传入的 ID 集合大小进行限制。 影响分析:如果前端触发了“全选”或者恶意传入超大的数组(例如 10 万个 ID),MyBatis 拼接出的 IN (...) SQL 语句会极其庞大。这极易突破 MySQL 的 max_allowed_packet 限制导致 SQL 执行失败,或者引发严重的慢查询,拖垮数据库。 优化建议:

    1. 在 DTO 层使用 JSR-303 注解限制集合大小(需配合 @Validated 生效)。
    2. 在 Service 层对超大集合使用 Lists.partition(ids, 1000) 进行分批处理。 代码示例: java @ApiModelProperty(value = "明细ID集合,单条传一个元素,批量传多个元素", required = true) @NotEmpty(message = "明细ID集合不能为空") @Size(max = 1000, message = "单次批量操作最多支持1000条") // 增加上限约束 private List<Long> detailIds;

    3. DTO 内部字段缺乏 JSR-303 校验注解(重要性:中,影响健壮性)

    问题描述:在 Dubbo 接口 NbCbAccDetailTagSummaryRemote 中,虽然使用了 @NotNull 校验入参对象本身是否为空,并且类上加了 @DubboService(validation = "true"),但是各个 DTO(如 NbCbAccDetailTagBindDTO、NbCbAccDetailTagDTO)内部的必填字段(如 detailIds)仅有 Swagger 的 required = true 标识,缺失了真正的 JSR-303 校验注解。 影响分析:Swagger 的 required 仅用于生成前端文档,不会在运行时拦截非法参数。如果调用方传入了 bindDTO 实例,但其内部的 detailIds 为 null 或空集合,请求会直接打到 Service 层甚至数据库层,可能引发 NPE 或错误的 SQL 执行。 优化建议:在 DTO 的必填字段上添加 @NotBlank、@NotNull、@NotEmpty 等注解。


    二、评分明细

    • 功能实现的正确性与健壮性(34/40分)
      • 理由:业务逻辑划分清晰,接口定义规范。扣分点在于 Dubbo 异常兜底处理缺失,以及未提供 MyBatis XML 文件(特别提醒:请务必确保新增的 Mapper XML 中没有使用任何子查询,严格遵守团队底线规则)。
    • 安全性与潜在风险(28/30分)
      • 理由:代码中未见明显的越权或注入风险。扣分点在于批量更新 IN 集合无边界控制,极端情况下可能引发数据库层面的拒绝服务(DoS)风险。
    • 最佳实践与可维护性(16/20分)
      • 理由:使用了 Lombok 和 Swagger,代码结构良好,分包合理。扣分点:DTO 中的时间字段使用了较老的 java.util.Date 并硬编码了 GMT+8 时区,现代 Java 开发推荐使用 java.time.LocalDateTime 配合全局时区配置;缺少字段级校验注解。
    • 性能与资源利用(4/5分)
      • 理由:整体资源利用合理。扣分点在于批量更新时如果数据量过大,未进行分批处理会造成内存和数据库网络 I/O 的瞬时压力。
    • 提交信息质量(5/5分)
      • 理由:Commit Message 非常优秀,遵循了 Angular 规范(feat(financial): ...),通过分点详细描述了变更内容,具有极高的可追溯性。

    总分:87分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!