feat: 采购批次有关联业务记录时,禁止整批删除,覆盖到货、验收、退货、入库、库存、费用台账及项目阶段引用,包括历史记录
This commit is contained in:
parent
3d2ac3efc0
commit
53947203b2
62
docs/purchase-batch-deletion.md
Normal file
62
docs/purchase-batch-deletion.md
Normal file
@ -0,0 +1,62 @@
|
||||
# 采购批次整批软删除
|
||||
|
||||
## 目标与范围
|
||||
|
||||
在“采购管理 → 采购申请”的默认批次列表操作列增加“删除”,确认后将采购批次及其有效明细一并软删除。只有当前批次的创建者具备此操作资格,其他管理者及系统管理员不能代删。
|
||||
|
||||
用户已明确删除层级、级联明细、创建者身份、整批软删除并保留历史附件,以及“有关联业务记录时禁止删除”。RCS 100;数据及权限变更按 Strict Gate 审查,以上核心规则已确认。本轮不执行真实业务数据删除,不改变库存、验收或项目阶段记录。
|
||||
|
||||
## 行为及边界
|
||||
|
||||
- 前端按当前登录账号与批次 `createBy` 比较,并沿用采购删除/管理功能权限;缺失创建者的历史批次不允许猜测归属。确认弹窗明确包含全部明细、保留历史附件,取消不发送请求。
|
||||
- 后端独立校验功能权限和真实创建者,获取目录写锁、批次行锁和明细行锁后执行。明细沿用现有删除服务的到货保护、锁定费用冲销和操作记录;历史完成、已入库等已有业务保护保留,异常时整笔事务回滚。
|
||||
- 新增 `purchase_batch.del_flag`,正常为 `0`,删除为 `2`;明细继续使用原有 `del_flag`。不物理删除批次、明细、附件、价格台账、业务编号或提交回执,不重用已删除批次编号。
|
||||
- 删除后不再出现在采购批次列表、候选、看板及普通明细中,不能通过旧页面继续编辑、确认、转入明细或上传附件。已保存的历史资料保留;不新增恢复入口。
|
||||
- 拒绝请求、并发变化和重复提交不能形成“批次已删除而明细仍有效”或相反的半完成状态。批次创建者可级联删除他人在该批次内创建的明细,身份依据始终是批次创建者。
|
||||
|
||||
## 关联业务禁止删除补充规格
|
||||
|
||||
- 目标:有关联业务的批次在级联删除前拒绝请求,批次、明细、附件、台账及关联记录均不变。
|
||||
- 关联范围:任一批次明细存在到货/验收记录(包括拒收、全退及历史记录)、任何状态的入库记录、库存来源批次或采购费用台账,或者批次被项目协作阶段的当前/历史版本引用。历史完成明细同样禁止删除;已软删除明细的业务引用仍须检查。
|
||||
- 边界:采购明细是本次级联删除对象;附件、操作日志、保存回执及编号本身不构成下游业务,不阻止无其他引用的批次软删除。退货通过其来源到货记录关联保护。
|
||||
- 并发约束:删除持有采购批次和有效明细行锁后查询关联业务;项目阶段新增批次引用前按批次 ID 顺序锁定有效批次,并在保存引用的同一事务中持有锁,避免“查时无引用、提交后有悬空引用”。普通画布读取不加写锁。
|
||||
- 范围:仅补充删除守卫、确认文案及采购阶段绑定时的并发校验;不改变创建者权限、软删除策略、其他采购操作或数据库结构。
|
||||
- 验收:每种业务关联均拒绝且无删除副作用;仅附件/日志时仍可删除;空批次的阶段引用也阻止删除;无关联正常删除;并发绑定和删除最多成功一方。
|
||||
- 计划:完善 Mapper 关联查询和批次绑定锁;执行隔离数据库、权限/事务及并发专项和既有采购回归;完成后删除本轮生成的临时测试源码、日志和产物。
|
||||
|
||||
## 实施计划与验收
|
||||
|
||||
1. 添加临时前端交互、后端权限/事务与 MyBatis 查询验证;先验证当前缺少整批软删除和创建者限制。
|
||||
2. 新增可重复执行的升级 SQL,更新安装定义;实现同事务的批次与明细软删除,并排除业务读取中的删除批次。
|
||||
3. 增加列表删除按钮、确认及防重复提交,复用同一规则约束既有空批次删除入口。
|
||||
4. 运行相关采购回归、编译和前端构建;检查中文方法注释及范围,清理本轮临时测试源码、配置和日志。
|
||||
|
||||
验收:创建者确认可删除整批;非创建者及伪造 API 无法删除;取消无写入;关联业务校验失败整批不变;历史及附件不被删除;各业务入口隐藏或拒绝已删除批次。
|
||||
|
||||
## 部署
|
||||
|
||||
已有数据库在启动新版代码前执行 `sql/projectdev/20261106_purchase_batch_soft_delete.sql`。该升级仅补充删除标记与索引,不修改已有批次的有效性,不删除业务行。
|
||||
|
||||
## 整批软删除验证记录(前序实现)
|
||||
|
||||
- FR-001 / AC-001(批次创建者权限与确认):PASS。前端隐藏非创建者入口,后端拒绝非创建者,管理员无代删特权。
|
||||
- FR-002 / AC-002(整批软删除与事务):PASS。实际 MyBatis SQL 和隔离 H2 数据库验证批次、明细标记、历史附件保留、重复删除及父/子写入失败回滚。
|
||||
- FR-003 / AC-003(有效性读取与并发):PASS。候选排除删除批次,旧编辑目标拒绝;并发条件更新失败后停止同步历史编号。
|
||||
- 后端相关回归:179 项通过,26 项依赖实际开发库/迁移开关的测试未启用;Maven 编译与测试成功。没有对实际数据库执行删数据、迁移或真实服务接口联调。
|
||||
- 前端专项:9 项通过,覆盖真实表格和确认框、取消、身份切换、重复点击、失败保留、转批次后的内部刷新。
|
||||
- 前端现有单元检查:351 项通过;采购交互回归:14 个文件共 90 项通过(使用 15 秒单例超时);生产构建成功。
|
||||
- 注释:已补充本轮新增/修改方法的中文说明,并检查权限、事务和历史保留约束与代码一致。
|
||||
- 范围与需求漂移:Scope Drift / Requirement Drift / Assumption Drift 均为 NONE。既有项目流程交互改动保留,该轮仅适配项目采购读取的删除过滤。
|
||||
- 临时测试源码、配置、日志及对应编译/报告产物在验证后清理;项目原有测试仅同步新业务规则和 SQL 条件。
|
||||
- 独立 Type Check、Lint 与真实浏览器/实际数据库端到端检查未单独执行。升级 SQL 已提供,实际数据库尚未应用。
|
||||
|
||||
## 关联业务守卫验证记录(本次补充)
|
||||
|
||||
- FR-004 / AC-004(关联业务禁止删除):PASS。实际 MyBatis SQL 在隔离 H2 数据库中验证到货/验收各状态、全退、入库各状态、库存、费用台账、历史完成明细、已软删除明细的业务引用及当前/历史阶段引用,均在任何删除写入前拒绝。
|
||||
- AC-005(无引用及历史保留):PASS。仅有附件、日志或其他批次的关联时仍允许整批软删除,原附件和日志保留;明细写入失败时真实 Spring 事务回滚,不扩大创建者权限。
|
||||
- AC-006(关联并发):PASS。两个独立事务分别验证先绑定/后删除、先删除/后绑定的竞争,后到操作等待行锁,并在读取提交结果后拒绝,不产生悬空引用。普通展示和清空范围不会新增源表锁。
|
||||
- 专项 33 项全部通过,其中本次临时专项 21 项;后端采购及相关助手回归共 211 项,185 项通过、26 项因开发库/迁移开关未启用而跳过,零失败。Maven 编译成功。
|
||||
- 前端本次仅调整确认提示,生产构建成功;前序的交互及单元结果见上节,本次未重复执行。独立 Type Check、Lint、真实 MySQL 与浏览器端到端检查未执行;未连接实际业务库实施数据变更。
|
||||
- 代码文档:新增锁定读取方法、关联 Mapper、阶段绑定入口及删除入口的中文注释已检查,明确事务、安全和历史关联保护约束。
|
||||
- 范围:仅关联守卫、提示及绑定并发校验,未新增数据库结构或改变其他业务;Scope Drift / Requirement Drift / Assumption Drift 均为 NONE。前序升级 SQL 仍需按部署说明应用,本次无需额外升级。
|
||||
- 本次临时测试源码、编译类、测试报告、编译清单记录及验证日志在完成后清理,保留既有测试文件。
|
||||
@ -432,7 +432,8 @@ public class PurchaseRequestController extends BaseController
|
||||
return success(java.util.Map.of("rows",rows,"batchId",request.getBatchId()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('warehouse:purchase:manage')")
|
||||
/** 批次删除沿用功能权限入口,真实创建者及关联业务条件由服务层持锁复验。 */
|
||||
@PreAuthorize("@ss.hasAnyPermi('warehouse:purchase:remove,warehouse:purchase:manage')")
|
||||
@Log(title = "采购批次", businessType = BusinessType.DELETE)
|
||||
@DeleteMapping("/batch/{id}")
|
||||
public AjaxResult removeBatch(@PathVariable Long id)
|
||||
|
||||
@ -16,6 +16,7 @@ public class AssistantQuotationContext {
|
||||
@Autowired private JdbcTemplate db;
|
||||
@Autowired private PurchaseSheetService sheets;
|
||||
@Autowired private IProjectInfoService projects;
|
||||
/** 仅展开本轮明确指定的有效批次报价上下文,软删除批次不能通过旧编号重新进入操作。 */
|
||||
public List<Map<String,Object>> targets(List<Map<String,Object>> messages) {
|
||||
if(!com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())
|
||||
throw new ServiceException("价格更正请由采购管理员协助办理",403);
|
||||
@ -28,7 +29,7 @@ public class AssistantQuotationContext {
|
||||
if(codes.size()>3)throw new ServiceException("本次涉及多个采购批次,请明确本次要更正的批次后继续");
|
||||
var result=new ArrayList<Map<String,Object>>();
|
||||
for(String code:codes) {
|
||||
var ids=db.queryForList("select id from purchase_batch where batch_no=?",code);
|
||||
var ids=db.queryForList("select id from purchase_batch where batch_no=? and del_flag='0'",code);
|
||||
if(ids.size()!=1)throw new ServiceException("未找到指定采购批次"+code+",请核对编号后继续;不会匹配到其他批次");
|
||||
var sheet=sheets.load(((Number)ids.get(0).get("id")).longValue());
|
||||
// Validate the complete scope before exposing any of its rows to the model.
|
||||
|
||||
@ -1358,6 +1358,7 @@ public class BusinessActionRegistry {
|
||||
private static Field[] prepend(Field field,Field[] rest){List<Field> values=new ArrayList<>();values.add(field);values.addAll(List.of(rest));return values.toArray(Field[]::new);}
|
||||
private static Field[] append(Field[] first,Field field){List<Field> values=new ArrayList<>(List.of(first));values.add(field);return values.toArray(Field[]::new);}
|
||||
|
||||
/** 注册业务引用候选;采购批次仅提供有效记录,避免助手把已删除批次当作新操作目标。 */
|
||||
private void registerReferences() {
|
||||
reference("assistantFile","","name","");
|
||||
reference("dictionaryTypeRecord","select dict_id id,dict_type code,dict_name name,status,update_time updateTime from sys_dict_type","name","system:dict:list,system:dict:query,system:dict:edit,system:dict:remove");
|
||||
@ -1379,7 +1380,7 @@ public class BusinessActionRegistry {
|
||||
reference("notice","select notice_id id,notice_title name,notice_type noticeType,status,update_time updateTime from sys_notice","name","system:notice:list,system:notice:query,system:notice:edit,system:notice:remove");
|
||||
reference("expense","select id,category_code code,category_name name,status,sort_order sortOrder from expense_category","name","project:budget:list,project:budget:edit,project:category:edit,project:project:manage,warehouse:purchase:list,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:import,warehouse:purchase:manage,warehouse:in:list,warehouse:in:add,warehouse:in:edit");
|
||||
reference("budget","select b.id,b.project_id projectId,b.expense_category_id expenseCategoryId,p.project_name name,e.category_name category,b.budget_amount budgetAmount,b.version from project_budget b join project_info p on p.id=b.project_id join expense_category e on e.id=b.expense_category_id","name","project:budget:list,project:budget:edit,project:project:manage");
|
||||
reference("batch","select b.id,b.batch_no code,b.batch_name name,b.supplier_id supplierId,s.name supplierName,b.business_date businessDate,b.purchase_status purchaseStatus from purchase_batch b left join supplier_info s on s.id=b.supplier_id","name","warehouse:purchase:list,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage");
|
||||
reference("batch","select b.id,b.batch_no code,b.batch_name name,b.supplier_id supplierId,s.name supplierName,b.business_date businessDate,b.purchase_status purchaseStatus from purchase_batch b left join supplier_info s on s.id=b.supplier_id where b.del_flag='0'","name","warehouse:purchase:list,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:manage");
|
||||
reference("purchase","select p.id,p.request_no code,p.material_name name,p.material_params spec,p.material_brand brand,p.unit,p.project_id projectId,j.project_name projectName,p.product_id productId,p.quantity,p.purchase_batch_id purchaseBatchId,b.batch_no batchNo,b.batch_name batchName,b.supplier_id supplierId,s.name supplierName,p.final_unit_price finalUnitPrice,p.estimated_unit_price estimatedUnitPrice,p.price_locked priceLocked,p.purchase_status purchaseStatus,p.historical,p.expense_category_id expenseCategoryId,p.purchase_purpose purchasePurpose,p.loan_id loanId,p.production_task_id productionTaskId,p.category,p.purchase_link purchaseLink,p.remark,p.update_time updateTime,coalesce(a.registered,0) registeredQuantity,p.quantity-coalesce(a.registered,0) remainingQuantity from purchase_request p left join project_info j on j.id=p.project_id left join purchase_batch b on b.id=p.purchase_batch_id left join supplier_info s on s.id=b.supplier_id left join(select purchase_request_id,sum(case when acceptance_status=0 then arrival_quantity when acceptance_status=1 then arrival_quantity-defective_quantity-returned_quantity else 0 end) registered from purchase_arrival group by purchase_request_id)a on a.purchase_request_id=p.id where p.del_flag='0'","name","warehouse:purchase:list,warehouse:purchase:query,warehouse:purchase:add,warehouse:purchase:edit,warehouse:purchase:remove,warehouse:purchase:manage");
|
||||
reference("arrival","select a.id,a.arrival_no code,p.material_name name,p.material_params spec,p.unit,p.project_id projectId,j.project_name projectName,p.purchase_batch_no batchNo,a.purchase_request_id purchaseRequestId,a.arrival_quantity arrivalQuantity,a.acceptance_status acceptanceStatus,a.defective_quantity defectiveQuantity,a.returned_quantity returnedQuantity,a.arrival_date arrivalDate,a.remark from purchase_arrival a join purchase_request p on p.id=a.purchase_request_id left join project_info j on j.id=p.project_id","name","warehouse:purchase:list,warehouse:purchase:edit,warehouse:purchase:remove,warehouse:purchase:manage");
|
||||
reference("receipt","select r.id,r.in_no code,i.product_name name,i.spec,i.unit,j.project_name projectName,r.source_project_id projectId,r.product_id productId,r.in_status inStatus,r.in_num quantity,r.receipt_root receiptRoot,r.area_id areaId,r.in_num-coalesce((select sum(c.in_num) from in_record c where c.parent_in_id=r.id and c.in_status=1),0) remainingQuantity from in_record r join product_info i on i.id=r.product_id left join project_info j on j.id=r.source_project_id","name","warehouse:in:list,warehouse:in:query,warehouse:in:confirm");
|
||||
@ -1653,7 +1654,7 @@ public class BusinessActionRegistry {
|
||||
return value instanceof Map<?,?>?"":Objects.toString(value,"");
|
||||
}
|
||||
|
||||
/** Edits are patches to an explicitly identified record, not replacements with invented defaults. */
|
||||
/** 编辑按明确目标读取当前值,不能以旧候选或旧会话继续修改已软删除的采购批次。 */
|
||||
private String existingRecordQuery(String action) {
|
||||
String sql=switch(action) {
|
||||
case "department.update"->"select dept_name deptName,parent_id parentId,order_num orderNum,leader,phone,email,status from sys_dept where dept_id=? and del_flag='0'";
|
||||
@ -1662,7 +1663,7 @@ public class BusinessActionRegistry {
|
||||
case "project.update"->"select project_code projectCode,project_name projectName,project_type projectType,total_amount totalAmount,project_status projectStatus,remark from project_info where id=? and del_flag='0'";
|
||||
case "purchase.update"->"select product_id productId,material_name materialName,material_params materialParams,material_brand materialBrand,unit,category,project_id projectId,expense_category_id expenseCategoryId,purchase_batch_id purchaseBatchId,quantity,final_unit_price finalUnitPrice,purchase_link purchaseLink,purchase_purpose purchasePurpose,loan_id loanId,production_task_id productionTaskId,remark from purchase_request where id=? and del_flag='0'";
|
||||
case "item.update"->"select product_name productName,category,brand,spec,unit,remark from product_info where id=?";
|
||||
case "batch.update"->"select batch_name batchName,supplier_id supplierId,date_format(business_date,'%Y-%m-%d') businessDate,purchase_status purchaseStatus,progress_remark progressRemark from purchase_batch where id=?";
|
||||
case "batch.update"->"select batch_name batchName,supplier_id supplierId,date_format(business_date,'%Y-%m-%d') businessDate,purchase_status purchaseStatus,progress_remark progressRemark from purchase_batch where id=? and del_flag='0'";
|
||||
case "area.update"->"select area_name areaName,cast(status as signed) status,remark from warehouse_area where id=?";
|
||||
case "supplier.save"->"select name,contact,phone,email,remark from supplier_info where id=? and active=1";
|
||||
case "dictionary.update"->"select dict_type dictType,dict_label dictLabel,dict_value dictValue,parent_code parentCode,dict_sort dictSort,status,remark from sys_dict_data where dict_code=?";
|
||||
|
||||
@ -21,12 +21,13 @@ public class PurchaseAcceptanceGenerationService {
|
||||
private final PurchaseAcceptanceReportService reports;private final PurchaseArrivalPhotoService photos;private final PurchaseDocumentService documents;private final JdbcTemplate db;private final ObjectMapper json;
|
||||
public record Input(String requestId,PurchaseAcceptanceReportService.Fields fields) { }
|
||||
public PurchaseAcceptanceGenerationService(PurchaseAcceptanceReportService reports,PurchaseArrivalPhotoService photos,PurchaseDocumentService documents,JdbcTemplate db,ObjectMapper json){this.reports=reports;this.photos=photos;this.documents=documents;this.db=db;this.json=json;}
|
||||
/** 生成并保存验收资料前锁定有效批次,保留原幂等校验,已删除批次不能再生成新资料。 */
|
||||
@Transactional(rollbackFor=Exception.class,isolation=Isolation.READ_COMMITTED)
|
||||
public PurchaseDocumentService.Attachment generate(long id,String version,Input input)throws Exception{
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage")&&!SecurityUtils.hasPermi("warehouse:purchase:edit"))throw new ServiceException("没有采购资料维护权限",403);
|
||||
if(input==null||input.requestId()==null||!input.requestId().matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"))throw new ServiceException("生成请求标识无效,请重新打开验收资料");
|
||||
// 与清单保存、资料上传保持批次→采购明细的锁顺序;验收变更不能穿过生成校验。
|
||||
if(db.queryForList("select id from purchase_batch where id=? for update",id).isEmpty())throw new ServiceException("采购批次不存在");
|
||||
if(db.queryForList("select id from purchase_batch where id=? and del_flag='0' for update",id).isEmpty())throw new ServiceException("采购批次不存在或已删除");
|
||||
db.queryForList("select id from purchase_request where purchase_batch_id=? and del_flag='0' order by id for update",id);
|
||||
var report=reports.export(id,version,input.fields());String fingerprint=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(json.writeValueAsBytes(report)));
|
||||
var previous=db.queryForList("select a.owner_id,cast(a.deleted as signed) deleted,g.target_type,g.target_id,g.document_kind from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where a.id=?",input.requestId());
|
||||
|
||||
@ -17,15 +17,17 @@ import com.ruoyi.warehouse.service.impl.CatalogWriteLock;
|
||||
public class PurchaseBoardService {
|
||||
private final JdbcTemplate db;private final CatalogWriteLock catalog;
|
||||
public PurchaseBoardService(JdbcTemplate db,CatalogWriteLock catalog){this.db=db;this.catalog=catalog;}
|
||||
/** 修改类别前持锁复核有效批次,旧看板页面不能改写软删除批次。 */
|
||||
public AjaxResult changeCategory(long id,Long category,Long expected,PurchaseBatchFundingService funding){
|
||||
catalog.acquire();var rows=db.queryForList("select expense_category_id from purchase_batch where id=? for update",Long.class,id);
|
||||
catalog.acquire();var rows=db.queryForList("select expense_category_id from purchase_batch where id=? and del_flag='0' for update",Long.class,id);
|
||||
if(rows.isEmpty())throw new ServiceException("采购批次不存在");
|
||||
if(!Objects.equals(rows.get(0),expected)&&!Objects.equals(rows.get(0),category))throw new ServiceException("费用类别已被其他人修改,请刷新核对");
|
||||
funding.change(id,category);return AjaxResult.success();
|
||||
}
|
||||
private record Filter(String sql,List<Object> args){}
|
||||
/** 列表、总数和金额汇总共用有效批次过滤,删除后不能以空批次重新出现在看板。 */
|
||||
private Filter filter(PurchaseBatch q){
|
||||
var sql=new StringBuilder(" where 1=1");var args=new ArrayList<Object>();
|
||||
var sql=new StringBuilder(" where b.del_flag='0'");var args=new ArrayList<Object>();
|
||||
if(q.getKeyword()!=null&&!q.getKeyword().isBlank()){if(q.getKeyword().length()>100)throw new ServiceException("搜索内容最多100字");sql.append(" and concat_ws(' ',b.batch_name,b.batch_no,s.name,b.progress_remark) like ?");args.add("%"+q.getKeyword().trim()+"%");}
|
||||
if(q.getProjectId()!=null){sql.append(" and exists(select 1 from purchase_request x where x.purchase_batch_id=b.id and x.del_flag='0' and x.project_id=?)");args.add(q.getProjectId());}
|
||||
if(q.getExpenseCategoryId()!=null){if(q.getExpenseCategoryId()==0)sql.append(" and b.expense_category_id is null");else{sql.append(" and b.expense_category_id=?");args.add(q.getExpenseCategoryId());}}
|
||||
|
||||
@ -18,13 +18,14 @@ import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
class PartialPurchaseConfirmTest {
|
||||
private PurchaseSheetService service;private PurchasePriceService prices;private String version;
|
||||
/** 模拟仍有效的批次持锁读取,验证分项确认不会锁定其他未报价行。 */
|
||||
@BeforeEach void setup(){
|
||||
var user=new SysUser();user.setUserId(1L);user.setUserName("admin");var login=new LoginUser(1L,null,user,Set.of("*:*:*"));SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(login,null));
|
||||
service=new PurchaseSheetService();var batches=mock(PurchaseBatchMapper.class);var requests=mock(PurchaseRequestMapper.class);prices=mock(PurchasePriceService.class);var jdbc=mock(JdbcTemplate.class);
|
||||
var batch=new PurchaseBatch();batch.setId(5L);batch.setSupplierId(8L);batch.setPurchaseStatus(1);batch.setExpenseCategoryId(2L);
|
||||
var quoted=new PurchaseRequest();quoted.setId(10L);quoted.setPurchaseStatus(0);quoted.setFinalUnitPrice(BigDecimal.ONE);
|
||||
var draft=new PurchaseRequest();draft.setId(11L);draft.setPurchaseStatus(0);
|
||||
when(batches.selectPurchaseBatchById(5L)).thenReturn(batch);when(requests.selectPurchaseSheetRows(5L)).thenAnswer(call->new ArrayList<>(List.of(quoted,draft)));when(jdbc.queryForList("select id from purchase_batch where id=? for update",5L)).thenReturn(List.of(Map.of("id",5L)));
|
||||
when(batches.selectPurchaseBatchById(5L)).thenReturn(batch);when(requests.selectPurchaseSheetRows(5L)).thenAnswer(call->new ArrayList<>(List.of(quoted,draft)));when(jdbc.queryForList("select id from purchase_batch where id=? and del_flag='0' for update",5L)).thenReturn(List.of(Map.of("id",5L)));
|
||||
ReflectionTestUtils.setField(service,"batches",batches);ReflectionTestUtils.setField(service,"requests",requests);ReflectionTestUtils.setField(service,"prices",prices);ReflectionTestUtils.setField(service,"suppliers",mock(SupplierService.class));ReflectionTestUtils.setField(service,"purchases",mock(IPurchaseRequestService.class));ReflectionTestUtils.setField(service,"jdbc",jdbc);ReflectionTestUtils.setField(service,"json",new ObjectMapper());version=service.load(5L).getVersion();
|
||||
}
|
||||
@AfterEach void cleanup(){SecurityContextHolder.clearContext();}
|
||||
|
||||
@ -51,12 +51,22 @@ class PurchaseBatchTransferTest {
|
||||
var invalid=f.create();invalid.setBatchId(2L);assertThrows(ServiceException.class,()->f.service.assignPurchaseBatch(invalid));verify(f.batches,never()).insertPurchaseBatch(any());
|
||||
}
|
||||
}
|
||||
@Test void emptyBatchWithDocumentsCannotBeDeletedAndNonEmptyBatchIsProtected(){
|
||||
Fixture f=new Fixture();when(f.batches.selectPurchaseBatchForUpdate(2L)).thenReturn(f.target);
|
||||
try(var security=mockStatic(SecurityUtils.class)){security.when(SecurityUtils::isAdmin).thenReturn(true);
|
||||
when(f.batches.countBatchDocuments(2L)).thenReturn(1);assertThrows(ServiceException.class,()->f.service.deletePurchaseBatchById(2L));verify(f.batches,never()).deletePurchaseBatchById(any());
|
||||
when(f.batches.countBatchDocuments(2L)).thenReturn(0);when(f.batches.countRequestsByBatchId(2L)).thenReturn(1);assertThrows(ServiceException.class,()->f.service.deletePurchaseBatchById(2L));
|
||||
when(f.batches.countRequestsByBatchId(2L)).thenReturn(0);f.service.deletePurchaseBatchById(2L);verify(f.batches).deletePurchaseBatchById(2L);
|
||||
/** 整批软删除允许保留已有附件;非空批次必须经明细删除业务处理,不能留下有效孤儿行。 */
|
||||
@Test void creatorSoftDeletesWholeBatchWithoutRemovingDocuments(){
|
||||
Fixture f=new Fixture();f.target.setCreateBy("owner");
|
||||
var details=mock(com.ruoyi.warehouse.service.IPurchaseRequestService.class);
|
||||
ReflectionTestUtils.setField(f.service,"purchaseRequestService",details);
|
||||
when(f.batches.selectPurchaseBatchForUpdate(2L)).thenReturn(f.target);
|
||||
when(f.batches.countBatchDocuments(2L)).thenReturn(1);
|
||||
when(f.batches.deletePurchaseBatchById(2L)).thenReturn(1);
|
||||
when(f.requests.selectPurchaseRequestIdsByBatchForUpdate(2L)).thenReturn(List.of(10L));
|
||||
try(var security=mockStatic(SecurityUtils.class)){
|
||||
security.when(SecurityUtils::getUsername).thenReturn("owner");
|
||||
security.when(()->SecurityUtils.hasPermi("warehouse:purchase:remove")).thenReturn(true);
|
||||
assertEquals(1,f.service.deletePurchaseBatchById(2L));
|
||||
verify(details).deletePurchaseRequestByIds(new Long[]{10L});
|
||||
verify(f.batches).deletePurchaseBatchById(2L);
|
||||
verify(f.batches,never()).countBatchDocuments(any());
|
||||
}
|
||||
}
|
||||
private static class Fixture{
|
||||
|
||||
@ -10,8 +10,14 @@ import org.apache.ibatis.annotations.Param;
|
||||
public interface PmPurchaseReadMapper {
|
||||
/** 从协作扩展确定原项目,不能将扩展主键用作采购 project_id。 */
|
||||
Long selectSourceProjectId(@Param("projectId") long projectId);
|
||||
/** 批次候选仅包含当前项目有效明细,搜索不扩大项目范围。 */
|
||||
/**
|
||||
* 在绑定事务中按主键顺序锁定有效源批次,使阶段引用保存与整批删除串行。
|
||||
* @param batchIds 已校验且按主键排序的非空批次集合
|
||||
* @return 实际锁定的有效主键;数量不足表示目标不存在或已删除,调用方必须拒绝绑定
|
||||
*/
|
||||
List<Long> selectBatchIdsForUpdate(@Param("batchIds") List<Long> batchIds);
|
||||
/** 批次候选仅包含未删除批次及当前项目有效明细,搜索不扩大项目范围。 */
|
||||
List<Map<String,Object>> selectOptions(@Param("sourceProjectId") long sourceProjectId,@Param("keyword") String keyword);
|
||||
/** 单条 SQL 取得全部关联批次的原项目验收事实;禁用 MyBatis 缓存以建立明确采样点。 */
|
||||
/** 单条 SQL 取得有效关联批次的原项目验收事实;整批删除后不再作为当前交付依据,历史快照保留。 */
|
||||
List<Map<String,Object>> selectLines(@Param("sourceProjectId") long sourceProjectId,@Param("batchIds") List<Long> batchIds);
|
||||
}
|
||||
|
||||
@ -184,14 +184,21 @@ public class PmStageCompletionServiceImpl implements IPmStageCompletionService {
|
||||
/** 仅返回已鉴权项目的批次摘要,选择器搜索不能突破原项目数据范围。 */
|
||||
public List<Map<String,Object>> purchaseOptions(long projectId,long iterationId,String keyword) { locked(projectId,iterationId,"read");if(keyword!=null&&keyword.length()>100)throw PmException.bad("搜索词过长");return purchases.options(projectId,keyword); }
|
||||
|
||||
/** 采购范围可在确认完成前调整;回退复制后首次保存同时确认本轮范围。 */
|
||||
/**
|
||||
* 保存采购阶段本轮的批次范围,沿用阶段维护权限及执行版本校验。
|
||||
* 持锁校验源批次直至范围提交,避免与整批删除竞争产生悬空引用;确认完成后不允许调整。
|
||||
* @param projectId 已鉴权的协作项目主键
|
||||
* @param iterationId 阶段所属迭代
|
||||
* @param stageId 采购阶段主键
|
||||
* @param input 预期执行版本及新批次集合;空集合表示清空范围
|
||||
*/
|
||||
public void batches(long projectId,long iterationId,long stageId,StagePurchaseInput input) {
|
||||
locked(projectId,iterationId,"write");var stage=stage(projectId,iterationId,stageId);maintainerOrManager(stage);
|
||||
if(!"PURCHASE".equals(text(stage,"node_type")))throw PmException.bad("只有采购阶段能绑定批次");
|
||||
var revision=revision(projectId,iterationId,stageId,number(stage,"current_revision_id"));expected(input.revisionId(),input.version(),revision);mutable(graphs.load(projectId,iterationId),stageId);
|
||||
List<Long> ids=input.batchIds()==null?List.of():input.batchIds();
|
||||
if(ids.size()>100||ids.stream().anyMatch(id->id==null||id<=0)||new HashSet<>(ids).size()!=ids.size())throw PmException.bad("批次最多100个,不能重复或为空");
|
||||
Map<String,Object> progress=purchases.readBatches(projectId,ids);
|
||||
Map<String,Object> progress=purchases.readBatchesForUpdate(projectId,ids);
|
||||
for(Object batch:(List<?>)progress.get("batches"))if(!Boolean.TRUE.equals(((Map<?,?>)batch).get("available")))throw PmException.bad("批次不存在或没有当前项目的有效明细");
|
||||
mapper.deleteBatches(number(revision,"id"));long actor=access.actor(),at=PmTime.now();for(Long id:ids)mapper.insertBatch(number(revision,"id"),id,actor,at);
|
||||
update(revision,map("purchase_scope_confirmed",true));revisions.advanceGraphVersion(projectId,iterationId);
|
||||
|
||||
@ -37,6 +37,22 @@ public class PmPurchaseProgressReader {
|
||||
return aggregate(batchIds,lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为保存采购阶段范围锁定源批次,再读取同一份项目验收事实;普通展示继续使用无锁读取。
|
||||
* @param projectId 已鉴权的协作项目主键,明细仍通过原项目校验归属
|
||||
* @param batchIds 已由命令入口校验的唯一有效批次 ID,最多100个,允许清空范围
|
||||
* @return 供绑定前归属检查的采购进度;批次不存在或已删除时抛出冲突
|
||||
* 调用方必须位于绑定事务中,锁需持有到阶段引用提交,不能在单独事务中提前释放。
|
||||
*/
|
||||
public Map<String,Object> readBatchesForUpdate(long projectId,List<Long> batchIds) {
|
||||
if(!batchIds.isEmpty()) {
|
||||
List<Long> ordered=batchIds.stream().sorted().toList();
|
||||
if(source.selectBatchIdsForUpdate(ordered).size()!=ordered.size())
|
||||
throw PmException.conflict("PURCHASE_BATCH_UNAVAILABLE","采购批次不存在或已删除,请刷新后重新选择");
|
||||
}
|
||||
return readBatches(projectId,batchIds);
|
||||
}
|
||||
|
||||
/** 画布按迭代批量采样,查询数不随采购阶段个数增长;同一批次引用不重复读取源数据。 */
|
||||
public Map<Long,Map<String,Object>> readAll(long projectId,long iterationId) {
|
||||
Map<Long,List<Long>> ranges=new LinkedHashMap<>();
|
||||
|
||||
@ -3,10 +3,16 @@
|
||||
<!--suppress SqlNoDataSourceInspection -->
|
||||
<mapper namespace="com.ruoyi.project.manage.mapper.PmPurchaseReadMapper">
|
||||
<select id="selectSourceProjectId" resultType="java.lang.Long">SELECT e.source_project_id FROM pm_collab_project e JOIN project_info p ON p.id=e.source_project_id AND p.del_flag='0' WHERE e.id=#{projectId}</select>
|
||||
<!-- 绑定阶段时先锁源批次,持锁至引用写入提交;删除方也先锁批次再查引用,两者不能同时通过。 -->
|
||||
<select id="selectBatchIdsForUpdate" resultType="java.lang.Long" useCache="false" flushCache="true">
|
||||
SELECT id FROM purchase_batch WHERE del_flag='0' AND id IN
|
||||
<foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
|
||||
ORDER BY id FOR UPDATE
|
||||
</select>
|
||||
<select id="selectOptions" resultType="java.util.LinkedHashMap" useCache="false" flushCache="true">
|
||||
SELECT b.id,b.batch_no AS batchNo,b.batch_name AS batchName,COUNT(*) AS lineCount FROM purchase_batch b
|
||||
JOIN purchase_request r ON r.purchase_batch_id=b.id AND r.project_id=#{sourceProjectId} AND r.del_flag='0'
|
||||
<where><if test="keyword != null and keyword != ''">b.batch_no LIKE CONCAT('%',#{keyword},'%') OR b.batch_name LIKE CONCAT('%',#{keyword},'%')</if></where>
|
||||
<where>b.del_flag='0'<if test="keyword != null and keyword != ''">AND (b.batch_no LIKE CONCAT('%',#{keyword},'%') OR b.batch_name LIKE CONCAT('%',#{keyword},'%'))</if></where>
|
||||
GROUP BY b.id,b.batch_no,b.batch_name ORDER BY b.id DESC LIMIT 200
|
||||
</select>
|
||||
<!-- 与采购明细页口径一致:历史采购视为已验收,普通明细扣除不良和退回;不再叠加入库量。
|
||||
@ -25,7 +31,7 @@
|
||||
AND scope_request.project_id=#{sourceProjectId} AND scope_request.del_flag='0'
|
||||
AND scope_request.purchase_batch_id IN <foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
|
||||
WHERE acceptance_status IN (0,1) GROUP BY purchase_request_id) a ON a.purchase_request_id=r.id
|
||||
WHERE b.id IN <foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
|
||||
WHERE b.del_flag='0' AND b.id IN <foreach collection="batchIds" item="id" open="(" close=")" separator=",">#{id}</foreach>
|
||||
ORDER BY b.id,r.id
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@ -6,22 +6,38 @@ import com.ruoyi.warehouse.domain.PurchaseBatch;
|
||||
|
||||
public interface PurchaseBatchMapper
|
||||
{
|
||||
/** 按列表筛选聚合有效批次及明细;整批软删除后不再返回空批次占位。 */
|
||||
List<PurchaseBatch> selectPurchaseBatchList(PurchaseBatch batch);
|
||||
/** 与列表共用有效批次筛选,确保汇总不计入软删除数据。 */
|
||||
java.util.Map<String, Object> selectPurchaseBatchTotals(PurchaseBatch batch);
|
||||
/** 转批次候选仅返回未删除且处于可接收状态的批次。 */
|
||||
List<PurchaseBatch> selectPurchaseBatchOptions(@Param("keyword") String keyword);
|
||||
/** 筛选候选排除已删除批次,避免旧数据重新成为操作目标。 */
|
||||
List<PurchaseBatch> selectPurchaseBatchFilterOptions(@Param("keyword") String keyword);
|
||||
/** 读取有效批次;软删除的主键按不存在处理,以阻止旧详情继续编辑。 */
|
||||
PurchaseBatch selectPurchaseBatchById(Long id);
|
||||
/** 在调用方事务中锁定有效批次,校验和写入前不复用会话缓存的旧记录。 */
|
||||
PurchaseBatch selectPurchaseBatchForUpdate(Long id);
|
||||
/** 编号查重包含删除批次,保留历史编号和安全重试回执,不能用于判断当前可编辑性。 */
|
||||
PurchaseBatch selectPurchaseBatchByNo(String batchNo);
|
||||
int insertPurchaseBatch(PurchaseBatch batch);
|
||||
/** 条件更新有效批次;返回零时调用方必须停止后续明细同步并回滚。 */
|
||||
int updatePurchaseBatch(PurchaseBatch batch);
|
||||
/** 仅修改有效批次的进度说明,防止删除前打开的编辑框继续改写历史。 */
|
||||
int updateBatchRemark(@Param("id") Long id, @Param("remark") String remark, @Param("username") String username);
|
||||
int countRequestsByBatchId(Long batchId);
|
||||
List<Long> selectBatchProjectIds(Long batchId);
|
||||
int countBatchDocuments(Long batchId);
|
||||
/**
|
||||
* 判断批次及全部明细是否已有下游业务引用;历史、撤销及已软删除明细的引用同样保护。
|
||||
* @param batchId 已由调用方锁定的采购批次主键
|
||||
* @return 有到货、入库、库存、费用台账、历史完成或项目阶段引用时为 true,附件与日志不计入
|
||||
*/
|
||||
boolean hasBatchBusinessReferences(Long batchId);
|
||||
int countRequestsByIds(Long[] requestIds);
|
||||
int assignRequests(@Param("requestIds") Long[] requestIds, @Param("batch") PurchaseBatch batch, @Param("updateBy") String updateBy);
|
||||
int syncRequestBatchNo(@Param("batchId") Long batchId, @Param("batchNo") String batchNo,
|
||||
@Param("updateBy") String updateBy);
|
||||
/** 仅更新删除标记;调用方须持锁完成创建者校验及明细软删除,历史与附件不物理移除。 */
|
||||
int deletePurchaseBatchById(Long id);
|
||||
}
|
||||
|
||||
@ -8,6 +8,8 @@ import com.ruoyi.warehouse.domain.PurchaseTaskSummary;
|
||||
public interface PurchaseRequestMapper
|
||||
{
|
||||
List<PurchaseRequest> selectPurchaseSheetRows(Long batchId);
|
||||
/** 按主键顺序锁定批次有效明细,保证与到货及整单编辑的并发操作串行执行。 */
|
||||
List<Long> selectPurchaseRequestIdsByBatchForUpdate(Long batchId);
|
||||
List<PurchaseRequest> selectPurchaseRequestList(PurchaseRequest purchaseRequest);
|
||||
PurchaseTaskSummary selectPurchaseTaskSummary();
|
||||
PurchaseRequest selectPurchaseRequestById(@Param("id") Long id, @Param("applicantId") Long applicantId);
|
||||
|
||||
@ -68,6 +68,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:import")&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("没有历史补录权限");
|
||||
int rows=insertArrival(arrival,true);var acceptance=new PurchaseArrivalAcceptanceRequest();acceptance.setAcceptanceStatus(1);acceptance.setDefectiveQuantity(BigDecimal.ZERO);acceptArrival(arrival.getId(),acceptance,true);return rows;
|
||||
}
|
||||
/** 沿用库存和采购明细锁登记到货;批次须仍有效,不能给整批删除后的旧明细补录。 */
|
||||
private int insertArrival(PurchaseArrival arrival,boolean historicalImport)
|
||||
{
|
||||
journal.lockInventory();
|
||||
@ -106,7 +107,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
|
||||
throw new ServiceException("已取消的采购申请不能登记到货");
|
||||
}
|
||||
if ((!historicalImport&&!Boolean.TRUE.equals(request.getPriceLocked())) || request.getFinalUnitPrice()==null) throw new ServiceException("请先确认采购并锁定报价,再登记到货");
|
||||
if(request.getPurchaseBatchId()==null || database.queryForObject("select count(*) from purchase_batch where id=? and supplier_id is not null",Long.class,request.getPurchaseBatchId())==0) throw new ServiceException("请先选择供应商并确认采购批次");
|
||||
if(request.getPurchaseBatchId()==null || database.queryForObject("select count(*) from purchase_batch where id=? and del_flag='0' and supplier_id is not null",Long.class,request.getPurchaseBatchId())==0) throw new ServiceException("请先选择有效供应商并确认未删除的采购批次");
|
||||
if (arrival.getArrivalQuantity() == null || arrival.getArrivalQuantity().signum() <= 0 || arrival.getArrivalQuantity().stripTrailingZeros().scale()>4)
|
||||
{
|
||||
throw new ServiceException("到货数量必须大于0");
|
||||
|
||||
@ -18,11 +18,12 @@ public class PurchaseBatchFundingService {
|
||||
private final PurchaseRequestMapper requests;private final PurchasePriceService prices;private final IPurchaseOperationLogService logs;
|
||||
public PurchaseBatchFundingService(JdbcTemplate db,CatalogWriteLock catalog,InventoryCostJournal inventory,PurchaseRequestMapper requests,PurchasePriceService prices,IPurchaseOperationLogService logs){this.db=db;this.catalog=catalog;this.inventory=inventory;this.requests=requests;this.prices=prices;this.logs=logs;}
|
||||
public void validate(Long category){if(category==null||db.queryForList("select id from expense_category where id=? and status=0",category).isEmpty())throw new ServiceException("请在采购批次选择有效的费用类别");}
|
||||
/** 统一调整有效批次的经费归属;与整批删除共用锁,已删除批次不能继续改费用。 */
|
||||
@Transactional
|
||||
public void change(long batch,Long category){
|
||||
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("仅采购批次管理员可统一已保存批次的费用类别",403);
|
||||
validate(category);catalog.acquire();inventory.lockInventory();
|
||||
if(db.queryForList("select id from purchase_batch where id=? for update",batch).isEmpty())throw new ServiceException("采购批次不存在");
|
||||
if(db.queryForList("select id from purchase_batch where id=? and del_flag='0' for update",batch).isEmpty())throw new ServiceException("采购批次不存在或已删除");
|
||||
var ids=db.queryForList("select id from purchase_request where purchase_batch_id=? and del_flag='0' and purchase_status<>5 order by id for update",Long.class,batch);
|
||||
for(Long id:ids){
|
||||
var old=requests.selectPurchaseRequestByIdForUpdate(id);if(Objects.equals(old.getExpenseCategoryId(),category))continue;
|
||||
|
||||
@ -15,6 +15,7 @@ import com.ruoyi.warehouse.mapper.PurchaseBatchMapper;
|
||||
import com.ruoyi.warehouse.mapper.PurchaseRequestMapper;
|
||||
import com.ruoyi.warehouse.service.IPurchaseOperationLogService;
|
||||
import com.ruoyi.warehouse.service.IPurchaseBatchService;
|
||||
import com.ruoyi.warehouse.service.IPurchaseRequestService;
|
||||
|
||||
@Service
|
||||
public class PurchaseBatchServiceImpl implements IPurchaseBatchService
|
||||
@ -31,6 +32,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
|
||||
@Autowired private PurchaseBatchNumber batchNumbers;
|
||||
@Autowired private CatalogWriteLock catalogWriteLock;
|
||||
@Autowired private PurchaseBatchFundingService funding;
|
||||
@Autowired private IPurchaseRequestService purchaseRequestService;
|
||||
|
||||
@Override
|
||||
public List<PurchaseBatch> selectPurchaseBatchList(PurchaseBatch batch)
|
||||
@ -69,6 +71,11 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
|
||||
return purchaseBatchMapper.insertPurchaseBatch(batch);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新有效批次并同步明细中的编号;条件更新失败时终止事务,防止并发删除后继续改写历史明细。
|
||||
* @param batch 经原有管理权限及供应商、费用归属规则校验的批次变更
|
||||
* @return 成功更新的批次数;批次已删除或并发失效时抛出业务异常
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public int updatePurchaseBatch(PurchaseBatch batch)
|
||||
@ -99,6 +106,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
|
||||
String username = SecurityUtils.getUsername();
|
||||
batch.setUpdateBy(username);
|
||||
int rows = purchaseBatchMapper.updatePurchaseBatch(batch);
|
||||
if (rows != 1) throw new ServiceException("采购批次已变化或已删除,请刷新后重试");
|
||||
purchaseBatchMapper.syncRequestBatchNo(batch.getId(), batch.getBatchNo(), username);
|
||||
PurchaseRequest query = new PurchaseRequest();
|
||||
query.setPurchaseBatchId(batch.getId());
|
||||
@ -195,22 +203,38 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
|
||||
return request.getRequestIds().length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 仅由批次创建者整批软删除,保留批次、明细的历史数据和附件。
|
||||
* 目录锁阻止新增/转批次,批次及明细行锁覆盖业务校验和级联删除;任何一步失败均回滚。
|
||||
* 所有下游业务引用(含历史记录)必须先排除;允许删除时复用明细服务保留原审计逻辑,不按明细创建者拆分。
|
||||
* @param id 要删除的采购批次主键,创建者从持锁读取的数据库记录取得
|
||||
* @return 本次标记删除的批次数;不存在、已删除、无权限或已有关联业务时抛出业务异常
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
@Transactional(isolation=org.springframework.transaction.annotation.Isolation.READ_COMMITTED)
|
||||
public int deletePurchaseBatchById(Long id)
|
||||
{
|
||||
checkManager();
|
||||
if (id == null || id <= 0) throw new ServiceException("请选择采购批次");
|
||||
if (!SecurityUtils.hasPermi("warehouse:purchase:remove") && !SecurityUtils.hasPermi("warehouse:purchase:manage"))
|
||||
throw new ServiceException("没有采购删除权限");
|
||||
catalogWriteLock.acquire();
|
||||
if (purchaseBatchMapper.selectPurchaseBatchForUpdate(id) == null)
|
||||
PurchaseBatch batch = purchaseBatchMapper.selectPurchaseBatchForUpdate(id);
|
||||
if (batch == null)
|
||||
{
|
||||
throw new ServiceException("采购批次不存在");
|
||||
throw new ServiceException("采购批次不存在或已删除,请刷新列表");
|
||||
}
|
||||
if (purchaseBatchMapper.countRequestsByBatchId(id) > 0)
|
||||
// 管理角色和系统管理员也不能代替真实创建者;缺失历史创建者时拒绝推断归属。
|
||||
if (StringUtils.isBlank(batch.getCreateBy()) || !batch.getCreateBy().equals(SecurityUtils.getUsername()))
|
||||
throw new ServiceException("只有采购批次的创建者可以删除");
|
||||
List<Long> requestIds = purchaseRequestMapper.selectPurchaseRequestIdsByBatchForUpdate(id);
|
||||
if (purchaseBatchMapper.hasBatchBusinessReferences(id))
|
||||
{
|
||||
throw new ServiceException("该批次仍有关联的采购申请,不能删除");
|
||||
throw new ServiceException("该批次已有关联的到货、验收、入库、库存、费用台账、历史业务或项目流程记录,禁止删除");
|
||||
}
|
||||
if(purchaseBatchMapper.countBatchDocuments(id)>0)throw new ServiceException("该空批次仍有附件或流程编号,请保留批次用于追溯,不会自动删除");
|
||||
return purchaseBatchMapper.deletePurchaseBatchById(id);
|
||||
if (!requestIds.isEmpty()) purchaseRequestService.deletePurchaseRequestByIds(requestIds.toArray(Long[]::new));
|
||||
int rows = purchaseBatchMapper.deletePurchaseBatchById(id);
|
||||
if (rows != 1) throw new ServiceException("采购批次已变化,删除未完成,请刷新后重试");
|
||||
return rows;
|
||||
}
|
||||
|
||||
private void validateSupplier(List<PurchaseRequest> rows,PurchaseBatch batch){
|
||||
|
||||
@ -153,11 +153,17 @@ public class PurchaseDocumentService {
|
||||
return db.queryForObject("select id from purchase_document_group where target_type=? and target_id=? and document_kind=?", Long.class, type, targetId, kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验资料所属批次或明细;读取允许保留的历史资料,写入持锁且只允许未删除业务。
|
||||
* @param type 经白名单校验的资料层级,batch 表示批次,detail 表示明细
|
||||
* @param id 资料所属业务记录主键,软删除不会清除该历史引用
|
||||
* @param lock 是否为资料修改操作,避免旧上传窗口在整批删除后继续新增或变更附件
|
||||
*/
|
||||
private void requireTarget(String type, Long id, boolean lock) {
|
||||
kinds(type);
|
||||
if (id == null || id <= 0) throw new ServiceException("请先保存采购批次或明细,再上传附件");
|
||||
String table = "batch".equals(type) ? "purchase_batch" : "purchase_request";
|
||||
if (db.queryForList("select id from " + table + " where id=?" + (lock ? " for update" : ""), id).isEmpty()) throw new ServiceException("采购批次或明细不存在,请刷新页面");
|
||||
if (db.queryForList("select id from " + table + " where id=?" + (lock ? " and del_flag='0' for update" : ""), id).isEmpty()) throw new ServiceException("采购批次或明细不存在或已删除,请刷新页面");
|
||||
}
|
||||
|
||||
static Map<String, String> kinds(String type) {
|
||||
|
||||
@ -602,6 +602,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
purchaseRequestMapper.updatePurchaseStatus(id,accepted.compareTo(active)>=0?4:accepted.signum()>0?3:2,existing.getProgressRemark(),SecurityUtils.getUsername());
|
||||
purchaseOperationLogService.record(id,existing.getRequestNo(),"CANCEL_REMAINING","取消未到货部分","取消数量:"+existing.getQuantity().subtract(active)+";原因:"+reason);return changed;
|
||||
}
|
||||
/** 校验有效项目及批次的统一经费科目,禁止直接接口把新明细挂到软删除批次。 */
|
||||
private void resolveFunding(PurchaseRequest request)
|
||||
{
|
||||
ProjectInfo project = null;
|
||||
@ -621,7 +622,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
|
||||
|
||||
ExpenseCategory category = null;
|
||||
if(request.getPurchaseBatchId()!=null){
|
||||
var batchCategories=taskDatabase.queryForList("select expense_category_id from purchase_batch where id=?",Long.class,request.getPurchaseBatchId());
|
||||
var batchCategories=taskDatabase.queryForList("select expense_category_id from purchase_batch where id=? and del_flag='0'",Long.class,request.getPurchaseBatchId());
|
||||
if(batchCategories.isEmpty()||batchCategories.get(0)==null)throw new ServiceException("请先在采购批次统一费用类别");
|
||||
if(request.getExpenseCategoryId()!=null&&!java.util.Objects.equals(request.getExpenseCategoryId(),batchCategories.get(0)))throw new ServiceException("费用类别已按批次管理,请在采购看板统一整批费用类别");
|
||||
request.setExpenseCategoryId(batchCategories.get(0));
|
||||
|
||||
@ -482,8 +482,9 @@ public class PurchaseSheetService
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
|
||||
} catch (Exception e) { throw new IllegalStateException("Cannot version purchase batch", e); }
|
||||
}
|
||||
/** 持锁确认批次仍有效,防止旧清单继续保存、确认或向软删除批次写入明细。 */
|
||||
private void lockBatch(Long id) {
|
||||
if (jdbc.queryForList("select id from purchase_batch where id=? for update", id).isEmpty()) throw new ServiceException("采购批次不存在");
|
||||
if (jdbc.queryForList("select id from purchase_batch where id=? and del_flag='0' for update", id).isEmpty()) throw new ServiceException("采购批次不存在或已删除");
|
||||
}
|
||||
private void requirePermission(String action) {
|
||||
if (!SecurityUtils.isAdmin() && !SecurityUtils.hasPermi("warehouse:purchase:manage")
|
||||
|
||||
@ -44,6 +44,7 @@
|
||||
<if test="params.amountDisplay == true">and (not exists(select 1 from sys_config adc where adc.config_key='wms.display.compactAmounts' and adc.config_value='true') or pr.final_unit_price is null or pr.final_unit_price<>0)</if>
|
||||
left join project_info pj on pj.id=pr.project_id
|
||||
<where>
|
||||
pb.del_flag='0'
|
||||
<if test="onlyMine == true">
|
||||
and exists(select 1 from purchase_request mine where mine.purchase_batch_id=pb.id and mine.del_flag='0' and mine.create_by=#{createBy}
|
||||
<if test="projectId != null">and mine.project_id=#{projectId}</if>
|
||||
@ -75,7 +76,7 @@
|
||||
pb.create_by, pb.create_time, pb.update_by, pb.update_time,
|
||||
(select count(*) from purchase_request pr where pr.purchase_batch_id = pb.id) as request_count
|
||||
from purchase_batch pb
|
||||
where pb.purchase_status in (1, 2)
|
||||
where pb.del_flag='0' and pb.purchase_status in (1, 2)
|
||||
<if test="keyword != null and keyword != ''">
|
||||
and (pb.batch_no like concat('%', #{keyword}, '%') or pb.batch_name like concat('%', #{keyword}, '%'))
|
||||
</if>
|
||||
@ -89,6 +90,7 @@
|
||||
(select count(*) from purchase_request pr where pr.purchase_batch_id = pb.id) as request_count
|
||||
from purchase_batch pb
|
||||
<where>
|
||||
pb.del_flag='0'
|
||||
<if test="keyword != null and keyword != ''">
|
||||
and (pb.batch_no like concat('%', #{keyword}, '%') or pb.batch_name like concat('%', #{keyword}, '%'))
|
||||
</if>
|
||||
@ -99,26 +101,27 @@
|
||||
|
||||
<select id="selectPurchaseBatchById" parameterType="Long" resultMap="PurchaseBatchResult">
|
||||
select id,expense_category_id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
|
||||
from purchase_batch where id = #{id}
|
||||
from purchase_batch where id = #{id} and del_flag='0'
|
||||
</select>
|
||||
|
||||
<select id="selectPurchaseBatchByNo" parameterType="String" resultMap="PurchaseBatchResult">
|
||||
<!-- 编号查重包含已删除批次,保留唯一性及原保存回执,不能重用历史编号。 -->
|
||||
select id,expense_category_id,supplier_id,business_date, batch_no, batch_name, purchase_status, progress_remark, create_by, create_time, update_by, update_time
|
||||
from purchase_batch where batch_no = #{batchNo} limit 1
|
||||
</select>
|
||||
|
||||
<select id="selectPurchaseBatchForUpdate" resultMap="PurchaseBatchResult">select * from purchase_batch where id=#{id} for update</select>
|
||||
<select id="selectPurchaseBatchForUpdate" resultMap="PurchaseBatchResult" flushCache="true" useCache="false">select * from purchase_batch where id=#{id} and del_flag='0' for update</select>
|
||||
<insert id="insertPurchaseBatch" parameterType="PurchaseBatch" useGeneratedKeys="true" keyProperty="id">
|
||||
insert into purchase_batch(batch_no, batch_name, purchase_status, progress_remark, create_by, create_time,supplier_id,business_date,expense_category_id)
|
||||
values(#{batchNo}, #{batchName}, #{purchaseStatus}, #{progressRemark}, #{createBy}, sysdate(),#{supplierId},#{businessDate},#{expenseCategoryId})
|
||||
</insert>
|
||||
|
||||
<update id="updateBatchRemark">update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id}</update>
|
||||
<update id="updateBatchRemark">update purchase_batch set progress_remark=#{remark}, update_by=#{username}, update_time=sysdate() where id=#{id} and del_flag='0'</update>
|
||||
<update id="updatePurchaseBatch" parameterType="PurchaseBatch">
|
||||
update purchase_batch
|
||||
set supplier_id=#{supplierId},business_date=#{businessDate}, batch_no = #{batchNo}, batch_name = #{batchName}, purchase_status = #{purchaseStatus},
|
||||
expense_category_id=#{expenseCategoryId}, progress_remark = #{progressRemark}, update_by = #{updateBy}, update_time = sysdate()
|
||||
where id = #{id}
|
||||
where id = #{id} and del_flag='0'
|
||||
</update>
|
||||
|
||||
<select id="countRequestsByBatchId" parameterType="Long" resultType="int">
|
||||
@ -136,6 +139,20 @@
|
||||
select count(*) from purchase_document_group g where g.target_type='batch' and g.target_id=#{batchId}
|
||||
and (coalesce(trim(g.document_no),'')<>'' or exists(select 1 from purchase_document_attachment a where a.group_id=g.id and a.deleted=0))
|
||||
</select>
|
||||
<!-- 只判断存在性,不统计所有关联数量。不能按数量、业务状态或明细 del_flag 排除历史引用;
|
||||
全退、拒收及撤销后也有业务记录。退货由其不可缺少的来源到货记录一并保护。
|
||||
阶段引用独立检查,因此空批次仍可被保护;附件、操作日志和编号不作为下游业务。 -->
|
||||
<select id="hasBatchBusinessReferences" resultType="boolean" flushCache="true" useCache="false">
|
||||
select case when
|
||||
exists(select 1 from pm_collab_stage_purchase_batch b where b.purchase_batch_id=#{batchId})
|
||||
or exists(select 1 from purchase_request r where r.purchase_batch_id=#{batchId} and (
|
||||
r.historical=1
|
||||
or exists(select 1 from purchase_arrival a where a.purchase_request_id=r.id)
|
||||
or exists(select 1 from in_record i where i.purchase_request_id=r.id)
|
||||
or exists(select 1 from stock_lot l where l.purchase_request_id=r.id)
|
||||
or exists(select 1 from purchase_price_ledger p where p.purchase_request_id=r.id)
|
||||
)) then 1 else 0 end
|
||||
</select>
|
||||
|
||||
<update id="assignRequests">
|
||||
update purchase_request
|
||||
@ -151,7 +168,8 @@
|
||||
where purchase_batch_id = #{batchId}
|
||||
</update>
|
||||
|
||||
<delete id="deletePurchaseBatchById" parameterType="Long">
|
||||
delete from purchase_batch where id = #{id}
|
||||
</delete>
|
||||
<!-- 服务层仅允许创建者操作,因此当前删除账号等于 create_by;不清空附件或任何历史外键。 -->
|
||||
<update id="deletePurchaseBatchById" parameterType="Long">
|
||||
update purchase_batch set del_flag='2',update_by=create_by,update_time=current_timestamp where id=#{id} and del_flag='0'
|
||||
</update>
|
||||
</mapper>
|
||||
|
||||
@ -105,6 +105,9 @@
|
||||
<select id="selectPurchaseSheetRows" resultMap="PurchaseRequestResult" flushCache="true" useCache="false">
|
||||
<include refid="selectPurchaseRequestVo"/> where pr.purchase_batch_id=#{batchId} and pr.del_flag='0' order by pr.id
|
||||
</select>
|
||||
<select id="selectPurchaseRequestIdsByBatchForUpdate" resultType="java.lang.Long" flushCache="true" useCache="false">
|
||||
select id from purchase_request where purchase_batch_id=#{batchId} and del_flag='0' order by id for update
|
||||
</select>
|
||||
<select id="selectPurchaseRequestList" parameterType="PurchaseRequest" resultMap="PurchaseRequestResult">
|
||||
<include refid="selectPurchaseRequestVo"/>
|
||||
<where>
|
||||
|
||||
@ -43,7 +43,7 @@
|
||||
</el-popover><span v-else :title="s.row.progressRemark">{{ s.row.progressRemark || '—' }}</span>
|
||||
</template></el-table-column>
|
||||
<el-table-column label="进度" width="110" align="center" class-name="business-status-cell"><template #default="s"><el-tag size="small" :type="(batchProgress(s.row).type) || 'primary'">{{ batchProgress(s.row).label }}</el-tag></template></el-table-column>
|
||||
<el-table-column label="操作" width="125" align="center" fixed="right" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" size="small" @click="openBatch(s.row)">打开</el-button><el-dropdown v-if="(s.row.arrivableCount>0 && s.row.supplierId) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" trigger="click" @command="batchArrival(s.row)" ><el-button link type="primary" size="small">更多<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu ><el-dropdown-item command="arrival">登记到货</el-dropdown-item></el-dropdown-menu></template></el-dropdown></template></el-table-column>
|
||||
<el-table-column label="操作" width="165" align="center" fixed="right" class-name="business-operation-cell"><template #default="s"><el-button link type="primary" size="small" :disabled="saving||deletingBatchId!==null" @click="openBatch(s.row)">打开</el-button><el-button v-if="canDeleteBatch(s.row)" link type="danger" size="small" :loading="deletingBatchId===s.row.id" :disabled="saving||deletingBatchId!==null" @click.stop="deleteBatch(s.row)">删除</el-button><el-dropdown v-if="(s.row.arrivableCount>0 && s.row.supplierId) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" trigger="click" :disabled="saving||deletingBatchId!==null" @command="batchArrival(s.row)" ><el-button link type="primary" size="small">更多<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu ><el-dropdown-item command="arrival">登记到货</el-dropdown-item></el-dropdown-menu></template></el-dropdown></template></el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
<div v-if="total && summary" class="batch-summary">筛选结果汇总:<span v-if="!compactAmounts">实际金额 {{ summary.actualTotalAmount == null ? '—' : '¥ ' + money(summary.actualTotalAmount) }}</span><span v-if="canViewQuotes">报价金额 ¥ {{ money(summary.totalAmount) }}<span v-if="summary.unpricedCount">({{ summary.unpricedCount }} 项未报价)</span></span></div>
|
||||
@ -90,7 +90,7 @@
|
||||
</el-form>
|
||||
|
||||
<el-alert v-if="moveOutcome&&!isEditing" type="success" :closable="false" class="mb8"><template #title>明细已转入目标批次,原报价、确认、到货和入库记录保留。</template><el-button link type="primary" @click="viewMoveTarget">查看目标批次</el-button></el-alert>
|
||||
<el-alert v-if="sheet.batch.id&&!sheet.rows.length" type="info" :closable="false" class="mb8"><template #title>这是空批次,默认保留。批次附件和流程编号不会随明细移动;有资料请保留用于追溯。</template><el-button link type="primary" :disabled="saving||isEditing" @click="deleteEmptyBatch">删除无资料的空批次</el-button></el-alert>
|
||||
<el-alert v-if="sheet.batch.id&&!sheet.rows.length" type="info" :closable="false" class="mb8"><template #title>这是空批次,可保留用于追溯。删除仅隐藏批次,历史、附件和流程编号仍然保留。</template><el-button v-if="canDeleteBatch(sheet.batch)" link type="danger" :disabled="saving||isEditing||deletingBatchId!==null" @click="deleteEmptyBatch">删除空批次</el-button></el-alert>
|
||||
<el-alert v-if="sheet.submissionKey && !saving" class="sheet-save-notice" type="warning" :closable="false" show-icon>
|
||||
<template #title>上次保存结果未确认。原内容可直接重试;修改前建议先核对保存结果。</template>
|
||||
<el-button link type="primary" @click="recoverSubmission">核对上次保存</el-button>
|
||||
@ -214,7 +214,8 @@ export default {
|
||||
setup(){const tableStage=ref(null),{height:gridHeight}=useContentHeight(tableStage),app=useAppStore();return {tableStage,gridHeight,pasteIssues:ref([]),cellSelection:ref(null),density:computed(()=>app.size),changedKeys:ref(new Set()),headerDirty:ref(false),structureDirty:ref(false),virtualStart:ref(0),virtualRowHeight:ref(40)}},
|
||||
name:'PurchaseBatchSheet', props:{projectId:Number,embedded:Boolean},
|
||||
components:{BatchCategory,ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')),PurchaseCell,PriceCorrection,HistoryCorrection,PurchaseDocuments,SupplierQuotation,PastePreview,PurchaseLookup:defineAsyncComponent(()=>import('./Lookup')),SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),BatchArrival:defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')),CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')),ExcelImportDialog:defineAsyncComponent(()=>import('@/components/ExcelImportDialog'))},
|
||||
data(){return {batchDetailsOpen:false,rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,onlyMine:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,remarkRowId:null,remarkDraft:'',remarkSaving:false,batches:[],total:0,summary:null,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
|
||||
/** 删除确认单独跟踪占用状态,避免确认期间重复操作;批次数据仍以服务端结果为准。 */
|
||||
data(){return {batchDetailsOpen:false,rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,onlyMine:false,viewMode:'batches',loading:true,creating:false,saving:false,deletingBatchId:null,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,remarkRowId:null,remarkDraft:'',remarkSaving:false,batches:[],total:0,summary:null,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
|
||||
computed:{
|
||||
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
|
||||
canViewQuotes(){const user=this.$store.getters;return canViewPurchaseQuotes(user.userId,user.roles)},
|
||||
@ -330,7 +331,39 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
async searchMove(keyword){const source=this.sheet?.batch.id;return runLatest(this,'moveBatches',()=>listPurchaseBatch({pageNum:1,pageSize:100,keyword}),{start:()=>{this.moveLoading=true},success:r=>{if(source!==this.sheet?.batch.id)return;const project=this.projectName(this.selected[0]?.projectId);this.moveBatches=(r.rows||[]).filter(b=>b.id!==source&&![4,5].includes(Number(b.purchaseStatus))&&(!b.projectNames||b.projectNames===project)&&(!this.moveSupplierLocked||String(b.supplierId)===String(this.sheet.batch.supplierId)))},finish:()=>{this.moveLoading=false}})},
|
||||
async moveRows(){if(!this.canMoveSelection||this.saving||(this.moveMode==='existing'&&!this.moveBatchId))return;this.saving=true;this.moveAttempted=true;this._moveRequest||={requestIds:this.selected.map(r=>r.id),requestKey:this._moveKey,...(this.moveMode==='new'?{newBatch:{...this.moveNew}}:{batchId:this.moveBatchId})};try{const result=await assignPurchaseBatch(this._moveRequest);const target=result.data?.batchId||this.moveBatchId;this.moveOpen=false;await this.openBatch(this.sheet.batch);this.moveOutcome=target;this.$modal.msgSuccess('已转批次,业务状态和历史记录未改变')}finally{this.saving=false}},
|
||||
async viewMoveTarget(){const id=this.moveOutcome;if(!id||this.saving)return;this.moveOutcome=null;if(!this.embedded&&this.$route.path==='/procurement/details'&&String(this.$route.query.purchaseBatchId)===String(id)){await this.openBatch({id});return}await this.$router.push({path:'/procurement/details',query:{purchaseBatchId:String(id)}})},
|
||||
async deleteEmptyBatch(){if(this.saving||this.isEditing||!this.sheet?.batch.id||this.sheet.rows.length)return;try{await this.$confirm('仅删除当前空批次编号。有附件或流程编号时后台会阻止删除;原明细和业务历史不会删除。','删除空批次',{type:'warning',confirmButtonText:'确认删除',cancelButtonText:'保留批次'});this.saving=true;await delPurchaseBatch(this.sheet.batch.id);this.clearDraft(this.draftId());this.sheet=null;this.editing=false;this.baseline='';this.moveOutcome=null;await this.loadBatches();this.$modal.msgSuccess('空批次已删除')}catch{}finally{this.saving=false}},
|
||||
/** 只比较批次真实创建账号;管理角色不代替创建者,缺失账号或创建者时不开放入口。 */
|
||||
canDeleteBatch(row){const username=this.$store.getters.name;return !!row?.id&&typeof username==='string'&&username.length>0&&row.createBy===username&&this.$auth.hasPermiOr(['warehouse:purchase:remove','warehouse:purchase:manage'])},
|
||||
/**
|
||||
* 确认后整批软删除并刷新列表;对话框期间即占用行操作,避免重复确认和提交。
|
||||
* @param row 要删除的批次摘要;确认后再次核对当前账号,真实归属仍由后端持锁复验
|
||||
* 删除成功才清理本机草稿及旧详情定位;失败保留原行,历史和附件不在前端删除。
|
||||
*/
|
||||
async deleteBatch(row){
|
||||
if(!this.canDeleteBatch(row)||this.saving||this.loading||this.deletingBatchId!=null)return
|
||||
const id=row.id
|
||||
this.deletingBatchId=id
|
||||
try{
|
||||
try{await this.$confirm(`确认删除采购批次“${row.batchName||row.batchNo||id}”(${row.batchNo||id})及其全部采购明细?删除后从业务列表隐藏,历史记录和附件保留。存在到货、验收、入库、库存、费用台账或项目流程引用等业务记录时,禁止删除。`,'删除采购批次',{type:'warning',closeOnClickModal:false,confirmButtonText:'确认删除',cancelButtonText:'取消'})}catch{return}
|
||||
if(!this.canDeleteBatch(row))return
|
||||
this.saving=true
|
||||
try{
|
||||
await delPurchaseBatch(id)
|
||||
this._sheetSequence=(this._sheetSequence||0)+1
|
||||
this.clearDraft(id)
|
||||
if(String(this.sheet?.batch?.id)===String(id)){this.sheet=null;this.editing=false;this.baseline='';this.moveOutcome=null}
|
||||
if(String(this.$route?.query?.purchaseBatchId)===String(id)){
|
||||
const query={...this.$route.query};delete query.purchaseBatchId
|
||||
await this.$router.replace({path:this.$route.path,query})
|
||||
}
|
||||
if(this.batches.length===1&&this.query.pageNum>1)this.query.pageNum--
|
||||
this.$modal.msgSuccess('采购批次及其明细已删除,历史和附件保留')
|
||||
await this.loadBatches()
|
||||
}catch{/* 请求层展示失败原因;不移除原行或清理失败批次的草稿。 */}
|
||||
finally{this.saving=false}
|
||||
}finally{this.deletingBatchId=null}
|
||||
},
|
||||
/** 空批次入口复用相同确认及创建者规则,避免已有详情页绕过列表权限。 */
|
||||
async deleteEmptyBatch(){if(this.isEditing||!this.sheet?.batch.id||this.sheet.rows.length)return;await this.deleteBatch(this.sheet.batch)},
|
||||
async loadLoans(row){
|
||||
const requests=this._loanRequests||(this._loanRequests=new Map()),request={projectId:row.projectId,itemId:row.productId}
|
||||
requests.set(row._key,request)
|
||||
@ -464,7 +497,8 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
|
||||
search(){this.query.pageNum=1;this.loadBatches()},resetQuery(){this.resetForm('query');this.query.projectId=this.projectId;this.queryDates=[];this.search()},
|
||||
emptyRow(){return {_key:'new-'+Date.now()+'-'+Math.random(),id:null,projectId:this.projectId||(this.sheet&&!this.sheet.unbatched?this.batchProject.value:this.commonProject)||null,expenseCategoryId:(!this.sheet?.unbatched?this.sheet?.batch?.expenseCategoryId:null)||this.commonCategory||null,materialName:'',materialBrand:'',materialParams:'',productId:null,productCode:null,unit:'',category:'',quantity:1,finalUnitPrice:null,actualUnitPrice:null,purchaseLink:'',remark:'',purchasePurpose:'SELF',productionTaskId:null,purchaseStatus:0}},
|
||||
async create(unbatched=false){return createPurchaseDraft(this,unbatched)},
|
||||
async openBatch(batch){const seq=this._sheetSequence=(this._sheetSequence||0)+1;this.loading=true;try{await loadAmountDisplay();const result=(await getPurchaseSheet(batch.id)).data;if(seq===this._sheetSequence)this.install(result)}finally{if(seq===this._sheetSequence)this.loading=false}},
|
||||
/** 删除期间阻止打开旧详情;其余保存流程仍可刷新清单,例如转批次成功后的重新读取。 */
|
||||
async openBatch(batch){if(this.deletingBatchId!=null)return;const seq=this._sheetSequence=(this._sheetSequence||0)+1;this.loading=true;try{await loadAmountDisplay();const result=(await getPurchaseSheet(batch.id)).data;if(seq===this._sheetSequence)this.install(result)}finally{if(seq===this._sheetSequence)this.loading=false}},
|
||||
install(sheet){const view=String(this.sheet?.batch?.id)===String(sheet.batch?.id)?{queue:this.rowQueue,sort:this.rowSort,keyword:this.rowFilter}:{queue:'all',sort:'original',keyword:''};sheet.submissionKey=null;sheet.rows=sheet.rows.map(r=>({...this.emptyRow(),...r,_key:'saved-'+r.id}));sheet.deletedIds=[];this.sheet=sheet;this.editCell=null;this.validationEnabled=false;this.onlyInvalid=false;this.baseline=this.serialize(sheet);this.editing=false;this.rowQueue=view.queue;this.rowSort=view.sort;this.rowFilter=view.keyword;this.viewSnapshot=null;this.mergeItems(sheet.rows.map(r=>({id:r.productId,productCode:r.productCode,productName:r.materialName,brand:r.materialBrand,spec:r.materialParams,unit:r.unit,category:r.category})).filter(r=>r.id));this.history=[];this.selected=[];this.commonProject=null;const categoryIds=[...new Set(sheet.rows.map(r=>r.expenseCategoryId).filter(Boolean))];this.commonCategory=categoryIds.length===1?categoryIds[0]:(this.categories.find(c=>c.categoryCode==='MATERIAL')||this.categories[0]||{}).id;this._activeCell=null;this.refreshDrafts?.();this.layout()},
|
||||
startEditing(){if(!this.canEdit || this.saving)return;this._editor.reset();this.cellSelection=null;this.snapshotView();this.editing=true;this.editCell=null;this._activeCell=null},
|
||||
async cancelEditing(){
|
||||
|
||||
@ -59,6 +59,7 @@ manage/
|
||||
流程画布的共享布局方案、数据边界、接口和验证记录见 [流程共享布局](docs/shared-flow-layout.md)。节点坐标、分区和排版结果按项目、迭代共用,仅由迭代创建者维护;节点生成、连线、框选/多选及分组也限定该创建者,其他成员(含其他项目管理者)只读数据库布局。阶段组父子关系、执行连线及回退记录继续由现有业务表保存。流程视图不再恢复或写入浏览器缓存,旧流程缓存直接清理;所有成员可临时平移、缩放、展开折叠及查看详情,浏览动作不保存。页面刷新或显式重新加载成功后恢复数据库坐标、统一展开及默认视口,后台静默同步保留当前浏览状态。
|
||||
|
||||
- 阶段节点展示已有描述的两行摘要,完整说明在阶段抽屉查看;拖入新阶段时可填写描述。
|
||||
- 所有成员单击阶段节点(含阶段组、子阶段和数量区域)仅临时选中,双击才打开详情;单击空白取消选中。历史版本、审批、编辑及折叠等明确操作按钮保留单击行为,选择不保存到数据库或浏览器缓存;普通成员仍不能框选、多选或修改布局。
|
||||
- 采购当前执行版本记录实际开始后即放行直接下游,蓝色连线标注“开始即放行”;采购仍须验收及人工确认才算完成。绿色表示真实完成,历史沿用保持琥珀色;多条入边须全部满足,阶段组仍须全部子阶段完成。详情展示服务端完整准入条件(含继承门禁),排期分别标示采购开始至开始、其他执行边结束至开始边界。
|
||||
- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发、测试和自定义,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。自定义类型按普通工作阶段要求交付齐备后提审,不支持承载子阶段。
|
||||
- 节点分类创建后固定,名称、负责人和说明可编辑;只有阶段组承载子阶段,其余分类沿用工作阶段规则。组内快捷创建可在提交前选择工作分类;复制迭代保留来源分类,回退换版沿用同一节点身份。
|
||||
|
||||
@ -7,10 +7,10 @@
|
||||
用户已明确继续由迭代创建者统一维护画布,RCS 100、RRS 55,无待确认业务歧义;本次仅收紧画布选择/配置入口并修正显式重载,不修改阶段/工作项其他权限,不修改或清空已有数据库布局,不需要数据库结构变更。
|
||||
|
||||
- FR-001:仅有效项目成员中的迭代创建者可维护节点位置、分区、框选/多选、对齐和分组;节点生成、执行连线及阶段组结构仍由该创建者配置。布局读取当前迭代 `createdBy` 与服务端 `layout.canEdit` 双重判断,节点生成/连线也核对当前账号与创建者,防止切换账号沿用旧摘要。后端在项目锁内核验迭代真实 `created_by`,项目管理者或系统管理员均无身份绕过。归档、结束、取消仍只读。
|
||||
- FR-002:其他成员不可框选、多选或鼠标/键盘拖动节点,不得提交布局;直接 PUT 同样拒绝且不得改变布局内容/版本。接收只读快照时丢弃未授权草稿、结束旧拖动/框选并清空节点及连线的选中高亮,恢复平移;不能用旧交互阻塞数据库刷新或触发离页保存。
|
||||
- FR-002:其他成员可单击临时选中一个阶段,但不可框选、多选或鼠标/键盘拖动节点,不得提交布局;直接 PUT 同样拒绝且不得改变布局内容/版本。从可编辑切换只读时丢弃未授权草稿、结束旧拖动/框选并清空原选区,恢复平移,随后仍可单选浏览;不能用旧交互阻塞数据库刷新或触发离页保存。
|
||||
- FR-003:数据库为布局唯一来源,停止所有流程视图 localStorage/sessionStorage 读写;仅移除 `pm-flow-view:` 和 `pm-flow-personal:` 前缀的旧键,不读取或迁移其内容,不影响登录信息及其他模块缓存。缩放、折叠与辅助开关仅在当前组件内临时生效,重进页面不恢复缓存。
|
||||
- FR-004:创建者当前未保存修改仍保留现有串行保存、版本冲突保护及网络失败重试;按用户/项目/迭代隔离的会话内未确认草稿只允许同一迭代创建者恢复,不作为已保存数据库布局。非创建者不恢复此类草稿。
|
||||
- FR-005:所有成员可平移、缩放、适应画布、展开/折叠及查看阶段详情,这些浏览动作不提交布局。数据库没有个人折叠或视口字段,页面重新挂载统一展开并使用默认视口;显式“重新加载共享布局”仅在确实应用原可见范围的数据库快照后重置浏览状态,失败或过期响应保留当前浏览状态。后台静默同步仍保留本页浏览状态。
|
||||
- FR-005:所有成员可单击选中阶段、双击打开详情,以及平移、缩放、适应画布、展开/折叠,这些浏览动作不提交布局。数据库没有个人选中、折叠或视口字段,页面重新挂载统一展开并使用默认视口;显式“重新加载共享布局”仅在确实应用原可见范围的数据库快照后重置浏览状态,失败或过期响应保留当前浏览状态。后台静默同步仍保留本页浏览状态。
|
||||
- AC-001:创建者保存后切换非创建者、刷新或模拟旧缓存,显示数据库坐标和分区,PUT 调用为0。
|
||||
- AC-002:非创建者(含其他管理者)的鼠标、方向键、自动布局、分区修改和直接 API 无法改库;创建者在不再担任项目管理者但仍是有效成员时仍可维护可写迭代布局。
|
||||
- AC-003:锁后身份/成员/生命周期复查、并发版本保护和创建者新草稿队列继续有效;缓存不可访问时仍正常从数据库加载。
|
||||
@ -42,6 +42,16 @@ FR-001 至 FR-004、AC-001 至 AC-003:PASS。Scope Drift、Requirement Drift
|
||||
|
||||
本轮未执行真实数据库事务/通知/MinIO或完整浏览器原生D3指针交互联调;专项是实际Vue组件运行验证,不等同于真实浏览器端到端验收。本轮21个临时测试、快照、计划、配置、class及日志文件和两个空目录已按精确清单清理,不保留临时执行入口。FR-001至FR-005及对应AC通过;Scope Drift、Requirement Drift、Assumption Drift均为NONE。
|
||||
|
||||
### 节点单击与双击交互(2026-11-06)
|
||||
|
||||
本轮为明确的前端交互调整,RCS 100、RRS 12,按 Normal Mode 执行;范围仅流程画布、阶段摘要组件及说明,不变更后端、数据库或布局维护资格。
|
||||
|
||||
- 阶段、阶段组、子阶段及数量区域单击仅选中,双击才打开对应当前版本详情;单击空白取消选择。按钮继续执行各自明确动作,按钮或连接点双击不误开详情,节点双击不再触发画布缩放。
|
||||
- 普通成员仅获得临时单选高亮,背景框选、多选键、拖动、连线及布局保存仍受迭代创建者门禁控制;静默重建保留选择,但选择不进入数据库或浏览器缓存。
|
||||
- 前端专项13项通过,使用真实 WorkFlow、Vue Flow、Element Plus和详情抽屉,Axios仅替换外部传输;覆盖创建者与成员、阶段组和子阶段、数量区域、按钮防误触、缩放、取消选择、静默更新和只读写入边界。先复现原单击打开及只读无法单选,再调整实现并验证通过。
|
||||
- 严格`vue-tsc`(含未使用声明检查)、`npm run build:prod`生产构建通过。整仓`npm test`中单元351/351通过,运行382项、62个文件通过;既有`app-release.spec.js`仍因引用缺失的`@/views/system/file/AppRelease.vue`无法加载,命令整体退出1,未扩展范围修改该系统模块。
|
||||
- 新增/修改方法的中文说明和只读选择注释已核对,独立只读审查未发现问题;仅进行组件运行验证,未执行原生浏览器端到端测试。专项测试、专用配置及日志等7个临时文件和空目录已清理,不保留临时执行入口。需求与验收符合,Scope Drift、Requirement Drift、Assumption Drift均为NONE。
|
||||
|
||||
## 数据及接口契约
|
||||
|
||||
- 新表 `pm_collab_flow_layout`,主键 `(project_id, iteration_id)`,复合外键指向现有迭代表;`layout_json`、独立 `version`、`updated_by`、`updated_at` 全部带中文注释。安装 SQL 同步增加,新环境及已有环境分别适用;升级为 025,仅新增此表,不删除旧表或业务数据。
|
||||
@ -56,7 +66,7 @@ FR-001 至 FR-004、AC-001 至 AC-003:PASS。Scope Drift、Requirement Drift
|
||||
- 数据库坐标为唯一共享来源;初始布局使用确定性的完整展开布局计算,避免个人折叠导致默认位置不同。缺少位置的新增节点采用相同规则补位。旧本机节点/分区/个人浏览缓存直接清理,不读取、不导入、不上报。
|
||||
- 所有成员的缩放/平移、展开折叠均为当前组件临时状态;创建者的框选高亮、辅助开关及辅助线也不持久化,不读写任何本地键。浏览动作不触发布局写入,框选后的实际排版则保存结果坐标。
|
||||
- 迭代创建者拖动结束、对齐/等距、自动布局及分区增删改/缩放后自动保存,约500ms合并;同一页面只允许一个在途写入,期间的新草稿在成功后用新版本继续串行提交。折叠隐藏节点的位置仍须保留,不可被部分可见画布覆盖。
|
||||
- 非创建者成员可缩放、平移、折叠、查看详情,但禁用框选/多选、拖动、自动布局、分区编辑、排版及鼠标/键盘绕过;项目或系统管理身份不例外,服务端再次鉴权。失权时同时清理 Vue Flow 选区及高亮,不能仅设置全局 selectable。
|
||||
- 非创建者成员可单选阶段、双击查看详情、缩放、平移、折叠,但禁用框选/多选、拖动、自动布局、分区编辑、排版及鼠标/键盘绕过;项目或系统管理身份不例外,服务端再次鉴权。失权时同时清理 Vue Flow 原选区及高亮,不能仅设置全局 selectable。单选通过节点级 selectable 开放,背景框选及多选键仍由全局创建者能力控制。
|
||||
- 显示加载、待保存、保存中、已保存及失败状态。瞬时失败保留草稿,可重试;版本/结构冲突明确提示,并由用户选择重新加载共享布局,不能将过期草稿自动套用新版本。无失败假成功提示。
|
||||
- 可编辑的创建者未保存/保存中或正在交互时不应用旧轮询快照;保存成功后若本地已有新编辑,不用旧响应覆盖草稿。非创建者及服务端只读快照放弃未授权草稿,数据库更新不得被旧草稿阻塞。接收新版本时保留当前组件视口、折叠及选区,不重开抽屉。离页请求不能写入另一个项目/迭代。
|
||||
- 后端返回的 canEdit 与前端当前迭代 createdBy 共同控制编辑能力,不能依赖项目管理角色;新建阶段后坐标须等最新阶段摘要到达才能保存,避免尚未加载的节点身份被错误拒绝。
|
||||
|
||||
@ -17,7 +17,7 @@
|
||||
<el-button v-if="selectedNodes.length" size="small" :disabled="!canEditLayout || busy || selectedNodes.some(node => !!node.parentNode) || sections.length >= 200" @click="createSelectionSection">选区设为分区</el-button>
|
||||
<span v-if="selectedNodes.length" class="flow-help">已选 {{ selectedNodes.length }} 个节点{{ sameScope ? '' : '(不同层级)' }}</span>
|
||||
</div>
|
||||
<div class="flow-tools"><span class="flow-help">{{ !canEditLayout ? '可平移、缩放及展开折叠;仅迭代创建者可编辑画布,刷新后统一展开' : canvasMode === 'section' ? '在空白处拖框创建分区;拖动分区标题栏可整体移动' : canvasMode === 'select' ? '拖框或点击选择节点;Ctrl / ⌘ 可加选;空格可平移' : '拖动平移;Shift 拖框 / Ctrl 或 ⌘ 点击多选;成员共享节点位置与分区' }}</span><el-button v-if="canManageStages" size="small" @click="stageOpen = true">管理阶段</el-button></div>
|
||||
<div class="flow-tools"><span class="flow-help">{{ !canEditLayout ? '单击选中、双击查看详情;可平移、缩放及展开折叠;仅迭代创建者可编辑画布' : canvasMode === 'section' ? '在空白处拖框创建分区;拖动分区标题栏可整体移动' : canvasMode === 'select' ? '拖框或单击选中、双击查看详情;Ctrl / ⌘ 可加选;空格可平移' : '单击选中、双击查看详情;拖动平移;Shift 拖框 / Ctrl 或 ⌘ 点击多选' }}</span><el-button v-if="canManageStages" size="small" @click="stageOpen = true">管理阶段</el-button></div>
|
||||
</div>
|
||||
<div class="flow-layout-status" role="status" aria-live="polite">
|
||||
<span :class="{ 'layout-error': layoutFailure }">{{ layoutStatus }}</span>
|
||||
@ -33,7 +33,7 @@
|
||||
:nodes-connectable="canConfigureStages && !busy && canvasMode !== 'section'" :edges-updatable="false" :nodes-draggable="canEditLayout && !busy && canvasMode !== 'section'"
|
||||
:elements-selectable="canEditLayout" :select-nodes-on-drag="canEditLayout" :selection-key-code="canEditLayout ? canvasMode === 'select' ? true : 'Shift' : null" :multi-selection-key-code="canEditLayout ? ['Control', 'Meta'] : null"
|
||||
:selection-mode="SelectionMode.Full" :pan-on-drag="canvasMode === 'pan' ? true : [1, 2]" :node-drag-threshold="3" :elevate-nodes-on-select="false"
|
||||
@connect="connectStages" @edge-click="edgeClicked" @node-click="selectNode" @node-drag-start="dragStarted" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport" @selection-start="selectionStarted" @selection-end="selecting = false">
|
||||
@connect="connectStages" @edge-click="edgeClicked" @node-double-click="openNodeDetails" @node-drag-start="dragStarted" @node-drag="nodeDragged" @node-drag-stop="dragStopped" @move-end="viewportMoved" @nodes-initialized="restoreViewport" @selection-start="selectionStarted" @selection-end="selecting = false">
|
||||
<Background :gap="22" :size="1" pattern-color="var(--el-border-color)" />
|
||||
<MiniMap pannable zoomable :node-color="minimapColor" node-stroke-color="var(--el-color-primary-light-3)" mask-color="var(--el-mask-color-extra-light)" />
|
||||
<Controls :show-interactive="false" />
|
||||
@ -172,18 +172,19 @@ watch(() => props.canManage, allowed => { if (!allowed) reworkSourceId.value = n
|
||||
/** 离开页签关闭抽屉并暂存当前组件视口;不读写浏览器缓存,也不凭旧定位重开审批。 */
|
||||
watch(() => props.active, async active => { if (active) { await nextTick(); await restoreViewport() } else { drawerStageId.value = null; drawerEditing.value = false; draftViewport.value = { ...viewport.value } } })
|
||||
|
||||
/** 按数据库坐标重建子画布;只为有布局资格者保留选区,配置与原有业务权限分别传给节点。 */
|
||||
/** 按数据库坐标重建子画布并保留临时选中;成员可单选阶段,但分区选择及结构修改仍需布局资格。 */
|
||||
function rebuild() {
|
||||
if (dragging.value) return
|
||||
const { layout: _layout, ...businessView } = props.view
|
||||
const signature = JSON.stringify([businessView, positions.value, sections.value, collapsedStages.value, props.canCreate, props.canManage, canConfigureStages.value, canEditLayout.value])
|
||||
if (signature === lastGraphSignature) return
|
||||
lastGraphSignature = signature
|
||||
const selected = new Set(canEditLayout.value ? getNodes.value.filter(node => node.selected).map(node => node.id) : [])
|
||||
const selected = new Set(getNodes.value.filter(node => node.selected && (canEditLayout.value || node.type !== 'section')).map(node => node.id))
|
||||
const graph = buildFlowGraph(props.view, positions.value, collapsedStages.value)
|
||||
for (const node of graph.nodes) if (node.data) { node.data.canWrite = props.canCreate; node.data.canManage = props.canManage; node.data.canConfigureStages = canConfigureStages.value; node.data.deleteBlockedReason = node.data.stage ? stageDeleteBlockedReason(node.data.stage, props.view.stages) : ''; node.connectable = !!node.data.stage && canConfigureStages.value }
|
||||
for (const edge of graph.edges) edge.selectable = canEditLayout.value && canConfigureStages.value && edge.data?.kind !== 'rework'
|
||||
nodes.value = [...canvasTools.sectionNodes(), ...graph.nodes].map(node => ({ ...node, selectable: canEditLayout.value, selected: selected.has(node.id) })); edges.value = graph.edges
|
||||
// 节点级 selectable 仅放开单选高亮;全局框选、修饰键多选、拖动和保存仍受创建者门禁控制。
|
||||
nodes.value = [...canvasTools.sectionNodes(), ...graph.nodes].map(node => ({ ...node, selectable: canEditLayout.value || node.type !== 'section', selected: selected.has(node.id) })); edges.value = graph.edges
|
||||
}
|
||||
/**
|
||||
* 工具按钮与合成点击共用创建者门禁;切换前结束旧框选,成员始终保留平移模式。
|
||||
@ -279,10 +280,16 @@ async function fitAll() {
|
||||
draftViewport.value = { ...viewport.value }
|
||||
} finally { movingProgrammatically = false }
|
||||
}
|
||||
/** 框选模式及修饰键点击只选节点,避免多选时误开抽屉;普通单击仍打开阶段详情。 */
|
||||
function selectNode(event: NodeMouseEvent) {
|
||||
/**
|
||||
* 双击阶段正文才打开详情,单击交由 Vue Flow 选中,避免选中或多选时意外弹出抽屉。
|
||||
* @param event 节点双击事件;操作按钮、连接点及修饰键双击不重复触发详情
|
||||
* @remarks 阻止节点双击继续冒泡给画布缩放;不会改变布局或保存选中状态。
|
||||
*/
|
||||
function openNodeDetails(event: NodeMouseEvent) {
|
||||
const mouse = event.event as MouseEvent
|
||||
if (canvasMode.value !== 'pan' || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey) return
|
||||
mouse.stopPropagation()
|
||||
if (!props.active || dragging.value || canvasMode.value === 'section' || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey) return
|
||||
if (mouse.target instanceof Element && mouse.target.closest('button, a, input, textarea, select, [role="button"], .vue-flow__handle')) return
|
||||
if (event.node.type === 'stage' || event.node.type === 'group') openDrawer(Number(event.node.id.slice(2)), 'current')
|
||||
}
|
||||
/** 当前或历史版本共用同一阶段抽屉,零号虚拟节点只展示未分配当前工作项。 */
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<Handle v-if="data.stage" id="in" type="target" :position="Position.Left" :connectable="!!data.canConfigureStages" :style="{ top: '42px' }" />
|
||||
<header class="stage-drag"><span class="phase-dot"></span><span v-if="data.stage" class="stage-type">{{ stageNodeTypeLabel(data.stage) }}</span><span class="stage-title"><strong :title="data.title">{{ data.title }}</strong><button v-if="data.stage?.canEditStage === true" type="button" class="nodrag nopan node-action" aria-label="修改阶段名称" :title="renameBlockedReason || '修改阶段名称'" :disabled="!!renameBlockedReason || !!data.busy" @pointerdown.stop @mousedown.stop @click.stop="emit('rename', data.stageId!)"><EditPen /></button></span><span v-if="data.stage?.isCurrent" class="stage-current">当前</span><button v-if="data.stage?.stageKind === 'GROUP'" class="nodrag stage-toggle" @click.stop="emit('toggle', data.stageId!)">{{ data.collapsed ? '展开' : '折叠' }}</button><span v-if="data.stage" class="stage-version">v{{ data.stage.revisionNo || 1 }}</span><button v-if="data.stage && data.canConfigureStages" type="button" class="nodrag nopan node-action node-delete" aria-label="删除阶段" :title="String(data.deleteBlockedReason || '删除空阶段')" :disabled="!!data.deleteBlockedReason || !!data.busy" @pointerdown.stop @mousedown.stop @click.stop="emit('remove', data.stageId!)"><Delete /></button></header>
|
||||
<p v-if="data.stage" class="phase-description" :class="{ empty: !data.stage.description?.trim() }" :title="data.stage.description || '未填写阶段描述'">{{ data.stage.description || '未填写阶段描述' }}</p>
|
||||
<div class="phase-body"><button class="nodrag stage-items" :title="data.stage ? `发起人:${data.stage.creatorName || '#' + data.stage.creatorId};负责人:${data.stage.ownerName || '未设置'}。点击查看交付与审批。` : '查看工作项'" @click.stop="emit('view', data.stageId!)">{{ data.stage?.nodeType === 'PURCHASE' ? `${data.stage.purchaseBatchCount || 0} 个批次 · ${data.stage.purchaseProgress || 0}%` : `${data.itemCount || 0} 个工作项` }}</button><span v-if="data.stage" class="stage-status" :title="appearance.description">{{ appearance.label }}</span></div>
|
||||
<div class="phase-body"><span class="stage-items" :title="data.stage ? `发起人:${data.stage.creatorName || '#' + data.stage.creatorId};负责人:${data.stage.ownerName || '未设置'}。双击节点查看交付与审批。` : '双击节点查看工作项'">{{ data.stage?.nodeType === 'PURCHASE' ? `${data.stage.purchaseBatchCount || 0} 个批次 · ${data.stage.purchaseProgress || 0}%` : `${data.itemCount || 0} 个工作项` }}</span><span v-if="data.stage" class="stage-status" :title="appearance.description">{{ appearance.label }}</span></div>
|
||||
<div v-if="data.stage" class="phase-plan" :class="{ warning: data.stage.scheduleReviewRequired || data.stage.overdue }" :title="planLabel(data.stage)">{{ planLabel(data.stage) }}</div>
|
||||
<div v-if="data.stage?.stageKind === 'GROUP'" class="group-summary">子阶段 {{ data.stage.completedChildStageCount || 0 }}/{{ data.stage.childStageCount || 0 }} 已完成 · 内部排期{{ data.stage.subtreeScheduleValidationStatus === 'VALID' ? '完整' : '待完善' }}</div>
|
||||
<div v-if="data.stage" class="phase-actions"><button v-if="data.canConfigureStages && data.stage.canCreateChildStage" class="nodrag stage-create" @click.stop="emit('createChild', data.stageId!)">+ 子阶段</button><button v-if="data.canWrite && data.stage.canCreateWorkItem" class="nodrag stage-create" @click.stop="emit('create', data.stageId!)">新建</button><button v-if="data.stage.canApproveCompletion || data.stage.canSubmitCompletion || data.stage.canConfirmPurchase" class="nodrag" @click.stop="emit('view', data.stageId!)">{{ data.stage.canApproveCompletion ? '审批' : data.stage.canConfirmPurchase ? '确认完成' : '提审' }}</button><button class="nodrag stage-history" @click.stop="emit('history', data.stageId!)">历史版本</button><button v-if="data.canManage && data.stage.canRework" class="nodrag stage-rework" @click.stop="emit('rework', data.stageId!)">回退</button></div>
|
||||
|
||||
19
sql/projectdev/20261106_purchase_batch_soft_delete.sql
Normal file
19
sql/projectdev/20261106_purchase_batch_soft_delete.sql
Normal file
@ -0,0 +1,19 @@
|
||||
-- 采购批次整批软删除:仅新增删除标记及索引,不删除或改写既有业务数据。
|
||||
-- 新版代码启动前执行;正常批次默认0,整批删除后为2,附件及历史引用原样保留。
|
||||
SET @batch_delete_schema = DATABASE();
|
||||
SET @batch_delete_ddl = IF(
|
||||
EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@batch_delete_schema AND TABLE_NAME='purchase_batch' AND COLUMN_NAME='del_flag'),
|
||||
'SELECT 1',
|
||||
'ALTER TABLE purchase_batch ADD COLUMN del_flag CHAR(1) NOT NULL DEFAULT ''0'' COMMENT ''删除标记:0正常,2整批软删除;历史和附件保留'''
|
||||
);
|
||||
PREPARE batch_delete_upgrade FROM @batch_delete_ddl;
|
||||
EXECUTE batch_delete_upgrade;
|
||||
DEALLOCATE PREPARE batch_delete_upgrade;
|
||||
SET @batch_delete_ddl = IF(
|
||||
EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=@batch_delete_schema AND TABLE_NAME='purchase_batch' AND INDEX_NAME='idx_purchase_batch_active'),
|
||||
'SELECT 1',
|
||||
'ALTER TABLE purchase_batch ADD INDEX idx_purchase_batch_active (del_flag,id)'
|
||||
);
|
||||
PREPARE batch_delete_upgrade FROM @batch_delete_ddl;
|
||||
EXECUTE batch_delete_upgrade;
|
||||
DEALLOCATE PREPARE batch_delete_upgrade;
|
||||
@ -7,12 +7,14 @@ create table if not exists purchase_batch (
|
||||
batch_name varchar(200) default null comment '采购批次名称',
|
||||
purchase_status tinyint(1) not null default 1 comment '批次状态:1规划中 2执行中 3已结束 4已归档 5已取消',
|
||||
progress_remark varchar(500) default null comment '进度说明',
|
||||
del_flag char(1) not null default '0' comment '删除标记:0正常,2整批软删除;历史和附件保留',
|
||||
create_by varchar(64) default null comment '创建人',
|
||||
create_time datetime default null comment '创建时间',
|
||||
update_by varchar(64) default null comment '更新人',
|
||||
update_time datetime default null comment '更新时间',
|
||||
primary key (id),
|
||||
unique key uk_purchase_batch_no (batch_no)
|
||||
unique key uk_purchase_batch_no (batch_no),
|
||||
key idx_purchase_batch_active (del_flag,id)
|
||||
) engine=innodb default charset=utf8mb4 comment='采购批次表';
|
||||
|
||||
alter table purchase_batch modify column purchase_status tinyint(1) not null default 1
|
||||
|
||||
Loading…
Reference in New Issue
Block a user