diff --git a/src/main/java/com/budwk/app/zhgh/activity/declarereimbursement/reimbursement/service/impl/ActivityReimbursementSchoolUnionServiceImpl.java b/src/main/java/com/budwk/app/zhgh/activity/declarereimbursement/reimbursement/service/impl/ActivityReimbursementSchoolUnionServiceImpl.java index 9be6ef5..00fee45 100644 --- a/src/main/java/com/budwk/app/zhgh/activity/declarereimbursement/reimbursement/service/impl/ActivityReimbursementSchoolUnionServiceImpl.java +++ b/src/main/java/com/budwk/app/zhgh/activity/declarereimbursement/reimbursement/service/impl/ActivityReimbursementSchoolUnionServiceImpl.java @@ -90,7 +90,7 @@ public class ActivityReimbursementSchoolUnionServiceImpl extends BaseServiceImpl if (Objects.equals(info.getActivityReimbursementMode(),"daily")){ detail.setActivityTime(String.valueOf(info.getApplyTime())); } - OutlayManageSchool school = dao().fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool school = OutlayManageSchool.lockActive(dao(), Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isEmpty(school)) { throw new BaseException("该年份没有设置金额!"); } @@ -111,7 +111,7 @@ public class ActivityReimbursementSchoolUnionServiceImpl extends BaseServiceImpl ActivityBudget budget = dao().fetch(ActivityBudget.class, Cnd.where("id", "=", info.getDeductionBudgetId())); if (ObjectUtil.isNotEmpty(budget)&&budget.getIsSchoolBudget()){ //如果分工会报销了校工会的余额 - OutlayManageSchool school = dao().fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool school = OutlayManageSchool.lockActive(dao(), Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isEmpty(school)) { throw new BaseException("该年份没有设置金额!"); } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetApplyStatisticsServiceImpl.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetApplyStatisticsServiceImpl.java index 23ecf1f..b97bea8 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetApplyStatisticsServiceImpl.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetApplyStatisticsServiceImpl.java @@ -71,7 +71,7 @@ public class ActivityBudgetApplyStatisticsServiceImpl extends BaseServiceImpl im public void doDelete(String id) { ActivityBudget budget = dao().fetch(ActivityBudget.class, id); if (budget.getOutlayManageSource().equals("ACTIVITY_BUDGET_TYPE_ONE")) { - OutlayManageSchool school = dao().fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool school = OutlayManageSchool.lockActive(dao(), Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isNotEmpty(school)) { school.setTotalQuota(school.getTotalQuota().subtract(budget.getTotalBudgetMoney())); updateIgnoreNull(school); diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetServiceImpl.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetServiceImpl.java index 58dd380..27309d5 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetServiceImpl.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/activityBudget/service/impl/ActivityBudgetServiceImpl.java @@ -156,7 +156,7 @@ public class ActivityBudgetServiceImpl extends BaseServiceImpl i } //如果申报的是校工会预算 if (activityBudget.getOutlayManageSource().equals("ACTIVITY_BUDGET_TYPE_ONE")) { - OutlayManageSchool outlayManageSchool = dao().fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool outlayManageSchool = OutlayManageSchool.lockActive(dao(), Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isNotEmpty(outlayManageSchool)) { if (StrUtil.isNotBlank(activityBudget.getId())) { //如果传过来有预算Id,代表是修改的,那么就减去原来的金额 diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolController.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolController.java index ce89d75..c6f7e5c 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolController.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolController.java @@ -8,19 +8,26 @@ import com.budwk.app.base.param.PageForm; import com.budwk.app.base.result.Result; import com.budwk.app.base.service.BaseService; import com.budwk.app.zhgh.dayofficework.outlay.outlayManage.school.model.OutlayManageSchool; +import com.budwk.app.zhgh.dayofficework.outlay.outlayManage.service.impl.OutlayAnnualAllocateService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; +import org.nutz.aop.interceptor.ioc.TransAop; +import org.nutz.dao.Chain; import org.nutz.dao.Cnd; import org.nutz.dao.Sqls; import org.nutz.dao.sql.Sql; +import org.nutz.ioc.aop.Aop; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.lang.util.NutMap; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Ok; +import org.nutz.trans.Atom; +import org.nutz.trans.Trans; import java.math.BigDecimal; +import java.sql.Connection; import java.util.List; /** @@ -38,6 +45,8 @@ public class OutlayManageSchoolController { @Inject private BaseService baseService; + @Inject + private OutlayAnnualAllocateService outlayAnnualAllocateService; @At("") @Ok("beetl:/platform/zhgh/dayofficework/outlay/outlayManage/school/manage/index.html") @@ -50,7 +59,7 @@ public class OutlayManageSchoolController { @ApiOperation("分页查询") @SaCheckPermission("outlay.outlayManage.school.manage") public Result pageData(PageForm pageForm, Integer year) { - Cnd cnd = Cnd.NEW(); + Cnd cnd = OutlayManageSchool.activeBudgets(); Sql sql = Sqls.create(""" SELECT * FROM `outlay_manage_school` $condition """); @@ -61,14 +70,31 @@ public class OutlayManageSchoolController { } + @At + @ApiOperation("查看校工会预算操作记录") + @SaCheckPermission("outlay.outlayManage.school.manage") + public Result logs(PageForm pageForm, Integer year) { + return Result.success(outlayAnnualAllocateService.allocationLogs( + pageForm.getPageNumber(), pageForm.getPageSize(), "school", year == null ? null : year.toString())); + } + @At @ApiOperation("修改预算") @SaCheckPermission("outlay.outlayManage.school.manage") @SLog(tag = "校工会预算分配", msg = "修改了预算分配的金额:${args[0]},id:${args[1]}") + @Aop(TransAop.READ_COMMITTED) public Result doSubmit(String totalQuota, String id) { - OutlayManageSchool outlayManageSchool = baseService.dao().fetch(OutlayManageSchool.class, id); - outlayManageSchool.setTotalQuota(new BigDecimal(totalQuota)); - baseService.updateIgnoreNull(outlayManageSchool); + BigDecimal total = new BigDecimal(totalQuota); + List budgets = baseService.listMap(Sqls.create( + "SELECT id,year,totalQuota,usedQuota,delFlag FROM outlay_manage_school WHERE id=@id AND COALESCE(delFlag,0)=0 FOR UPDATE").setParam("id", id)); + if (budgets.isEmpty()) return Result.error("校工会预算不存在"); + NutMap before = budgets.get(0); + BigDecimal used = before.get("usedQuota") == null ? BigDecimal.ZERO : new BigDecimal(before.getString("usedQuota")); + if (total.compareTo(used) < 0) + return Result.error("校工会预算总额度不能低于已使用额度"); + baseService.dao().update(OutlayManageSchool.class, Chain.make("totalQuota", total), Cnd.where("id", "=", id)); + outlayAnnualAllocateService.auditSchoolBudget(before.getInt("year"), "修改预算", before, + outlayAnnualAllocateService.schoolBudgetSnapshot(id), null); return Result.success(); } @@ -77,7 +103,7 @@ public class OutlayManageSchoolController { @ApiOperation("查看是否分配") @SaCheckPermission("outlay.outlayManage.school.manage") public Result getIsAllocationOutlay(Integer year) { - int count = baseService.dao().count(OutlayManageSchool.class, Cnd.where("year", "=", year)); + int count = baseService.dao().count(OutlayManageSchool.class, OutlayManageSchool.activeBudgets().and("year", "=", year)); return Result.success(count); } @@ -85,8 +111,32 @@ public class OutlayManageSchoolController { @ApiOperation("重置预算") @SaCheckPermission("outlay.outlayManage.school.manage") @SLog(tag = "校工会预算分配", msg = "重置了预算分配的金额:${args[0]}") + @Aop(TransAop.READ_COMMITTED) public Result resetOutlay(Integer year) { - int count = baseService.dao().clear(OutlayManageSchool.class, Cnd.where("year", "=", year)); + List budgets = baseService.listMap(Sqls.create( + """ + SELECT id,year,totalQuota,usedQuota,delFlag FROM outlay_manage_school + WHERE year=@year AND COALESCE(delFlag,0)=0 ORDER BY id FOR UPDATE + """).setParam("year", year)); + if (budgets.isEmpty()) return Result.success(0); + List budgetIds = budgets.stream().map(row -> row.getString("id")).toList(); + List activeAllocations = baseService.listMap(Sqls.create(""" + SELECT l.id FROM outlay_annual_allocate_log l + WHERE JSON_UNQUOTE(JSON_EXTRACT(l.afterData,'$.schoolBudgetId')) IN (@budgetIds) + AND ((l.allocateType='base' AND EXISTS ( + SELECT 1 FROM outlay_annual_base a WHERE a.id=l.allocateId AND a.year=@year AND a.status=1 + )) OR (l.allocateType='special' AND EXISTS ( + SELECT 1 FROM outlay_annual_special a WHERE a.id=l.allocateId AND a.year=@year AND a.status=1 + ))) + LIMIT 1 + """).setParam("budgetIds", budgetIds).setParam("year", year)); + if (!activeAllocations.isEmpty()) return Result.error("该年度校工会预算已用于分工会下拨,无法重置"); + int count = baseService.dao().update(OutlayManageSchool.class, + Chain.make("delFlag", true).add("updatedAt", System.currentTimeMillis()), Cnd.where("id", "in", budgetIds)); + for (NutMap before : budgets) { + outlayAnnualAllocateService.auditSchoolBudget(year, "重置预算", before, + outlayAnnualAllocateService.schoolBudgetSnapshot(before.getString("id")), null); + } return Result.success(count); } @@ -94,7 +144,7 @@ public class OutlayManageSchoolController { @ApiOperation("下发预算") @SaCheckPermission("outlay.outlayManage.school.manage") @SLog(tag = "校工会预算分配", msg = "下发预算的金额:${args[0]}") - public Result issuedOutlay() { + public Result issuedOutlay(Integer year) { /* Sql sql = Sqls.create(""" SELECT totalBudgetMoney @@ -110,10 +160,40 @@ public class OutlayManageSchoolController { BigDecimal totalBudgetMoney = budgetList.stream() .map(v->new BigDecimal(v.getString("totalBudgetMoney"))) // 提取 money 属性 .reduce(BigDecimal.ZERO, BigDecimal::add);*/ + int budgetYear = year == null ? DateUtil.thisYear() : year; + Result[] result = new Result[1]; + Trans.exec(Connection.TRANSACTION_REPEATABLE_READ, (Atom) () -> result[0] = issueAnnualBudget(budgetYear)); + return result[0]; + } + + private Result issueAnnualBudget(int budgetYear) { + List budgets = baseService.listMap(Sqls.create(""" + SELECT id,year,totalQuota,usedQuota,COALESCE(delFlag,0) delFlag FROM outlay_manage_school + WHERE year=@year ORDER BY updatedAt DESC,createdAt DESC,id FOR UPDATE + """).setParam("year", budgetYear)); + if (budgets.stream().anyMatch(budget -> budget.getInt("delFlag") == 0)) + return Result.error("该年度校工会预算已分配"); + NutMap before = budgets.isEmpty() ? null : budgets.get(0); OutlayManageSchool outlayManageSchool = new OutlayManageSchool(); - outlayManageSchool.setYear(DateUtil.thisYear()); + outlayManageSchool.setYear(budgetYear); // outlayManageSchool.setTotalQuota(totalBudgetMoney); + if (before != null) { + BigDecimal used = before.get("usedQuota") == null ? BigDecimal.ZERO : new BigDecimal(before.getString("usedQuota")); + outlayManageSchool.setUsedQuota(used); + outlayManageSchool.setTotalQuota(used.max(BigDecimal.ZERO)); + } baseService.insert(outlayManageSchool); + String id = outlayManageSchool.getId(); + String remark = null; + if (before != null) { + String previousId = before.getString("id"); + Sql moveDetails = baseService.execute(Sqls.create(""" + UPDATE outlay_use_detail SET outlayManageId=@id WHERE outlayManageId=@previousId + """).setParam("id", id).setParam("previousId", previousId)); + remark = "原预算 ID " + previousId + ",承接 " + moveDetails.getUpdateCount() + " 条使用明细"; + } + outlayAnnualAllocateService.auditSchoolBudget(budgetYear, before == null ? "年度分配" : "重新分配预算", + before, outlayAnnualAllocateService.schoolBudgetSnapshot(id), remark); return Result.success(); } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolUseDetailController.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolUseDetailController.java index 03d9ab5..7fd163e 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolUseDetailController.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/controller/OutlayManageSchoolUseDetailController.java @@ -74,7 +74,7 @@ public class OutlayManageSchoolUseDetailController { @ApiOperation("查询校工会所有的预算") @SaCheckPermission("outlay.outlayManage.school.useDetail") public Result getOutlayManageList() { - List schoolList = baseService.dao().query(OutlayManageSchool.class, Cnd.NEW().desc("year")); + List schoolList = baseService.dao().query(OutlayManageSchool.class, OutlayManageSchool.activeBudgets().desc("year")); return Result.success(schoolList); } @@ -82,7 +82,8 @@ public class OutlayManageSchoolUseDetailController { @ApiOperation("查询报销了有多少钱") @SaCheckPermission("outlay.outlayManage.school.useDetail") public Result getApplyMoney(String outlayManageId,String projectName) { - OutlayManageSchool school = baseService.dao().fetch(OutlayManageSchool.class, Cnd.where("id", "=", outlayManageId)); + OutlayManageSchool school = baseService.dao().fetch(OutlayManageSchool.class, OutlayManageSchool.activeBudgets().and("id", "=", outlayManageId)); + if (school == null) return Result.error("校工会预算未分配或已重置"); if (StrUtil.isEmpty(outlayManageId)){ return Result.success(Map.of("totalMoney", 0, "totalQuota", school.getTotalQuota(), "usedQuota", school.getUsedQuota())); } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/model/OutlayManageSchool.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/model/OutlayManageSchool.java index dcfc41f..0cab89c 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/model/OutlayManageSchool.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/school/model/OutlayManageSchool.java @@ -3,7 +3,11 @@ package com.budwk.app.zhgh.dayofficework.outlay.outlayManage.school.model; import com.budwk.app.base.model.BaseModel; import lombok.Data; import lombok.EqualsAndHashCode; +import org.nutz.dao.Cnd; +import org.nutz.dao.Dao; +import org.nutz.dao.Sqls; import org.nutz.dao.entity.annotation.*; +import org.nutz.dao.sql.Sql; import java.io.Serializable; import java.math.BigDecimal; @@ -43,4 +47,17 @@ public class OutlayManageSchool extends BaseModel implements Serializable { @Default("0") @ColDefine(customType = "decimal(10,2)") private BigDecimal usedQuota; + + public static Cnd activeBudgets() { + return Cnd.NEW().and(Cnd.exps("delFlag", "=", false).or("delFlag", "is", null)); + } + + public static OutlayManageSchool lockActive(Dao dao, Cnd condition) { + Sql sql = Sqls.create("SELECT * FROM outlay_manage_school $condition FOR UPDATE"); + sql.setCondition(condition.and(Cnd.exps("delFlag", "=", false).or("delFlag", "is", null))); + sql.setEntity(dao.getEntity(OutlayManageSchool.class)); + sql.setCallback(Sqls.callback.entity()); + dao.execute(sql); + return sql.getObject(OutlayManageSchool.class); + } } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/service/impl/OutlayAnnualAllocateService.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/service/impl/OutlayAnnualAllocateService.java index 133abad..cd6bb6b 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/service/impl/OutlayAnnualAllocateService.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/service/impl/OutlayAnnualAllocateService.java @@ -2,6 +2,8 @@ package com.budwk.app.zhgh.dayofficework.outlay.outlayManage.service.impl; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.util.StrUtil; +import com.budwk.app.base.exception.BaseException; +import com.budwk.app.base.page.Pagination; import com.budwk.app.base.result.Result; import com.budwk.app.base.service.impl.BaseServiceImpl; import com.budwk.app.zhgh.dayofficework.outlay.outlayManage.union.model.OutlayManageUnion; @@ -13,7 +15,11 @@ import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.util.NutMap; import java.math.BigDecimal; +import java.sql.PreparedStatement; import java.time.Year; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -21,6 +27,8 @@ import java.util.UUID; @IocBean(args = {"refer:dao"}) public class OutlayAnnualAllocateService extends BaseServiceImpl { + private static final int GENERATE_BATCH_SIZE = 100; + public OutlayAnnualAllocateService(Dao dao) { super(dao); } public Sql sql(String text, Object... args) { @@ -45,7 +53,7 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl0)" : " AND a.status<>2" + amountMatchCondition(amountMatch)) + + ("special".equals(type) ? " AND a.status<>2 AND (@projectName='' OR LOCATE(@projectName,a.projectName)>0)" : " AND a.status<>2" + amountMatchCondition(amountMatch)) + " ORDER BY un.unionCode,a.createdAt DESC", "year", year, "unionId", StrUtil.blankToDefault(unionId, ""), "projectName", StrUtil.blankToDefault(StrUtil.trim(projectName), "")); @@ -127,42 +135,142 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl unions = listMap(sql("SELECT id FROM sys_union WHERE (@unionId='' OR id=@unionId) ORDER BY id", - "unionId", StrUtil.blankToDefault(unionId, ""))); - int added = 0; + // 年度下拨、调整和重置均先锁校工会预算,再按分工会 ID 顺序加锁。 + List schoolBudgets = lockSchoolBudgets(year); + List unions = listMap(sql("SELECT id,name,unionCode FROM sys_union" + + (StrUtil.isBlank(unionId) ? "" : " WHERE id=@unionId") + " ORDER BY id FOR UPDATE", "unionId", unionId)); + if (unions.isEmpty()) return Result.success("已生成0条记录,已有记录保持不变"); + + List unionIds = unions.stream().map(row -> row.getString("id")).toList(); + Map oldRecords = new HashMap<>(); + for (NutMap row : listMap(sql(""" + SELECT ranked.* FROM ( + SELECT a.*,un.id matchedUnionId,ROW_NUMBER() OVER ( + PARTITION BY un.id ORDER BY (a.status=2),a.updatedAt DESC,a.createdAt DESC,a.id + ) recordPosition + FROM outlay_annual_base a JOIN sys_union un ON un.id=a.unionId + WHERE a.year=@year AND un.id IN (@unionIds) + ) ranked WHERE ranked.recordPosition=1 + """, "year", year, "unionIds", unionIds))) { + row.remove("recordPosition"); + oldRecords.put((String) row.remove("matchedUnionId"), row); + } + unions = unions.stream().filter(union -> { + NutMap old = oldRecords.get(union.getString("id")); + return old == null || old.getInt("status") == 2; + }).toList(); + if (unions.isEmpty()) return Result.success("已生成0条记录,已有记录保持不变"); + unionIds = unions.stream().map(row -> row.getString("id")).toList(); + + Map memberCounts = new HashMap<>(); + for (NutMap row : listMap(sql("SELECT un.id unionId,COUNT(DISTINCT m.id) memberCount FROM " + + (current ? "vw_user" : "member_history") + " m JOIN sys_union un ON un.id=m.unionId" + + " WHERE m.member=1 AND un.id IN (@unionIds)" + (current ? "" : " AND m.year=@year") + + " GROUP BY un.id", "year", year, "unionIds", unionIds))) { + memberCounts.put(row.getString("unionId"), row.getInt("memberCount")); + } + + Map budgets = new HashMap<>(); + for (NutMap row : listMap(sql(""" + SELECT b.id,b.totalQuota,b.usedQuota,un.id unionId FROM outlay_manage_union b + JOIN sys_union un ON un.id=b.unionId + WHERE b.year=@year AND un.id IN (@unionIds) FOR UPDATE + """, "year", year, "unionIds", unionIds))) { + if (budgets.putIfAbsent(row.getString("unionId"), row) != null) + throw new IllegalArgumentException("该分工会年度预算存在重复记录,不能下拨"); + } + List missingBudgetIds = unionIds.stream().filter(id -> !budgets.containsKey(id)).toList(); + Map previousSurpluses = new HashMap<>(); + if (!missingBudgetIds.isEmpty()) { + for (NutMap row : listMap(sql(""" + SELECT un.id unionId,COALESCE(b.totalQuota,0)-COALESCE(b.usedQuota,0) surplus + FROM outlay_manage_union b JOIN sys_union un ON un.id=b.unionId + WHERE b.year=@year AND un.id IN (@unionIds) + """, "year", year - 1, "unionIds", missingBudgetIds))) { + previousSurpluses.putIfAbsent(row.getString("unionId"), decimal(row.get("surplus"))); + } + } + + long now = System.currentTimeMillis(); + String actor = StpUtil.getLoginIdAsString(); + List newBudgets = new ArrayList<>(); + List budgetUpdates = new ArrayList<>(); + List newRecords = new ArrayList<>(); + Map beforeByRecordId = new HashMap<>(); + BigDecimal allocationTotal = BigDecimal.ZERO; for (NutMap union : unions) { String uid = union.getString("id"); - lockUnion(uid); - NutMap old = first(sql("SELECT * FROM outlay_annual_base WHERE year=@year AND unionId=@unionId", "year", year, "unionId", uid)); - if (old != null && old.getInt("status") != 2) continue; - NutMap count = first(sql("SELECT COUNT(DISTINCT id) memberCount FROM " + (current ? "vw_user" : "member_history") + - " WHERE member=1 AND unionId=@unionId" + (current ? "" : " AND year=@year"), "unionId", uid, "year", year)); - int members = count.getInt("memberCount"); + int members = memberCounts.getOrDefault(uid, 0); BigDecimal calculated = standard.multiply(BigDecimal.valueOf(members)); if (!moneyValid(calculated)) throw new IllegalArgumentException("计算金额超出允许范围"); - syncBudget(year, uid, calculated); - String id = old == null ? UUID.randomUUID().toString().replace("-", "") : old.getString("id"); - if (old == null) { - execute(sql(""" - INSERT INTO outlay_annual_base - (id,year,unionId,memberCount,standard,calculatedMoney,allocateMoney,remark,status,version,createdAt,createdBy,updatedAt,updatedBy) - VALUES (@id,@year,@unionId,@count,@standard,@money,@money,'',1,0,@now,@actor,@now,@actor) - """, "id", id, "year", year, "unionId", uid, "count", members, "standard", standard, - "money", calculated, "now", System.currentTimeMillis(), "actor", StpUtil.getLoginIdAsString())); + allocationTotal = allocationTotal.add(calculated); + NutMap budget = budgets.get(uid); + if (budget == null) { + BigDecimal total = previousSurpluses.getOrDefault(uid, BigDecimal.ZERO).add(calculated); + validateBudgetTotal(total); + newBudgets.add(new Object[]{UUID.randomUUID().toString().replace("-", ""), year, uid, + union.get("name"), union.get("unionCode"), total, now, now, actor, actor}); } else { - // 复用已重置记录,保留原操作日志及年度、分工会唯一约束。 - execute(sql(""" - UPDATE outlay_annual_base SET memberCount=@count,standard=@standard,calculatedMoney=@money, - allocateMoney=@money,remark='',status=1,version=version+1,updatedAt=@now,updatedBy=@actor - WHERE id=@id - """, "count", members, "standard", standard, "money", calculated, "id", id, - "now", System.currentTimeMillis(), "actor", StpUtil.getLoginIdAsString())); + validateBudgetUpdate(budget, calculated); + budgetUpdates.add(new Object[]{budget.getString("id"), calculated, now, actor}); } - audit("base", id, old == null ? "生成" : "重新生成", old, - first(sql("SELECT * FROM outlay_annual_base WHERE id=@id", "id", id)), "生成年度人数快照"); - added++; + String id = UUID.randomUUID().toString().replace("-", ""); + newRecords.add(new Object[]{id, year, uid, members, standard, calculated, calculated, now, actor, now, actor}); + beforeByRecordId.put(id, oldRecords.get(uid)); } - return Result.success("已生成" + added + "条记录,已有记录保持不变"); + + String schoolBudgetId = changeSchoolBudget(year, schoolBudgets, null, allocationTotal, + "下拨基础经费", "本次下拨 " + unions.size() + " 个分工会,共 " + allocationTotal.toPlainString() + " 元"); + writeGenerateRows(""" + INSERT INTO outlay_manage_union + (id,year,unionId,unionName,unionCode,totalQuota,usedQuota,delFlag,createdAt,updatedAt,createdBy,updatedBy) + VALUES + """, "(?,?,?,?,?,?,0,0,?,?,?,?)", ",", "", newBudgets); + writeGenerateRows("UPDATE outlay_manage_union b JOIN (", + "SELECT ? id,CAST(? AS DECIMAL(10,2)) delta,? updatedAt,? updatedBy", " UNION ALL ", """ + ) v ON v.id=b.id + SET b.totalQuota=COALESCE(b.totalQuota,0)+v.delta,b.updatedAt=v.updatedAt,b.updatedBy=v.updatedBy + """, budgetUpdates); + writeGenerateRows(""" + INSERT INTO outlay_annual_base + (id,year,unionId,memberCount,standard,calculatedMoney,allocateMoney,remark,status,version,createdAt,createdBy,updatedAt,updatedBy) + VALUES + """, "(?,?,?,?,?,?,?,'',1,0,?,?,?,?)", ",", "", newRecords); + List savedRecords = listMap(sql("SELECT * FROM outlay_annual_base WHERE id IN (@ids)", + "ids", new ArrayList<>(beforeByRecordId.keySet()))); + if (savedRecords.size() != beforeByRecordId.size()) throw new IllegalStateException("基础经费记录写入不完整"); + List logs = new ArrayList<>(); + for (NutMap after : savedRecords) { + String id = after.getString("id"); + NutMap before = beforeByRecordId.get(id); + after.put("schoolBudgetId", schoolBudgetId); + logs.add(new Object[]{UUID.randomUUID().toString().replace("-", ""), id, + before == null ? "生成" : "重新生成", before == null ? null : Json.toJson(before), + Json.toJson(after), before == null ? "生成年度人数快照" : "原记录 ID " + before.getString("id"), now, actor}); + } + writeGenerateRows(""" + INSERT INTO outlay_annual_allocate_log + (id,allocateType,allocateId,action,beforeData,afterData,remark,createdAt,createdBy) + VALUES + """, "(?,'base',?,?,?,?,?,?,?)", ",", "", logs); + return Result.success("已生成" + savedRecords.size() + "条记录,已有记录保持不变"); + } + + private void writeGenerateRows(String prefix, String rowSql, String separator, String suffix, List rows) { + if (rows.isEmpty()) return; + dao().run(connection -> { + for (int from = 0; from < rows.size(); from += GENERATE_BATCH_SIZE) { + int to = Math.min(from + GENERATE_BATCH_SIZE, rows.size()); + String text = prefix + String.join(separator, Collections.nCopies(to - from, rowSql)) + suffix; + try (PreparedStatement statement = connection.prepareStatement(text)) { + int parameter = 1; + for (Object[] values : rows.subList(from, to)) { + for (Object value : values) statement.setObject(parameter++, value); + } + statement.executeUpdate(); + } + } + }); } private void lockUnion(String unionId) { @@ -185,12 +293,15 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl 9999 || StrUtil.isBlank(unionId) || !moneyValid(allocateMoney) || remark != null && remark.length() > 1000) return Result.error("请填写有效年度、分工会和金额,说明最多1000字"); + List schoolBudgets = lockSchoolBudgets(year); lockUnion(unionId); NutMap old = first(sql("SELECT * FROM " + table + " WHERE id=@id FOR UPDATE", "id", id)); if (old != null && (old.getInt("year") != year || !unionId.equals(old.getString("unionId")))) return Result.error("已有记录不能变更年度和分工会"); if (old != null && (version == null || old.getInt("version") != version)) return Result.error("记录已更新,请刷新后重试"); + if ("special".equals(type) && old != null && old.getInt("status") == 2) + return Result.error("该专项经费已删除"); boolean confirmed = old != null && old.getInt("status") == 1; BigDecimal calculated = null; if ("base".equals(type)) { @@ -208,6 +319,13 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl schoolBudgets = lockSchoolBudgets(year); + lockUnion(unionId); + NutMap before = first(sql("SELECT * FROM outlay_annual_special WHERE id=@id FOR UPDATE", "id", id)); + if (before == null) return Result.error("专项经费不存在"); + if (before.getInt("status") == 2) return Result.success("专项经费已删除"); + if (before.getInt("version") != version) return Result.error("记录已更新,请刷新后重试"); + + BigDecimal amount = before.getInt("status") == 1 ? decimal(before.get("allocateMoney")) : BigDecimal.ZERO; + String remark = "删除专项经费,扣回分工会预算 " + amount.toPlainString() + " 元"; + if (amount.signum() != 0) { + String schoolBudgetId = chargedSchoolBudgetId("special", id); + if (schoolBudgetId != null) { + changeSchoolBudget(year, schoolBudgets, schoolBudgetId, amount.negate(), + "退回专项经费", before.getString("projectName")); + } + syncBudget(year, unionId, amount.negate()); + } + + execute(sql(""" + UPDATE outlay_annual_special SET status=2,version=version+1,updatedAt=@now,updatedBy=@actor WHERE id=@id + """, "id", id, "now", System.currentTimeMillis(), "actor", StpUtil.getLoginIdAsString())); + audit("special", id, "删除专项经费", before, + first(sql("SELECT * FROM outlay_annual_special WHERE id=@id", "id", id)), remark); + return Result.success("专项经费已删除"); + } + public Result resetBaseRecords(Integer year, String unionId, String amountMatch) { if (year == null || year != Year.now().getValue()) return Result.error("只能重置当前年度的分配记录"); + List schoolBudgets = lockSchoolBudgets(year); List candidates = listMap(sql(""" SELECT id,unionId,version FROM outlay_annual_base a WHERE year=@year AND status IN (0,1) AND (@unionId='' OR unionId=@unionId) """ + amountMatchCondition(amountMatch) + " ORDER BY unionId,id", "year", year, "unionId", StrUtil.blankToDefault(unionId, ""))); int count = 0; + String refundBudgetId = null; + BigDecimal refundTotal = BigDecimal.ZERO; for (NutMap candidate : candidates) { String id = candidate.getString("id"); lockUnion(candidate.getString("unionId")); @@ -244,7 +399,16 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl lockSchoolBudgets(int year) { + return listMap(sql("SELECT id,year,totalQuota,usedQuota,delFlag FROM outlay_manage_school WHERE year=@year AND COALESCE(delFlag,0)=0 FOR UPDATE", "year", year)); + } + + private String chargedSchoolBudgetId(String type, String recordId) { + NutMap charge = first(sql(""" + SELECT JSON_UNQUOTE(JSON_EXTRACT(afterData,'$.schoolBudgetId')) schoolBudgetId + FROM outlay_annual_allocate_log + WHERE allocateType=@type AND allocateId=@id AND JSON_EXTRACT(afterData,'$.schoolBudgetId') IS NOT NULL + ORDER BY createdAt DESC,id DESC LIMIT 1 + """, "type", type, "id", recordId)); + return charge == null ? null : charge.getString("schoolBudgetId"); + } + + private String changeSchoolBudget(int year, List budgets, String expectedId, BigDecimal delta, + String action, String remark) { + if (budgets.isEmpty()) throw new BaseException(year + "年度校工会预算尚未设置"); + if (budgets.size() > 1) throw new BaseException(year + "年度校工会预算存在重复记录"); + NutMap budget = budgets.get(0); + String id = budget.getString("id"); + if (expectedId != null && !expectedId.equals(id)) throw new BaseException("原校工会预算记录已变更,无法同步经费"); + BigDecimal used = decimal(budget.get("usedQuota")); + BigDecimal remaining = decimal(budget.get("totalQuota")).subtract(used); + if (delta.signum() > 0 && remaining.compareTo(delta) < 0) + throw new BaseException(year + "年度校工会预算余额不足,本次需要 " + delta.toPlainString() + + " 元,剩余 " + remaining.toPlainString() + " 元"); + if (delta.signum() < 0 && used.add(delta).signum() < 0) + throw new BaseException("校工会已使用额度不足,无法退回下拨经费"); + if (delta.signum() != 0) { + execute(sql(""" + UPDATE outlay_manage_school SET usedQuota=COALESCE(usedQuota,0)+@delta,updatedAt=@now,updatedBy=@actor + WHERE id=@id + """, "delta", delta, "id", id, "now", System.currentTimeMillis(), "actor", StpUtil.getLoginIdAsString())); + auditSchoolBudget(year, action, budget, schoolBudgetSnapshot(id), remark); + } + return id; + } + private void syncBudget(int year, String unionId, BigDecimal delta) { List budgets = listMap(sql("SELECT * FROM outlay_manage_union WHERE year=@year AND unionId=@unionId FOR UPDATE", "year", year, "unionId", unionId)); @@ -267,7 +473,7 @@ public class OutlayAnnualAllocateService extends BaseServiceImpl * @param isEdit 是否为编辑场景 */ private void updateOutlayManage(String id, OutlayUseDetail outlayUseDetail, String outlayType, Boolean isEdit) { - OutlayUseDetail detail = fetch(id); + Sql sql = Sqls.create("SELECT * FROM outlay_use_detail WHERE id=@id FOR UPDATE"); + sql.setParam("id", id); + sql.setEntity(dao().getEntity(OutlayUseDetail.class)); + sql.setCallback(Sqls.callback.entity()); + dao().execute(sql); + OutlayUseDetail detail = sql.getObject(OutlayUseDetail.class); if (detail == null) { return; } if ("school".equals(outlayType)) { - OutlayManageSchool manageSchool = dao().fetch(OutlayManageSchool.class, detail.getOutlayManageId()); + OutlayManageSchool manageSchool = OutlayManageSchool.lockActive(dao(), Cnd.where("id", "=", detail.getOutlayManageId())); if (manageSchool == null) { - return; + throw new BaseException("校工会预算未分配或已重置"); } manageSchool.setUsedQuota(manageSchool.getUsedQuota().subtract(detail.getAdjustMoney())); if (Boolean.TRUE.equals(isEdit) && outlayUseDetail != null) { diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/union/controller/OutlayAnnualAllocateController.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/union/controller/OutlayAnnualAllocateController.java index 9f8ffab..33e0873 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/union/controller/OutlayAnnualAllocateController.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayManage/union/controller/OutlayAnnualAllocateController.java @@ -123,6 +123,14 @@ public class OutlayAnnualAllocateController { return outlayAnnualAllocateService.resetBaseRecords(year, unionId, amountMatch); } + @At + @POST + @Aop(TransAop.READ_COMMITTED) + @SaCheckPermission("outlay.outlayManage.union.allocate") + public Result deleteSpecial(String id, Integer version) { + return outlayAnnualAllocateService.deleteSpecial(id, version); + } + @At @POST @Aop(TransAop.READ_COMMITTED) @@ -136,10 +144,8 @@ public class OutlayAnnualAllocateController { @At @SaCheckPermission("outlay.outlayManage.union.allocate") public Result logs(PageForm pageForm, String type, String id) { - return Result.success(outlayAnnualAllocateService.listPageMap(pageForm.getPageNumber(), pageForm.getPageSize(), outlayAnnualAllocateService.sql(""" - SELECT l.*,u.username operatorName FROM outlay_annual_allocate_log l - LEFT JOIN sys_user u ON u.id=l.createdBy - WHERE l.allocateType=@type AND l.allocateId=@id ORDER BY l.createdAt DESC,l.id - """, "type", type, "id", id))); + if (!"base".equals(type) && !"special".equals(type)) return Result.error("经费类型错误"); + return Result.success(outlayAnnualAllocateService.allocationLogs( + pageForm.getPageNumber(), pageForm.getPageSize(), type, id)); } } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/interceptor/OutlayReimburseSchoolZxAuditPostInterceptor.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/interceptor/OutlayReimburseSchoolZxAuditPostInterceptor.java index bc99ce9..6eca4a3 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/interceptor/OutlayReimburseSchoolZxAuditPostInterceptor.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/interceptor/OutlayReimburseSchoolZxAuditPostInterceptor.java @@ -42,7 +42,7 @@ public class OutlayReimburseSchoolZxAuditPostInterceptor implements FlowIntercep detail.setActivityTime(outlayReimburse.getActivityTime()); // 更新校工会经费表 if (outlayReimburse.getOutlayManageSource().equals("ACTIVITY_BUDGET_TYPE_ONE")) { - OutlayManageSchool school = dao.fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool school = OutlayManageSchool.lockActive(dao, Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isEmpty(school)) { throw new BaseException("该年份没有设置金额!"); } @@ -57,7 +57,7 @@ public class OutlayReimburseSchoolZxAuditPostInterceptor implements FlowIntercep ActivityBudget budget = dao.fetch(ActivityBudget.class, Cnd.where("id", "=", outlayReimburse.getBudgetId())); if (ObjectUtil.isNotEmpty(budget)&&budget.getIsSchoolBudget()){ //如果分工会报销了校工会的余额 - OutlayManageSchool school = dao.fetch(OutlayManageSchool.class, Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool school = OutlayManageSchool.lockActive(dao, Cnd.where("year", "=", DateUtil.thisYear())); if (ObjectUtil.isEmpty(school)) { throw new BaseException("该年份没有设置金额!"); } diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/service/impl/OutlayReimburseApplyServiceImpl.java b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/service/impl/OutlayReimburseApplyServiceImpl.java index 0b5524f..c01017f 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/service/impl/OutlayReimburseApplyServiceImpl.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/outlay/outlayReimburse/service/impl/OutlayReimburseApplyServiceImpl.java @@ -116,8 +116,8 @@ public class OutlayReimburseApplyServiceImpl extends BaseServiceImpl|\\p{Cntrl}]", "_") + ".pdf"; + return new PdfExport(fileName, renderDocument(form, true, collectPrint)); } /** @@ -238,9 +245,13 @@ public class UnionReimburseExportServiceImpl implements UnionReimburseExportServ if ("UNION_REIMBURSE_PROJECT_5".equals(project)) { data.put("project", "√协会活动"); } - data.put("activity", text(form.getActivityName())); - data.put("reason", text(form.getPaymentNotes())); - data.put("notes", text(form.getNotes())); + String activityName = text(form.getActivityName()); + String paymentNotes = text(form.getPaymentNotes()); + data.put("activity", activityName); + // 活动模板的活动名称栏兼容原 reason 占位符。 + data.put("reason", "UNION_REIMBURSE_PROJECT_1".equals(project) ? paymentNotes : activityName); + data.put("notes", StrUtil.blankToDefault(paymentNotes, text(form.getNotes()))); + data.put("remark", paymentNotes); // 附件只有上传文件数量,没有纸质页数,模板明确标注为“附件份数”。 data.put("attachments", form.getFiles() == null ? 0 : form.getFiles().size()); List details = form.getPaymentDetails(); @@ -304,7 +315,8 @@ public class UnionReimburseExportServiceImpl implements UnionReimburseExportServ } data.put("invoices", invoices); data.put("invoiceTotal", invoiceTotal.setScale(2).toPlainString()); - data.put("invoiceCount", invoices.isEmpty() ? text(form.getInvoiceNumber()) : invoices.size()); + data.put("invoiceCount", invoices.size()); + data.put("invoiceNumber", invoices.size()); // 验真状态没有单独落库,导出模板不可将其固定写成“已验真”。 data.put("person", text(form.getCondolenceUserName())); data.put("personNo", text(form.getCondolenceLoginName())); diff --git a/src/main/java/com/budwk/app/zhgh/dayofficework/unionReimburse/service/impl/UnionReimburseServiceImpl.java b/src/main/java/com/budwk/app/zhgh/dayofficework/unionReimburse/service/impl/UnionReimburseServiceImpl.java index 2c8b292..4557918 100644 --- a/src/main/java/com/budwk/app/zhgh/dayofficework/unionReimburse/service/impl/UnionReimburseServiceImpl.java +++ b/src/main/java/com/budwk/app/zhgh/dayofficework/unionReimburse/service/impl/UnionReimburseServiceImpl.java @@ -124,7 +124,7 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i /** * 在同一事务内保存申请和发票明细,正式提交及重新提交时校验支付信息。 * @param unionReimburse 申请表单,paymentDetails 为支付方式、金额及对私收款资料组成的明细列表 - * @param stateId 1 表示保存草稿,2 表示提交;提交时至少需要一张发票 + * @param stateId 1 表示保存草稿,2 表示提交;发票选填 * @return Result 成功或失败结果,msg 包含失败明细的行号及原因 */ @Override @@ -133,8 +133,9 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (unionReimburse == null) { return Result.error("报销数据不能为空"); } - if (stateId == 2 && Lang.isEmpty(unionReimburse.getInvoiceDetails())) { - return Result.error("提交前请至少上传一张发票"); + if (stateId == 2 && !"UNION_REIMBURSE_PROJECT_1".equals(unionReimburse.getReimburseProject()) + && StrUtil.isBlank(unionReimburse.getPaymentNotes())) { + return Result.error("请填写报销事由"); } // 保存、提交及重提均对已上传的发票检查完整性。 Result invoiceResult = validateInvoiceDetails(unionReimburse); @@ -372,11 +373,69 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (StrUtil.isBlank(id)) { return; } - // 删除申请主记录时同步清理发票明细,避免遗留无归属的发票关联数据。 + UnionReimburse reimburse = lockApply(id); + if (reimburse == null) { + return; + } + if (!AuthUtil.hasRoleOr(RoleConstant.SYSADMIN.name()) + && (!Integer.valueOf(1).equals(reimburse.getStateId()) + || !Objects.equals(reimburse.getUserId(), SecurityUtil.getUserId()))) { + throw new BaseException("无权删除该报销记录"); + } + + Sql detailSql = Sqls.create("SELECT * FROM outlay_use_detail WHERE outlayReimburseId=@id ORDER BY id FOR UPDATE"); + detailSql.setParam("id", id); + detailSql.setEntity(dao().getEntity(OutlayUseDetail.class)); + detailSql.setCallback(Sqls.callback.entities()); + dao().execute(detailSql); + List details = detailSql.getList(OutlayUseDetail.class); + if (!details.isEmpty()) { + String budgetTable = switch (StrUtil.blankToDefault(reimburse.getReimburseFundSource(), "")) { + case "UNION_REIMBURSE_FUND_SOURCE_1" -> "outlay_manage_school"; + case "UNION_REIMBURSE_FUND_SOURCE_2" -> "outlay_manage_union"; + case "UNION_REIMBURSE_FUND_SOURCE_3" -> "outlay_manage_club"; + default -> throw new BaseException("无法确认使用详情对应的经费来源"); + }; + for (OutlayUseDetail detail : details) { + refundDeletedUseDetail(budgetTable, detail); + } + dao().clear(OutlayUseDetail.class, Cnd.where("outlayReimburseId", "=", id)); + } + this.dao().clear(UnionReimburseInvoiceDetail.class, Cnd.where("reimburseId", "=", id)); this.delete(id); } + private UnionReimburse lockApply(String id) { + Sql sql = Sqls.create("SELECT * FROM union_reimburse WHERE id=@id FOR UPDATE"); + sql.setParam("id", id); + sql.setEntity(dao().getEntity(UnionReimburse.class)); + sql.setCallback(Sqls.callback.entity()); + dao().execute(sql); + return sql.getObject(UnionReimburse.class); + } + + private void refundDeletedUseDetail(String budgetTable, OutlayUseDetail detail) { + BigDecimal amount = detail.getAdjustMoney(); + if (amount == null || amount.signum() == 0) return; + Sql refund = Sqls.create("UPDATE " + budgetTable + """ + SET usedQuota=COALESCE(usedQuota,0)-@amount + WHERE id=@id AND COALESCE(usedQuota,0)>=@amount + """); + refund.setParam("id", detail.getOutlayManageId()); + refund.setParam("amount", amount); + dao().execute(refund); + if (refund.getUpdateCount() == 0) { + Sql existing = Sqls.create("SELECT COUNT(*) FROM " + budgetTable + " WHERE id=@id"); + existing.setParam("id", detail.getOutlayManageId()); + existing.setCallback(Sqls.callback.integer()); + dao().execute(existing); + if (existing.getInt() != 0) { + throw new BaseException("预算已使用额度小于本次退回金额,无法删除报销记录"); + } + } + } + @Override public List getUserBankHistory(String payer) { if (StrUtil.isBlank(payer)) { @@ -524,7 +583,7 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i } if ("UNION_REIMBURSE_FUND_SOURCE_1".equals(reimburseFundSource)) { OutlayManageSchool outlayManageSchool = dao().fetch(OutlayManageSchool.class, - Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool.activeBudgets().and("year", "=", DateUtil.thisYear())); if (outlayManageSchool == null) { return Result.error("校工会经费未分配"); } @@ -563,22 +622,11 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (!List.of(3, 4, 5).contains(submitType)) { return Result.error("无效的审核操作类型"); } - UnionReimburse dbRecord = this.fetch(reimburseId); + UnionReimburse dbRecord = lockApply(reimburseId); if (dbRecord == null) { return Result.error("记录不存在"); } if ("UNION_REIMBURSE_FUND_SOURCE_3".equals(dbRecord.getReimburseFundSource())) { - // 同一申请审核串行处理,避免重复点击导致协会已使用额度累计两次。 - Sql lockSql = Sqls.create("SELECT * FROM union_reimburse WHERE id=@id FOR UPDATE"); - lockSql.setParam("id", reimburseId); - lockSql.setEntity(dao().getEntity(UnionReimburse.class)); - lockSql.setCallback(Sqls.callback.entities()); - dao().execute(lockSql); - List records = lockSql.getList(UnionReimburse.class); - if (records.isEmpty()) { - return Result.error("记录不存在"); - } - dbRecord = records.get(0); if (submitType == 3 && Integer.valueOf(3).equals(dbRecord.getStateId())) { return Result.success(); } @@ -591,15 +639,13 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (Integer.valueOf(3).equals(dbRecord.getStateId())) { return Result.success(); } - if (!skipBudgetDeduct(dbRecord)) { - Result validateResult = validateFundSourceBeforeSubmit(dbRecord); - if (validateResult != null) { - return validateResult; - } - Result deductResult = deductBudgetAndSaveUseDetail(dbRecord); - if (deductResult != null && deductResult.getCode() != 0) { - return deductResult; - } + Result validateResult = validateFundSourceBeforeSubmit(dbRecord); + if (validateResult != null) { + return validateResult; + } + Result deductResult = deductBudgetAndSaveUseDetail(dbRecord); + if (deductResult != null && deductResult.getCode() != 0) { + return deductResult; } } dbRecord.setReviewTime(new Date()); @@ -642,7 +688,7 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (newMoney == null || newMoney.compareTo(BigDecimal.ZERO) <= 0) { return Result.error("实际报销金额必须大于0"); } - UnionReimburse dbRecord = this.fetch(id); + UnionReimburse dbRecord = lockApply(id); if (dbRecord == null) { return Result.error("未找到对应的报销记录"); } @@ -651,11 +697,16 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i if (newMoney.compareTo(declaredMoney) > 0) { return Result.error("实际报销金额不能超过申请金额:" + declaredMoney.toPlainString()); } - if (Integer.valueOf(3).equals(dbRecord.getStateId()) && !skipBudgetDeduct(dbRecord)) { + if (Integer.valueOf(3).equals(dbRecord.getStateId())) { OutlayUseDetail oldDetail = dao().fetch(OutlayUseDetail.class, Cnd.where("outlayReimburseId", "=", dbRecord.getId())); BigDecimal oldMoney = oldDetail != null && oldDetail.getAdjustMoney() != null ? oldDetail.getAdjustMoney() : getApplyMoney(dbRecord); + // 旧版通过的慰问和专项活动没有扣账明细,首次调整时按全额入账。 + if (oldDetail == null && ("UNION_REIMBURSE_PROJECT_1".equals(dbRecord.getReimburseProject()) + || "UNION_REIMBURSE_PROJECT_4".equals(dbRecord.getReimburseProject()))) { + oldMoney = BigDecimal.ZERO; + } Result syncResult = syncApprovedActualAmount(dbRecord, oldDetail, oldMoney, newMoney); if (syncResult != null && syncResult.getCode() != 0) { return syncResult; @@ -1042,8 +1093,7 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i BigDecimal applyMoney = getApplyMoney(unionReimburse); String reimburseFundSource = unionReimburse.getReimburseFundSource(); if ("UNION_REIMBURSE_FUND_SOURCE_1".equals(reimburseFundSource)) { - OutlayManageSchool outlayManageSchool = dao().fetch(OutlayManageSchool.class, - Cnd.where("year", "=", DateUtil.thisYear())); + OutlayManageSchool outlayManageSchool = OutlayManageSchool.lockActive(dao(), Cnd.where("year", "=", DateUtil.thisYear())); if (outlayManageSchool == null) { return Result.error("校工会经费未分配"); } @@ -1056,7 +1106,7 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i return Result.success(); } if ("UNION_REIMBURSE_FUND_SOURCE_2".equals(reimburseFundSource)) { - OutlayManageUnion outlayManageUnion = dao().fetch(OutlayManageUnion.class, + OutlayManageUnion outlayManageUnion = lockUnionBudget( Cnd.where("unionId", "=", unionReimburse.getUnionId()).and("year", "=", DateUtil.thisYear())); if (outlayManageUnion == null) { return Result.error("分工会经费未分配"); @@ -1094,14 +1144,13 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i return Result.error("不支持的经费来源"); } - /** - * 慰问和专项活动费用不占用经费预算,审核通过及后续调整实际金额时都不写预算台账。 - */ - private boolean skipBudgetDeduct(UnionReimburse unionReimburse) { - return unionReimburse != null && Set.of( - "UNION_REIMBURSE_PROJECT_1", - "UNION_REIMBURSE_PROJECT_4" - ).contains(unionReimburse.getReimburseProject()); + private OutlayManageUnion lockUnionBudget(Cnd condition) { + Sql sql = Sqls.create("SELECT * FROM outlay_manage_union $condition FOR UPDATE"); + sql.setCondition(condition); + sql.setEntity(dao().getEntity(OutlayManageUnion.class)); + sql.setCallback(Sqls.callback.entity()); + dao().execute(sql); + return sql.getObject(OutlayManageUnion.class); } /** @@ -1111,9 +1160,11 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i BigDecimal oldMoney, BigDecimal newMoney) { BigDecimal diffMoney = newMoney.subtract(safeMoney(oldMoney)).setScale(2, RoundingMode.HALF_UP); String reimburseFundSource = unionReimburse.getReimburseFundSource(); + int budgetYear = unionReimburse.getReviewTime() == null ? DateUtil.thisYear() : DateUtil.year(unionReimburse.getReviewTime()); if ("UNION_REIMBURSE_FUND_SOURCE_1".equals(reimburseFundSource)) { - OutlayManageSchool outlayManageSchool = dao().fetch(OutlayManageSchool.class, - Cnd.where("year", "=", DateUtil.thisYear())); + Cnd condition = oldDetail == null ? Cnd.where("year", "=", budgetYear) + : Cnd.where("id", "=", oldDetail.getOutlayManageId()); + OutlayManageSchool outlayManageSchool = OutlayManageSchool.lockActive(dao(), condition); if (outlayManageSchool == null) { return Result.error("校工会经费未分配"); } @@ -1125,8 +1176,10 @@ public class UnionReimburseServiceImpl extends BaseServiceImpl i return Result.success(); } if ("UNION_REIMBURSE_FUND_SOURCE_2".equals(reimburseFundSource)) { - OutlayManageUnion outlayManageUnion = dao().fetch(OutlayManageUnion.class, - Cnd.where("unionId", "=", unionReimburse.getUnionId()).and("year", "=", DateUtil.thisYear())); + Cnd condition = oldDetail == null + ? Cnd.where("unionId", "=", unionReimburse.getUnionId()).and("year", "=", budgetYear) + : Cnd.where("id", "=", oldDetail.getOutlayManageId()); + OutlayManageUnion outlayManageUnion = lockUnionBudget(condition); if (outlayManageUnion == null) { return Result.error("分工会经费未分配"); } diff --git a/src/main/resources/db/script/20261116/annual_base_active_unique_key.sql b/src/main/resources/db/script/20261116/annual_base_active_unique_key.sql new file mode 100644 index 0000000..2edfb5b --- /dev/null +++ b/src/main/resources/db/script/20261116/annual_base_active_unique_key.sql @@ -0,0 +1,11 @@ +-- 同一年度、同一分工会仅保留一条有效基础经费记录,已重置记录可按原 ID 追溯。 +SET @replace_annual_base_key = IF(EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'outlay_annual_base' + AND INDEX_NAME = 'uk_annual_base_year_union' +), 'ALTER TABLE `outlay_annual_base` DROP INDEX `uk_annual_base_year_union`, + ADD UNIQUE KEY `uk_annual_base_active_year_union` (`year`,`unionId`,(CASE WHEN `status` = 2 THEN NULL ELSE 1 END))', 'DO 0'); +PREPARE replace_annual_base_key FROM @replace_annual_base_key; +EXECUTE replace_annual_base_key; +DEALLOCATE PREPARE replace_annual_base_key; diff --git a/src/main/resources/db/script/20261116/union_reimburse_desc_project.sql b/src/main/resources/db/script/20261116/union_reimburse_desc_project.sql new file mode 100644 index 0000000..ddfbd19 --- /dev/null +++ b/src/main/resources/db/script/20261116/union_reimburse_desc_project.sql @@ -0,0 +1,34 @@ +INSERT INTO union_reimburse_desc (id, code, reimburseProject, name, fileDesc, location, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, projectTip) VALUES ('3b6134d2c4614a38ba6202ee184e1e5e', 'C', 'UNION_REIMBURSE_PROJECT_3', '日常活动', '无需上传附件,请提供纸质材料到校工会', 6, 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794817845311, '17a7f8ad3ee947b4a26175049a9c253d', 1794817845311, false, '请提供以下纸质材料到校工会: +(1)活动费用发票; +(2)活动策划方案(模板见工会网页下载中心); +(3)参加活动人员名单(需要提供姓名和工号); +(4)活动相关照片(至少需要两张及以上能够体现活动场面的全景或局部照片)。'); +INSERT INTO union_reimburse_desc (id, code, reimburseProject, name, fileDesc, location, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, projectTip) VALUES ('7c394d2fc4a845588eb44607983c39ce', 'B', 'UNION_REIMBURSE_PROJECT_2', '文体活动', '无需上传附件,请提供纸质材料到校工会', 6, 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794817832577, '17a7f8ad3ee947b4a26175049a9c253d', 1794820245842, false, '请提供以下纸质材料到校工会: +(1)活动费用发票; +(2)参加活动人员名单(需要提供姓名和工号); +(3)活动相关照片(至少需要两张及以上能够体现活动场面的全景或局部照片)。'); +INSERT INTO union_reimburse_desc (id, code, reimburseProject, name, fileDesc, location, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, projectTip) VALUES ('d16dffaf74b1421c8f17712dd35b9a35', 'D', 'UNION_REIMBURSE_PROJECT_4', '专项活动', '无需上传附件,请提供纸质材料到校工会', 6, 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794817857027, '17a7f8ad3ee947b4a26175049a9c253d', 1794820237103, false, '专项经费必须专款专用,严禁挤占挪用、随意调剂。请各经办人严格按照审定预算范围、用途、额度使用资金,严禁无预算、超预算开支。 +请提供以下纸质材料到校工会: +(1)活动费用发票; +(2)活动策划方案(模板见工会网页下载中心); +(3)参加活动人员名单(需要提供姓名和工号); +(4)活动相关照片(至少需要两张及以上能够体现活动场面的全景或局部照片)。 +(5)纪念品发放签收单(模板见工会网页下载中心)(欢迎递交活动通讯稿)'); +INSERT INTO union_reimburse_desc (id, code, reimburseProject, name, fileDesc, location, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, projectTip) VALUES ('f3d7c3ecd7ef4e348824356cbf9d8cc0', 'A', 'UNION_REIMBURSE_PROJECT_1', '慰问', '无需上传附件', 6, 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794817820427, '17a7f8ad3ee947b4a26175049a9c253d', 1794817820427, false, '无需上传附件'); + + +-- 兼容已执行旧版建表脚本的数据库。 +SET @replace_annual_base_key = IF(EXISTS ( + SELECT 1 FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'outlay_annual_base' AND INDEX_NAME = 'uk_annual_base_year_union' +), 'ALTER TABLE `outlay_annual_base` DROP INDEX `uk_annual_base_year_union`, + ADD UNIQUE KEY `uk_annual_base_active_year_union` (`year`,`unionId`,(CASE WHEN `status` = 2 THEN NULL ELSE 1 END))', 'DO 0'); +PREPARE replace_annual_base_key FROM @replace_annual_base_key; +EXECUTE replace_annual_base_key; +DEALLOCATE PREPARE replace_annual_base_key; + +INSERT INTO condolence_type (id, code, name, money, way, disabled, isUploadFile, uploadFileDesc, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, isDisabled, location, uploadMeetingRecord, enable) VALUES ('0928c486334d47cd9210401b66682b7c', 'E', '生病住院', 500.00, '慰问金 (A)', false, true, '线下需要提供出院记录', 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794816909142, '17a7f8ad3ee947b4a26175049a9c253d', 1794818359692, false, null, 3, false, true); +INSERT INTO condolence_type (id, code, name, money, way, disabled, isUploadFile, uploadFileDesc, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, isDisabled, location, uploadMeetingRecord, enable) VALUES ('2c156770bb894927b83ab20c7c30f023', 'G', '会员去世', 500.00, '慰问金 (A)', false, true, '需要提供购买的慰问品发票,慰问照片', 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794816932875, '17a7f8ad3ee947b4a26175049a9c253d', 1794818370427, false, null, 5, false, true); +INSERT INTO condolence_type (id, code, name, money, way, disabled, isUploadFile, uploadFileDesc, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, isDisabled, location, uploadMeetingRecord, enable) VALUES ('67520e16dfa84789986ebb56dc3bec8a', 'A', '结婚', 500.00, '慰问金 (A)', false, true, '线下需要提供会员结婚证复印件', 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794816886376, '17a7f8ad3ee947b4a26175049a9c253d', 1794818341477, false, null, 1, false, true); +INSERT INTO condolence_type (id, code, name, money, way, disabled, isUploadFile, uploadFileDesc, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, isDisabled, location, uploadMeetingRecord, enable) VALUES ('8ae1f27210ce4479b61e0429e753e6a1', 'H', '直系亲属去世', 500.00, '慰问金 (A)', false, false, null, 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794816921409, '17a7f8ad3ee947b4a26175049a9c253d', 1794817738427, false, null, 4, false, true); +INSERT INTO condolence_type (id, code, name, money, way, disabled, isUploadFile, uploadFileDesc, sortNum, createdBy, createdAt, updatedBy, updatedAt, delFlag, isDisabled, location, uploadMeetingRecord, enable) VALUES ('f7b212f35a414b5f80411edc9f0d29c0', 'D', '生育', 500.00, '慰问金 (A)', false, true, '线下需要提供慰问照片(会员与婴儿合影照,或慰问人员与会员和婴儿的合影照)', 0, '17a7f8ad3ee947b4a26175049a9c253d', 1794816898275, '17a7f8ad3ee947b4a26175049a9c253d', 1794818351493, false, null, 2, false, true); diff --git a/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/school/manage/index.html b/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/school/manage/index.html index 97311d9..cb064fc 100644 --- a/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/school/manage/index.html +++ b/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/school/manage/index.html @@ -12,7 +12,7 @@ layout("/layouts/platform.html"){ 分配重置 + 历史操作记录 @@ -63,6 +64,12 @@ layout("/layouts/platform.html"){ {{row.totalQuota}} 元 + + @@ -79,11 +86,31 @@ layout("/layouts/platform.html"){ @click="$set(row,'edit',true);$set(row,'totalQuota2',row.totalQuota);"> 编辑 + 操作记录 + + + + + + + + + + + + + + + + + + @@ -99,15 +126,66 @@ layout("/layouts/platform.html"){ {prop: 'year', label: '年度'}, {prop: 'unit', label: '单位'}, {prop: 'totalQuota', label: '预算费用'}, + {prop: 'usedQuota', label: '已使用额度'}, + {prop: 'remainingQuota', label: '剩余额度'}, ], pageForm: { year: this.$moment().format("YYYY") }, - isAllocation: false + isAllocation: false, + logsVisible: false, + logsLoading: false, + logs: [], + logYear: '', + logPage: 1, + logTotal: 0, + logRequestSequence: 0 } }, components: {}, methods: { + showLogs(year) { + this.logYear = year || '' + this.logPage = 1 + this.logTotal = 0 + this.logs = [] + this.logsVisible = true + this.loadLogs() + }, + changeLogPage(page) { + if (page === this.logPage) return + this.logPage = page + this.loadLogs() + }, + async loadLogs() { + const sequence = ++this.logRequestSequence + this.logsLoading = true + try { + const params = {pageNumber: this.logPage, pageSize: 10} + if (this.logYear) params.year = this.logYear + const resp = await this.$axios.post("/platform/outlay/outlayManage/schoolManage/logs", params) + if (sequence !== this.logRequestSequence) return + this.logs = resp.data.list || [] + this.logTotal = resp.data.totalCount + } catch (e) { + if (sequence === this.logRequestSequence) this.logs = [] + } finally { + if (sequence === this.logRequestSequence) this.logsLoading = false + } + }, + budgetSnapshot(value) { + if (!value) return '—' + try { + const budget = JSON.parse(value) + if (!budget) return '—' + const total = Number(budget.totalQuota || 0) + const used = Number(budget.usedQuota || 0) + const amount = '总额度 ' + total.toFixed(2) + ' 元,已使用 ' + used.toFixed(2) + ' 元,剩余 ' + (total - used).toFixed(2) + ' 元' + return Number(budget.delFlag) === 1 ? '已重置,' + amount : amount + } catch (e) { + return value + } + }, doSubmit(row) { this.$confirm('您确定要提交此条记录吗?', '提示', { confirmButtonText: '确定', @@ -127,7 +205,7 @@ layout("/layouts/platform.html"){ }) }, resetOutlay() { - this.$confirm('您确定要重置今年的记录吗?', '提示', { + this.$confirm('您确定要重置 ' + this.pageForm.year + ' 年的记录吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' @@ -144,7 +222,7 @@ layout("/layouts/platform.html"){ }) }, issuedOutlay() { - this.$confirm('您确定要下发今年的记录吗?', '提示', { + this.$confirm('您确定要分配 ' + this.pageForm.year + ' 年的预算吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' @@ -160,11 +238,14 @@ layout("/layouts/platform.html"){ }) }) }, + changeBudgetYear() { + this.getIsAllocation() + this.doSearch() + }, getIsAllocation() { - this.$axios.post("/platform/outlay/outlayManage/schoolManage/getIsAllocationOutlay", { - year: this.pageForm.year - }).then((resp) => { - if (resp.code === 0) { + const year = this.pageForm.year + this.$axios.post("/platform/outlay/outlayManage/schoolManage/getIsAllocationOutlay", {year}).then((resp) => { + if (resp.code === 0 && year === this.pageForm.year) { this.isAllocation = (resp.data > 0) } }) diff --git a/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/union/allocate/annual.html b/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/union/allocate/annual.html index 0835864..242ee9f 100644 --- a/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/union/allocate/annual.html +++ b/src/main/resources/views/platform/zhgh/dayofficework/outlay/outlayManage/union/allocate/annual.html @@ -98,9 +98,10 @@ layout("/layouts/platform.html"){ - @@ -218,7 +219,7 @@ layout("/layouts/platform.html"){ time(value) { return value?this.$moment(Number(value)).format('YYYY-MM-DD HH:mm:ss'):'—' }, snapshot(value) { if (!value) return '—' - try { const v=JSON.parse(value); return v.year+'年 / '+(v.memberCount==null?(v.projectName || ''):v.memberCount+'人 × '+v.standard+'元,计算 '+v.calculatedMoney+'元')+' / 实际 '+v.allocateMoney+'元 / '+(Number(v.status)===2?'已重置':Number(v.status)===1?'已下拨':'待下拨') } + try { const v=JSON.parse(value); return v.year+'年 / '+(v.memberCount==null?(v.projectName || ''):v.memberCount+'人 × '+v.standard+'元,计算 '+v.calculatedMoney+'元')+' / 实际 '+v.allocateMoney+'元 / '+(Number(v.status)===2?(v.memberCount==null?'已删除':'已重置'):Number(v.status)===1?'已下拨':'待下拨') } catch(e) { return value } }, doExport() { @@ -321,6 +322,17 @@ layout("/layouts/platform.html"){ this.doSearch() } catch(e) {} finally { this.busy=false } }, + async deleteSpecial(row) { + if (this.busy) return + this.busy=true + try { + await this.$confirm('确定删除专项经费「'+row.projectName+'」?已下拨的金额将退回。','删除专项经费', + {type:'warning',confirmButtonText:'删除'}) + const resp=await this.request('deleteSpecial',{id:row.id,version:row.version}) + this.$message.success(resp.msg) + this.doSearch() + } catch(e) {} finally { this.busy=false } + }, async resetBaseRecords() { if (this.busy || !this.isCurrentYear) return const params={year:this.query.year,unionId:this.query.unionId || '',amountMatch:this.query.amountMatch} diff --git a/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/apply/index.html b/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/apply/index.html index 86b5cb4..ac01ee2 100644 --- a/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/apply/index.html +++ b/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/apply/index.html @@ -120,9 +120,6 @@ layout("/layouts/platform.html"){ {{item.name}} - - {{getProjectTipByProject(formData.reimburseProject)}} - {{formData.userName}}({{formData.loginName}}) @@ -281,7 +278,7 @@ layout("/layouts/platform.html"){ - + + v-if="formData.reimburseProject && formData.reimburseProject !== 'UNION_REIMBURSE_PROJECT_1'"> @@ -445,17 +442,8 @@ layout("/layouts/platform.html"){ upload_mode="drag" > - -
- {{ formData.condolenceFilesNotes || getFileDescByProject(formData.reimburseProject) - || '需要提供购买的慰问品发票,慰问照片' }} -
-
- -
- {{ getFileDescByProject(formData.reimburseProject) || '请上传活动照片、参加人员名单、付款凭证等相关材料' - }} -
+ +
{{ attachmentNotice }}
@@ -620,11 +608,11 @@ layout("/layouts/platform.html"){
发票明细列表
- 提交时至少上传一张发票,上传后须通过验真。每条明细对应一张发票图片或单页 PDF。 + {{ isManualReimburseAmount ? '发票选填;上传后报销金额不得超过发票总额。' : '发票选填;无发票时按支付信息汇总报销金额。' }}上传后须通过验真,每条明细对应一张发票图片或单页 PDF。
- 提交时必填 + 发票选填,上传须验真 新增发票 @@ -834,7 +822,7 @@ layout("/layouts/platform.html"){ paymentWay: [{required: true, message: "请选择支付方式", trigger: ["change", "blur"]}], reimburseProject: [{required: true, message: "请选择报销项目", trigger: ["change", "blur"]}], reimburseFundSource: [{required: true, message: "请选择经费来源", trigger: ["change", "blur"]}], - // 报销事由仅在慰问项目显示,提交和重新提交时拒绝空值及纯空白。 + // 活动项目提交和重新提交时均须填写非空白报销事由。 paymentNotes: [{required: true, whitespace: true, message: "请填写报销事由", trigger: ["change", "blur"]}], // 所属协会仅在协会经费显示,候选范围由后端当前会员关系确定。 clubId: [{required: true, message: "请选择所属协会", trigger: ["change", "blur"]}], @@ -971,6 +959,16 @@ layout("/layouts/platform.html"){ const selectedType = this.typeOptions.find(item => item.id === typeId) return selectedType ? selectedType.code : "" }, + attachmentNotice() { + const project = this.formData.reimburseProject + if (!project) return "" + const fileDesc = this.getFileDescByProject(project) + if (project === "UNION_REIMBURSE_PROJECT_1") { + const selectedType = this.typeOptions.find(item => item.id === this.formData.condolenceTypeId) + return (selectedType && selectedType.uploadFileDesc) || fileDesc || "需要提供购买的慰问品发票,慰问照片" + } + return this.getProjectTipByProject(project) || fileDesc || "请上传活动照片、参加人员名单、付款凭证等相关材料" + }, // 协会经费按菜单授权查看年度剩余额度,其他经费沿用原余额可见范围。 canViewFundBalance() { return this.$auth.hasRoleOr(["SYSADMIN", "SCHOOL_UNION_ADMIN"]) @@ -1089,6 +1087,7 @@ layout("/layouts/platform.html"){ }, ensureFormData(formData) { const nextFormData = formData || {} + if (nextFormData.paymentNotes == null) this.$set(nextFormData, "paymentNotes", "") if (!Array.isArray(nextFormData.invoiceDetails)) { this.$set(nextFormData, "invoiceDetails", []) } @@ -1663,10 +1662,6 @@ layout("/layouts/platform.html"){ return false } const invoiceDetails = this.formData.invoiceDetails || [] - if (!invoiceDetails.length) { - this.$message.warning("提交前请至少上传一张发票") - return false - } for (let i = 0; i < invoiceDetails.length; i++) { const currentDetail = invoiceDetails[i] if (!currentDetail.invoiceFiles || currentDetail.invoiceFiles.length === 0) { @@ -1729,11 +1724,6 @@ layout("/layouts/platform.html"){ this.syncLegacyPaymentFields(submitData.paymentDetails, submitData) return submitData }, - updateReimburseAmount(value) { - this.$set(this.formData, "money", value) - const details = this.formData.paymentDetails || [] - if (details.length === 1) this.$set(details[0], "money", value) - }, // 金额输入允许编辑中的空值和末尾小数点;非法字符或超出两位小数时恢复原值,避免改变金额含义。 inputPaymentMoney(row, value) { const previous = row.money diff --git a/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/desc/basicForm.js b/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/desc/basicForm.js index aaa8953..1b8daa4 100644 --- a/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/desc/basicForm.js +++ b/src/main/resources/views/platform/zhgh/dayofficework/unionReimburse/desc/basicForm.js @@ -10,12 +10,19 @@ const basicForm = { + + + + + - @@ -29,8 +36,11 @@ const basicForm = { `, data() { return { - formData: {}, + formData: {reimburseProject: ''}, + projectOptions: [], + projectOptionsLoading: false, formRules: { + reimburseProject: [{required: true, message: '请选择关联报销项目', trigger: 'change'}], code: [{required: true, message: '必填', trigger: ['blur', 'change']}], name: [{required: true, message: '必填', trigger: ['blur', 'change']}], fileDesc: [{required: true, message: '必填', trigger: ['blur', 'change']}], @@ -38,9 +48,18 @@ const basicForm = { } }, methods: { - onOpen(row) { - if(row && row.id) { - this.formData = clone(row) + async onOpen(row) { + this.formData = row && row.id ? clone(row) : {reimburseProject: ''} + this.$nextTick(() => this.$refs.formRef.clearValidate()) + if (this.projectOptions.length || this.projectOptionsLoading) return + + this.projectOptionsLoading = true + try { + this.projectOptions = await this.$businessTool.getDictOptions("UNION_REIMBURSE_PROJECT") + } catch { + this.$message.warning("报销项目加载失败,请重新打开表单") + } finally { + this.projectOptionsLoading = false } }, onSubmit() { diff --git a/src/main/resources/views/platform/zhghh5/dayofficework/unionReimburse/apply/index.html b/src/main/resources/views/platform/zhghh5/dayofficework/unionReimburse/apply/index.html index 04e8732..a998367 100644 --- a/src/main/resources/views/platform/zhghh5/dayofficework/unionReimburse/apply/index.html +++ b/src/main/resources/views/platform/zhghh5/dayofficework/unionReimburse/apply/index.html @@ -331,11 +331,6 @@ layout("/layouts/platform_h5.html"){ required is-link > - - - @@ -641,14 +636,19 @@ layout("/layouts/platform_h5.html"){ autosize :rules="[{ required: true, message: '请填写参加随行人员' }]" required> - + + - - - item.id === typeId) return selectedType ? selectedType.code : "" }, + attachmentRequired() { + return this.formData.reimburseProject === "UNION_REIMBURSE_PROJECT_4" + }, + attachmentNotice() { + const project = this.formData.reimburseProject + if (!project) return "" + const desc = Array.isArray(this.descOptions) + ? this.descOptions.find(item => item.reimburseProject === project) : null + if (project === "UNION_REIMBURSE_PROJECT_1") { + const selectedType = this.typeOptions.find(item => item.id === this.formData.condolenceTypeId) + return (selectedType && selectedType.uploadFileDesc) || (desc && desc.fileDesc) + || "需要提供购买的慰问品发票,慰问照片" + } + const fileDesc = project === "UNION_REIMBURSE_PROJECT_5" ? "协会活动附件说明" : (desc && desc.fileDesc) + return (desc && desc.projectTip) || fileDesc || "请上传活动照片、参加人员名单、付款凭证等相关材料" + }, // 协会经费按菜单授权查看年度剩余额度,其他经费沿用原余额可见范围。 canViewFundBalance() { return this.$auth.hasRoleOr(["SYSADMIN", "SCHOOL_UNION_ADMIN"]) @@ -1943,10 +1953,6 @@ layout("/layouts/platform_h5.html"){ return false } const invoiceDetails = this.formData.invoiceDetails || [] - if (!invoiceDetails.length) { - this.$toast.fail("提交前请至少上传一张发票") - return false - } for (let i = 0; i < invoiceDetails.length; i++) { const currentDetail = invoiceDetails[i] if (!currentDetail.invoiceFiles || currentDetail.invoiceFiles.length === 0) { @@ -2194,11 +2200,6 @@ layout("/layouts/platform_h5.html"){ this.syncLegacyPaymentFields(submitData.paymentDetails, submitData) return submitData }, - updateReimburseAmount(value) { - this.$set(this.formData, "money", value) - const details = this.formData.paymentDetails || [] - if (details.length === 1) this.$set(details[0], "money", value) - }, // 金额输入允许编辑中的空值和末尾小数点;非法字符或超出两位小数时恢复原值,避免改变金额含义。 inputPaymentMoney(row, value) { const previous = row.money @@ -2523,7 +2524,7 @@ layout("/layouts/platform_h5.html"){ const matchedFundSource = this.reimburseFundSourceColumns.find(item => item.value === code) return matchedFundSource ? matchedFundSource.text : "" }, - // 查询管理端配置的报销项目提示。 + // 查询管理端配置的附件说明和报销项目提示。 queryProjectDesc() { return this.$axios.post("/platform/unionReimburse/desc/queryFileDesc") .then((resp) => { @@ -2532,14 +2533,6 @@ layout("/layouts/platform_h5.html"){ } }) }, - // 根据当前选择的报销项目获取管理端配置的提示内容。 - getProjectTipByProject(projectCode) { - if (!this.descOptions || !Array.isArray(this.descOptions)) { - return "" - } - const project = this.descOptions.find(item => item.reimburseProject === projectCode) - return project ? project.projectTip : "" - }, initDictOptions() { return this.$businessTool.getDictOptions("UNION_REIMBURSE_TYPE").then((reimburseTypeData) => { this.$set(this, "reimburseTypeColumns", reimburseTypeData.map(item => ({value: item.code, text: item.name})))