Commit d7f6b5a33077e6dd88f9ed1a430295512d5b4802

Authored by 房远帅
1 parent 1fcd7b1a

采购-资金支付:资金支付台账

Showing 26 changed files with 2247 additions and 28 deletions
... ... @@ -185,6 +185,41 @@ public GetXxxBo(Xxx dto) {
185 185 **本次实现(2026-11-10)**:`requestDate=LocalDate.now()`、`payMethod` 固定「电汇」由 `buildDraft` 统一写入;自动带出来源单信息、请款附件、明细预付金额与合计;对方户名/开户行/账号、请款说明、补充说明附件、明细申请金额留空由 `update` 补充(`update` 的 `matchApplyAmount` 仍要求传全量明细,编辑页从详情 `lines` 取 `planId` 后逐行填 `applyAmount`)。
186 186 **后续调整(2026-11-10)**:删除 `GetFundPaymentGenerateDataBo`(含 `LineBo`)与 `getGenerateData` 中「从落库单据读回再组装 Bo」的整段;Service 方法改名 `generate` 返回 `String`,Controller 返回 `InvokeResult<String>`。接口路径 `/generateData` 保留兼容,Swagger 文案改为「调用即落库,仅返回请款单ID」。
187 187
  188 +## 29. 新建「资金台账」这类宽表模块:包/表名避让 + 五处列名对齐 + 分月筛选
  189 +
  190 +**坑**:项目已有「应收款台账」占用 `sc/impl/ledger`、`sc/controller/ledger`、`resources/mappers/ledger` 和 `receipt_ledger_info` 表;新台账若直接叫 `ledger` 会混淆。宽表 60+ 字段,DDL / Entity / resultMap / `<sql>` SELECT / Bo 任一处漏列或拼错列名,都是运行时才暴露(Java 编译查不出)。分月筛选用 `YEAR(col)/MONTH(col)` 会让索引失效。
  191 +**后果**:包冲突或 SQL 报 Unknown column;列表字段悄悄返回 null 且无人发现;按月查询全表扫描。
  192 +**正确做法**:
  193 +1. 新模块用独立包名/表名(本次 `procurement/fundledger` + `fund_ledger`),表名字符集跟随同业务老表(资金支付系 `utf8mb3`)。先 Grep 全仓确认无同名表。
  194 +2. 写完后用脚本比对 DDL 列名、实体字段(驼峰转下划线)、resultMap column、公共 SELECT 列、Bo 字段五处集合,必须完全一致(本次各 70 列,Bo 有意少 `createById/updateById` 两个不对外字段)。
  195 +3. 分月筛选:Vo 收 `Integer year + Integer month`,Controller 用 `YearMonth.of(y,m).atDay(1)/atEndOfMonth()` 换算成 `LocalDate applyDateStart/applyDateEnd`,XML 用 `>= / <=`(可用 `idx_apply_date`);同时保留日期区间入参供「申报日期」筛选,两组共用同一组条件。
  196 +4. 权限后缀照抄既有:查询 `:query`、修改 `:modify`、平账 `:reconciliation`(应收款台账已有);**不要自创 `:red`**(第 21 条),冲红复用 `:modify`。
  197 +5. 派生字段(欠票额/欠单额/增票余款/对比/是否清欠等)在「先做基础方法」阶段只建列 + 注释写清公式,**不写回填/重算**;但「平账后是否清欠改为否」这类状态动作属于基础方法,要在 Service 内落库(`lambdaUpdate().set(..., false)`),不可留给后续。
  198 +**本次实现(2026-11-13)**:`fund_ledger` 一个计划一条(`uk_fl_plan_id`),基础方法 = 分页列表 / 详情 / 修改(来票时间·数量·金额、出库单数量、备注)/ 冲红(金额·说明·附件)/ 平账(说明·附件 + 清欠校验与置否)。列表与详情共用 `GetFundLedgerBo`(第 28 条口径,不复制第二份 Bo)。台账行生成与各业务字段的数据更新逻辑本期明确不做。
  199 +
  200 +## 30. 取 `@TableField(exist = false)` 字段必须走带联表的 Mapper 方法,MP 内置查询恒为 null
  201 +
  202 +**坑**:这类字段不是数据库列(值来自 JOIN 其它表或 GROUP_CONCAT),`selectById` / `selectList` / `selectBatchIds` / `getById` / `this.list()` 都不会查询它,结果永远 null,且编译和 IDE 诊断都不报错。资金台账刷新就踩了两次:
  203 +1. `procurementPlanMapper.selectById(planId)` 取 `purchaseDepartmentName` / `regionName` / `supplierName`,实际全是 null(改用 `findById`,XML 里 JOIN `sys_dept` / `base_data_company_short` / 供应商表);
  204 +2. `procurementPlanLineMapper.selectList(...)` 取 `productName`(来自 `LEFT JOIN base_data_breed_relationship br`),台账「品种」列全空(改用 `getByProcurementPlanId`)。
  205 +
  206 +**常见非持久化字段(取数前先看实体注解,不要凭字段名猜)**:
  207 +- `ProcurementPlan`:`supplierName`、`companyShortName`、`companyFullName`、`purchaseDepartmentName`、`regionName`、`priceCode`、`workshopName`、`showExamine`、`showExamineDetail`、`showApplyPayment`
  208 +- `ProcurementPlanLine`:`planCode`、`productName`、`workshopName`
  209 +- `ProcurementWeighingTicket`:`workshopCode`、`planCodes`、`planIds`、`showExamine`、`showExamineDetail`、`showApplyPayment`
  210 +- `ProcurementWarehouseReceiveOrder`:`planDate`、`workshopCode`、`showExamine`、`showExamineDetail`、`showApplyPayment`(注意该实体的 `planCodes`/`planIds`/`workshopName` 是数据库冗余列,可直接用内置查询)
  211 +- `ShipmentsPlan`:`workshopName`
  212 +- `FundPaymentRequest`:`showExamine`、`showExamineDetail`(由代码填充,不是查询)
  213 +
  214 +**后果**:字段静默为空,页面列空白、按名称匹配/限额计算失效,运行时无任何报错,排查成本高。
  215 +
  216 +**正确做法**:
  217 +1. 取数写代码前先确认目标实体字段是否带 `@TableField(exist = false)`;只要带,禁止用 MP 内置查询方法取值。
  218 +2. 改用 Mapper XML 里带联表的方法:`procurementPlanMapper.findById(id)`、`procurementPlanLineMapper.getByProcurementPlanId(planId)` / `getByProcurementPlanIds(ids)`、`shipmentsPlanMapper.getById(id)`;没有现成方法就在该 Mapper XML 公共 `<sql>` 片段补 JOIN 与列,再新增查询方法。
  219 +3. 只用到数据库列的取数(如仅 `code`、`deliveryMode`、`settlementRatio`、`approvalStatus`)继续用内置查询即可,不必一律替换。
  220 +4. 同类禁止:`@TableField(exist = false)` 字段也不能写进 `Wrappers.lambdaQuery().eq/orderBy` 条件(MyBatis-Plus 取不到列名会直接抛异常)。
  221 +5. 新增非持久化字段时,在实体注释里写明来源表,并在对应 Mapper XML 的公共片段同步带出,避免调用方误用内置查询。
  222 +
188 223 ---
189 224
190 225 ## 回写模板(新增踩坑时复制)
... ...
... ... @@ -3075,8 +3075,7 @@ CREATE TABLE IF NOT EXISTS `fund_payment_request` (
3075 3075 `total_apply_amount` decimal(14,2) DEFAULT NULL COMMENT '合计-申请金额(明细申请金额之和)',
3076 3076 `flow_node` varchar(50) DEFAULT NULL COMMENT '流程节点 GYGLKZJY-供应管理科资金管理员 GYGLKZG-供应管理科主管',
3077 3077 `approval_status` varchar(20) NOT NULL COMMENT '审核状态 DRAFT-草稿 AUDIT-审核中 PASS-审核通过 REFUSE-已驳回',
3078   - `gyglkzg_id` varchar(32) DEFAULT NULL COMMENT '供应管理科主管审核人ID(审核通过时记录)',
3079   - `gyglkzg_name` varchar(64) DEFAULT NULL COMMENT '供应管理科主管审核人',
  3078 + `approval_pass_time` datetime DEFAULT NULL COMMENT '审核通过时间(流程审核通过时写入)',
3080 3079 `deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否作废 0-有效单 1-作废单(作废单只能查看;码单作废联动全部作废)',
3081 3080 `create_by_id` varchar(32) NOT NULL COMMENT '创建人ID',
3082 3081 `create_by` varchar(64) NOT NULL COMMENT '创建人',
... ... @@ -3111,3 +3110,86 @@ CREATE TABLE IF NOT EXISTS `fund_payment_request_line` (
3111 3110 ALTER TABLE procurement_plan
3112 3111 ADD COLUMN request_file_ids varchar(1000) DEFAULT NULL COMMENT '请款附件文件ID集合(多文件,逗号分隔)',
3113 3112 ADD COLUMN request_file_names varchar(1000) DEFAULT NULL COMMENT '请款附件文件名称集合(多文件,逗号分隔)';
  3113 +
  3114 +-- 资金台账:一个采购计划对应一条数据,按申报日期(计划完成/审核通过时间)分月展示
  3115 +-- 业务字段为来源单据的冗余快照,本期只建表与基础方法,数据回填/重算逻辑后续补充
  3116 +CREATE TABLE IF NOT EXISTS `fund_ledger` (
  3117 + `id` varchar(32) NOT NULL COMMENT 'ID',
  3118 + `plan_id` varchar(32) NOT NULL COMMENT '采购计划ID(一个计划对应一条数据)',
  3119 + `apply_date` date DEFAULT NULL COMMENT '申报日期(计划完成日期/审核通过时间,分月筛选依据)',
  3120 + `plan_code` varchar(50) DEFAULT NULL COMMENT '计划单编号',
  3121 + `supplier_name` varchar(200) DEFAULT NULL COMMENT '供料单位名称(供应商名称)',
  3122 + `purchase_department` varchar(32) DEFAULT NULL COMMENT '采购处ID',
  3123 + `purchase_department_name` varchar(100) DEFAULT NULL COMMENT '采购处名称',
  3124 + `region` varchar(32) DEFAULT NULL COMMENT '区域ID',
  3125 + `region_name` varchar(100) DEFAULT NULL COMMENT '区域名称',
  3126 + `delivery_date` date DEFAULT NULL COMMENT '计划到厂日期(交货日期)',
  3127 + `plan_quantity` decimal(14,2) DEFAULT NULL COMMENT '数量(计划品种总数量,来源采购计划,单位吨)',
  3128 + `product_names` varchar(1000) DEFAULT NULL COMMENT '品种(计划品种所有,逗号隔开)',
  3129 + `plan_remark` varchar(500) DEFAULT NULL COMMENT '备注(计划单备注)',
  3130 + `first_arrival_date` date DEFAULT NULL COMMENT '第一次到厂时间(第一次过磅码单日期)',
  3131 + `first_arrival_quantity` decimal(14,2) DEFAULT NULL COMMENT '第一次到场数量(第一次过磅数量,单位公斤)',
  3132 + `second_arrival_date` date DEFAULT NULL COMMENT '第二次到厂时间(第二次过磅码单日期)',
  3133 + `second_arrival_quantity` decimal(14,2) DEFAULT NULL COMMENT '第二次到场数量(第二次过磅数量,单位公斤)',
  3134 + `third_arrival_date` date DEFAULT NULL COMMENT '第三次到厂时间(第三次过磅码单日期)',
  3135 + `third_arrival_quantity` decimal(14,2) DEFAULT NULL COMMENT '第三次到场数量(第三次过磅数量,单位公斤)',
  3136 + `total_arrival_quantity` decimal(14,2) DEFAULT NULL COMMENT '合计到场数量(过磅数量合计)',
  3137 + `min_invoice_price` decimal(14,2) DEFAULT NULL COMMENT '增票最低价格(计划单品种最低采购价)',
  3138 + `first_invoice_prepay_amount` decimal(14,2) DEFAULT NULL COMMENT '第一次增票预付金额(过磅品种数量*金额累加)',
  3139 + `first_prepay_limit` decimal(14,2) DEFAULT NULL COMMENT '第一次预付比例界限(第一次增票预付金额*结算比例)',
  3140 + `second_invoice_prepay_amount` decimal(14,2) DEFAULT NULL COMMENT '第二次增票预付金额(过磅品种数量*金额累加)',
  3141 + `second_prepay_limit` decimal(14,2) DEFAULT NULL COMMENT '第二次预付比例界限(第二次增票预付金额*结算比例)',
  3142 + `third_invoice_prepay_amount` decimal(14,2) DEFAULT NULL COMMENT '第三次增票预付金额(过磅品种数量*金额累加)',
  3143 + `third_prepay_limit` decimal(14,2) DEFAULT NULL COMMENT '第三次预付比例界限(第三次增票预付金额*结算比例)',
  3144 + `total_prepay_limit` decimal(14,2) DEFAULT NULL COMMENT '预付比例界限金额合计(按车累加)',
  3145 + `first_prepay_date` date DEFAULT NULL COMMENT '第一次增票预付日期(第一次请款日期)',
  3146 + `first_prepay_paid` decimal(14,2) DEFAULT NULL COMMENT '第一次增票预付(第一次请款金额)',
  3147 + `second_prepay_date` date DEFAULT NULL COMMENT '第二次增票预付日期(第二次请款日期)',
  3148 + `second_prepay_paid` decimal(14,2) DEFAULT NULL COMMENT '第二次增票预付(第二次请款金额)',
  3149 + `third_prepay_date` date DEFAULT NULL COMMENT '第三次增票预付日期(第三次请款日期)',
  3150 + `third_prepay_paid` decimal(14,2) DEFAULT NULL COMMENT '第三次增票预付(第三次请款金额)',
  3151 + `total_prepay_paid` decimal(14,2) DEFAULT NULL COMMENT '增票预付合计(增票预付金额累加)',
  3152 + `available_prepay_amount` decimal(14,2) DEFAULT NULL COMMENT '可预付款(万元)(预付比例界限金额合计-增票预付合计)/10000',
  3153 + `red_amount` decimal(14,2) DEFAULT NULL COMMENT '冲红金额',
  3154 + `first_receive_date` date DEFAULT NULL COMMENT '第一次入库日期(仓库收料单)',
  3155 + `first_receive_quantity` decimal(14,2) DEFAULT NULL COMMENT '第一次入库数量(合计实收数,仓库收料单)',
  3156 + `first_receive_amount` decimal(14,2) DEFAULT NULL COMMENT '第一次增票入库金额(含税价格,仓库收料单)',
  3157 + `second_receive_date` date DEFAULT NULL COMMENT '第二次入库日期(仓库收料单)',
  3158 + `second_receive_quantity` decimal(14,2) DEFAULT NULL COMMENT '第二次入库数量(合计实收数,仓库收料单)',
  3159 + `second_receive_amount` decimal(14,2) DEFAULT NULL COMMENT '第二次增票入库金额(含税价格,仓库收料单)',
  3160 + `third_receive_date` date DEFAULT NULL COMMENT '第三次入库日期(仓库收料单)',
  3161 + `third_receive_quantity` decimal(14,2) DEFAULT NULL COMMENT '第三次入库数量(合计实收数,仓库收料单)',
  3162 + `third_receive_amount` decimal(14,2) DEFAULT NULL COMMENT '第三次增票入库金额(含税价格,仓库收料单)',
  3163 + `total_receive_quantity` decimal(14,2) DEFAULT NULL COMMENT '入库数量合计',
  3164 + `total_receive_amount` decimal(14,2) DEFAULT NULL COMMENT '增票入库金额合计',
  3165 + `invoice_date` date DEFAULT NULL COMMENT '来票时间',
  3166 + `invoice_quantity` decimal(14,2) DEFAULT NULL COMMENT '来票数量(保留两位小数)',
  3167 + `invoice_amount` decimal(14,2) DEFAULT NULL COMMENT '来票金额(保留两位小数)',
  3168 + `owed_invoice_amount` decimal(14,2) DEFAULT NULL COMMENT '欠票额(增票入库金额合计-来票金额)',
  3169 + `outstock_quantity` decimal(14,2) DEFAULT NULL COMMENT '出库单数量(保留两位小数)',
  3170 + `owed_order_amount` decimal(14,2) DEFAULT NULL COMMENT '欠单额(入库数量合计-出库单数量)',
  3171 + `invoice_balance_amount` decimal(14,2) DEFAULT NULL COMMENT '增票余款(增票入库金额合计-增票预付合计)',
  3172 + `stock_complete_diff` decimal(14,2) DEFAULT NULL COMMENT '是否入库完(合计到厂数量-入库数量合计,为0表示已入完)',
  3173 + `final_payment_date` date DEFAULT NULL COMMENT '增票付余款日期(尾款请款单审核通过日期)',
  3174 + `final_payment_amount` decimal(14,2) DEFAULT NULL COMMENT '付增票余款金额(尾款请款单申请金额)',
  3175 + `compare_amount` decimal(14,2) DEFAULT NULL COMMENT '对比(增票余款-付增票余款金额)',
  3176 + `clear_debt` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否清欠 1-是 0-否(差额不为0为是;平账后置否)',
  3177 + `remark` varchar(500) DEFAULT NULL COMMENT '备注(台账备注,修改页可改)',
  3178 + `red_remark` varchar(500) DEFAULT NULL COMMENT '冲红说明(多行文本)',
  3179 + `red_file_ids` varchar(1000) DEFAULT NULL COMMENT '冲红附件文件ID集合(多文件,逗号分隔)',
  3180 + `red_file_names` varchar(1000) DEFAULT NULL COMMENT '冲红附件文件名称集合(多文件,逗号分隔)',
  3181 + `balance_remark` varchar(500) DEFAULT NULL COMMENT '平账说明(多行文本)',
  3182 + `balance_file_ids` varchar(1000) DEFAULT NULL COMMENT '平账附件文件ID集合(多文件,逗号分隔)',
  3183 + `balance_file_names` varchar(1000) DEFAULT NULL COMMENT '平账附件文件名称集合(多文件,逗号分隔)',
  3184 + `create_by_id` varchar(32) NOT NULL COMMENT '创建人ID',
  3185 + `create_by` varchar(64) NOT NULL COMMENT '创建人',
  3186 + `update_by_id` varchar(32) DEFAULT NULL COMMENT '更新人ID',
  3187 + `update_by` varchar(64) DEFAULT NULL COMMENT '更新人',
  3188 + `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  3189 + `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  3190 + PRIMARY KEY (`id`),
  3191 + UNIQUE KEY `uk_fl_plan_id` (`plan_id`),
  3192 + KEY `idx_fl_apply_date` (`apply_date`),
  3193 + KEY `idx_fl_clear_debt_apply` (`clear_debt`, `apply_date`),
  3194 + KEY `idx_fl_plan_code` (`plan_code`)
  3195 +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COMMENT='资金台账';
... ...
  1 +package com.lframework.xingyun.sc.bo.procurement;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonFormat;
  4 +import com.lframework.starter.common.constants.StringPool;
  5 +import io.swagger.annotations.ApiModelProperty;
  6 +import java.io.Serializable;
  7 +import java.math.BigDecimal;
  8 +import java.time.LocalDate;
  9 +import java.time.LocalDateTime;
  10 +import lombok.Data;
  11 +
  12 +/**
  13 + * 资金台账列表/详情(一个采购计划对应一条数据)
  14 + * 列表按需求展示至「备注」,查看页另外展示冲红说明、平账说明、冲红附件、平账附件
  15 + */
  16 +@Data
  17 +public class GetFundLedgerBo implements Serializable {
  18 +
  19 + private static final long serialVersionUID = 1L;
  20 +
  21 + @ApiModelProperty("ID")
  22 + private String id;
  23 +
  24 + @ApiModelProperty("采购计划ID")
  25 + private String planId;
  26 +
  27 + @ApiModelProperty("申报日期(计划完成日期/审核通过时间)")
  28 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  29 + private LocalDate applyDate;
  30 +
  31 + @ApiModelProperty("计划单编号")
  32 + private String planCode;
  33 +
  34 + @ApiModelProperty("供料单位名称")
  35 + private String supplierName;
  36 +
  37 + @ApiModelProperty("采购处ID")
  38 + private String purchaseDepartment;
  39 +
  40 + @ApiModelProperty("采购处名称")
  41 + private String purchaseDepartmentName;
  42 +
  43 + @ApiModelProperty("区域ID")
  44 + private String region;
  45 +
  46 + @ApiModelProperty("区域名称")
  47 + private String regionName;
  48 +
  49 + @ApiModelProperty("计划到厂日期(交货日期)")
  50 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  51 + private LocalDate deliveryDate;
  52 +
  53 + @ApiModelProperty("数量(计划品种总数量)")
  54 + private BigDecimal planQuantity;
  55 +
  56 + @ApiModelProperty("品种(逗号隔开)")
  57 + private String productNames;
  58 +
  59 + @ApiModelProperty("备注(计划单备注)")
  60 + private String planRemark;
  61 +
  62 + @ApiModelProperty("第一次到厂时间")
  63 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  64 + private LocalDate firstArrivalDate;
  65 +
  66 + @ApiModelProperty("第一次到场数量")
  67 + private BigDecimal firstArrivalQuantity;
  68 +
  69 + @ApiModelProperty("第二次到厂时间")
  70 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  71 + private LocalDate secondArrivalDate;
  72 +
  73 + @ApiModelProperty("第二次到场数量")
  74 + private BigDecimal secondArrivalQuantity;
  75 +
  76 + @ApiModelProperty("第三次到厂时间")
  77 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  78 + private LocalDate thirdArrivalDate;
  79 +
  80 + @ApiModelProperty("第三次到场数量")
  81 + private BigDecimal thirdArrivalQuantity;
  82 +
  83 + @ApiModelProperty("合计到场数量")
  84 + private BigDecimal totalArrivalQuantity;
  85 +
  86 + @ApiModelProperty("增票最低价格")
  87 + private BigDecimal minInvoicePrice;
  88 +
  89 + @ApiModelProperty("第一次增票预付金额")
  90 + private BigDecimal firstInvoicePrepayAmount;
  91 +
  92 + @ApiModelProperty("第一次预付比例界限")
  93 + private BigDecimal firstPrepayLimit;
  94 +
  95 + @ApiModelProperty("第二次增票预付金额")
  96 + private BigDecimal secondInvoicePrepayAmount;
  97 +
  98 + @ApiModelProperty("第二次预付比例界限")
  99 + private BigDecimal secondPrepayLimit;
  100 +
  101 + @ApiModelProperty("第三次增票预付金额")
  102 + private BigDecimal thirdInvoicePrepayAmount;
  103 +
  104 + @ApiModelProperty("第三次预付比例界限")
  105 + private BigDecimal thirdPrepayLimit;
  106 +
  107 + @ApiModelProperty("预付比例界限金额合计")
  108 + private BigDecimal totalPrepayLimit;
  109 +
  110 + @ApiModelProperty("第一次增票预付日期")
  111 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  112 + private LocalDate firstPrepayDate;
  113 +
  114 + @ApiModelProperty("第一次增票预付")
  115 + private BigDecimal firstPrepayPaid;
  116 +
  117 + @ApiModelProperty("第二次增票预付日期")
  118 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  119 + private LocalDate secondPrepayDate;
  120 +
  121 + @ApiModelProperty("第二次增票预付")
  122 + private BigDecimal secondPrepayPaid;
  123 +
  124 + @ApiModelProperty("第三次增票预付日期")
  125 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  126 + private LocalDate thirdPrepayDate;
  127 +
  128 + @ApiModelProperty("第三次增票预付")
  129 + private BigDecimal thirdPrepayPaid;
  130 +
  131 + @ApiModelProperty("增票预付合计")
  132 + private BigDecimal totalPrepayPaid;
  133 +
  134 + @ApiModelProperty("可预付款(万元)")
  135 + private BigDecimal availablePrepayAmount;
  136 +
  137 + @ApiModelProperty("冲红金额")
  138 + private BigDecimal redAmount;
  139 +
  140 + @ApiModelProperty("第一次入库日期")
  141 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  142 + private LocalDate firstReceiveDate;
  143 +
  144 + @ApiModelProperty("第一次入库数量")
  145 + private BigDecimal firstReceiveQuantity;
  146 +
  147 + @ApiModelProperty("第一次增票入库金额")
  148 + private BigDecimal firstReceiveAmount;
  149 +
  150 + @ApiModelProperty("第二次入库日期")
  151 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  152 + private LocalDate secondReceiveDate;
  153 +
  154 + @ApiModelProperty("第二次入库数量")
  155 + private BigDecimal secondReceiveQuantity;
  156 +
  157 + @ApiModelProperty("第二次增票入库金额")
  158 + private BigDecimal secondReceiveAmount;
  159 +
  160 + @ApiModelProperty("第三次入库日期")
  161 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  162 + private LocalDate thirdReceiveDate;
  163 +
  164 + @ApiModelProperty("第三次入库数量")
  165 + private BigDecimal thirdReceiveQuantity;
  166 +
  167 + @ApiModelProperty("第三次增票入库金额")
  168 + private BigDecimal thirdReceiveAmount;
  169 +
  170 + @ApiModelProperty("入库数量合计")
  171 + private BigDecimal totalReceiveQuantity;
  172 +
  173 + @ApiModelProperty("增票入库金额合计")
  174 + private BigDecimal totalReceiveAmount;
  175 +
  176 + @ApiModelProperty("来票时间")
  177 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  178 + private LocalDate invoiceDate;
  179 +
  180 + @ApiModelProperty("来票数量")
  181 + private BigDecimal invoiceQuantity;
  182 +
  183 + @ApiModelProperty("来票金额")
  184 + private BigDecimal invoiceAmount;
  185 +
  186 + @ApiModelProperty("欠票额(增票入库金额合计-来票金额)")
  187 + private BigDecimal owedInvoiceAmount;
  188 +
  189 + @ApiModelProperty("出库单数量")
  190 + private BigDecimal outstockQuantity;
  191 +
  192 + @ApiModelProperty("欠单额(入库数量合计-出库单数量)")
  193 + private BigDecimal owedOrderAmount;
  194 +
  195 + @ApiModelProperty("增票余款(增票入库金额合计-增票预付合计)")
  196 + private BigDecimal invoiceBalanceAmount;
  197 +
  198 + @ApiModelProperty("是否入库完(合计到厂数量-入库数量合计,为0表示已入完)")
  199 + private BigDecimal stockCompleteDiff;
  200 +
  201 + @ApiModelProperty("增票付余款日期(尾款请款单审核通过日期)")
  202 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  203 + private LocalDate finalPaymentDate;
  204 +
  205 + @ApiModelProperty("付增票余款金额(尾款请款单申请金额)")
  206 + private BigDecimal finalPaymentAmount;
  207 +
  208 + @ApiModelProperty("对比(增票余款-付增票余款金额)")
  209 + private BigDecimal compareAmount;
  210 +
  211 + @ApiModelProperty("是否清欠 true-是 false-否")
  212 + private Boolean clearDebt;
  213 +
  214 + @ApiModelProperty("备注")
  215 + private String remark;
  216 +
  217 + @ApiModelProperty("冲红说明(查看页)")
  218 + private String redRemark;
  219 +
  220 + @ApiModelProperty("平账说明(查看页)")
  221 + private String balanceRemark;
  222 +
  223 + @ApiModelProperty("冲红附件文件ID集合(查看页)")
  224 + private String redFileIds;
  225 +
  226 + @ApiModelProperty("冲红附件文件名称集合(查看页)")
  227 + private String redFileNames;
  228 +
  229 + @ApiModelProperty("平账附件文件ID集合(查看页)")
  230 + private String balanceFileIds;
  231 +
  232 + @ApiModelProperty("平账附件文件名称集合(查看页)")
  233 + private String balanceFileNames;
  234 +
  235 + @ApiModelProperty("创建人")
  236 + private String createBy;
  237 +
  238 + @ApiModelProperty("创建时间")
  239 + @JsonFormat(pattern = StringPool.DATE_TIME_PATTERN)
  240 + private LocalDateTime createTime;
  241 +
  242 + @ApiModelProperty("更新人")
  243 + private String updateBy;
  244 +
  245 + @ApiModelProperty("更新时间")
  246 + @JsonFormat(pattern = StringPool.DATE_TIME_PATTERN)
  247 + private LocalDateTime updateTime;
  248 +}
... ...
  1 +package com.lframework.xingyun.sc.procurement.controller.fundledger;
  2 +
  3 +import com.lframework.starter.common.exceptions.impl.DefaultClientException;
  4 +import com.lframework.starter.web.core.annotations.security.HasPermission;
  5 +import com.lframework.starter.web.core.components.resp.InvokeResult;
  6 +import com.lframework.starter.web.core.components.resp.InvokeResultBuilder;
  7 +import com.lframework.starter.web.core.components.resp.PageResult;
  8 +import com.lframework.starter.web.core.controller.DefaultBaseController;
  9 +import com.lframework.starter.web.core.utils.PageResultUtil;
  10 +import com.lframework.xingyun.sc.bo.procurement.GetFundLedgerBo;
  11 +import com.lframework.xingyun.sc.procurement.entity.fundledger.FundLedger;
  12 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
  13 +import com.lframework.xingyun.sc.procurement.vo.fundledger.BalanceFundLedgerVo;
  14 +import com.lframework.xingyun.sc.procurement.vo.fundledger.QueryFundLedgerVo;
  15 +import com.lframework.xingyun.sc.procurement.vo.fundledger.RedFundLedgerVo;
  16 +import com.lframework.xingyun.sc.procurement.vo.fundledger.UpdateFundLedgerVo;
  17 +import io.swagger.annotations.Api;
  18 +import io.swagger.annotations.ApiImplicitParam;
  19 +import io.swagger.annotations.ApiOperation;
  20 +import java.time.YearMonth;
  21 +import java.util.List;
  22 +import java.util.stream.Collectors;
  23 +import javax.annotation.Resource;
  24 +import javax.validation.Valid;
  25 +import javax.validation.constraints.NotBlank;
  26 +import org.springframework.util.CollectionUtils;
  27 +import org.springframework.validation.annotation.Validated;
  28 +import org.springframework.web.bind.annotation.GetMapping;
  29 +import org.springframework.web.bind.annotation.PostMapping;
  30 +import org.springframework.web.bind.annotation.PutMapping;
  31 +import org.springframework.web.bind.annotation.RequestBody;
  32 +import org.springframework.web.bind.annotation.RequestMapping;
  33 +import org.springframework.web.bind.annotation.RestController;
  34 +
  35 +/**
  36 + * 资金台账(供应管理科资金管理员)
  37 + */
  38 +@Api(tags = "资金台账")
  39 +@Validated
  40 +@RestController
  41 +@RequestMapping("/procurement/fundLedger")
  42 +public class FundLedgerController extends DefaultBaseController {
  43 +
  44 + @Resource
  45 + private FundLedgerService fundLedgerService;
  46 +
  47 + @ApiOperation("分页查询资金台账(分月展示,传年份+月份时按该月申报日期筛选)")
  48 + @HasPermission({"procure-manage:fund-ledger:query"})
  49 + @GetMapping("/query")
  50 + public InvokeResult<PageResult<GetFundLedgerBo>> query(@Valid QueryFundLedgerVo vo) {
  51 + // 年-月筛选换算为申报日期起止,与「申报日期」范围筛选共用同一组条件
  52 + if (vo.getYear() != null && vo.getMonth() != null) {
  53 + if (vo.getYear() < 1900 || vo.getYear() > 9999) {
  54 + throw new DefaultClientException("年份不合法!");
  55 + }
  56 + if (vo.getMonth() < 1 || vo.getMonth() > 12) {
  57 + throw new DefaultClientException("月份必须在1-12之间!");
  58 + }
  59 + YearMonth yearMonth = YearMonth.of(vo.getYear(), vo.getMonth());
  60 + vo.setApplyDateStart(yearMonth.atDay(1));
  61 + vo.setApplyDateEnd(yearMonth.atEndOfMonth());
  62 + }
  63 +
  64 + PageResult<FundLedger> pageResult = fundLedgerService.query(
  65 + getPageIndex(vo), getPageSize(vo), vo);
  66 +
  67 + List<GetFundLedgerBo> results = null;
  68 + if (!CollectionUtils.isEmpty(pageResult.getDatas())) {
  69 + results = pageResult.getDatas().stream().map(entity -> {
  70 + GetFundLedgerBo bo = new GetFundLedgerBo();
  71 + org.springframework.beans.BeanUtils.copyProperties(entity, bo);
  72 + return bo;
  73 + }).collect(Collectors.toList());
  74 + }
  75 + return InvokeResultBuilder.success(PageResultUtil.rebuild(pageResult, results));
  76 + }
  77 +
  78 + @ApiOperation("查看资金台账详情")
  79 + @ApiImplicitParam(value = "ID", name = "id", paramType = "query", required = true)
  80 + @HasPermission({"procure-manage:fund-ledger:query"})
  81 + @GetMapping("")
  82 + public InvokeResult<GetFundLedgerBo> findById(@NotBlank(message = "ID不能为空!") String id) {
  83 + return InvokeResultBuilder.success(fundLedgerService.findDetail(id));
  84 + }
  85 +
  86 + @ApiOperation("修改资金台账(仅来票时间/数量/金额、出库单数量、备注可改)")
  87 + @HasPermission({"procure-manage:fund-ledger:modify"})
  88 + @PutMapping("")
  89 + public InvokeResult<Void> update(@RequestBody @Valid UpdateFundLedgerVo vo) {
  90 + fundLedgerService.update(vo);
  91 + return InvokeResultBuilder.success();
  92 + }
  93 +
  94 + @ApiOperation("冲红(冲红金额、说明、附件)")
  95 + @HasPermission({"procure-manage:fund-ledger:modify"})
  96 + @PutMapping("/red")
  97 + public InvokeResult<Void> red(@RequestBody @Valid RedFundLedgerVo vo) {
  98 + fundLedgerService.red(vo);
  99 + return InvokeResultBuilder.success();
  100 + }
  101 +
  102 + @ApiOperation("平账(仅清欠状态可平账,平账后是否清欠改为否)")
  103 + @HasPermission({"procure-manage:fund-ledger:reconciliation"})
  104 + @PutMapping("/balance")
  105 + public InvokeResult<Void> balance(@RequestBody @Valid BalanceFundLedgerVo vo) {
  106 + fundLedgerService.balance(vo);
  107 + return InvokeResultBuilder.success();
  108 + }
  109 +
  110 + @ApiOperation("重建资金台账(按全部已审核通过采购计划生成/刷新,历史数据补数用,返回处理计划数)")
  111 + @HasPermission({"procure-manage:fund-ledger:modify"})
  112 + @PostMapping("/rebuild")
  113 + public InvokeResult<Integer> rebuild() {
  114 + return InvokeResultBuilder.success(fundLedgerService.rebuildAll());
  115 + }
  116 +}
... ...
... ... @@ -11,11 +11,11 @@ import com.lframework.xingyun.sc.procurement.entity.fundpayment.FundPaymentReque
11 11 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestService;
12 12 import com.lframework.xingyun.sc.procurement.vo.fundpayment.CreateFundPaymentRequestVo;
13 13 import com.lframework.xingyun.sc.procurement.vo.fundpayment.FundPaymentOtherAttachmentVo;
  14 +import com.lframework.xingyun.sc.procurement.vo.fundpayment.GenerateFundPaymentRequestVo;
14 15 import com.lframework.xingyun.sc.procurement.vo.fundpayment.QueryFundPaymentRequestVo;
15 16 import com.lframework.xingyun.sc.procurement.vo.fundpayment.UpdateFundPaymentRequestVo;
16 17 import io.swagger.annotations.Api;
17 18 import io.swagger.annotations.ApiImplicitParam;
18   -import io.swagger.annotations.ApiImplicitParams;
19 19 import io.swagger.annotations.ApiOperation;
20 20 import java.util.List;
21 21 import java.util.stream.Collectors;
... ... @@ -29,7 +29,6 @@ import org.springframework.web.bind.annotation.PostMapping;
29 29 import org.springframework.web.bind.annotation.PutMapping;
30 30 import org.springframework.web.bind.annotation.RequestBody;
31 31 import org.springframework.web.bind.annotation.RequestMapping;
32   -import org.springframework.web.bind.annotation.RequestMethod;
33 32 import org.springframework.web.bind.annotation.RestController;
34 33
35 34 /**
... ... @@ -72,16 +71,12 @@ public class FundPaymentRequestController extends DefaultBaseController {
72 71 }
73 72
74 73 @ApiOperation("按来源单生成草稿请款单(调用即落库,仅返回请款单ID;自动带出/计算的字段直接生成,需手填的字段凭 ID 查询详情后修改补充。"
75   - + "请款日期=生成当天、付款方式固定电汇;同一来源单已有草稿时幂等返回该单ID。推荐 POST,保留 GET 兼容)")
76   - @ApiImplicitParams({
77   - @ApiImplicitParam(value = "生成来源 PLAN/TICKET/RECEIVE", name = "source", paramType = "query", required = true),
78   - @ApiImplicitParam(value = "来源单ID", name = "sourceId", paramType = "query", required = true)
79   - })
  74 + + "请款日期=生成当天、付款方式固定电汇;可指定请款单类型与补充附件;同一来源单已有草稿时幂等返回该单ID)")
80 75 @HasPermission({"procure-manage:payment-request:add"})
81   - @RequestMapping(value = "/generateData", method = {RequestMethod.POST, RequestMethod.GET})
82   - public InvokeResult<String> generate(@NotBlank(message = "生成来源不能为空!") String source,
83   - @NotBlank(message = "来源单ID不能为空!") String sourceId) {
84   - return InvokeResultBuilder.success(fundPaymentRequestService.generate(source, sourceId));
  76 + @PostMapping("/generateData")
  77 + public InvokeResult<String> generate(@RequestBody @Valid GenerateFundPaymentRequestVo vo) {
  78 + return InvokeResultBuilder.success(fundPaymentRequestService.generate(vo.getSource(), vo.getSourceId(),
  79 + vo.getRequestKind(), vo.getSupplementFileIds(), vo.getSupplementFileNames()));
85 80 }
86 81
87 82 @ApiOperation("一次性提交新增请款单(草稿,含全部手填字段;与生成接口生成草稿后走修改补充二选一)")
... ...
  1 +package com.lframework.xingyun.sc.procurement.entity.fundledger;
  2 +
  3 +import com.baomidou.mybatisplus.annotation.FieldFill;
  4 +import com.baomidou.mybatisplus.annotation.TableField;
  5 +import com.baomidou.mybatisplus.annotation.TableName;
  6 +import com.lframework.starter.web.core.dto.BaseDto;
  7 +import com.lframework.starter.web.core.entity.BaseEntity;
  8 +import java.math.BigDecimal;
  9 +import java.time.LocalDate;
  10 +import java.time.LocalDateTime;
  11 +import lombok.Data;
  12 +
  13 +/**
  14 + * <p>
  15 + * 资金台账(一个采购计划对应一条数据,按申报日期分月展示)
  16 + * 业务字段为来源单据的冗余快照,本期只建表与基础方法,数据回填/重算逻辑后续补充
  17 + * </p>
  18 + *
  19 + */
  20 +@Data
  21 +@TableName("fund_ledger")
  22 +public class FundLedger extends BaseEntity implements BaseDto {
  23 +
  24 + private static final long serialVersionUID = 1L;
  25 +
  26 + public static final String CACHE_NAME = "FundLedger";
  27 +
  28 + /**
  29 + * ID
  30 + */
  31 + private String id;
  32 +
  33 + /**
  34 + * 采购计划ID(一个计划对应一条数据)
  35 + */
  36 + private String planId;
  37 +
  38 + /**
  39 + * 申报日期(计划完成日期/审核通过时间,分月筛选依据)
  40 + */
  41 + private LocalDate applyDate;
  42 +
  43 + /**
  44 + * 计划单编号
  45 + */
  46 + private String planCode;
  47 +
  48 + /**
  49 + * 供料单位名称(供应商名称)
  50 + */
  51 + private String supplierName;
  52 +
  53 + /**
  54 + * 采购处ID
  55 + */
  56 + private String purchaseDepartment;
  57 +
  58 + /**
  59 + * 采购处名称
  60 + */
  61 + private String purchaseDepartmentName;
  62 +
  63 + /**
  64 + * 区域ID
  65 + */
  66 + private String region;
  67 +
  68 + /**
  69 + * 区域名称
  70 + */
  71 + private String regionName;
  72 +
  73 + /**
  74 + * 计划到厂日期(交货日期)
  75 + */
  76 + private LocalDate deliveryDate;
  77 +
  78 + /**
  79 + * 数量(计划品种总数量,来源采购计划,单位吨)
  80 + */
  81 + private BigDecimal planQuantity;
  82 +
  83 + /**
  84 + * 品种(计划品种所有,逗号隔开)
  85 + */
  86 + private String productNames;
  87 +
  88 + /**
  89 + * 备注(计划单备注)
  90 + */
  91 + private String planRemark;
  92 +
  93 + /**
  94 + * 第一次到厂时间(第一次过磅码单日期)
  95 + */
  96 + private LocalDate firstArrivalDate;
  97 +
  98 + /**
  99 + * 第一次到场数量(第一次过磅数量,单位公斤)
  100 + */
  101 + private BigDecimal firstArrivalQuantity;
  102 +
  103 + /**
  104 + * 第二次到厂时间(第二次过磅码单日期)
  105 + */
  106 + private LocalDate secondArrivalDate;
  107 +
  108 + /**
  109 + * 第二次到场数量(第二次过磅数量,单位公斤)
  110 + */
  111 + private BigDecimal secondArrivalQuantity;
  112 +
  113 + /**
  114 + * 第三次到厂时间(第三次过磅码单日期)
  115 + */
  116 + private LocalDate thirdArrivalDate;
  117 +
  118 + /**
  119 + * 第三次到场数量(第三次过磅数量,单位公斤)
  120 + */
  121 + private BigDecimal thirdArrivalQuantity;
  122 +
  123 + /**
  124 + * 合计到场数量(过磅数量合计)
  125 + */
  126 + private BigDecimal totalArrivalQuantity;
  127 +
  128 + /**
  129 + * 增票最低价格(计划单品种最低采购价)
  130 + */
  131 + private BigDecimal minInvoicePrice;
  132 +
  133 + /**
  134 + * 第一次增票预付金额(过磅品种数量*金额累加)
  135 + */
  136 + private BigDecimal firstInvoicePrepayAmount;
  137 +
  138 + /**
  139 + * 第一次预付比例界限(第一次增票预付金额*结算比例)
  140 + */
  141 + private BigDecimal firstPrepayLimit;
  142 +
  143 + /**
  144 + * 第二次增票预付金额(过磅品种数量*金额累加)
  145 + */
  146 + private BigDecimal secondInvoicePrepayAmount;
  147 +
  148 + /**
  149 + * 第二次预付比例界限(第二次增票预付金额*结算比例)
  150 + */
  151 + private BigDecimal secondPrepayLimit;
  152 +
  153 + /**
  154 + * 第三次增票预付金额(过磅品种数量*金额累加)
  155 + */
  156 + private BigDecimal thirdInvoicePrepayAmount;
  157 +
  158 + /**
  159 + * 第三次预付比例界限(第三次增票预付金额*结算比例)
  160 + */
  161 + private BigDecimal thirdPrepayLimit;
  162 +
  163 + /**
  164 + * 预付比例界限金额合计(按车累加)
  165 + */
  166 + private BigDecimal totalPrepayLimit;
  167 +
  168 + /**
  169 + * 第一次增票预付日期(第一次请款日期)
  170 + */
  171 + private LocalDate firstPrepayDate;
  172 +
  173 + /**
  174 + * 第一次增票预付(第一次请款金额)
  175 + */
  176 + private BigDecimal firstPrepayPaid;
  177 +
  178 + /**
  179 + * 第二次增票预付日期(第二次请款日期)
  180 + */
  181 + private LocalDate secondPrepayDate;
  182 +
  183 + /**
  184 + * 第二次增票预付(第二次请款金额)
  185 + */
  186 + private BigDecimal secondPrepayPaid;
  187 +
  188 + /**
  189 + * 第三次增票预付日期(第三次请款日期)
  190 + */
  191 + private LocalDate thirdPrepayDate;
  192 +
  193 + /**
  194 + * 第三次增票预付(第三次请款金额)
  195 + */
  196 + private BigDecimal thirdPrepayPaid;
  197 +
  198 + /**
  199 + * 增票预付合计(增票预付金额累加)
  200 + */
  201 + private BigDecimal totalPrepayPaid;
  202 +
  203 + /**
  204 + * 可预付款(万元)(预付比例界限金额合计-增票预付合计)/10000
  205 + */
  206 + private BigDecimal availablePrepayAmount;
  207 +
  208 + /**
  209 + * 冲红金额
  210 + */
  211 + private BigDecimal redAmount;
  212 +
  213 + /**
  214 + * 第一次入库日期(仓库收料单)
  215 + */
  216 + private LocalDate firstReceiveDate;
  217 +
  218 + /**
  219 + * 第一次入库数量(合计实收数,仓库收料单)
  220 + */
  221 + private BigDecimal firstReceiveQuantity;
  222 +
  223 + /**
  224 + * 第一次增票入库金额(含税价格,仓库收料单)
  225 + */
  226 + private BigDecimal firstReceiveAmount;
  227 +
  228 + /**
  229 + * 第二次入库日期(仓库收料单)
  230 + */
  231 + private LocalDate secondReceiveDate;
  232 +
  233 + /**
  234 + * 第二次入库数量(合计实收数,仓库收料单)
  235 + */
  236 + private BigDecimal secondReceiveQuantity;
  237 +
  238 + /**
  239 + * 第二次增票入库金额(含税价格,仓库收料单)
  240 + */
  241 + private BigDecimal secondReceiveAmount;
  242 +
  243 + /**
  244 + * 第三次入库日期(仓库收料单)
  245 + */
  246 + private LocalDate thirdReceiveDate;
  247 +
  248 + /**
  249 + * 第三次入库数量(合计实收数,仓库收料单)
  250 + */
  251 + private BigDecimal thirdReceiveQuantity;
  252 +
  253 + /**
  254 + * 第三次增票入库金额(含税价格,仓库收料单)
  255 + */
  256 + private BigDecimal thirdReceiveAmount;
  257 +
  258 + /**
  259 + * 入库数量合计
  260 + */
  261 + private BigDecimal totalReceiveQuantity;
  262 +
  263 + /**
  264 + * 增票入库金额合计
  265 + */
  266 + private BigDecimal totalReceiveAmount;
  267 +
  268 + /**
  269 + * 来票时间
  270 + */
  271 + private LocalDate invoiceDate;
  272 +
  273 + /**
  274 + * 来票数量(保留两位小数)
  275 + */
  276 + private BigDecimal invoiceQuantity;
  277 +
  278 + /**
  279 + * 来票金额(保留两位小数)
  280 + */
  281 + private BigDecimal invoiceAmount;
  282 +
  283 + /**
  284 + * 欠票额(增票入库金额合计-来票金额)
  285 + */
  286 + private BigDecimal owedInvoiceAmount;
  287 +
  288 + /**
  289 + * 出库单数量(保留两位小数)
  290 + */
  291 + private BigDecimal outstockQuantity;
  292 +
  293 + /**
  294 + * 欠单额(入库数量合计-出库单数量)
  295 + */
  296 + private BigDecimal owedOrderAmount;
  297 +
  298 + /**
  299 + * 增票余款(增票入库金额合计-增票预付合计)
  300 + */
  301 + private BigDecimal invoiceBalanceAmount;
  302 +
  303 + /**
  304 + * 是否入库完(合计到厂数量-入库数量合计,为0表示已入完)
  305 + */
  306 + private BigDecimal stockCompleteDiff;
  307 +
  308 + /**
  309 + * 增票付余款日期(尾款请款单审核通过日期)
  310 + */
  311 + private LocalDate finalPaymentDate;
  312 +
  313 + /**
  314 + * 付增票余款金额(尾款请款单申请金额)
  315 + */
  316 + private BigDecimal finalPaymentAmount;
  317 +
  318 + /**
  319 + * 对比(增票余款-付增票余款金额)
  320 + */
  321 + private BigDecimal compareAmount;
  322 +
  323 + /**
  324 + * 是否清欠 1-是 0-否(差额不为0为是;平账后置否)
  325 + */
  326 + private Boolean clearDebt;
  327 +
  328 + /**
  329 + * 备注(台账备注,修改页可改)
  330 + */
  331 + private String remark;
  332 +
  333 + /**
  334 + * 冲红说明(多行文本)
  335 + */
  336 + private String redRemark;
  337 +
  338 + /**
  339 + * 冲红附件文件ID集合(多文件,逗号分隔)
  340 + */
  341 + private String redFileIds;
  342 +
  343 + /**
  344 + * 冲红附件文件名称集合(多文件,逗号分隔)
  345 + */
  346 + private String redFileNames;
  347 +
  348 + /**
  349 + * 平账说明(多行文本)
  350 + */
  351 + private String balanceRemark;
  352 +
  353 + /**
  354 + * 平账附件文件ID集合(多文件,逗号分隔)
  355 + */
  356 + private String balanceFileIds;
  357 +
  358 + /**
  359 + * 平账附件文件名称集合(多文件,逗号分隔)
  360 + */
  361 + private String balanceFileNames;
  362 +
  363 + /**
  364 + * 创建人ID
  365 + */
  366 + @TableField(fill = FieldFill.INSERT)
  367 + private String createById;
  368 +
  369 + /**
  370 + * 创建人
  371 + */
  372 + @TableField(fill = FieldFill.INSERT)
  373 + private String createBy;
  374 +
  375 + /**
  376 + * 更新人ID
  377 + */
  378 + @TableField(fill = FieldFill.INSERT_UPDATE)
  379 + private String updateById;
  380 +
  381 + /**
  382 + * 更新人
  383 + */
  384 + @TableField(fill = FieldFill.INSERT_UPDATE)
  385 + private String updateBy;
  386 +
  387 + /**
  388 + * 创建时间
  389 + */
  390 + @TableField(fill = FieldFill.INSERT)
  391 + private LocalDateTime createTime;
  392 +
  393 + /**
  394 + * 更新时间
  395 + */
  396 + @TableField(fill = FieldFill.INSERT_UPDATE)
  397 + private LocalDateTime updateTime;
  398 +}
... ...
... ... @@ -187,6 +187,11 @@ public class FundPaymentRequest extends BaseEntity implements BaseDto {
187 187 private String approvalStatus;
188 188
189 189 /**
  190 + * 审核通过时间(流程审核通过时写入,资金台账取此时间作为付款日期)
  191 + */
  192 + private LocalDateTime approvalPassTime;
  193 +
  194 + /**
190 195 * 是否作废 0-有效单 1-作废单(作废单只能查看;码单作废联动全部作废)
191 196 */
192 197 private Boolean deleted;
... ...
... ... @@ -42,6 +42,7 @@ import com.lframework.xingyun.sc.procurement.service.buyout.ProcurementBuyoutApp
42 42 import com.lframework.xingyun.sc.procurement.service.change.ProcurementPlanChangeLineService;
43 43 import com.lframework.xingyun.sc.procurement.service.change.ProcurementPlanChangeService;
44 44 import com.lframework.xingyun.sc.procurement.service.contract.ProcurementContractService;
  45 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
45 46 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanLineService;
46 47 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanService;
47 48 import com.lframework.xingyun.sc.procurement.service.weighing.ProcurementWeighingTicketPlanService;
... ... @@ -95,6 +96,8 @@ public class ProcurementPlanChangeServiceImpl extends
95 96 @Resource
96 97 private ProcurementContractService procurementContractService;
97 98 @Resource
  99 + private FundLedgerService fundLedgerService;
  100 + @Resource
98 101 private ProcurementWeighingTicketPlanService weighingTicketPlanService;
99 102 @Resource
100 103 private ProcurementWeighingTicketService weighingTicketService;
... ... @@ -884,6 +887,13 @@ public class ProcurementPlanChangeServiceImpl extends
884 887 }
885 888 contractVo.setProcurementContractLineList(contractLineVoList);
886 889 procurementContractService.create(contractVo);
  890 +
  891 + // 变更后:原计划作废(冻结)/归档的台账删除,新生成的子计划生成台账
  892 + List<String> ledgerPlanIds = new ArrayList<>();
  893 + ledgerPlanIds.add(planId);
  894 + ledgerPlanIds.addAll(procurementPlanService.listSubPlan(planId).stream()
  895 + .map(ProcurementPlan::getId).collect(Collectors.toList()));
  896 + fundLedgerService.generateByPlanIds(ledgerPlanIds);
887 897 } else if ("REFUSE".equals(approvalStatus)) {
888 898 List<SysRole> roles = sysRoleService.getByUserId(entity.getCreateById());
889 899 List<String> roleCodes = CollectionUtil.isEmpty(roles) ? new java.util.ArrayList<>()
... ...
  1 +package com.lframework.xingyun.sc.procurement.impl.fundledger;
  2 +
  3 +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  4 +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  5 +import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  6 +import com.github.pagehelper.PageInfo;
  7 +import com.lframework.starter.common.exceptions.impl.DefaultClientException;
  8 +import com.lframework.starter.common.utils.Assert;
  9 +import com.lframework.starter.common.utils.CollectionUtil;
  10 +import com.lframework.starter.common.utils.StringUtil;
  11 +import com.lframework.starter.web.core.annotations.oplog.OpLog;
  12 +import com.lframework.starter.web.core.components.resp.PageResult;
  13 +import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
  14 +import com.lframework.starter.web.core.utils.IdUtil;
  15 +import com.lframework.starter.web.core.utils.OpLogUtil;
  16 +import com.lframework.starter.web.core.utils.PageHelperUtil;
  17 +import com.lframework.starter.web.core.utils.PageResultUtil;
  18 +import com.lframework.starter.web.inner.components.oplog.OtherOpLogType;
  19 +import com.lframework.xingyun.sc.bo.procurement.GetFundLedgerBo;
  20 +import com.lframework.xingyun.sc.procurement.entity.ProcurementPlan;
  21 +import com.lframework.xingyun.sc.procurement.entity.ProcurementPlanLine;
  22 +import com.lframework.xingyun.sc.procurement.entity.fundledger.FundLedger;
  23 +import com.lframework.xingyun.sc.procurement.entity.fundpayment.FundPaymentRequest;
  24 +import com.lframework.xingyun.sc.procurement.entity.fundpayment.FundPaymentRequestLine;
  25 +import com.lframework.xingyun.sc.procurement.entity.receive.ProcurementWarehouseReceiveOrder;
  26 +import com.lframework.xingyun.sc.procurement.entity.receive.ProcurementWarehouseReceiveOrderLine;
  27 +import com.lframework.xingyun.sc.procurement.entity.weighing.ProcurementWeighingTicket;
  28 +import com.lframework.xingyun.sc.procurement.entity.weighing.ProcurementWeighingTicketLine;
  29 +import com.lframework.xingyun.sc.procurement.mappers.fundledger.FundLedgerMapper;
  30 +import com.lframework.xingyun.sc.procurement.mappers.fundpayment.FundPaymentRequestLineMapper;
  31 +import com.lframework.xingyun.sc.procurement.mappers.fundpayment.FundPaymentRequestMapper;
  32 +import com.lframework.xingyun.sc.procurement.mappers.plan.ProcurementPlanLineMapper;
  33 +import com.lframework.xingyun.sc.procurement.mappers.plan.ProcurementPlanMapper;
  34 +import com.lframework.xingyun.sc.procurement.mappers.receive.ProcurementWarehouseReceiveOrderLineMapper;
  35 +import com.lframework.xingyun.sc.procurement.mappers.receive.ProcurementWarehouseReceiveOrderMapper;
  36 +import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketLineMapper;
  37 +import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketMapper;
  38 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
  39 +import com.lframework.xingyun.sc.procurement.vo.fundledger.BalanceFundLedgerVo;
  40 +import com.lframework.xingyun.sc.procurement.vo.fundledger.QueryFundLedgerVo;
  41 +import com.lframework.xingyun.sc.procurement.vo.fundledger.RedFundLedgerVo;
  42 +import com.lframework.xingyun.sc.procurement.vo.fundledger.UpdateFundLedgerVo;
  43 +import java.math.BigDecimal;
  44 +import java.math.RoundingMode;
  45 +import java.time.LocalDateTime;
  46 +import java.util.ArrayList;
  47 +import java.util.Collection;
  48 +import java.util.Comparator;
  49 +import java.util.HashMap;
  50 +import java.util.List;
  51 +import java.util.Map;
  52 +import java.util.Objects;
  53 +import java.util.stream.Collectors;
  54 +import javax.annotation.Resource;
  55 +import org.springframework.context.ApplicationContext;
  56 +import org.springframework.stereotype.Service;
  57 +import org.springframework.transaction.annotation.Transactional;
  58 +import org.springframework.transaction.support.TransactionSynchronization;
  59 +import org.springframework.transaction.support.TransactionSynchronizationManager;
  60 +
  61 +/**
  62 + * 资金台账(一个采购计划对应一条数据,按申报日期分月展示)
  63 + * 来源字段由计划/过磅码单/请款单/仓库收料单汇总,派生字段随汇总重算;手工填写与冲红/平账数据保留
  64 + */
  65 +@Service
  66 +public class FundLedgerServiceImpl
  67 + extends BaseMpServiceImpl<FundLedgerMapper, FundLedger>
  68 + implements FundLedgerService {
  69 +
  70 + private static final String STATUS_PASS = "PASS";
  71 + private static final String SOURCE_PLAN = "PLAN";
  72 + private static final String SOURCE_TICKET = "TICKET";
  73 + private static final String SOURCE_RECEIVE = "RECEIVE";
  74 +
  75 + private static final BigDecimal HUNDRED = BigDecimal.valueOf(100);
  76 + private static final BigDecimal TEN_THOUSAND = BigDecimal.valueOf(10000);
  77 +
  78 + @Resource
  79 + private ProcurementPlanMapper procurementPlanMapper;
  80 + @Resource
  81 + private ProcurementPlanLineMapper procurementPlanLineMapper;
  82 + @Resource
  83 + private ProcurementWeighingTicketMapper weighingTicketMapper;
  84 + @Resource
  85 + private ProcurementWeighingTicketLineMapper weighingTicketLineMapper;
  86 + @Resource
  87 + private FundPaymentRequestMapper fundPaymentRequestMapper;
  88 + @Resource
  89 + private FundPaymentRequestLineMapper fundPaymentRequestLineMapper;
  90 + @Resource
  91 + private ProcurementWarehouseReceiveOrderMapper receiveOrderMapper;
  92 + @Resource
  93 + private ProcurementWarehouseReceiveOrderLineMapper receiveOrderLineMapper;
  94 + @Resource
  95 + private ApplicationContext applicationContext;
  96 +
  97 + @Override
  98 + public PageResult<FundLedger> query(Integer pageIndex, Integer pageSize, QueryFundLedgerVo vo) {
  99 + Assert.greaterThanZero(pageIndex);
  100 + Assert.greaterThanZero(pageSize);
  101 +
  102 + PageHelperUtil.startPage(pageIndex, pageSize);
  103 + List<FundLedger> datas = getBaseMapper().query(vo);
  104 +
  105 + return PageResultUtil.convert(new PageInfo<>(datas));
  106 + }
  107 +
  108 + @Override
  109 + public GetFundLedgerBo findDetail(String id) {
  110 + Assert.notBlank(id);
  111 +
  112 + FundLedger entity = getBaseMapper().findById(id);
  113 + if (entity == null) {
  114 + throw new DefaultClientException("资金台账不存在!");
  115 + }
  116 +
  117 + GetFundLedgerBo bo = new GetFundLedgerBo();
  118 + org.springframework.beans.BeanUtils.copyProperties(entity, bo);
  119 + return bo;
  120 + }
  121 +
  122 + @Override
  123 + @Transactional(rollbackFor = Exception.class)
  124 + @OpLog(type = OtherOpLogType.class, name = "修改资金台账,ID:{}", params = {"#vo.id"})
  125 + public void update(UpdateFundLedgerVo vo) {
  126 + Assert.notBlank(vo.getId(), "ID不能为空!");
  127 +
  128 + FundLedger entity = assertExists(vo.getId());
  129 + // 只更新可改字段,用 lambdaUpdate 显式 set 保证允许清空;其余为来源单据快照,不允许修改
  130 + this.update(Wrappers.lambdaUpdate(FundLedger.class)
  131 + .set(FundLedger::getInvoiceDate, vo.getInvoiceDate())
  132 + .set(FundLedger::getInvoiceQuantity, vo.getInvoiceQuantity())
  133 + .set(FundLedger::getInvoiceAmount, vo.getInvoiceAmount())
  134 + .set(FundLedger::getOutstockQuantity, vo.getOutstockQuantity())
  135 + .set(FundLedger::getRemark, vo.getRemark())
  136 + .eq(FundLedger::getId, vo.getId()));
  137 +
  138 + // 来票/出库单数量变更后重算欠票额、欠单额、清欠等派生字段(事务提交后执行,避免拖慢修改接口)
  139 + refreshAfterCommit(java.util.Collections.singletonList(entity.getPlanId()));
  140 +
  141 + OpLogUtil.setVariable("id", vo.getId());
  142 + OpLogUtil.setExtra(entity);
  143 + }
  144 +
  145 + @Override
  146 + @Transactional(rollbackFor = Exception.class)
  147 + @OpLog(type = OtherOpLogType.class, name = "资金台账冲红,ID:{}", params = {"#vo.id"})
  148 + public void red(RedFundLedgerVo vo) {
  149 + Assert.notBlank(vo.getId(), "ID不能为空!");
  150 +
  151 + FundLedger entity = assertExists(vo.getId());
  152 + // 冲红金额按页面填写值覆盖(清欠差额计算使用本字段)
  153 + this.update(Wrappers.lambdaUpdate(FundLedger.class)
  154 + .set(FundLedger::getRedAmount, vo.getRedAmount())
  155 + .set(FundLedger::getRedRemark, vo.getRedRemark())
  156 + .set(FundLedger::getRedFileIds, vo.getRedFileIds())
  157 + .set(FundLedger::getRedFileNames, vo.getRedFileNames())
  158 + .eq(FundLedger::getId, vo.getId()));
  159 +
  160 + // 冲红金额参与清欠差额计算,冲红后重算清欠状态(事务提交后执行)
  161 + refreshAfterCommit(java.util.Collections.singletonList(entity.getPlanId()));
  162 +
  163 + OpLogUtil.setVariable("id", vo.getId());
  164 + OpLogUtil.setExtra(entity);
  165 + }
  166 +
  167 + @Override
  168 + @Transactional(rollbackFor = Exception.class)
  169 + @OpLog(type = OtherOpLogType.class, name = "资金台账平账,ID:{}", params = {"#vo.id"})
  170 + public void balance(BalanceFundLedgerVo vo) {
  171 + Assert.notBlank(vo.getId(), "ID不能为空!");
  172 +
  173 + FundLedger entity = assertExists(vo.getId());
  174 + if (!Boolean.TRUE.equals(entity.getClearDebt())) {
  175 + throw new DefaultClientException("当前台账不是清欠状态,无法平账!");
  176 + }
  177 +
  178 + // 平账后是否清欠改为否
  179 + this.update(Wrappers.lambdaUpdate(FundLedger.class)
  180 + .set(FundLedger::getBalanceRemark, vo.getBalanceRemark())
  181 + .set(FundLedger::getBalanceFileIds, vo.getBalanceFileIds())
  182 + .set(FundLedger::getBalanceFileNames, vo.getBalanceFileNames())
  183 + .set(FundLedger::getClearDebt, false)
  184 + .eq(FundLedger::getId, vo.getId()));
  185 +
  186 + OpLogUtil.setVariable("id", vo.getId());
  187 + OpLogUtil.setExtra(entity);
  188 + }
  189 +
  190 + @Override
  191 + @Transactional(rollbackFor = Exception.class)
  192 + public void generateByPlanId(String planId) {
  193 + if (StringUtil.isBlank(planId)) {
  194 + return;
  195 + }
  196 + ProcurementPlan plan = procurementPlanMapper.selectById(planId);
  197 + // 计划已删除/归档/作废(冻结)时,不再保留其台账数据
  198 + if (plan == null || Boolean.TRUE.equals(plan.getDeleted()) || Boolean.TRUE.equals(plan.getFrozen())) {
  199 + this.remove(Wrappers.lambdaQuery(FundLedger.class).eq(FundLedger::getPlanId, planId));
  200 + return;
  201 + }
  202 +
  203 + FundLedger exists = getByPlanId(planId);
  204 + if (exists == null) {
  205 + FundLedger data = new FundLedger();
  206 + data.setId(IdUtil.getId());
  207 + data.setPlanId(planId);
  208 + data.setClearDebt(false);
  209 + this.save(data);
  210 + }
  211 +
  212 + refreshAfterCommit(java.util.Collections.singletonList(planId));
  213 + }
  214 +
  215 + @Override
  216 + public void generateByPlanIds(Collection<String> planIds) {
  217 + if (CollectionUtil.isEmpty(planIds)) {
  218 + return;
  219 + }
  220 + planIds.stream()
  221 + .filter(StringUtil::isNotBlank)
  222 + .distinct()
  223 + .forEach(this::generateByPlanId);
  224 + }
  225 +
  226 + @Override
  227 + public void refreshByPlanIds(Collection<String> planIds) {
  228 + if (CollectionUtil.isEmpty(planIds)) {
  229 + return;
  230 + }
  231 + // 逐条刷新、逐条提交:单个计划刷新失败不影响其它计划,一致性由重建接口兜底
  232 + planIds.stream()
  233 + .filter(StringUtil::isNotBlank)
  234 + .distinct()
  235 + .forEach(this::refreshByPlanId);
  236 + }
  237 +
  238 + @Override
  239 + @Transactional(rollbackFor = Exception.class)
  240 + public void refreshByPlanId(String planId) {
  241 + if (StringUtil.isBlank(planId)) {
  242 + return;
  243 + }
  244 + FundLedger ledger = getByPlanId(planId);
  245 + // 取带部门/区域名称的计划(findById 关联 sys_dept)
  246 + ProcurementPlan plan = procurementPlanMapper.findById(planId);
  247 + // 计划已删除/归档/作废(冻结)时删除其台账,不再重算
  248 + if (plan == null || Boolean.TRUE.equals(plan.getDeleted()) || Boolean.TRUE.equals(plan.getFrozen())) {
  249 + if (ledger != null) {
  250 + this.remove(Wrappers.lambdaQuery(FundLedger.class).eq(FundLedger::getPlanId, planId));
  251 + }
  252 + return;
  253 + }
  254 + if (ledger == null) {
  255 + return;
  256 + }
  257 +
  258 + // ===== 1. 计划基础信息 =====
  259 + LocalDateTime passTime = plan.getApprovalPassTime();
  260 + // 采购处、区域均同时保留ID与名称(名称未带出时用ID兜底)
  261 + String purchaseDepartment = plan.getPurchaseDepartment();
  262 + String purchaseDepartmentName = StringUtil.isNotBlank(plan.getPurchaseDepartmentName())
  263 + ? plan.getPurchaseDepartmentName() : purchaseDepartment;
  264 + String region = plan.getRegion();
  265 + String regionName = StringUtil.isNotBlank(plan.getRegionName())
  266 + ? plan.getRegionName() : region;
  267 +
  268 + // 品种名称、分厂名称等为非数据库字段,需用带联表的查询(getByProcurementPlanId)
  269 + List<ProcurementPlanLine> planLines = procurementPlanLineMapper.getByProcurementPlanId(planId);
  270 + String productNames = CollectionUtil.isEmpty(planLines) ? null
  271 + : planLines.stream()
  272 + .map(ProcurementPlanLine::getProductName)
  273 + .filter(StringUtil::isNotBlank)
  274 + .distinct()
  275 + .collect(Collectors.joining(","));
  276 + BigDecimal minInvoicePrice = CollectionUtil.isEmpty(planLines) ? null
  277 + : planLines.stream()
  278 + .map(ProcurementPlanLine::getActualPurchasePrice)
  279 + .filter(Objects::nonNull)
  280 + .min(Comparator.naturalOrder())
  281 + .orElse(null);
  282 + // 品种实际采购价(预付金额按品种取价,取第一行)
  283 + Map<String, BigDecimal> priceByProduct = new HashMap<>();
  284 + for (ProcurementPlanLine line : planLines) {
  285 + if (StringUtil.isNotBlank(line.getProductId()) && line.getActualPurchasePrice() != null
  286 + && !priceByProduct.containsKey(line.getProductId())) {
  287 + priceByProduct.put(line.getProductId(), line.getActualPurchasePrice());
  288 + }
  289 + }
  290 + BigDecimal settlementRatio = plan.getSettlementRatio() == null
  291 + ? HUNDRED : plan.getSettlementRatio();
  292 +
  293 + // ===== 2. 到厂(过磅码单)及每次增票预付金额/预付比例界限 =====
  294 + List<ProcurementWeighingTicketLine> planTicketLines = weighingTicketLineMapper.selectList(
  295 + Wrappers.lambdaQuery(ProcurementWeighingTicketLine.class)
  296 + .eq(ProcurementWeighingTicketLine::getProcurementPlanId, planId));
  297 + Map<String, List<ProcurementWeighingTicketLine>> ticketLineMap = planTicketLines.stream()
  298 + .filter(l -> StringUtil.isNotBlank(l.getWeighingTicketId()))
  299 + .collect(Collectors.groupingBy(ProcurementWeighingTicketLine::getWeighingTicketId));
  300 +
  301 + List<ProcurementWeighingTicket> validTickets = new ArrayList<>();
  302 + if (!ticketLineMap.isEmpty()) {
  303 + List<ProcurementWeighingTicket> tickets =
  304 + weighingTicketMapper.selectBatchIds(ticketLineMap.keySet());
  305 + // 有效码单:未作废 + 审核通过 + 已上传签字凭证(completeTime 非空),与请款/结算口径一致
  306 + validTickets = tickets.stream()
  307 + .filter(t -> t != null && !Boolean.TRUE.equals(t.getDeleted())
  308 + && STATUS_PASS.equals(t.getApprovalStatus())
  309 + && t.getCompleteTime() != null)
  310 + .sorted(Comparator.comparing(
  311 + t -> t.getFirstGrossWeightTime() != null ? t.getFirstGrossWeightTime() : t.getCreateTime(),
  312 + Comparator.nullsLast(Comparator.naturalOrder())))
  313 + .collect(Collectors.toList());
  314 + }
  315 +
  316 + BigDecimal totalArrivalQuantity = BigDecimal.ZERO;
  317 + BigDecimal totalPrepayLimit = BigDecimal.ZERO;
  318 + List<BigDecimal> arrivalQuantities = new ArrayList<>();
  319 + List<BigDecimal> invoicePrepayAmounts = new ArrayList<>();
  320 + List<BigDecimal> prepayLimits = new ArrayList<>();
  321 + for (ProcurementWeighingTicket ticket : validTickets) {
  322 + List<ProcurementWeighingTicketLine> lines = ticketLineMap.getOrDefault(ticket.getId(),
  323 + new ArrayList<>());
  324 + BigDecimal arrivalQuantity = lines.stream()
  325 + .map(ProcurementWeighingTicketLine::getQuantity)
  326 + .filter(Objects::nonNull)
  327 + .reduce(BigDecimal.ZERO, BigDecimal::add);
  328 + // 增票预付金额 = Σ(过磅数量kg→吨 × 该品种实际采购价元/吨)
  329 + BigDecimal invoicePrepayAmount = BigDecimal.ZERO;
  330 + for (ProcurementWeighingTicketLine line : lines) {
  331 + if (line.getQuantity() == null) {
  332 + continue;
  333 + }
  334 + // 计划明细的实际采购价必不为空,按品种直接取价
  335 + BigDecimal price = priceByProduct.get(line.getProductId());
  336 + invoicePrepayAmount = invoicePrepayAmount.add(
  337 + line.getQuantity().movePointLeft(3).multiply(price));
  338 + }
  339 + // 预付金额先按展示口径保留两位,再乘结算比例,保证「展示金额×比例=展示界限」自洽
  340 + BigDecimal invoicePrepayAmountRounded = invoicePrepayAmount.setScale(2, RoundingMode.HALF_UP);
  341 + BigDecimal prepayLimit = invoicePrepayAmountRounded.multiply(settlementRatio)
  342 + .divide(HUNDRED, 2, RoundingMode.HALF_UP);
  343 +
  344 + arrivalQuantities.add(arrivalQuantity);
  345 + invoicePrepayAmounts.add(invoicePrepayAmountRounded);
  346 + prepayLimits.add(prepayLimit);
  347 + totalArrivalQuantity = totalArrivalQuantity.add(arrivalQuantity);
  348 + // 预付比例界限金额合计按车累加(全部车次)
  349 + totalPrepayLimit = totalPrepayLimit.add(prepayLimit);
  350 + }
  351 +
  352 + // ===== 3. 请款单(增票预付 + 尾款) =====
  353 + List<FundPaymentRequestLine> planRequestLines = fundPaymentRequestLineMapper.selectList(
  354 + Wrappers.lambdaQuery(FundPaymentRequestLine.class)
  355 + .eq(FundPaymentRequestLine::getPlanId, planId));
  356 + //Map<requestId, 该计划明细申请金额合计>
  357 + Map<String, BigDecimal> applyAmountByRequest = planRequestLines.stream()
  358 + .filter(l -> StringUtil.isNotBlank(l.getRequestId()) && l.getApplyAmount() != null)
  359 + .collect(Collectors.groupingBy(FundPaymentRequestLine::getRequestId,
  360 + Collectors.reducing(BigDecimal.ZERO, FundPaymentRequestLine::getApplyAmount,
  361 + BigDecimal::add)));
  362 + List<FundPaymentRequest> validRequests = new ArrayList<>();
  363 + if (!applyAmountByRequest.isEmpty()) {
  364 + validRequests = fundPaymentRequestMapper.selectBatchIds(applyAmountByRequest.keySet()).stream()
  365 + .filter(r -> r != null && !Boolean.TRUE.equals(r.getDeleted())
  366 + && STATUS_PASS.equals(r.getApprovalStatus()))
  367 + // 按创建时间排序:第一次增票预付取最早创建的那张有效请款单
  368 + .sorted(Comparator.comparing(FundPaymentRequest::getCreateTime,
  369 + Comparator.nullsLast(Comparator.naturalOrder())))
  370 + .collect(Collectors.toList());
  371 + }
  372 +
  373 + // 增票预付:码单阶段预付(TICKET)+ 买断自提首付款(PLAN)
  374 + List<FundPaymentRequest> prepayRequests = validRequests.stream()
  375 + .filter(r -> SOURCE_TICKET.equals(r.getSource()) || SOURCE_PLAN.equals(r.getSource()))
  376 + .collect(Collectors.toList());
  377 + BigDecimal totalPrepayPaid = BigDecimal.ZERO;
  378 + List<LocalDateTime> prepayTimes = new ArrayList<>();
  379 + List<BigDecimal> prepayPaids = new ArrayList<>();
  380 + for (FundPaymentRequest request : prepayRequests) {
  381 + // 每次预付金额 = 该请款单中本计划的申请金额合计;合计 = 所有有效请款单的申请金额累加
  382 + BigDecimal amount = applyAmountByRequest.getOrDefault(request.getId(), BigDecimal.ZERO);
  383 + // 预付日期取请款单创建时间
  384 + prepayTimes.add(request.getCreateTime());
  385 + prepayPaids.add(amount);
  386 + totalPrepayPaid = totalPrepayPaid.add(amount);
  387 + }
  388 +
  389 + // 尾款:仓库收料单来源(含送货到厂一次性结算、退料、买断自提尾款)
  390 + List<FundPaymentRequest> finalRequests = validRequests.stream()
  391 + .filter(r -> SOURCE_RECEIVE.equals(r.getSource()))
  392 + .collect(Collectors.toList());
  393 + BigDecimal finalPaymentAmount = BigDecimal.ZERO;
  394 + LocalDateTime finalPaymentTime = null;
  395 + for (FundPaymentRequest request : finalRequests) {
  396 + finalPaymentAmount = finalPaymentAmount
  397 + .add(applyAmountByRequest.getOrDefault(request.getId(), BigDecimal.ZERO));
  398 + // 付增票余款日期取尾款请款单的审核通过时间(不用更新时间,避免后续操作覆盖)
  399 + LocalDateTime requestPassTime = request.getApprovalPassTime();
  400 + if (requestPassTime != null && (finalPaymentTime == null || requestPassTime.isBefore(finalPaymentTime))) {
  401 + finalPaymentTime = requestPassTime;
  402 + }
  403 + }
  404 +
  405 + // ===== 4. 入库(仓库收料单) =====
  406 + List<ProcurementWarehouseReceiveOrderLine> planReceiveLines = receiveOrderLineMapper.selectList(
  407 + Wrappers.lambdaQuery(ProcurementWarehouseReceiveOrderLine.class)
  408 + .eq(ProcurementWarehouseReceiveOrderLine::getProcurementPlanId, planId));
  409 + Map<String, List<ProcurementWarehouseReceiveOrderLine>> receiveLineMap = planReceiveLines.stream()
  410 + .filter(l -> StringUtil.isNotBlank(l.getReceiveOrderId()))
  411 + .collect(Collectors.groupingBy(ProcurementWarehouseReceiveOrderLine::getReceiveOrderId));
  412 + List<ProcurementWarehouseReceiveOrder> validReceives = new ArrayList<>();
  413 + if (!receiveLineMap.isEmpty()) {
  414 + validReceives = receiveOrderMapper.selectBatchIds(receiveLineMap.keySet()).stream()
  415 + .filter(r -> r != null && !Boolean.TRUE.equals(r.getDeleted())
  416 + && STATUS_PASS.equals(r.getApprovalStatus()))
  417 + .sorted(Comparator.comparing(
  418 + r -> r.getTicketDate() != null ? r.getTicketDate() : r.getCreateTime().toLocalDate(),
  419 + Comparator.nullsLast(Comparator.naturalOrder())))
  420 + .collect(Collectors.toList());
  421 + }
  422 +
  423 + BigDecimal totalReceiveQuantity = BigDecimal.ZERO;
  424 + BigDecimal totalReceiveAmount = BigDecimal.ZERO;
  425 + List<ProcurementWarehouseReceiveOrder> receiveOrders = new ArrayList<>();
  426 + List<BigDecimal> receiveQuantities = new ArrayList<>();
  427 + List<BigDecimal> receiveAmounts = new ArrayList<>();
  428 + for (ProcurementWarehouseReceiveOrder receive : validReceives) {
  429 + List<ProcurementWarehouseReceiveOrderLine> lines = receiveLineMap.getOrDefault(receive.getId(),
  430 + new ArrayList<>());
  431 + BigDecimal quantity = lines.stream()
  432 + .map(ProcurementWarehouseReceiveOrderLine::getActualQuantity)
  433 + .filter(Objects::nonNull)
  434 + .reduce(BigDecimal.ZERO, BigDecimal::add);
  435 + BigDecimal amount = lines.stream()
  436 + .map(ProcurementWarehouseReceiveOrderLine::getTaxAmount)
  437 + .filter(Objects::nonNull)
  438 + .reduce(BigDecimal.ZERO, BigDecimal::add);
  439 + receiveOrders.add(receive);
  440 + receiveQuantities.add(quantity);
  441 + receiveAmounts.add(amount);
  442 + totalReceiveQuantity = totalReceiveQuantity.add(quantity);
  443 + totalReceiveAmount = totalReceiveAmount.add(amount);
  444 + }
  445 +
  446 + // ===== 5. 派生字段 =====
  447 + BigDecimal invoiceAmount = ledger.getInvoiceAmount() == null ? BigDecimal.ZERO : ledger.getInvoiceAmount();
  448 + BigDecimal outstockQuantity = ledger.getOutstockQuantity() == null
  449 + ? BigDecimal.ZERO : ledger.getOutstockQuantity();
  450 + BigDecimal redAmount = ledger.getRedAmount() == null ? BigDecimal.ZERO : ledger.getRedAmount();
  451 +
  452 + // 欠票额 = 增票入库金额合计 - 来票金额
  453 + BigDecimal owedInvoiceAmount = totalReceiveAmount.subtract(invoiceAmount).setScale(2, RoundingMode.HALF_UP);
  454 + // 欠单额 = 入库数量合计 - 出库单数量
  455 + BigDecimal owedOrderAmount = totalReceiveQuantity.subtract(outstockQuantity)
  456 + .setScale(2, RoundingMode.HALF_UP);
  457 + // 增票余款 = 增票入库金额合计 - 增票预付合计
  458 + BigDecimal invoiceBalanceAmount = totalReceiveAmount.subtract(totalPrepayPaid)
  459 + .setScale(2, RoundingMode.HALF_UP);
  460 + // 是否入库完 = 合计到厂数量 - 入库数量合计(差值展示,0 表示已入完)
  461 + BigDecimal stockCompleteDiff = totalArrivalQuantity.subtract(totalReceiveQuantity)
  462 + .setScale(2, RoundingMode.HALF_UP);
  463 + // 对比 = 增票余款 - 付增票余款金额
  464 + BigDecimal compareAmount = invoiceBalanceAmount.subtract(finalPaymentAmount)
  465 + .setScale(2, RoundingMode.HALF_UP);
  466 + // 可预付款(万元)= (预付比例界限金额合计 - 增票预付合计)/ 10000
  467 + BigDecimal availablePrepayAmount = totalPrepayLimit.subtract(totalPrepayPaid)
  468 + .divide(TEN_THOUSAND, 2, RoundingMode.HALF_UP);
  469 + // 是否清欠:增票入库金额合计 -(增票预付合计 - 冲红金额 + 付增票余款金额)≠ 0 为是;已平账的保持否
  470 + BigDecimal debtDiff = totalReceiveAmount
  471 + .subtract(totalPrepayPaid.subtract(redAmount).add(finalPaymentAmount));
  472 + boolean balanced = StringUtil.isNotBlank(ledger.getBalanceRemark())
  473 + || StringUtil.isNotBlank(ledger.getBalanceFileIds());
  474 + boolean clearDebt = !balanced && debtDiff.compareTo(BigDecimal.ZERO) != 0;
  475 +
  476 + // ===== 6. 回写(来源字段可清空,全部显式 set;手工/冲红/平账字段不动) =====
  477 + LambdaUpdateWrapper<FundLedger> wrapper = Wrappers.lambdaUpdate(FundLedger.class)
  478 + .set(FundLedger::getApplyDate, passTime == null ? null : passTime.toLocalDate())
  479 + .set(FundLedger::getPlanCode, planCodeWithType(plan))
  480 + .set(FundLedger::getSupplierName, plan.getSupplierName())
  481 + .set(FundLedger::getPurchaseDepartment, purchaseDepartment)
  482 + .set(FundLedger::getPurchaseDepartmentName, purchaseDepartmentName)
  483 + .set(FundLedger::getRegion, region)
  484 + .set(FundLedger::getRegionName, regionName)
  485 + .set(FundLedger::getDeliveryDate, plan.getDeliveryDate())
  486 + .set(FundLedger::getPlanQuantity, plan.getTotalQuantity())
  487 + .set(FundLedger::getProductNames, productNames)
  488 + .set(FundLedger::getPlanRemark, plan.getRemark())
  489 + // 到场(只展示前三次,合计全算)
  490 + .set(FundLedger::getFirstArrivalDate, arrivalDate(validTickets, 0))
  491 + .set(FundLedger::getFirstArrivalQuantity, valueAt(arrivalQuantities, 0))
  492 + .set(FundLedger::getSecondArrivalDate, arrivalDate(validTickets, 1))
  493 + .set(FundLedger::getSecondArrivalQuantity, valueAt(arrivalQuantities, 1))
  494 + .set(FundLedger::getThirdArrivalDate, arrivalDate(validTickets, 2))
  495 + .set(FundLedger::getThirdArrivalQuantity, valueAt(arrivalQuantities, 2))
  496 + .set(FundLedger::getTotalArrivalQuantity, totalArrivalQuantity.setScale(2, RoundingMode.HALF_UP))
  497 + // 增票最低价格与每次预付
  498 + .set(FundLedger::getMinInvoicePrice, minInvoicePrice)
  499 + .set(FundLedger::getFirstInvoicePrepayAmount, valueAt(invoicePrepayAmounts, 0))
  500 + .set(FundLedger::getFirstPrepayLimit, valueAt(prepayLimits, 0))
  501 + .set(FundLedger::getSecondInvoicePrepayAmount, valueAt(invoicePrepayAmounts, 1))
  502 + .set(FundLedger::getSecondPrepayLimit, valueAt(prepayLimits, 1))
  503 + .set(FundLedger::getThirdInvoicePrepayAmount, valueAt(invoicePrepayAmounts, 2))
  504 + .set(FundLedger::getThirdPrepayLimit, valueAt(prepayLimits, 2))
  505 + .set(FundLedger::getTotalPrepayLimit, totalPrepayLimit.setScale(2, RoundingMode.HALF_UP))
  506 + // 请款(只展示前三次,合计全算)
  507 + .set(FundLedger::getFirstPrepayDate, prepayDate(prepayTimes, 0))
  508 + .set(FundLedger::getFirstPrepayPaid, valueAt(prepayPaids, 0))
  509 + .set(FundLedger::getSecondPrepayDate, prepayDate(prepayTimes, 1))
  510 + .set(FundLedger::getSecondPrepayPaid, valueAt(prepayPaids, 1))
  511 + .set(FundLedger::getThirdPrepayDate, prepayDate(prepayTimes, 2))
  512 + .set(FundLedger::getThirdPrepayPaid, valueAt(prepayPaids, 2))
  513 + .set(FundLedger::getTotalPrepayPaid, totalPrepayPaid.setScale(2, RoundingMode.HALF_UP))
  514 + .set(FundLedger::getAvailablePrepayAmount, availablePrepayAmount)
  515 + // 入库(只展示前三次,合计全算)
  516 + .set(FundLedger::getFirstReceiveDate, receiveDate(receiveOrders, 0))
  517 + .set(FundLedger::getFirstReceiveQuantity, valueAt(receiveQuantities, 0))
  518 + .set(FundLedger::getFirstReceiveAmount, valueAt(receiveAmounts, 0))
  519 + .set(FundLedger::getSecondReceiveDate, receiveDate(receiveOrders, 1))
  520 + .set(FundLedger::getSecondReceiveQuantity, valueAt(receiveQuantities, 1))
  521 + .set(FundLedger::getSecondReceiveAmount, valueAt(receiveAmounts, 1))
  522 + .set(FundLedger::getThirdReceiveDate, receiveDate(receiveOrders, 2))
  523 + .set(FundLedger::getThirdReceiveQuantity, valueAt(receiveQuantities, 2))
  524 + .set(FundLedger::getThirdReceiveAmount, valueAt(receiveAmounts, 2))
  525 + .set(FundLedger::getTotalReceiveQuantity, totalReceiveQuantity.setScale(2, RoundingMode.HALF_UP))
  526 + .set(FundLedger::getTotalReceiveAmount, totalReceiveAmount.setScale(2, RoundingMode.HALF_UP))
  527 + // 派生字段
  528 + .set(FundLedger::getOwedInvoiceAmount, owedInvoiceAmount)
  529 + .set(FundLedger::getOwedOrderAmount, owedOrderAmount)
  530 + .set(FundLedger::getInvoiceBalanceAmount, invoiceBalanceAmount)
  531 + .set(FundLedger::getStockCompleteDiff, stockCompleteDiff)
  532 + .set(FundLedger::getFinalPaymentDate,
  533 + finalPaymentTime == null ? null : finalPaymentTime.toLocalDate())
  534 + .set(FundLedger::getFinalPaymentAmount, finalPaymentAmount.setScale(2, RoundingMode.HALF_UP))
  535 + .set(FundLedger::getCompareAmount, compareAmount)
  536 + .set(FundLedger::getClearDebt, clearDebt)
  537 + .eq(FundLedger::getId, ledger.getId());
  538 + this.update(wrapper);
  539 + }
  540 +
  541 + @Override
  542 + public void refreshByTicketId(String ticketId) {
  543 + if (StringUtil.isBlank(ticketId)) {
  544 + return;
  545 + }
  546 + refreshAfterCommit(ticketPlanIds(ticketId));
  547 + }
  548 +
  549 + @Override
  550 + public void refreshByRequestId(String requestId) {
  551 + if (StringUtil.isBlank(requestId)) {
  552 + return;
  553 + }
  554 + FundPaymentRequest request = fundPaymentRequestMapper.selectById(requestId);
  555 + if (request == null) {
  556 + return;
  557 + }
  558 + List<String> planIds = splitIds(request.getPlanIds());
  559 + if (CollectionUtil.isEmpty(planIds)) {
  560 + planIds = fundPaymentRequestLineMapper.selectList(
  561 + Wrappers.lambdaQuery(FundPaymentRequestLine.class)
  562 + .eq(FundPaymentRequestLine::getRequestId, requestId))
  563 + .stream().map(FundPaymentRequestLine::getPlanId)
  564 + .filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());
  565 + }
  566 + refreshAfterCommit(planIds);
  567 + }
  568 +
  569 + @Override
  570 + public void refreshByReceiveId(String receiveId) {
  571 + if (StringUtil.isBlank(receiveId)) {
  572 + return;
  573 + }
  574 + ProcurementWarehouseReceiveOrder receive = receiveOrderMapper.selectById(receiveId);
  575 + if (receive == null) {
  576 + return;
  577 + }
  578 + List<String> planIds = splitIds(receive.getPlanIds());
  579 + if (CollectionUtil.isEmpty(planIds)) {
  580 + planIds = receiveOrderLineMapper.selectList(
  581 + Wrappers.lambdaQuery(ProcurementWarehouseReceiveOrderLine.class)
  582 + .eq(ProcurementWarehouseReceiveOrderLine::getReceiveOrderId, receiveId))
  583 + .stream().map(ProcurementWarehouseReceiveOrderLine::getProcurementPlanId)
  584 + .filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());
  585 + }
  586 + refreshAfterCommit(planIds);
  587 + }
  588 +
  589 + @Override
  590 + public int rebuildAll() {
  591 + // 历史补数:先清理已删除/归档/作废(冻结)计划的台账,再为有效计划生成/刷新
  592 + // 不加事务,逐条提交,避免一次性大事务
  593 + List<FundLedger> ledgers = this.list();
  594 + for (FundLedger ledger : ledgers) {
  595 + ProcurementPlan plan = procurementPlanMapper.selectById(ledger.getPlanId());
  596 + if (plan == null || Boolean.TRUE.equals(plan.getDeleted()) || Boolean.TRUE.equals(plan.getFrozen())) {
  597 + this.removeById(ledger.getId());
  598 + }
  599 + }
  600 + // 审核通过的正常计划 + 补单/变更生成的新计划(planType 非空)
  601 + List<ProcurementPlan> plans = procurementPlanMapper.selectList(
  602 + Wrappers.lambdaQuery(ProcurementPlan.class)
  603 + .eq(ProcurementPlan::getDeleted, false)
  604 + .eq(ProcurementPlan::getFrozen, false)
  605 + .and(w -> w.eq(ProcurementPlan::getApprovalStatus, STATUS_PASS)
  606 + .or().isNotNull(ProcurementPlan::getPlanType)));
  607 + for (ProcurementPlan plan : plans) {
  608 + generateByPlanId(plan.getId());
  609 + }
  610 + return plans.size();
  611 + }
  612 +
  613 + private FundLedger getByPlanId(String planId) {
  614 + LambdaQueryWrapper<FundLedger> wrapper = Wrappers.lambdaQuery(FundLedger.class)
  615 + .eq(FundLedger::getPlanId, planId);
  616 + List<FundLedger> list = this.list(wrapper);
  617 + return CollectionUtil.isEmpty(list) ? null : list.get(0);
  618 + }
  619 +
  620 + /**
  621 + * 台账刷新统一在事务提交后执行:写接口只负责单据落库,避免重算拖慢审核/作废等主流程;
  622 + * 无事务上下文(补数等场景)时立即执行。刷新失败不影响主单据,可由重建接口兜底。
  623 + */
  624 + private void refreshAfterCommit(Collection<String> planIds) {
  625 + if (CollectionUtil.isEmpty(planIds)) {
  626 + return;
  627 + }
  628 + final List<String> distinctPlanIds = planIds.stream()
  629 + .filter(StringUtil::isNotBlank)
  630 + .distinct()
  631 + .collect(Collectors.toList());
  632 + if (distinctPlanIds.isEmpty()) {
  633 + return;
  634 + }
  635 + if (TransactionSynchronizationManager.isSynchronizationActive()) {
  636 + TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
  637 + @Override
  638 + public void afterCommit() {
  639 + try {
  640 + applicationContext.getBean(FundLedgerService.class).refreshByPlanIds(distinctPlanIds);
  641 + } catch (Exception ignored) {
  642 + // 台账刷新失败不影响主单据,可由重建接口兜底
  643 + }
  644 + }
  645 + });
  646 + } else {
  647 + applicationContext.getBean(FundLedgerService.class).refreshByPlanIds(distinctPlanIds);
  648 + }
  649 + }
  650 +
  651 + /**
  652 + * 台账展示的计划编号:正常计划为编号;补单/变更计划为 编号+类型(补、变、变 补),与单据打印口径一致
  653 + */
  654 + private String planCodeWithType(ProcurementPlan plan) {
  655 + String code = StringUtil.isBlank(plan.getCode()) ? "" : plan.getCode();
  656 + String planType = StringUtil.isBlank(plan.getPlanType()) ? "" : plan.getPlanType();
  657 + return code + planType;
  658 + }
  659 +
  660 + private List<String> ticketPlanIds(String ticketId) {
  661 + return weighingTicketLineMapper.selectList(
  662 + Wrappers.lambdaQuery(ProcurementWeighingTicketLine.class)
  663 + .eq(ProcurementWeighingTicketLine::getWeighingTicketId, ticketId))
  664 + .stream().map(ProcurementWeighingTicketLine::getProcurementPlanId)
  665 + .filter(StringUtil::isNotBlank).distinct().collect(Collectors.toList());
  666 + }
  667 +
  668 + /**
  669 + * 第 N 车的到厂日期(N 从 0 开始,超过次数返回 null)
  670 + */
  671 + private java.time.LocalDate arrivalDate(List<ProcurementWeighingTicket> tickets, int index) {
  672 + if (tickets.size() <= index) {
  673 + return null;
  674 + }
  675 + ProcurementWeighingTicket ticket = tickets.get(index);
  676 + if (ticket.getFirstGrossWeightTime() != null) {
  677 + return ticket.getFirstGrossWeightTime().toLocalDate();
  678 + }
  679 + return ticket.getCreateTime() == null ? null : ticket.getCreateTime().toLocalDate();
  680 + }
  681 +
  682 + /**
  683 + * 第 N 次请款日期(N 从 0 开始,超过次数返回 null)
  684 + */
  685 + private java.time.LocalDate prepayDate(List<LocalDateTime> times, int index) {
  686 + if (times.size() <= index || times.get(index) == null) {
  687 + return null;
  688 + }
  689 + return times.get(index).toLocalDate();
  690 + }
  691 +
  692 + /**
  693 + * 第 N 次入库日期(N 从 0 开始,超过次数返回 null)
  694 + */
  695 + private java.time.LocalDate receiveDate(List<ProcurementWarehouseReceiveOrder> receives, int index) {
  696 + if (receives.size() <= index) {
  697 + return null;
  698 + }
  699 + ProcurementWarehouseReceiveOrder receive = receives.get(index);
  700 + if (receive.getTicketDate() != null) {
  701 + return receive.getTicketDate();
  702 + }
  703 + return receive.getCreateTime() == null ? null : receive.getCreateTime().toLocalDate();
  704 + }
  705 +
  706 + private BigDecimal valueAt(List<BigDecimal> values, int index) {
  707 + return values.size() <= index ? null : values.get(index);
  708 + }
  709 +
  710 + private List<String> splitIds(String joined) {
  711 + if (StringUtil.isBlank(joined)) {
  712 + return new ArrayList<>();
  713 + }
  714 + return java.util.Arrays.stream(joined.split("[,,]"))
  715 + .map(String::trim)
  716 + .filter(s -> !s.isEmpty())
  717 + .distinct()
  718 + .collect(Collectors.toList());
  719 + }
  720 +
  721 + private FundLedger assertExists(String id) {
  722 + FundLedger entity = this.getById(id);
  723 + if (entity == null) {
  724 + throw new DefaultClientException("资金台账不存在!");
  725 + }
  726 + return entity;
  727 + }
  728 +}
... ...
... ... @@ -39,6 +39,7 @@ import com.lframework.xingyun.sc.procurement.mappers.receive.ProcurementWarehous
39 39 import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketLineMapper;
40 40 import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketMapper;
41 41 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestLineService;
  42 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
42 43 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestService;
43 44 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentSupplierService;
44 45 import com.lframework.xingyun.sc.procurement.vo.fundpayment.CreateFundPaymentRequestVo;
... ... @@ -49,6 +50,7 @@ import com.lframework.xingyun.sc.procurement.vo.fundpayment.UpdateFundPaymentReq
49 50 import java.math.BigDecimal;
50 51 import java.math.RoundingMode;
51 52 import java.time.LocalDate;
  53 +import java.time.LocalDateTime;
52 54 import java.util.ArrayList;
53 55 import java.util.Collections;
54 56 import java.util.HashMap;
... ... @@ -97,6 +99,8 @@ public class FundPaymentRequestServiceImpl
97 99 @Resource
98 100 private FundPaymentRequestLineService requestLineService;
99 101 @Resource
  102 + private FundLedgerService fundLedgerService;
  103 + @Resource
100 104 private FundPaymentSupplierService fundPaymentSupplierService;
101 105 @Resource
102 106 private ProcurementPlanMapper procurementPlanMapper;
... ... @@ -159,7 +163,8 @@ public class FundPaymentRequestServiceImpl
159 163 @Override
160 164 @Transactional(rollbackFor = Exception.class)
161 165 @OpLog(type = OtherOpLogType.class, name = "按来源单生成请款单草稿,来源单ID:{}", params = {"#sourceId"})
162   - public String generate(String source, String sourceId) {
  166 + public String generate(String source, String sourceId, String requestKind,
  167 + String supplementFileIds, String supplementFileNames) {
163 168 Assert.notBlank(source);
164 169 Assert.notBlank(sourceId);
165 170 assertSourceValid(source);
... ... @@ -168,7 +173,7 @@ public class FundPaymentRequestServiceImpl
168 173 FundPaymentRequest entity = findDraft(source, sourceId);
169 174 if (entity == null) {
170 175 // 能自动带出/计算的字段直接落库,申请金额等需人工填写的字段留空,由前端修改请款单时补充
171   - entity = buildDraft(source, sourceId, null);
  176 + entity = buildDraft(source, sourceId, null, requestKind, supplementFileIds, supplementFileNames);
172 177 } else {
173 178 throw new DefaultClientException("该过磅码单已存在在途请款单,审核通过后再生成下一张请款单!");
174 179 }
... ... @@ -198,7 +203,7 @@ public class FundPaymentRequestServiceImpl
198 203 public String create(CreateFundPaymentRequestVo vo) {
199 204 assertSourceValid(vo.getSource());
200 205 // 来源单校验、自动带出数据、明细计算统一收敛到 buildDraft,与生成接口生成的草稿口径一致
201   - FundPaymentRequest entity = buildDraft(vo.getSource(), vo.getSourceId(), vo);
  206 + FundPaymentRequest entity = buildDraft(vo.getSource(), vo.getSourceId(), vo, null, null, null);
202 207
203 208 OpLogUtil.setVariable("id", entity.getId());
204 209 OpLogUtil.setExtra(entity);
... ... @@ -210,8 +215,11 @@ public class FundPaymentRequestServiceImpl
210 215 * 按来源单生成草稿请款单:能自动带出/计算的字段一次性落库,需人工填写的字段留空,由前端修改请款单时补充。
211 216 *
212 217 * @param vo 一次性提交的手填数据;为 null 时(生成接口)只生成草稿、不校验申请金额
  218 + * @param requestKind 生成接口指定的请款单类型(NORMAL/SUPPLEMENT),create 路径由 vo 提供
213 219 */
214   - private FundPaymentRequest buildDraft(String source, String sourceId, CreateFundPaymentRequestVo vo) {
  220 + private FundPaymentRequest buildDraft(String source, String sourceId, CreateFundPaymentRequestVo vo,
  221 + String requestKind, String supplementFileIds,
  222 + String supplementFileNames) {
215 223 // 来源单可用性校验 + 占用校验(同一时间同一来源只能生成一张在途请款单)
216 224 FundPaymentRequest context = buildContext(source, sourceId);
217 225 // 明细以服务端按来源单计算为准(预付金额不可篡改);申请金额需人工填写,草稿阶段留空
... ... @@ -247,12 +255,19 @@ public class FundPaymentRequestServiceImpl
247 255 entity.setFlowNode(NODE_GYGLKZJY);
248 256
249 257 if (vo != null) {
  258 + // 请款单类型由用户在新增时选择
  259 + entity.setRequestKind(resolveRequestKind(context.getSource(), vo.getRequestKind()));
250 260 // 对方户名/开户银行/账号来自资金支付供应商信息
251 261 applySupplier(entity, vo.getSupplierId(), vo.getPayeeName(), vo.getBankName(), vo.getBankAccount());
252 262 entity.setRequestRemark(vo.getRequestRemark());
253 263 entity.setSupplementRemark(vo.getSupplementRemark());
254 264 entity.setSupplementFileIds(vo.getSupplementFileIds());
255 265 entity.setSupplementFileNames(vo.getSupplementFileNames());
  266 + } else if (StringUtil.isNotBlank(requestKind)) {
  267 + // 生成接口直接指定请款单类型与补充附件
  268 + entity.setRequestKind(resolveRequestKind(source, requestKind));
  269 + entity.setSupplementFileIds(supplementFileIds);
  270 + entity.setSupplementFileNames(supplementFileNames);
256 271 }
257 272
258 273 fillTotalAmount(entity, lines);
... ... @@ -269,6 +284,22 @@ public class FundPaymentRequestServiceImpl
269 284 }
270 285 }
271 286
  287 + /**
  288 + * 请款单类型:默认正常;用户选择补充请款单时,仅过磅码单来源可用
  289 + */
  290 + private String resolveRequestKind(String source, String requestKind) {
  291 + if (StringUtil.isBlank(requestKind) || KIND_NORMAL.equals(requestKind)) {
  292 + return KIND_NORMAL;
  293 + }
  294 + if (!KIND_SUPPLEMENT.equals(requestKind)) {
  295 + throw new DefaultClientException("请款单类型不合法!");
  296 + }
  297 + if (!SOURCE_TICKET.equals(source)) {
  298 + throw new DefaultClientException("仅过磅码单来源可生成补充请款单!");
  299 + }
  300 + return KIND_SUPPLEMENT;
  301 + }
  302 +
272 303 @Override
273 304 @Transactional(rollbackFor = Exception.class)
274 305 @OpLog(type = OtherOpLogType.class, name = "修改资金支付请款单,ID:{}", params = {"#vo.id"})
... ... @@ -288,6 +319,10 @@ public class FundPaymentRequestServiceImpl
288 319
289 320 FundPaymentRequest entity = new FundPaymentRequest();
290 321 entity.setId(vo.getId());
  322 + // 请款单类型由用户在修改时选择:未传时保留原类型
  323 + String requestKind = StringUtil.isBlank(vo.getRequestKind())
  324 + ? oldEntity.getRequestKind() : vo.getRequestKind();
  325 + entity.setRequestKind(resolveRequestKind(oldEntity.getSource(), requestKind));
291 326 applySupplier(entity, vo.getSupplierId(), vo.getPayeeName(), vo.getBankName(), vo.getBankAccount());
292 327 entity.setRequestRemark(vo.getRequestRemark());
293 328 entity.setSupplementRemark(vo.getSupplementRemark());
... ... @@ -387,6 +422,9 @@ public class FundPaymentRequestServiceImpl
387 422 .set(FundPaymentRequest::getFlowNode, null)
388 423 .eq(FundPaymentRequest::getId, id));
389 424
  425 + // 作废后联动刷新关联计划资金台账(预付/尾款数据随之减少)
  426 + fundLedgerService.refreshByRequestId(id);
  427 +
390 428 OpLogUtil.setVariable("id", id);
391 429 OpLogUtil.setExtra(entity);
392 430 }
... ... @@ -427,7 +465,14 @@ public class FundPaymentRequestServiceImpl
427 465 this.update(Wrappers.lambdaUpdate(FundPaymentRequest.class)
428 466 .set(FundPaymentRequest::getApprovalStatus, approvalStatus)
429 467 .set(FundPaymentRequest::getFlowNode, STATUS_PASS.equals(approvalStatus) ? null : NODE_GYGLKZJY)
  468 + // 审核通过时记录审核通过时间(台账付款日期取该时间,避免后续更新时间覆盖)
  469 + .set(STATUS_PASS.equals(approvalStatus), FundPaymentRequest::getApprovalPassTime, LocalDateTime.now())
430 470 .eq(FundPaymentRequest::getId, id));
  471 +
  472 + // 仅审核通过才计入资金台账(增票预付/尾款数据),其余状态不更新台账数据
  473 + if (STATUS_PASS.equals(approvalStatus)) {
  474 + fundLedgerService.refreshByRequestId(id);
  475 + }
431 476 }
432 477
433 478 @Override
... ... @@ -476,6 +521,9 @@ public class FundPaymentRequestServiceImpl
476 521 FundPaymentRequest::getApprovalStatus, STATUS_REFUSE)
477 522 .eq(FundPaymentRequest::getId, request.getId()));
478 523 }
  524 +
  525 + // 码单作废联动作废后刷新关联计划资金台账
  526 + requests.forEach(request -> fundLedgerService.refreshByRequestId(request.getId()));
479 527 }
480 528
481 529 /**
... ... @@ -555,13 +603,8 @@ public class FundPaymentRequestServiceImpl
555 603 context.setTicketId(receive.getWeighingTicketId());
556 604 context.setTicketCode(receive.getWeighingTicketCode());
557 605 context.setReceiveId(receive.getId());
558   - // 过磅码单类型为退料换料(RETURN)的才是补充请款单(在仓库收料单生成,只生成一张);其余均为正常请款单
559   - boolean supplement = false;
560   - if (StringUtil.isNotBlank(receive.getWeighingTicketId())) {
561   - ProcurementWeighingTicket linkedTicket = weighingTicketMapper.selectById(receive.getWeighingTicketId());
562   - supplement = linkedTicket != null && "RETURN".equals(linkedTicket.getType());
563   - }
564   - context.setRequestKind(supplement ? KIND_SUPPLEMENT : KIND_NORMAL);
  606 + // 补充请款单由用户在新增/修改时选择(不按码单类型自动判定),默认正常请款单
  607 + context.setRequestKind(KIND_NORMAL);
565 608 return context;
566 609 }
567 610
... ... @@ -915,8 +958,9 @@ public class FundPaymentRequestServiceImpl
915 958 if (ticket.getCompleteTime() == null) {
916 959 throw new DefaultClientException("过磅码单未完成(未上传签字凭证),无法生成请款单!");
917 960 }
  961 + // 退料换料码单不允许在码单阶段生成请款单,只能在仓库收料单中生成一张有效请款单
918 962 if ("RETURN".equals(ticket.getType())) {
919   - throw new DefaultClientException("退料过磅码单不允许生成请款单,请在仓库收料单上申请!");
  963 + throw new DefaultClientException("退料换料过磅码单不允许生成请款单,请在仓库收料单中申请!");
920 964 }
921 965 // 关联计划必须送货到厂且流程已完成(码单完成状态)
922 966 List<String> planIdList = ticketLinesPlanIds(ticketId);
... ... @@ -971,7 +1015,7 @@ public class FundPaymentRequestServiceImpl
971 1015 if (occupied > 0) {
972 1016 throw new DefaultClientException("该仓库收料单已存在请款单,不允许重复生成!");
973 1017 }
974   - // 退料换料码单的补充请款单只生成一张(同码单链维度占用)
  1018 + // 退料换料码单只在仓库收料单中生成一张有效请款单(同码单链维度占用)
975 1019 if (StringUtil.isNotBlank(receive.getWeighingTicketId())) {
976 1020 ProcurementWeighingTicket linkedTicket = weighingTicketMapper.selectById(receive.getWeighingTicketId());
977 1021 if (linkedTicket != null && "RETURN".equals(linkedTicket.getType())) {
... ... @@ -980,7 +1024,7 @@ public class FundPaymentRequestServiceImpl
980 1024 .eq(FundPaymentRequest::getTicketId, receive.getWeighingTicketId())
981 1025 .eq(FundPaymentRequest::getDeleted, false));
982 1026 if (supplementOccupied > 0) {
983   - throw new DefaultClientException("该退料换料码单已生成过补充请款单,不允许重复生成!");
  1027 + throw new DefaultClientException("该退料换料码单已生成过请款单,不允许重复生成!");
984 1028 }
985 1029 }
986 1030 }
... ...
... ... @@ -41,6 +41,7 @@ import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighin
41 41 import com.lframework.xingyun.sc.procurement.service.buyout.ProcurementBuyoutApplyService;
42 42 import com.lframework.xingyun.sc.procurement.service.contract.ProcurementContractService;
43 43 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestService;
  44 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
44 45 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanLineService;
45 46 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanService;
46 47 import com.lframework.xingyun.sc.procurement.service.quotation.SalesmanQuotationService;
... ... @@ -93,6 +94,8 @@ public class ProcurementPlanServiceImpl extends BaseMpServiceImpl<ProcurementPla
93 94 private ProcurementContractService procurementContractService;
94 95 @Resource
95 96 private FundPaymentRequestService fundPaymentRequestService;
  97 + @Resource
  98 + private FundLedgerService fundLedgerService;
96 99
97 100 @Override
98 101 public PageResult<ProcurementPlan> query(Integer pageIndex, Integer pageSize,
... ... @@ -617,6 +620,8 @@ public class ProcurementPlanServiceImpl extends BaseMpServiceImpl<ProcurementPla
617 620
618 621 //如果是子计划且审核通过,检查主计划下所有子计划是否都已通过
619 622 if ("PASS".equals(approvalStatus)) {
  623 + // 审核通过时生成资金台账(一个计划一条,已存在则刷新)
  624 + fundLedgerService.generateByPlanId(id);
620 625
621 626 // 判断当前计划是否为子计划(parentId不为空)
622 627 if (StringUtils.isNotBlank(currentPlan.getParentId())) {
... ...
... ... @@ -45,6 +45,7 @@ import com.lframework.xingyun.sc.procurement.mappers.receive.ProcurementWarehous
45 45 import com.lframework.xingyun.sc.procurement.mappers.settle.ProcurementMaterialSettleDetailMapper;
46 46 import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketMapper;
47 47 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestService;
  48 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
48 49 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanLineService;
49 50 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanService;
50 51 import com.lframework.xingyun.sc.procurement.service.receive.ProcurementWarehouseReceiveOrderLineService;
... ... @@ -168,6 +169,8 @@ public class ProcurementWarehouseReceiveOrderServiceImpl
168 169 private SysRoleService sysRoleService;
169 170 @Resource
170 171 private FundPaymentRequestService fundPaymentRequestService;
  172 + @Resource
  173 + private FundLedgerService fundLedgerService;
171 174
172 175 @Override
173 176 public PageResult<ProcurementWarehouseReceiveOrder> query(Integer pageIndex, Integer pageSize,
... ... @@ -520,6 +523,11 @@ public class ProcurementWarehouseReceiveOrderServiceImpl
520 523 .set(ProcurementWarehouseReceiveOrder::getApprovalStatus, approvalStatus)
521 524 .set(ProcurementWarehouseReceiveOrder::getFlowNode, approvalStatus.equals("PASS") ? null : NODE_YLHSG)
522 525 .eq(ProcurementWarehouseReceiveOrder::getId, id));
  526 +
  527 + // 仅审核通过才计入资金台账(入库数据),其余状态不更新台账数据
  528 + if ("PASS".equals(approvalStatus)) {
  529 + fundLedgerService.refreshByReceiveId(id);
  530 + }
523 531 }
524 532
525 533 @Override
... ... @@ -660,6 +668,9 @@ public class ProcurementWarehouseReceiveOrderServiceImpl
660 668 ProcurementWarehouseReceiveOrder::getApprovalStatus, STATUS_REFUSE)
661 669 .eq(ProcurementWarehouseReceiveOrder::getId, order.getId()));
662 670 }
  671 +
  672 + // 作废后联动刷新关联计划资金台账(入库数据随之减少)
  673 + orders.forEach(o -> fundLedgerService.refreshByReceiveId(o.getId()));
663 674 }
664 675
665 676 @Override
... ... @@ -689,6 +700,9 @@ public class ProcurementWarehouseReceiveOrderServiceImpl
689 700 ProcurementWarehouseReceiveOrder::getApprovalStatus, STATUS_REFUSE)
690 701 .eq(ProcurementWarehouseReceiveOrder::getId, order.getId()));
691 702 }
  703 +
  704 + // 作废后联动刷新关联计划资金台账(入库数据随之减少)
  705 + orders.forEach(o -> fundLedgerService.refreshByReceiveId(o.getId()));
692 706 }
693 707
694 708 /**
... ...
... ... @@ -37,6 +37,7 @@ import com.lframework.xingyun.sc.procurement.entity.replenish.ProcurementPlanRep
37 37 import com.lframework.xingyun.sc.procurement.mappers.replenish.ProcurementPlanReplenishMapper;
38 38 import com.lframework.xingyun.sc.procurement.service.buyout.ProcurementBuyoutApplyService;
39 39 import com.lframework.xingyun.sc.procurement.service.contract.ProcurementContractService;
  40 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
40 41 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanLineService;
41 42 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanService;
42 43 import com.lframework.xingyun.sc.procurement.service.replenish.ProcurementPlanReplenishLineService;
... ... @@ -92,6 +93,8 @@ public class ProcurementPlanReplenishServiceImpl
92 93 private FlowTaskWrapperMapper flowTaskWrapperMapper;
93 94 @Resource
94 95 private ProcurementContractService procurementContractService;
  96 + @Resource
  97 + private FundLedgerService fundLedgerService;
95 98
96 99
97 100 @Override
... ... @@ -568,6 +571,13 @@ public class ProcurementPlanReplenishServiceImpl
568 571 }
569 572 }
570 573
  574 + // 补单审核通过生成的新计划同步生成资金台账(多分厂时主计划冻结,只保留子计划台账)
  575 + List<String> ledgerPlanIds = new ArrayList<>();
  576 + ledgerPlanIds.add(archivedMain.getId());
  577 + ledgerPlanIds.addAll(procurementPlanService.listSubPlan(archivedMain.getId()).stream()
  578 + .map(ProcurementPlan::getId).collect(Collectors.toList()));
  579 + fundLedgerService.generateByPlanIds(ledgerPlanIds);
  580 +
571 581 } else if ("REFUSE".equals(approvalStatus)) {
572 582 List<SysRole> roles = sysRoleService.getByUserId(entity.getCreateById());
573 583 List<String> roleCodes = CollectionUtil.isEmpty(roles) ? new java.util.ArrayList<>()
... ...
... ... @@ -38,6 +38,7 @@ import com.lframework.xingyun.sc.procurement.entity.weighing.ProcurementWeighing
38 38 import com.lframework.xingyun.sc.procurement.entity.weighing.ProcurementWeighingTicketPlan;
39 39 import com.lframework.xingyun.sc.procurement.mappers.weighing.ProcurementWeighingTicketMapper;
40 40 import com.lframework.xingyun.sc.procurement.service.fundpayment.FundPaymentRequestService;
  41 +import com.lframework.xingyun.sc.procurement.service.fundledger.FundLedgerService;
41 42 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanLineService;
42 43 import com.lframework.xingyun.sc.procurement.service.plan.ProcurementPlanService;
43 44 import com.lframework.xingyun.sc.procurement.service.settle.ProcurementMaterialSettleDetailService;
... ... @@ -130,6 +131,8 @@ public class ProcurementWeighingTicketServiceImpl
130 131 private ProcurementBuyoutAccountOrderService buyoutAccountOrderService;
131 132 @Resource
132 133 private FundPaymentRequestService fundPaymentRequestService;
  134 + @Resource
  135 + private FundLedgerService fundLedgerService;
133 136
134 137 @Override
135 138 public PageResult<ProcurementWeighingTicket> query(Integer pageIndex, Integer pageSize,
... ... @@ -388,6 +391,14 @@ public class ProcurementWeighingTicketServiceImpl
388 391 }
389 392 });
390 393 recalcPlanDiffFlags(diffPlanIds);
  394 +
  395 + // 原码单已作废,联动刷新其关联计划的资金台账(到场数据随之减少)
  396 + fundLedgerService.refreshByTicketId(originId);
  397 + }
  398 +
  399 + // 仅审核通过才计入资金台账(到场数据与预付界限),其余状态不更新台账数据
  400 + if (STATUS_PASS.equals(approvalStatus)) {
  401 + fundLedgerService.refreshByTicketId(id);
391 402 }
392 403 }
393 404
... ... @@ -597,6 +608,9 @@ public class ProcurementWeighingTicketServiceImpl
597 608 // 联动作废该码单关联的全部请款单(含码单来源、该码单收料单来源,审核中的先终止流程再作废)
598 609 fundPaymentRequestService.deleteByWeighingTicketId(id);
599 610
  611 + // 码单作废后联动刷新关联计划资金台账(到场数据随之减少)
  612 + fundLedgerService.refreshByTicketId(id);
  613 +
600 614 OpLogUtil.setVariable("id", id);
601 615 OpLogUtil.setExtra(entity);
602 616 }
... ...
  1 +package com.lframework.xingyun.sc.procurement.mappers.fundledger;
  2 +
  3 +import com.lframework.starter.web.core.mapper.BaseMapper;
  4 +import com.lframework.xingyun.sc.procurement.entity.fundledger.FundLedger;
  5 +import com.lframework.xingyun.sc.procurement.vo.fundledger.QueryFundLedgerVo;
  6 +import java.util.List;
  7 +import org.apache.ibatis.annotations.Param;
  8 +
  9 +public interface FundLedgerMapper extends BaseMapper<FundLedger> {
  10 +
  11 + /**
  12 + * 分页查询资金台账
  13 + */
  14 + List<FundLedger> query(@Param("vo") QueryFundLedgerVo vo);
  15 +
  16 + /**
  17 + * 单条查询
  18 + */
  19 + FundLedger findById(@Param("id") String id);
  20 +}
... ...
  1 +package com.lframework.xingyun.sc.procurement.service.fundledger;
  2 +
  3 +import com.lframework.starter.web.core.components.resp.PageResult;
  4 +import com.lframework.starter.web.core.service.BaseMpService;
  5 +import com.lframework.xingyun.sc.bo.procurement.GetFundLedgerBo;
  6 +import com.lframework.xingyun.sc.procurement.entity.fundledger.FundLedger;
  7 +import com.lframework.xingyun.sc.procurement.vo.fundledger.BalanceFundLedgerVo;
  8 +import com.lframework.xingyun.sc.procurement.vo.fundledger.QueryFundLedgerVo;
  9 +import com.lframework.xingyun.sc.procurement.vo.fundledger.RedFundLedgerVo;
  10 +import com.lframework.xingyun.sc.procurement.vo.fundledger.UpdateFundLedgerVo;
  11 +
  12 +public interface FundLedgerService extends BaseMpService<FundLedger> {
  13 +
  14 + /**
  15 + * 分页查询资金台账(分月展示)
  16 + */
  17 + PageResult<FundLedger> query(Integer pageIndex, Integer pageSize, QueryFundLedgerVo vo);
  18 +
  19 + /**
  20 + * 查看资金台账详情
  21 + */
  22 + GetFundLedgerBo findDetail(String id);
  23 +
  24 + /**
  25 + * 修改资金台账(仅来票时间/数量/金额、出库单数量、备注可改)
  26 + */
  27 + void update(UpdateFundLedgerVo vo);
  28 +
  29 + /**
  30 + * 冲红(冲红金额、说明、附件)
  31 + */
  32 + void red(RedFundLedgerVo vo);
  33 +
  34 + /**
  35 + * 平账(仅清欠状态可平账,平账后是否清欠改为否)
  36 + */
  37 + void balance(BalanceFundLedgerVo vo);
  38 +
  39 + /**
  40 + * 采购计划审核通过时生成台账(一个计划一条,已存在则刷新),幂等;
  41 + * 计划已删除/归档/作废(冻结)时删除对应台账
  42 + */
  43 + void generateByPlanId(String planId);
  44 +
  45 + /**
  46 + * 批量生成台账(计划变更、补单等生成的新计划使用),内部去重;
  47 + * 已作废(冻结)/归档的计划会删除其台账
  48 + */
  49 + void generateByPlanIds(java.util.Collection<String> planIds);
  50 +
  51 + /**
  52 + * 按采购计划重算台账全部来源字段与派生字段(保留手工填写与冲红/平账数据)
  53 + */
  54 + void refreshByPlanId(String planId);
  55 +
  56 + /**
  57 + * 批量按采购计划重算台账(内部去重,供事务提交后统一刷新使用)
  58 + */
  59 + void refreshByPlanIds(java.util.Collection<String> planIds);
  60 +
  61 + /**
  62 + * 过磅码单审核通过/作废后联动刷新其关联计划的台账
  63 + */
  64 + void refreshByTicketId(String ticketId);
  65 +
  66 + /**
  67 + * 请款单审核通过/作废/取消后联动刷新其关联计划的台账
  68 + */
  69 + void refreshByRequestId(String requestId);
  70 +
  71 + /**
  72 + * 仓库收料单审核通过/作废后联动刷新其关联计划的台账
  73 + */
  74 + void refreshByReceiveId(String receiveId);
  75 +
  76 + /**
  77 + * 按全部已审核通过的采购计划重建台账(历史数据补数,返回处理计划数)
  78 + */
  79 + int rebuildAll();
  80 +}
... ...
... ... @@ -27,8 +27,13 @@ public interface FundPaymentRequestService extends BaseMpService<FundPaymentRequ
27 27 * 来源单信息、请款附件、请款单类型、请款日期(当天)、付款方式(电汇)、明细预付金额与合计均自动带出/计算;
28 28 * 对方户名/开户行/账号、请款说明、补充说明及附件、明细申请金额留空,由前端凭 ID 查询详情后走修改请款单补充。
29 29 * 同一来源单已有草稿时幂等返回该单ID,不重复生成。
  30 + *
  31 + * @param requestKind 请款单类型 NORMAL-正常 SUPPLEMENT-补充请款单(为空默认正常;补充请款单仅过磅码单来源可用)
  32 + * @param supplementFileIds 补充说明附件文件ID集合(补充请款单填写)
  33 + * @param supplementFileNames 补充说明附件文件名称集合
30 34 */
31   - String generate(String source, String sourceId);
  35 + String generate(String source, String sourceId, String requestKind,
  36 + String supplementFileIds, String supplementFileNames);
32 37
33 38 /**
34 39 * 新增请款单(草稿,供应管理科资金管理员)
... ...
  1 +package com.lframework.xingyun.sc.procurement.vo.fundledger;
  2 +
  3 +import io.swagger.annotations.ApiModel;
  4 +import io.swagger.annotations.ApiModelProperty;
  5 +import java.io.Serializable;
  6 +import javax.validation.constraints.NotBlank;
  7 +import lombok.Data;
  8 +
  9 +/**
  10 + * 资金台账平账Vo(仅清欠状态可平账,平账后是否清欠改为否)
  11 + */
  12 +@Data
  13 +@ApiModel("资金台账平账Vo")
  14 +public class BalanceFundLedgerVo implements Serializable {
  15 +
  16 + private static final long serialVersionUID = 1L;
  17 +
  18 + @NotBlank(message = "ID不能为空!")
  19 + @ApiModelProperty("ID")
  20 + private String id;
  21 +
  22 + @ApiModelProperty("平账说明(多行文本)")
  23 + private String balanceRemark;
  24 +
  25 + @ApiModelProperty("平账附件文件ID集合(多文件,逗号分隔)")
  26 + private String balanceFileIds;
  27 +
  28 + @ApiModelProperty("平账附件文件名称集合(多文件,逗号分隔)")
  29 + private String balanceFileNames;
  30 +}
... ...
  1 +package com.lframework.xingyun.sc.procurement.vo.fundledger;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonFormat;
  4 +import com.lframework.starter.common.constants.StringPool;
  5 +import com.lframework.starter.web.core.components.validation.TypeMismatch;
  6 +import com.lframework.starter.web.core.vo.SortPageVo;
  7 +import io.swagger.annotations.ApiModel;
  8 +import io.swagger.annotations.ApiModelProperty;
  9 +import java.io.Serializable;
  10 +import java.time.LocalDate;
  11 +import lombok.Data;
  12 +
  13 +/**
  14 + * 查询资金台账Vo(列表分月展示)
  15 + */
  16 +@Data
  17 +@ApiModel("查询资金台账Vo")
  18 +public class QueryFundLedgerVo extends SortPageVo implements Serializable {
  19 +
  20 + private static final long serialVersionUID = 1L;
  21 +
  22 + @ApiModelProperty("年份(与月份同时传时按该年月筛选申报日期)")
  23 + private Integer year;
  24 +
  25 + @ApiModelProperty("月份 1-12(与年份同时传时按该年月筛选申报日期)")
  26 + private Integer month;
  27 +
  28 + @ApiModelProperty("申报日期-开始")
  29 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  30 + @TypeMismatch(message = "申报日期开始格式有误!")
  31 + private LocalDate applyDateStart;
  32 +
  33 + @ApiModelProperty("申报日期-结束")
  34 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  35 + @TypeMismatch(message = "申报日期结束格式有误!")
  36 + private LocalDate applyDateEnd;
  37 +
  38 + @ApiModelProperty("计划单编号(模糊匹配)")
  39 + private String planCode;
  40 +
  41 + @ApiModelProperty("供料单位名称(模糊匹配)")
  42 + private String supplierName;
  43 +
  44 + @ApiModelProperty("采购处ID(精确匹配)")
  45 + private String purchaseDepartment;
  46 +
  47 + @ApiModelProperty("采购处名称(模糊匹配)")
  48 + private String purchaseDepartmentName;
  49 +
  50 + @ApiModelProperty("区域ID(精确匹配)")
  51 + private String region;
  52 +
  53 + @ApiModelProperty("区域名称(模糊匹配)")
  54 + private String regionName;
  55 +
  56 + @ApiModelProperty("是否清欠 true-是 false-否")
  57 + private Boolean clearDebt;
  58 +}
... ...
  1 +package com.lframework.xingyun.sc.procurement.vo.fundledger;
  2 +
  3 +import io.swagger.annotations.ApiModel;
  4 +import io.swagger.annotations.ApiModelProperty;
  5 +import java.io.Serializable;
  6 +import java.math.BigDecimal;
  7 +import javax.validation.constraints.NotBlank;
  8 +import javax.validation.constraints.NotNull;
  9 +import lombok.Data;
  10 +
  11 +/**
  12 + * 资金台账冲红Vo
  13 + */
  14 +@Data
  15 +@ApiModel("资金台账冲红Vo")
  16 +public class RedFundLedgerVo implements Serializable {
  17 +
  18 + private static final long serialVersionUID = 1L;
  19 +
  20 + @NotBlank(message = "ID不能为空!")
  21 + @ApiModelProperty("ID")
  22 + private String id;
  23 +
  24 + @NotNull(message = "冲红金额不能为空!")
  25 + @ApiModelProperty("冲红金额(保留两位小数)")
  26 + private BigDecimal redAmount;
  27 +
  28 + @ApiModelProperty("冲红说明(多行文本)")
  29 + private String redRemark;
  30 +
  31 + @ApiModelProperty("冲红附件文件ID集合(多文件,逗号分隔)")
  32 + private String redFileIds;
  33 +
  34 + @ApiModelProperty("冲红附件文件名称集合(多文件,逗号分隔)")
  35 + private String redFileNames;
  36 +}
... ...
  1 +package com.lframework.xingyun.sc.procurement.vo.fundledger;
  2 +
  3 +import com.fasterxml.jackson.annotation.JsonFormat;
  4 +import com.lframework.starter.common.constants.StringPool;
  5 +import com.lframework.starter.web.core.components.validation.TypeMismatch;
  6 +import io.swagger.annotations.ApiModel;
  7 +import io.swagger.annotations.ApiModelProperty;
  8 +import java.io.Serializable;
  9 +import java.math.BigDecimal;
  10 +import java.time.LocalDate;
  11 +import javax.validation.constraints.NotBlank;
  12 +import lombok.Data;
  13 +
  14 +/**
  15 + * 修改资金台账Vo(仅来票信息、出库单数量、备注可改,其余为来源单据快照)
  16 + */
  17 +@Data
  18 +@ApiModel("修改资金台账Vo")
  19 +public class UpdateFundLedgerVo implements Serializable {
  20 +
  21 + private static final long serialVersionUID = 1L;
  22 +
  23 + @NotBlank(message = "ID不能为空!")
  24 + @ApiModelProperty("ID")
  25 + private String id;
  26 +
  27 + @ApiModelProperty("来票时间")
  28 + @JsonFormat(pattern = StringPool.DATE_PATTERN)
  29 + @TypeMismatch(message = "来票时间格式有误!")
  30 + private LocalDate invoiceDate;
  31 +
  32 + @ApiModelProperty("来票数量(保留两位小数)")
  33 + private BigDecimal invoiceQuantity;
  34 +
  35 + @ApiModelProperty("来票金额(保留两位小数)")
  36 + private BigDecimal invoiceAmount;
  37 +
  38 + @ApiModelProperty("出库单数量(保留两位小数)")
  39 + private BigDecimal outstockQuantity;
  40 +
  41 + @ApiModelProperty("备注")
  42 + private String remark;
  43 +}
... ...
... ... @@ -18,6 +18,9 @@ public class CreateFundPaymentRequestVo implements Serializable {
18 18 @ApiModelProperty("生成来源 PLAN-采购计划 TICKET-过磅码单 RECEIVE-仓库收料单")
19 19 private String source;
20 20
  21 + @ApiModelProperty("请款单类型 NORMAL-正常 SUPPLEMENT-补充请款单(选择补充请款单时必须上传补充附件)")
  22 + private String requestKind;
  23 +
21 24 @NotBlank(message = "来源单ID不能为空!")
22 25 @ApiModelProperty("来源单ID(计划ID/码单ID/收料单ID)")
23 26 private String sourceId;
... ...
  1 +package com.lframework.xingyun.sc.procurement.vo.fundpayment;
  2 +
  3 +import io.swagger.annotations.ApiModelProperty;
  4 +import lombok.Data;
  5 +
  6 +import javax.validation.constraints.NotBlank;
  7 +import java.io.Serializable;
  8 +
  9 +/**
  10 + * 按来源单生成草稿请款单
  11 + */
  12 +@Data
  13 +public class GenerateFundPaymentRequestVo implements Serializable {
  14 +
  15 + private static final long serialVersionUID = 1L;
  16 +
  17 + @NotBlank(message = "生成来源不能为空!")
  18 + @ApiModelProperty("生成来源 PLAN-采购计划 TICKET-过磅码单 RECEIVE-仓库收料单")
  19 + private String source;
  20 +
  21 + @NotBlank(message = "来源单ID不能为空!")
  22 + @ApiModelProperty("来源单ID(计划ID/码单ID/收料单ID)")
  23 + private String sourceId;
  24 +
  25 + @ApiModelProperty("请款单类型 NORMAL-正常 SUPPLEMENT-补充请款单(为空默认正常,补充请款单仅过磅码单来源可用)")
  26 + private String requestKind;
  27 +
  28 + @ApiModelProperty("补充说明附件文件ID集合(补充请款单填写)")
  29 + private String supplementFileIds;
  30 +
  31 + @ApiModelProperty("补充说明附件文件名称集合")
  32 + private String supplementFileNames;
  33 +}
... ...
... ... @@ -21,6 +21,9 @@ public class UpdateFundPaymentRequestVo implements Serializable {
21 21 @ApiModelProperty("ID")
22 22 private String id;
23 23
  24 + @ApiModelProperty("请款单类型 NORMAL-正常 SUPPLEMENT-补充请款单(选择补充请款单时必须上传补充附件)")
  25 + private String requestKind;
  26 +
24 27 @ApiModelProperty("资金支付供应商信息ID(对方户名/开户银行/账号来源)")
25 28 private String supplierId;
26 29
... ...
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<!DOCTYPE mapper
  3 + PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4 + "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5 +<mapper namespace="com.lframework.xingyun.sc.procurement.mappers.fundledger.FundLedgerMapper">
  6 +
  7 + <resultMap id="FundLedgerResult"
  8 + type="com.lframework.xingyun.sc.procurement.entity.fundledger.FundLedger">
  9 + <id column="id" property="id"/>
  10 + <result column="plan_id" property="planId"/>
  11 + <result column="apply_date" property="applyDate"/>
  12 + <result column="plan_code" property="planCode"/>
  13 + <result column="supplier_name" property="supplierName"/>
  14 + <result column="purchase_department" property="purchaseDepartment"/>
  15 + <result column="purchase_department_name" property="purchaseDepartmentName"/>
  16 + <result column="region" property="region"/>
  17 + <result column="region_name" property="regionName"/>
  18 + <result column="delivery_date" property="deliveryDate"/>
  19 + <result column="plan_quantity" property="planQuantity"/>
  20 + <result column="product_names" property="productNames"/>
  21 + <result column="plan_remark" property="planRemark"/>
  22 + <result column="first_arrival_date" property="firstArrivalDate"/>
  23 + <result column="first_arrival_quantity" property="firstArrivalQuantity"/>
  24 + <result column="second_arrival_date" property="secondArrivalDate"/>
  25 + <result column="second_arrival_quantity" property="secondArrivalQuantity"/>
  26 + <result column="third_arrival_date" property="thirdArrivalDate"/>
  27 + <result column="third_arrival_quantity" property="thirdArrivalQuantity"/>
  28 + <result column="total_arrival_quantity" property="totalArrivalQuantity"/>
  29 + <result column="min_invoice_price" property="minInvoicePrice"/>
  30 + <result column="first_invoice_prepay_amount" property="firstInvoicePrepayAmount"/>
  31 + <result column="first_prepay_limit" property="firstPrepayLimit"/>
  32 + <result column="second_invoice_prepay_amount" property="secondInvoicePrepayAmount"/>
  33 + <result column="second_prepay_limit" property="secondPrepayLimit"/>
  34 + <result column="third_invoice_prepay_amount" property="thirdInvoicePrepayAmount"/>
  35 + <result column="third_prepay_limit" property="thirdPrepayLimit"/>
  36 + <result column="total_prepay_limit" property="totalPrepayLimit"/>
  37 + <result column="first_prepay_date" property="firstPrepayDate"/>
  38 + <result column="first_prepay_paid" property="firstPrepayPaid"/>
  39 + <result column="second_prepay_date" property="secondPrepayDate"/>
  40 + <result column="second_prepay_paid" property="secondPrepayPaid"/>
  41 + <result column="third_prepay_date" property="thirdPrepayDate"/>
  42 + <result column="third_prepay_paid" property="thirdPrepayPaid"/>
  43 + <result column="total_prepay_paid" property="totalPrepayPaid"/>
  44 + <result column="available_prepay_amount" property="availablePrepayAmount"/>
  45 + <result column="red_amount" property="redAmount"/>
  46 + <result column="first_receive_date" property="firstReceiveDate"/>
  47 + <result column="first_receive_quantity" property="firstReceiveQuantity"/>
  48 + <result column="first_receive_amount" property="firstReceiveAmount"/>
  49 + <result column="second_receive_date" property="secondReceiveDate"/>
  50 + <result column="second_receive_quantity" property="secondReceiveQuantity"/>
  51 + <result column="second_receive_amount" property="secondReceiveAmount"/>
  52 + <result column="third_receive_date" property="thirdReceiveDate"/>
  53 + <result column="third_receive_quantity" property="thirdReceiveQuantity"/>
  54 + <result column="third_receive_amount" property="thirdReceiveAmount"/>
  55 + <result column="total_receive_quantity" property="totalReceiveQuantity"/>
  56 + <result column="total_receive_amount" property="totalReceiveAmount"/>
  57 + <result column="invoice_date" property="invoiceDate"/>
  58 + <result column="invoice_quantity" property="invoiceQuantity"/>
  59 + <result column="invoice_amount" property="invoiceAmount"/>
  60 + <result column="owed_invoice_amount" property="owedInvoiceAmount"/>
  61 + <result column="outstock_quantity" property="outstockQuantity"/>
  62 + <result column="owed_order_amount" property="owedOrderAmount"/>
  63 + <result column="invoice_balance_amount" property="invoiceBalanceAmount"/>
  64 + <result column="stock_complete_diff" property="stockCompleteDiff"/>
  65 + <result column="final_payment_date" property="finalPaymentDate"/>
  66 + <result column="final_payment_amount" property="finalPaymentAmount"/>
  67 + <result column="compare_amount" property="compareAmount"/>
  68 + <result column="clear_debt" property="clearDebt"/>
  69 + <result column="remark" property="remark"/>
  70 + <result column="red_remark" property="redRemark"/>
  71 + <result column="red_file_ids" property="redFileIds"/>
  72 + <result column="red_file_names" property="redFileNames"/>
  73 + <result column="balance_remark" property="balanceRemark"/>
  74 + <result column="balance_file_ids" property="balanceFileIds"/>
  75 + <result column="balance_file_names" property="balanceFileNames"/>
  76 + <result column="create_by_id" property="createById"/>
  77 + <result column="create_by" property="createBy"/>
  78 + <result column="update_by_id" property="updateById"/>
  79 + <result column="update_by" property="updateBy"/>
  80 + <result column="create_time" property="createTime"/>
  81 + <result column="update_time" property="updateTime"/>
  82 + </resultMap>
  83 +
  84 + <sql id="FL_sql">
  85 + SELECT
  86 + tb.id,
  87 + tb.plan_id,
  88 + tb.apply_date,
  89 + tb.plan_code,
  90 + tb.supplier_name,
  91 + tb.purchase_department,
  92 + tb.purchase_department_name,
  93 + tb.region,
  94 + tb.region_name,
  95 + tb.delivery_date,
  96 + tb.plan_quantity,
  97 + tb.product_names,
  98 + tb.plan_remark,
  99 + tb.first_arrival_date,
  100 + tb.first_arrival_quantity,
  101 + tb.second_arrival_date,
  102 + tb.second_arrival_quantity,
  103 + tb.third_arrival_date,
  104 + tb.third_arrival_quantity,
  105 + tb.total_arrival_quantity,
  106 + tb.min_invoice_price,
  107 + tb.first_invoice_prepay_amount,
  108 + tb.first_prepay_limit,
  109 + tb.second_invoice_prepay_amount,
  110 + tb.second_prepay_limit,
  111 + tb.third_invoice_prepay_amount,
  112 + tb.third_prepay_limit,
  113 + tb.total_prepay_limit,
  114 + tb.first_prepay_date,
  115 + tb.first_prepay_paid,
  116 + tb.second_prepay_date,
  117 + tb.second_prepay_paid,
  118 + tb.third_prepay_date,
  119 + tb.third_prepay_paid,
  120 + tb.total_prepay_paid,
  121 + tb.available_prepay_amount,
  122 + tb.red_amount,
  123 + tb.first_receive_date,
  124 + tb.first_receive_quantity,
  125 + tb.first_receive_amount,
  126 + tb.second_receive_date,
  127 + tb.second_receive_quantity,
  128 + tb.second_receive_amount,
  129 + tb.third_receive_date,
  130 + tb.third_receive_quantity,
  131 + tb.third_receive_amount,
  132 + tb.total_receive_quantity,
  133 + tb.total_receive_amount,
  134 + tb.invoice_date,
  135 + tb.invoice_quantity,
  136 + tb.invoice_amount,
  137 + tb.owed_invoice_amount,
  138 + tb.outstock_quantity,
  139 + tb.owed_order_amount,
  140 + tb.invoice_balance_amount,
  141 + tb.stock_complete_diff,
  142 + tb.final_payment_date,
  143 + tb.final_payment_amount,
  144 + tb.compare_amount,
  145 + tb.clear_debt,
  146 + tb.remark,
  147 + tb.red_remark,
  148 + tb.red_file_ids,
  149 + tb.red_file_names,
  150 + tb.balance_remark,
  151 + tb.balance_file_ids,
  152 + tb.balance_file_names,
  153 + tb.create_by_id,
  154 + tb.create_by,
  155 + tb.update_by_id,
  156 + tb.update_by,
  157 + tb.create_time,
  158 + tb.update_time
  159 + FROM fund_ledger AS tb
  160 + </sql>
  161 +
  162 + <select id="query" resultMap="FundLedgerResult">
  163 + <include refid="FL_sql"/>
  164 + <where>
  165 + <if test="vo.applyDateStart != null">
  166 + AND tb.apply_date &gt;= #{vo.applyDateStart}
  167 + </if>
  168 + <if test="vo.applyDateEnd != null">
  169 + AND tb.apply_date &lt;= #{vo.applyDateEnd}
  170 + </if>
  171 + <if test="vo.planCode != null and vo.planCode != ''">
  172 + AND tb.plan_code LIKE CONCAT('%', #{vo.planCode}, '%')
  173 + </if>
  174 + <if test="vo.supplierName != null and vo.supplierName != ''">
  175 + AND tb.supplier_name LIKE CONCAT('%', #{vo.supplierName}, '%')
  176 + </if>
  177 + <if test="vo.purchaseDepartment != null and vo.purchaseDepartment != ''">
  178 + AND tb.purchase_department = #{vo.purchaseDepartment}
  179 + </if>
  180 + <if test="vo.purchaseDepartmentName != null and vo.purchaseDepartmentName != ''">
  181 + AND tb.purchase_department_name LIKE CONCAT('%', #{vo.purchaseDepartmentName}, '%')
  182 + </if>
  183 + <if test="vo.region != null and vo.region != ''">
  184 + AND tb.region = #{vo.region}
  185 + </if>
  186 + <if test="vo.regionName != null and vo.regionName != ''">
  187 + AND tb.region_name LIKE CONCAT('%', #{vo.regionName}, '%')
  188 + </if>
  189 + <if test="vo.clearDebt != null">
  190 + AND tb.clear_debt = #{vo.clearDebt}
  191 + </if>
  192 + </where>
  193 + ORDER BY tb.apply_date DESC, tb.create_time DESC
  194 + </select>
  195 +
  196 + <select id="findById" resultMap="FundLedgerResult">
  197 + <include refid="FL_sql"/>
  198 + <where>
  199 + AND tb.id = #{id}
  200 + </where>
  201 + </select>
  202 +</mapper>
... ...
... ... @@ -38,6 +38,7 @@
38 38 <result column="total_apply_amount" property="totalApplyAmount"/>
39 39 <result column="flow_node" property="flowNode"/>
40 40 <result column="approval_status" property="approvalStatus"/>
  41 + <result column="approval_pass_time" property="approvalPassTime"/>
41 42 <result column="deleted" property="deleted"/>
42 43 <result column="create_by_id" property="createById"/>
43 44 <result column="create_by" property="createBy"/>
... ... @@ -81,6 +82,7 @@
81 82 tb.total_apply_amount,
82 83 tb.flow_node,
83 84 tb.approval_status,
  85 + tb.approval_pass_time,
84 86 tb.deleted,
85 87 tb.create_by_id,
86 88 tb.create_by,
... ...