Merge remote-tracking branch 'origin/project' into project

# Conflicts:
#	ruoyi-admin/src/main/java/com/ruoyi/web/service/warehouse/PurchaseAcceptanceGenerationService.java
#	ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchFundingService.java
#	ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseBatchServiceImpl.java
#	ruoyi-system/src/main/java/com/ruoyi/warehouse/service/impl/PurchaseDocumentService.java
#	ruoyi-system/src/main/resources/mapper/warehouse/PurchaseBatchMapper.xml
#	ruoyi-ui-vue3/src/components/PurchaseSheet/index.vue
This commit is contained in:
lixiaolong 2026-11-09 11:34:13 +08:00
commit bd1393fc0f
29 changed files with 284 additions and 179 deletions

View 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 仍需按部署说明应用,本次无需额外升级。
- 本次临时测试源码、编译类、测试报告、编译清单记录及验证日志在完成后清理,保留既有测试文件。

View File

@ -439,7 +439,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)

View File

@ -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.

View File

@ -1360,6 +1360,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");
@ -1381,7 +1382,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");
@ -1655,7 +1656,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'";
@ -1664,7 +1665,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,actual_unit_price actualUnitPrice,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=?";

View File

@ -26,9 +26,7 @@ public class PurchaseAcceptanceGenerationService {
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("生成请求标识无效,请重新打开验收资料");
// 与清单保存、资料上传保持批次→采购明细的锁顺序;验收变更不能穿过生成校验。
var owners=db.queryForList("select id,create_by from purchase_batch where id=? for update",id);
if(owners.isEmpty())throw new ServiceException("采购批次不存在");
if(!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以生成批次验收资料",403);
if(db.queryForList("select id from purchase_batch where id=? 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());
@ -37,14 +35,14 @@ public class PurchaseAcceptanceGenerationService {
if(((Number)p.get("owner_id")).longValue()!=SecurityUtils.getUserId()||((Number)p.get("deleted")).intValue()!=0||!"batch".equals(p.get("target_type"))||((Number)p.get("target_id")).longValue()!=id||!"ACCEPTANCE".equals(p.get("document_kind")))throw new ServiceException("生成请求已失效,请重新打开验收资料");
var file=documents.content("batch",id,input.requestId());
try(var pdf=Loader.loadPDF(file.bytes())){if(!fingerprint.equals(pdf.getDocumentInformation().getCustomMetadataValue("CMVR-Acceptance-Fingerprint")))throw new ServiceException("本次生成内容已变化,请重新生成");}
return new PurchaseDocumentService.Attachment(input.requestId(),file.name(),file.contentType(),file.bytes().length,SecurityUtils.getUsername(),null,true);
return new PurchaseDocumentService.Attachment(input.requestId(),file.name(),file.contentType(),file.bytes().length,SecurityUtils.getUsername(),null);
}
var temporary=Files.createTempFile("purchase-acceptance-",".pdf");
try{
try(var output=Files.newOutputStream(temporary)){PurchaseAcceptancePdf.write(report,photoId->photos.content(photoId).bytes(),output,fingerprint);}
if(Files.size(temporary)>10L*1024*1024)throw new ServiceException("生成的验收资料超过单个附件10 MB限制,请联系管理员处理");
byte[] bytes=Files.readAllBytes(temporary);String label=report.batchName().replaceAll("[\\\\/:*?\"<>|\\p{Cntrl}]","_");if(label.length()>120)label=label.substring(0,120);
return documents.uploadGenerated("batch",id,"ACCEPTANCE",input.requestId(),new GeneratedFile(label+"_验收资料_待签章.pdf",bytes));
return documents.upload("batch",id,"ACCEPTANCE",input.requestId(),new GeneratedFile(label+"_验收资料_待签章.pdf",bytes));
}finally{Files.deleteIfExists(temporary);}
}
private record GeneratedFile(String name,byte[] bytes) implements MultipartFile {

View File

@ -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());}}

View File

@ -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();}

View File

@ -53,12 +53,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{

View File

@ -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);
}

View File

@ -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);

View File

@ -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<>();

View File

@ -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>

View File

@ -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);
}

View File

@ -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);

View File

@ -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();
@ -108,7 +109,7 @@ public class PurchaseArrivalServiceImpl implements IPurchaseArrivalService
}
if(!historicalImport&&PurchaseArrivalPhotoService.ids(arrival.getPhotoIds()).isEmpty())throw new ServiceException("登记到货至少需要1张照片,请先上传到货照片");
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");

View File

@ -20,11 +20,9 @@ public class PurchaseBatchFundingService {
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")&&!SecurityUtils.hasPermi("warehouse:purchase:edit"))throw new ServiceException("仅采购批次管理员可统一已保存批次的费用类别",403);
if(!SecurityUtils.isAdmin()&&!SecurityUtils.hasPermi("warehouse:purchase:manage"))throw new ServiceException("仅采购批次管理员可统一已保存批次的费用类别",403);
validate(category);catalog.acquire();inventory.lockInventory();
var owners=db.queryForList("select create_by from purchase_batch where id=? for update",batch);
if(owners.isEmpty())throw new ServiceException("采购批次不存在");
if(!com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)owners.get(0).get("create_by"),null))throw new ServiceException("仅批次创建人、采购管理员或超级管理员可以统一费用类别",403);
if(db.queryForList("select id from purchase_batch where id=? 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;

View File

@ -31,7 +31,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
@Autowired private PurchaseBatchNumber batchNumbers;
@Autowired private CatalogWriteLock catalogWriteLock;
@Autowired private PurchaseBatchFundingService funding;
@Autowired private org.springframework.context.ApplicationEventPublisher liveEvents;
@Override
public List<PurchaseBatch> selectPurchaseBatchList(PurchaseBatch batch)
@ -80,7 +79,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
{
throw new ServiceException("采购批次不存在");
}
com.ruoyi.warehouse.util.PurchaseDataAccess.require(existing);
if(batch.getExpenseCategoryId()==null)batch.setExpenseCategoryId(existing.getExpenseCategoryId());
if(!java.util.Objects.equals(existing.getExpenseCategoryId(),batch.getExpenseCategoryId()))funding.change(batch.getId(),batch.getExpenseCategoryId());
if (existing.getSupplierId() != null && !java.util.Objects.equals(existing.getSupplierId(), batch.getSupplierId())) {
@ -111,7 +109,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
+ ";状态:" + batchStatusText(existing.getPurchaseStatus()) + " → "
+ batchStatusText(batch.getPurchaseStatus()));
}
if(liveEvents!=null)liveEvents.publishEvent(new com.ruoyi.warehouse.domain.PurchaseSheetChanged(batch.getId(),null));
return rows;
}
@ -147,7 +144,7 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
// projection only after its lock has been acquired and the session cache flushed.
if(row!=null)row=purchaseRequestMapper.selectPurchaseRequestById(requestId,null);
if(row==null||Integer.valueOf(5).equals(row.getPurchaseStatus()))throw new ServiceException("已取消或不存在的采购不能转批次");
com.ruoyi.warehouse.util.PurchaseDataAccess.require(row);requests.add(row);
requests.add(row);
}
var projects=requests.stream().map(PurchaseRequest::getProjectId).collect(java.util.stream.Collectors.toSet());
if(projects.size()!=1||projects.contains(null))throw new ServiceException("一批采购对应一个项目,请按项目分别转批次");
@ -175,7 +172,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
}else{
batch=purchaseBatchMapper.selectPurchaseBatchById(request.getBatchId());
if(batch==null)throw new ServiceException("目标采购批次不存在");
com.ruoyi.warehouse.util.PurchaseDataAccess.require(batch);
if(Integer.valueOf(4).equals(batch.getPurchaseStatus())||Integer.valueOf(5).equals(batch.getPurchaseStatus()))throw new ServiceException("目标批次已归档或取消,请选择其他批次");
if(requests.stream().anyMatch(row->java.util.Objects.equals(row.getPurchaseBatchId(),batch.getId())))throw new ServiceException("所选明细已在目标批次,无需转入");
if(purchaseBatchMapper.selectBatchProjectIds(batch.getId()).stream().anyMatch(id->!projects.contains(id)))throw new ServiceException("目标批次属于其他项目,请选择同项目批次或新建批次");
@ -196,9 +192,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(),
"BATCH_ASSIGN", "分配采购批次", "批次:" + previous + " → " + batchDisplay(batch)+";仅调整归组,确认状态、报价、费用及到货入库关联不变");
}
// Moving a row invalidates both rooms, including the room it has just left.
batchIds.add(batch.getId());
if(liveEvents!=null)for(Long id:batchIds)liveEvents.publishEvent(new com.ruoyi.warehouse.domain.PurchaseSheetChanged(id,null));
return request.getRequestIds().length;
}
@ -212,7 +205,6 @@ public class PurchaseBatchServiceImpl implements IPurchaseBatchService
{
throw new ServiceException("采购批次不存在");
}
com.ruoyi.warehouse.util.PurchaseDataAccess.require(purchaseBatchMapper.selectPurchaseBatchById(id));
if (purchaseBatchMapper.countRequestsByBatchId(id) > 0)
{
throw new ServiceException("该批次仍有关联的采购申请,不能删除");

View File

@ -35,18 +35,14 @@ public class PurchaseDocumentService {
@Autowired private com.ruoyi.common.storage.BusinessFileStorage storage;
@Value("${purchase.documents-path:}") private String configuredPath;
public record Attachment(String id,String name,String contentType,int size,String uploadedBy,String uploadedAt,boolean serverGenerated) {
public Attachment(String id,String name,String contentType,int size,String uploadedBy,String uploadedAt){this(id,name,contentType,size,uploadedBy,uploadedAt,false);}
}
public record Group(String kind, String label, String number, int version, List<Attachment> files, boolean editable) {
public Group(String kind,String label,String number,int version,List<Attachment> files){this(kind,label,number,version,files,false);}
}
public record Attachment(String id, String name, String contentType, int size, String uploadedBy, String uploadedAt) { }
public record Group(String kind, String label, String number, int version, List<Attachment> files) { }
public record Content(byte[] bytes, String name, String contentType, boolean previewable) { }
public record Validated(byte[] bytes, String type) { }
@Transactional(readOnly = true)
public List<Group> list(String type, Long targetId) {
requirePermission(false); boolean editable=requireTarget(type, targetId, false);
requirePermission(false); requireTarget(type, targetId, false);
List<Group> result = new ArrayList<>();
for (var kind : kinds(type).entrySet()) {
var groups = db.queryForList("select id,document_no,version from purchase_document_group where target_type=? and target_id=? and document_kind=?", type, targetId, kind.getKey());
@ -58,11 +54,11 @@ public class PurchaseDocumentService {
// 合并展示历史报价附件,保留原归属与报价访问门禁;报价编号不再展示或维护。
if("REQUEST".equals(kind.getKey())&&com.ruoyi.warehouse.util.PurchaseQuoteAccess.allowed())
for(var legacy:db.queryForList("select id from purchase_document_group where target_type=? and target_id=? and document_kind='QUOTE'",type,targetId))attachments.addAll(files(legacy.get("id")));
result.add(new Group(kind.getKey(),kind.getValue(),number,version,List.copyOf(attachments),editable));
result.add(new Group(kind.getKey(),kind.getValue(),number,version,List.copyOf(attachments)));
}
return result;
}
private List<Attachment> files(Object group){return db.query("select id,original_name,content_type,byte_size,create_by,create_time,server_generated from purchase_document_attachment where group_id=? and deleted=0 order by create_time desc,id desc",(r,n)->new Attachment(r.getString(1),r.getString(2),r.getString(3),r.getInt(4),r.getString(5),r.getString(6),r.getBoolean(7)),group);}
private List<Attachment> files(Object group){return db.query("select id,original_name,content_type,byte_size,create_by,create_time from purchase_document_attachment where group_id=? and deleted=0 order by create_time desc,id",(r,n)->new Attachment(r.getString(1),r.getString(2),r.getString(3),r.getInt(4),r.getString(5),r.getString(6)),group);}
@Transactional
public void saveNumber(String type, Long targetId, String kind, String number, Integer version) {
@ -78,9 +74,7 @@ public class PurchaseDocumentService {
}
@Transactional
public Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file) {return upload(type,targetId,kind,uploadId,file,false);}
@Transactional public Attachment uploadGenerated(String type,Long targetId,String kind,String uploadId,MultipartFile file){return upload(type,targetId,kind,uploadId,file,true);}
private Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file,boolean generated) {
public Attachment upload(String type, Long targetId, String kind, String uploadId, MultipartFile file) {
requirePermission(true); requireKind(type, kind); requireId(uploadId);
if (file == null || file.isEmpty() || file.getSize() > MAX_BYTES) throw new ServiceException("请上传不超过10 MB的附件");
String name = safeName(file.getOriginalFilename());
@ -96,13 +90,13 @@ public class PurchaseDocumentService {
String sha = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(valid.bytes()));
requireTarget(type, targetId, true);
long group = ensureGroup(type, targetId, kind);
var prior = db.queryForList("select group_id,owner_id,sha256,original_name,content_type,byte_size,deleted,server_generated from purchase_document_attachment where id=?", uploadId);
var prior = db.queryForList("select group_id,owner_id,sha256,original_name,content_type,byte_size,deleted from purchase_document_attachment where id=?", uploadId);
if (!prior.isEmpty()) {
var row = prior.get(0);
if (((Number) row.get("group_id")).longValue() != group || ((Number) row.get("owner_id")).longValue() != SecurityUtils.getUserId()
|| !sha.equals(row.get("sha256")) || !name.equals(row.get("original_name")) || ((Number) row.get("deleted")).intValue() != 0 || truth(row.get("server_generated"))!=generated)
|| !sha.equals(row.get("sha256")) || !name.equals(row.get("original_name")) || ((Number) row.get("deleted")).intValue() != 0)
throw new ServiceException("上传请求已变化,请重新选择附件");
return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null,generated);
return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null);
}
int limit="REQUEST".equals(kind)?20:MAX_FILES;
int count="REQUEST".equals(kind)?db.queryForObject("select count(*) from purchase_document_attachment a join purchase_document_group g on g.id=a.group_id where g.target_type=? and g.target_id=? and g.document_kind in ('REQUEST','QUOTE') and a.deleted=0",Integer.class,type,targetId):db.queryForObject("select count(*) from purchase_document_attachment where group_id=? and deleted=0",Integer.class,group);
@ -115,9 +109,9 @@ public class PurchaseDocumentService {
if (TransactionSynchronizationManager.isSynchronizationActive()) TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override public void afterCompletion(int status) { if (status != STATUS_COMMITTED) deleteFailed(rollbackFile); }
});
db.update("insert into purchase_document_attachment(id,group_id,original_name,content_type,byte_size,sha256,owner_id,create_by,server_generated) values(?,?,?,?,?,?,?,?,?)",
uploadId, group, name, valid.type(), valid.bytes().length, sha, SecurityUtils.getUserId(), SecurityUtils.getUsername(),generated);
return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null,generated);
db.update("insert into purchase_document_attachment(id,group_id,original_name,content_type,byte_size,sha256,owner_id,create_by) values(?,?,?,?,?,?,?,?)",
uploadId, group, name, valid.type(), valid.bytes().length, sha, SecurityUtils.getUserId(), SecurityUtils.getUsername());
return new Attachment(uploadId, name, valid.type(), valid.bytes().length, SecurityUtils.getUsername(), null);
} catch (RuntimeException e) { deleteFailed(stored); throw e; }
catch (Exception e) { deleteFailed(stored); throw new ServiceException("附件读取或保存失败,请检查文件后重试"); }
}
@ -126,8 +120,6 @@ public class PurchaseDocumentService {
public void remove(String type, Long targetId, String id) {
requirePermission(true); requireId(id); requireTarget(type, targetId, true);
requireFileAccess(type,targetId,id);
if(!db.queryForList("select id from purchase_acceptance_confirmation where attachment_id=? limit 1",id).isEmpty())
throw new ServiceException("该签章附件已用于验收确认,请保留原件;需要补充时请上传新版本");
if (db.update("update purchase_document_attachment a join purchase_document_group g on g.id=a.group_id set a.deleted=1,a.deleted_by=?,a.deleted_time=current_timestamp where a.id=? and a.deleted=0 and g.target_type=? and g.target_id=?", SecurityUtils.getUsername(), id, type, targetId) != 1)
throw new ServiceException("附件不存在或已移除,请刷新资料");
// Keep private bytes and removal metadata for audit. Never delete another business record.
@ -161,16 +153,11 @@ 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);
}
private static boolean truth(Object value){return Boolean.TRUE.equals(value)||value instanceof Number n&&n.intValue()!=0;}
private boolean requireTarget(String type, Long id, boolean 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";
var targets=db.queryForList("select id,create_by"+("detail".equals(type)?",(select b.create_by from purchase_batch b where b.id=purchase_request.purchase_batch_id) batch_create_by":"")+" from " + table + " where id=?" + ("detail".equals(type)?" and del_flag='0'":"") + (lock ? " for update" : ""),id);
if(targets.isEmpty())throw new ServiceException("采购批次或明细不存在,请刷新页面");
boolean editable=com.ruoyi.warehouse.util.PurchaseDataAccess.canEdit((String)targets.get(0).get("create_by"),(String)targets.get(0).get("batch_create_by"));
if(lock&&!editable)throw new ServiceException("只能维护自己创建的批次或采购明细附件",403);
return editable;
if (db.queryForList("select id from " + table + " where id=?" + (lock ? " for update" : ""), id).isEmpty()) throw new ServiceException("采购批次或明细不存在,请刷新页面");
}
static Map<String, String> kinds(String type) {

View File

@ -603,6 +603,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;
@ -622,7 +623,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));

View File

@ -509,8 +509,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")

View File

@ -3,7 +3,6 @@
<mapper namespace="com.ruoyi.warehouse.mapper.PurchaseBatchMapper">
<resultMap type="PurchaseBatch" id="PurchaseBatchResult">
<id property="id" column="id"/>
<result property="creatorName" column="creator_name"/>
<result property="expenseCategoryId" column="expense_category_id"/>
<result property="supplierId" column="supplier_id"/><result property="supplierName" column="supplier_name"/><result property="businessDate" column="business_date"/>
<result property="batchNo" column="batch_no"/>
@ -28,7 +27,7 @@
</resultMap>
<sql id="batchListQuery">
select (select u.nick_name from sys_user u where convert(u.user_name using utf8mb4) collate utf8mb4_unicode_ci=convert(pb.create_by using utf8mb4) collate utf8mb4_unicode_ci limit 1) creator_name, pb.id, pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
select pb.id, pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name,pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
pb.create_by, pb.create_time, pb.update_by, pb.update_time, count(pr.id) as request_count,
group_concat(distinct pj.project_name order by pj.project_name separator '、') project_names,
coalesce(sum(case when pr.purchase_status&lt;&gt;5 then pr.estimated_amount else 0 end),0) total_amount,
@ -66,8 +65,7 @@
<if test='progress == "confirm"'>having unpriced_count=0 and unlocked_count&gt;0</if>
<if test='progress == "open"'>having open_count&gt;0</if>
<if test='progress == "completed"'>having open_count=0</if>
order by case when pending_count&gt;0 then 0 when open_count&gt;0 or request_count=0 then 1 else 2 end,
pb.business_date desc, pb.create_time desc, pb.id desc
order by pb.id desc
</sql>
<select id="selectPurchaseBatchList" parameterType="PurchaseBatch" resultMap="PurchaseBatchResult"><include refid="batchListQuery"/></select>
<select id="selectPurchaseBatchTotals" parameterType="PurchaseBatch" resultType="map">select sum(actual_total_amount) as actualTotalAmount, sum(total_amount) as totalAmount, sum(unpriced_count) as unpricedCount from (<include refid="batchListQuery"/>) totals</select>
@ -75,32 +73,33 @@
<select id="selectPurchaseBatchOptions" parameterType="String" resultMap="PurchaseBatchResult">
select pb.id,pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name, pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
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 and pr.del_flag='0') as request_count
(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)
<if test="keyword != null and keyword != ''">
and (pb.batch_no like concat('%', #{keyword}, '%') or pb.batch_name like concat('%', #{keyword}, '%'))
</if>
order by pb.business_date desc, pb.create_time desc, pb.id desc
order by pb.id desc
limit 100
</select>
<select id="selectPurchaseBatchFilterOptions" parameterType="String" resultMap="PurchaseBatchResult">
select pb.id,pb.supplier_id,pb.business_date,(select s.name from supplier_info s where s.id=pb.supplier_id) supplier_name, pb.batch_no, pb.batch_name, pb.purchase_status, pb.progress_remark,
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 and pr.del_flag='0') as request_count
(select count(*) from purchase_request pr where pr.purchase_batch_id = pb.id) as request_count
from purchase_batch pb
<where>
<if test="keyword != null and keyword != ''">
and (pb.batch_no like concat('%', #{keyword}, '%') or pb.batch_name like concat('%', #{keyword}, '%'))
</if>
</where>
order by pb.business_date desc, pb.create_time desc, pb.id desc
order by pb.id desc
limit 100
</select>
<select id="selectPurchaseBatchById" parameterType="Long" resultMap="PurchaseBatchResult">
select (select u.nick_name from sys_user u where convert(u.user_name using utf8mb4) collate utf8mb4_unicode_ci=convert(pb.create_by using utf8mb4) collate utf8mb4_unicode_ci limit 1) creator_name, pb.* from purchase_batch pb where pb.id = #{id}
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}
</select>
<select id="selectPurchaseBatchByNo" parameterType="String" resultMap="PurchaseBatchResult">
@ -123,8 +122,7 @@
</update>
<select id="countRequestsByBatchId" parameterType="Long" resultType="int">
<!-- Deleted details remain as audit history and must not make an otherwise empty batch undeletable. -->
select count(*) from purchase_request where purchase_batch_id = #{batchId} and del_flag='0'
select count(*) from purchase_request where purchase_batch_id = #{batchId}
</select>
<select id="countRequestsByIds" parameterType="Long" resultType="int">

View File

@ -113,6 +113,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>

View File

@ -32,12 +32,11 @@
<el-table-column prop="supplierName" label="供应商" min-width="130" show-overflow-tooltip><template #default="s">{{ s.row.supplierName || '待定' }}</template></el-table-column>
<el-table-column label="项目" prop="projectNames" min-width="150" show-overflow-tooltip><template #default="s">{{ s.row.projectNames || '—' }}</template></el-table-column>
<el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="businessDate" label="日期" width="115" show-overflow-tooltip/>
<el-table-column label="批次创建人" width="110" show-overflow-tooltip><template #default="s">{{s.row.creatorName||s.row.createBy||'—'}}</template></el-table-column>
<el-table-column prop="requestCount" label="明细数" width="90" align="center" show-overflow-tooltip/>
<el-table-column v-if="!compactAmounts" label="实际总金额" width="140" align="right" show-overflow-tooltip><template #default="s">{{ s.row.actualTotalAmount==null?'—':money(s.row.actualTotalAmount) }}</template></el-table-column>
<el-table-column v-if="canViewQuotes" label="报价合计" width="140" align="right" show-overflow-tooltip><template #default="s">{{ money(s.row.totalAmount) }}<span v-if="s.row.unpricedCount" class="secondary">{{ s.row.unpricedCount }}项未报价</span></template></el-table-column>
<el-table-column label="备注" min-width="180" class-name="business-control-cell"><template #default="s">
<el-popover v-if="s.row.editable!==false&&$can(['warehouse:purchase:manage'])" :visible="remarkRowId === s.row.id" placement="bottom" :width="320" trigger="click">
<el-popover v-if="$can(['warehouse:purchase:manage'])" :visible="remarkRowId === s.row.id" placement="bottom" :width="320" trigger="click">
<template #reference><button class="batch-remark" :class="{empty: !s.row.progressRemark}" :title="s.row.progressRemark || '点击填写备注'" @click.stop="beginBatchRemark(s.row)"><span>{{ s.row.progressRemark || '填写备注' }}</span><span class="batch-remark-edit">✎</span></button></template>
<div class="batch-remark-title">批次备注</div><el-input v-model="remarkDraft" type="textarea" :rows="4" maxlength="500" show-word-limit placeholder="填写采购进展、注意事项等" :disabled="remarkSaving" />
<div class="batch-remark-actions"><el-button size="small" :disabled="remarkSaving" @click="remarkRowId=null">取消</el-button><el-button size="small" type="primary" :loading="remarkSaving" @click="saveBatchRemark(s.row)">保存</el-button></div>
@ -54,11 +53,11 @@
<template v-else>
<div class="sheet-heading">
<el-button class="sheet-heading__back" size="small" :disabled="saving" icon="el-icon-back" @click="back">{{ sheet.unbatched?'待组批':'返回' }}</el-button>
<div class="sheet-heading__identity"><h2 :title="sheet.unbatched?'未组批采购明细':[sheet.batch.batchName,sheet.batch.batchNo,'供应商:'+supplierName,'项目:'+(batchProject.mixed?'历史多项目批次':projectName(batchProject.value)),formatDateTime(sheet.batch.businessDate)].filter(Boolean).join(' · ')">{{ sheet.unbatched?'未组批采购明细':sheet.batch.batchName||sheet.batch.batchNo||'新采购批次' }}</h2><span v-if="!sheet.unbatched&&!isEditing" class="sheet-heading__meta" :title="supplierName">{{ supplierName }}</span><el-tag v-if="!sheet.unbatched&&!isEditing" size="small" effect="plain">{{ categories.find(c=>String(c.id)===String(sheet.batch.expenseCategoryId))?.categoryName||'费用类别待统一' }}</el-tag><el-tag v-if="isEditing" size="small" effect="plain" class="sheet-heading__state">编辑中</el-tag><span v-if="sheet.batch.id" class="sheet-heading__meta" :title="'批次创建人:'+(sheet.batch.creatorName||sheet.batch.createBy||'—')">批次创建人:{{sheet.batch.creatorName||sheet.batch.createBy||'—'}}</span><purchase-presence :state="live" :editing="isEditing" :rows="sheet.rows" :columns="columns" @retry="_live?.retry()"/></div>
<div class="sheet-heading__identity"><h2 :title="sheet.unbatched?'未组批采购明细':[sheet.batch.batchName,sheet.batch.batchNo,'供应商:'+supplierName,'项目:'+(batchProject.mixed?'历史多项目批次':projectName(batchProject.value)),formatDateTime(sheet.batch.businessDate)].filter(Boolean).join(' · ')">{{ sheet.unbatched?'未组批采购明细':sheet.batch.batchName||sheet.batch.batchNo||'新采购批次' }}</h2><span v-if="!sheet.unbatched&&!isEditing" class="sheet-heading__meta" :title="supplierName">{{ supplierName }}</span><el-tag v-if="!sheet.unbatched&&!isEditing" size="small" effect="plain">{{ categories.find(c=>String(c.id)===String(sheet.batch.expenseCategoryId))?.categoryName||'费用类别待统一' }}</el-tag><el-tag v-if="isEditing" size="small" effect="plain" class="sheet-heading__state">编辑中</el-tag></div>
<div class="sheet-toolbar">
<el-button v-if="canEdit && !editing" type="primary" plain size="small" icon="el-icon-edit" :disabled="saving" @click="startEditing">编辑</el-button>
<template v-if="isEditing">
<el-button size="small" :disabled="saving||live.saving" @click="cancelEditing">{{live.enabled?'结束编辑':'取消编辑'}}</el-button>
<el-button size="small" :disabled="saving" @click="cancelEditing">取消编辑</el-button>
<el-button size="small" :disabled="saving" :aria-expanded="batchDetailsOpen" @click="batchDetailsOpen=!batchDetailsOpen">{{ sheet.unbatched?'默认设置':'批次信息' }}<business-icon :name="batchDetailsOpen?'arrow-up':'arrow-down'"/></el-button>
<el-button type="primary" plain size="small" icon="el-icon-plus" @click="add" :disabled="saving" v-if="$can(['warehouse:purchase:add','warehouse:purchase:manage'])">加一行</el-button>
<el-button size="small" icon="el-icon-document-copy" @click="duplicate" :disabled="saving || !selected.length" v-if="$can(['warehouse:purchase:add','warehouse:purchase:manage'])">复制选中行</el-button>
@ -79,14 +78,14 @@
</div>
</div>
<el-form v-if="isEditing&&batchDetailsOpen" inline size="small" label-width="84px" class="batch-form" :disabled="saving||sheet.batch.editable===false||live.headerBusy" @focusin="rememberHeader">
<el-form v-if="isEditing&&batchDetailsOpen" inline size="small" label-width="84px" class="batch-form" :disabled="saving" @focusin="rememberHeader">
<el-form-item v-if="!sheet.unbatched" label="批次"><el-input :model-value="sheet.batch.batchNo || '保存后自动生成'" disabled /></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="供应商"><supplier-picker v-if="isEditing && !supplierLocked" v-model="sheet.batch.supplierId" /><table-text v-else :value="supplierName" /></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="所属项目" required><el-select v-if="isEditing && !batchProject.mixed" ref="batchProjectSelect" :model-value="batchProject.value" filterable placeholder="选择一次,整批明细沿用" aria-label="批次所属项目" :disabled="!!projectId" @change="setBatchProject"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName"/></el-select><span v-else>{{ batchProject.mixed?'历史多项目批次(按明细保留)':batchProject.value?projectName(batchProject.value):'待选择' }}</span></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="日期"><el-date-picker v-if="isEditing" v-model="sheet.batch.businessDate" type="date" value-format="YYYY-MM-DD" :clearable="false" /><span v-else>{{ formatDateTime(sheet.batch.businessDate) }}</span></el-form-item>
<el-form-item v-if="sheet.unbatched" label="默认分类"><el-select v-model="commonCategory" filterable><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-else label="费用类别" required><el-select ref="batchCategorySelect" :model-value="sheet.batch.expenseCategoryId" filterable placeholder="整批使用一个费用类别" :disabled="sheet.batch.editable===false" aria-label="批次费用类别" @change="setBatchCategory"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-else label="费用类别" required><el-select ref="batchCategorySelect" :model-value="sheet.batch.expenseCategoryId" filterable placeholder="整批使用一个费用类别" :disabled="!!sheet.batch.id&&!$can(['warehouse:purchase:manage'])" aria-label="批次费用类别" @change="setBatchCategory"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName"/></el-select></el-form-item>
<el-form-item v-if="!sheet.unbatched" label="名称"><el-input v-if="isEditing" v-model="sheet.batch.batchName" maxlength="100" placeholder="选填" /><table-text v-else :value="sheet.batch.batchName" /></el-form-item>
</el-form>
@ -120,9 +119,8 @@
<el-table-column v-if="column.field==='finalUnitPrice'" key="amount" label="报价金额" width="115" align="left" show-overflow-tooltip><template #default="s">{{ hasPrice(s.row)?money(Number(s.row.quantity)*Number(s.row.finalUnitPrice)):'—' }}</template></el-table-column>
</template>
<el-table-column v-if="!sheet.unbatched" key="arrival-progress" label="已验收 / 待验收 / 未到" width="167" show-overflow-tooltip><template #default="s">{{ s.row.acceptedQuantity || 0 }} / {{ s.row.pendingArrivalQuantity || 0 }} / {{ s.row.id ? s.row.remainingQuantity : s.row.quantity }}</template></el-table-column>
<el-table-column key="creator" label="明细创建人" width="110" show-overflow-tooltip><template #default="s">{{s.row.creatorName||s.row.createBy||'本人(新增)'}}</template></el-table-column>
<el-table-column key="status" label="状态" width="104" :fixed="isEditing?false:'right'" align="center" class-name="business-status-cell"><template #default="s"><el-tag size="small" :type="(rowState(s.row).type) || 'primary'">{{ rowState(s.row).label }}</el-tag></template></el-table-column>
<el-table-column v-if="!isEditing" key="operations" label="操作" width="180" fixed="right" align="center" class-name="business-operation-cell"><template #default="s"><el-button v-if="canArrive(s.row)&&!Number(s.row.pendingArrivalQuantity)&&!(Number(s.row.acceptedQuantity)>Number(s.row.receivedQuantity||0)&&$can(['warehouse:in:list']))&&$can(['warehouse:purchase:edit','warehouse:purchase:manage'])" :disabled="saving || isEditing" size="small" link type="primary" @click="arrival([s.row])" >到货</el-button><el-button v-if="s.row.editable!==false&&!s.row.historical && Number(s.row.purchaseStatus)!==5 && Number(s.row.pendingArrivalQuantity)>0 && $can(['warehouse:purchase:edit','warehouse:purchase:manage'])" :disabled="saving||isEditing" link type="primary" @click="$refs.arrival.open([s.row],'acceptance')">验收</el-button><el-button v-if="!Number(s.row.pendingArrivalQuantity)&&!s.row.historical && Number(s.row.acceptedQuantity)>Number(s.row.receivedQuantity||0) && $can(['warehouse:in:list'])" :disabled="saving||isEditing" link type="primary" @click="$router.push({path:'/warehouse/pending',query:{sourceGroup:'B:'+sheet.batch.id,projectId:s.row.projectId}})">入库</el-button><el-button v-if="s.row.id" link type="primary" size="small" @click="records(s.row)">到货记录</el-button><el-button v-if="rowActions(s.row).length===1" size="small" link type="primary" :disabled="saving||!s.row.id" @click="runRowCommand('attachments',s.row)">附件</el-button><el-dropdown v-else trigger="click" class="row-more" :disabled="saving" @command="command=>runRowCommand(command,s.row)"><el-button size="small" link type="primary" :disabled="saving">更多<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item v-for="action in rowActions(s.row)" :key="action.command" :command="action.command" :disabled="saving||action.disabled">{{ action.label }}</el-dropdown-item></el-dropdown-menu></template></el-dropdown></template></el-table-column>
<el-table-column v-if="!isEditing" key="operations" label="操作" width="180" fixed="right" align="center" class-name="business-operation-cell"><template #default="s"><el-button v-if="canArrive(s.row)&&!Number(s.row.pendingArrivalQuantity)&&!(Number(s.row.acceptedQuantity)>Number(s.row.receivedQuantity||0)&&$can(['warehouse:in:list']))&&$can(['warehouse:purchase:edit','warehouse:purchase:manage'])" :disabled="saving || isEditing" size="small" link type="primary" @click="arrival([s.row])" >到货</el-button><el-button v-if="!s.row.historical && Number(s.row.purchaseStatus)!==5 && Number(s.row.pendingArrivalQuantity)>0 && $can(['warehouse:purchase:edit','warehouse:purchase:manage'])" :disabled="saving||isEditing" link type="primary" @click="$refs.arrival.open([s.row],'acceptance')">验收</el-button><el-button v-if="!Number(s.row.pendingArrivalQuantity)&&!s.row.historical && Number(s.row.acceptedQuantity)>Number(s.row.receivedQuantity||0) && $can(['warehouse:in:list'])" :disabled="saving||isEditing" link type="primary" @click="$router.push({path:'/warehouse/pending',query:{sourceGroup:'B:'+sheet.batch.id,projectId:s.row.projectId}})">入库</el-button><el-button v-if="s.row.id" link type="primary" size="small" @click="records(s.row)">到货记录</el-button><el-button v-if="rowActions(s.row).length===1" size="small" link type="primary" :disabled="saving||!s.row.id" @click="runRowCommand('attachments',s.row)">附件</el-button><el-dropdown v-else trigger="click" class="row-more" :disabled="saving" @command="command=>runRowCommand(command,s.row)"><el-button size="small" link type="primary" :disabled="saving">更多<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item v-for="action in rowActions(s.row)" :key="action.command" :command="action.command" :disabled="saving||action.disabled">{{ action.label }}</el-dropdown-item></el-dropdown-menu></template></el-dropdown></template></el-table-column>
</el-table>
</div>
<div v-if="isEditing && validationEnabled" class="sheet-validation" aria-live="polite">
@ -133,7 +131,7 @@
</div>
<div class="sheet-footer">
<div>显示 {{ visibleRows.length }} / {{ sheet.rows.length }} 行<span v-if="!compactAmounts" class="secondary-inline">实际总金额 {{ actualTotal==null?'—':'¥ '+money(actualTotal) }}</span><span v-if="canViewQuotes" class="secondary-inline">报价总金额 ¥ {{ money(amount) }} <span v-if="unpriced">({{ unpriced }} 行未报价)</span></span><el-tooltip content="选中后直接输入,Delete/Backspace 清空内容;拖动或 Shift 扩选。Ctrl/⌘+C/V 复制粘贴,Ctrl/⌘+D/R 向下/右填充,Z 撤销,Y 或 Shift+Z 重做。Tab 横移、输入后 Enter 换行、F2/双击编辑、Esc 取消本格修改。" placement="top"><business-icon name="question" /></el-tooltip></div>
<div><el-button size="small" :disabled="saving || dirty || !selected.length || !selected.every(canArrive)" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="arrival(selected)" >批量到货</el-button><el-button v-if="isEditing" size="small" type="primary" :loading="saving" :disabled="!dirty||live.saving" @click="save">{{ sheet.unbatched?'保存未组批明细':'保存清单' }}</el-button><el-button size="small" type="success" plain icon="el-icon-lock" :disabled="saving || !canConfirm" v-if="canViewQuotes&&!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="confirm" >确认采购</el-button></div>
<div><el-button size="small" :disabled="saving || dirty || !selected.length || !selected.every(canArrive)" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="arrival(selected)" >批量到货</el-button><el-button v-if="isEditing" size="small" type="primary" :loading="saving" :disabled="!dirty" @click="save">{{ sheet.unbatched?'保存未组批明细':'保存清单' }}</el-button><el-button size="small" type="success" plain icon="el-icon-lock" :disabled="saving || !canConfirm" v-if="canViewQuotes&&!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:edit','warehouse:purchase:manage']))" @click="confirm" >确认采购</el-button></div>
</div>
<div v-if="selectionStats" class="sheet-selection-stats" role="status" aria-live="polite"><span>选区 {{ selectionStats.rowCount }} 行 · {{ selectionStats.cellCount }} 格</span><span v-if="selectionStats.numeric">{{ selectionStats.numeric.label }}:计数 {{ selectionStats.numeric.count }} · 合计 {{ selectionStats.numeric.sum }} · 平均 {{ selectionStats.numeric.average }}</span><span v-else-if="selectionStats.numericCount">数值 {{ selectionStats.numericCount }} 格(不同字段/单位不混合计)</span><span v-if="selectionStats.quantities.length">数量:{{ selectionStats.quantities.map(group=>group.total+' '+(group.unit||'未填单位')).join(' / ') }}</span><span v-if="!compactAmounts">选中行实际金额 {{ selectionStats.actual?.amount===null?'—':'¥ '+selectionStats.actual?.amount }}<small v-if="selectionStats.actual?.unpricedCount">({{ selectionStats.actual.unpricedCount }} 行未填)</small></span><span v-if="canViewQuotes">选中行报价金额 {{ selectionStats.quote.amount===null?'—':'¥ '+selectionStats.quote.amount }}<small v-if="selectionStats.quote.unpricedCount">({{ selectionStats.quote.unpricedCount }} 行未报价)</small></span></div>
</template>
@ -153,16 +151,6 @@
</el-alert>
</template>
</excel-import-dialog>
<el-dialog v-model="conflictOpen" title="核对同时修改的内容" width="min(960px,96vw)" append-to-body :close-on-click-modal="false">
<p>其他位置的修改已自动合并。以下内容需要选择,操作只更新草稿,核对后再保存。</p>
<el-table :data="conflictData?.conflicts||[]" border max-height="440">
<el-table-column prop="rowName" label="位置" min-width="145"/><el-table-column prop="label" label="字段" min-width="120"/>
<el-table-column label="我的内容" min-width="180"><template #default="s">{{conflictText(s.row.mine)}}</template></el-table-column>
<el-table-column label="最新内容" min-width="180"><template #default="s">{{conflictText(s.row.current)}}</template></el-table-column>
<el-table-column label="保留" width="195"><template #default="s"><el-radio-group v-model="conflictChoices[s.$index]" size="small"><el-radio-button value="mine">我的</el-radio-button><el-radio-button value="current">最新</el-radio-button></el-radio-group></template></el-table-column>
</el-table>
<template #footer><el-button @click="conflictOpen=false">返回编辑</el-button><el-button type="primary" :disabled="!conflictChoices.length||conflictChoices.some(c=>!c)" @click="resolveConflicts">应用到草稿</el-button></template>
</el-dialog>
<supplier-quotation ref="quotation" v-model="quoteImportOpen" :sheet="sheet" :export-rows="inquiryExportSourceRows" :selection-active="selected.length>0" :supplier-name="supplierName" :disabled="saving || dirty" :compact-amounts="compactAmounts" :can-edit="!!canEdit&&canViewQuotes" :can-export="canExportInquiry" @apply="applyQuotes" @busy="quoteLoading=$event"/>
<el-dialog :close-on-press-escape="!saving" :close-on-click-modal="!saving" :show-close="!saving" title="转采购批次" v-model="moveOpen" width="min(580px,96vw)" append-to-body>
<p>已选 {{ selected.length }} 项 · 只调整批次归组,不改变数量、报价、确认状态及到货/入库记录。</p>
@ -175,7 +163,7 @@
</el-dialog>
<batch-arrival ref="arrival" separate-acceptance @changed="arrivalChanged" />
<el-dialog title="到货记录" v-model="recordsOpen" width="900px" append-to-body>
<p>{{ recordsItem }}</p><el-table :data="arrivalRecords" size="small"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="arrivalDate" label="日期" show-overflow-tooltip min-width="100"/><el-table-column prop="arrivalQuantity" label="数量" show-overflow-tooltip min-width="100"/><el-table-column label="验收" show-overflow-tooltip min-width="100"><template #default="s">{{ ['待验收','合格','不合格'][s.row.acceptanceStatus] || '已撤销' }}</template></el-table-column><el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos v-model="s.row.photos" :request-id="recordsRequest?.id" :arrival-id="s.row.id" :supplementable="recordsRequest?.editable!==false&&$can(['warehouse:purchase:edit','warehouse:purchase:manage'])" readonly compact/></template></el-table-column><el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="160"/></el-table>
<p>{{ recordsItem }}</p><el-table :data="arrivalRecords" size="small"><el-table-column :formatter="(row,column,value)=>$dateTime(value)" prop="arrivalDate" label="日期" show-overflow-tooltip min-width="100"/><el-table-column prop="arrivalQuantity" label="数量" show-overflow-tooltip min-width="100"/><el-table-column label="验收" show-overflow-tooltip min-width="100"><template #default="s">{{ ['待验收','合格','不合格'][s.row.acceptanceStatus] || '已撤销' }}</template></el-table-column><el-table-column label="到货照片" width="130" class-name="business-control-cell"><template #default="s"><arrival-photos :model-value="s.row.photos||[]" readonly compact/></template></el-table-column><el-table-column prop="remark" label="备注" show-overflow-tooltip min-width="160"/></el-table>
<template #footer><div ><el-button @click="recordsOpen=false">关闭</el-button><el-button type="primary" @click="goArrival">去到货验收</el-button></div></template>
</el-dialog>
</div>
@ -187,14 +175,10 @@ import { registerPageGuard } from '@/utils/page-guards'
import { purchaseProjectState, purchaseBatchProjectChanges } from '@/utils/purchase-project'
import { runLatest } from '@/utils/query-session'
import { defineAsyncComponent } from 'vue'
import {createPurchaseLive} from '@/utils/purchase-sheet-live'
import {resolvePurchaseSheetConflicts} from '@/utils/purchase-sheet-conflicts'
import {listPurchaseBatch,updatePurchaseBatchRemark,getPurchaseSheet,getUnbatchedSheet,savePurchaseSheet,getPurchaseSheetSubmission,confirmPurchaseSheet,purchaseSheetOptions,listPurchaseArrival,assignPurchaseBatch,delPurchaseBatch,purchasePlanOptions,updatePurchaseStatus} from '@/api/warehouse/purchase'
import {projectOptions,categoryOptions} from '@/api/project/project'
import {loanOptions} from '@/api/project/loan'
import PurchaseCell from './Cell.vue'
import PurchasePresence from './Presence.vue'
import {livePresenceColor} from '@/utils/purchase-live-presence'
import PriceCorrection from './PriceCorrection.vue'
import HistoryCorrection from './HistoryCorrection.vue'
import PurchaseDocuments from '@/components/PurchaseDocuments'
@ -229,8 +213,8 @@ function purchaseRouteStamp(route) {
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:{PurchasePresence,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 {live:{enabled:false,connected:false,headerBusy:false,peers:[],clientId:'',status:'',saveStatus:'',issue:'',saving:false,blocked:false},conflictData:null,conflictOpen:false,conflictChoices:[],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:'',recordsRequest:null,arrivalRecords:[]}},
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:[]}},
computed:{
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
canViewQuotes(){const user=this.$store.getters;return canViewPurchaseQuotes(user.userId,user.roles)},
@ -267,40 +251,30 @@ data(){return {live:{enabled:false,connected:false,headerBusy:false,peers:[],cli
rowErrors(){if(!this.validationEnabled||!this.sheet||!this.isEditing)return [];const changed=this.activeRows().filter(r=>!r.id||this.changedKeys.has(r._key)),core=changed.filter(row=>!this.referenceOnly(row));return [...collectRowErrors(core,this.items,core.map(r=>this.originalIndex(r)+1),this.units,this.activeCategoryLabels),...changed.filter(row=>referencePriceError(row)).map(row=>({rowKey:row._key,line:this.originalIndex(row)+1,field:'actualUnitPrice',message:referencePriceError(row)}))]},
errorKeys(){return new Set(this.rowErrors.map(e=>e.rowKey))},
errorFields(){const result={};this.rowErrors.forEach(e=>{result[e.rowKey+'|'+e.field]=e.message});return result},
canMoveSelection(){return this.selected.length>0 && this.selected.every(r=>r.editable!==false&&r.id&&Number(r.purchaseStatus)!==5)&&new Set(this.selected.map(r=>String(r.projectId))).size===1},
canMoveSelection(){return this.selected.length>0 && this.selected.every(r=>r.id&&Number(r.purchaseStatus)!==5)&&new Set(this.selected.map(r=>String(r.projectId))).size===1},
moveSupplierLocked(){return this.selected.some(r=>r.priceLocked||r.historical||Number(r.acceptedQuantity)>0||Number(r.pendingArrivalQuantity)>0)},
canAdd(){return this.$auth.hasPermiOr(['warehouse:purchase:add','warehouse:purchase:manage'])},
canEdit(){return this.sheet && ((!this.sheet.batch.id&&!this.sheet.version)?this.canAdd:this.$auth.hasPermiOr(['warehouse:purchase:edit','warehouse:purchase:manage']))},
isEditing(){return this.editing && this.canEdit},
canRemoveSelection(){return this.selected.length>0 && this.selected.every(r=>!this.readonly(r) && (!r.id?this.canAdd:this.$auth.hasPermiOr(['warehouse:purchase:remove','warehouse:purchase:manage'])) && !(Number(r.acceptedQuantity)>0 || Number(r.pendingArrivalQuantity)>0))},
dirty(){return !!this.sheet&&(Object.keys(this.sheet.liveText||{}).length>0||!this.baseline||this.changedKeys.size>0||this.headerDirty||this.structureDirty)},
dirty(){return !!this.sheet&&(!this.baseline||this.changedKeys.size>0||this.headerDirty||this.structureDirty)},
supplierLocked(){return !!this.sheet.batch.supplierId && this.sheet.rows.some(r=>r.priceLocked || r.historical || Number(r.acceptedQuantity)>0 || Number(r.pendingArrivalQuantity)>0)},
supplierName(){return this.sheet?.batch?.supplierName || this.sheet?.rows?.find(r=>r.supplierName)?.supplierName || '待定'},
nameItems(){return this.nameOptions || this.items},
columns(){const columns=[{field:'materialName',label:'物品名称',width:180,required:true},{field:'materialBrand',label:'品牌',width:110},{field:'materialParams',label:'规格型号',width:210},{field:'quantity',label:'数量',width:100,required:true},{field:'unit',label:'单位',width:75,required:true},{field:'finalUnitPrice',label:'报价单价',width:115},{field:'projectId',label:'项目',width:210,required:true},{field:'expenseCategoryId',label:'费用分类',width:150,required:true},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(5,0,{field:'actualUnitPrice',label:'实际单价',width:115});if(this.extras)columns.push({field:'productionTaskId',label:'生产计划',width:200},{field:'purchasePurpose',label:'用途',width:130},{field:'loanId',label:'归还借用',width:200},{field:'remark',label:'备注',width:180});return columns.filter(column=>!['purchasePurpose','loanId'].includes(column.field)&&(column.field!=='finalUnitPrice'||this.canViewQuotes)&&(column.field!=='projectId'||this.sheet?.unbatched||this.batchProject.mixed)&&(column.field!=='expenseCategoryId'||this.sheet?.unbatched))},
amount(){return this.sheet.rows.reduce((sum,r)=>sum+(Number(r.purchaseStatus)!==5?Number(r.quantity||0)*Number(r.finalUnitPrice||0):0),0)},
unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Number(r.purchaseStatus)!==5).length},
confirmationRows(){return (this.selected.length?this.selected:this.visibleRows).filter(r=>r.editable!==false&&!r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5)},
confirmationRows(){return (this.selected.length?this.selected:this.visibleRows).filter(r=>!r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5)},
canConfirm(){return this.canViewQuotes && this.sheet.batch.id && !this.dirty && this.confirmationRows.length>0 && this.confirmationRows.every(this.hasPrice)},
},
watch:{sheet(){this._live?.start(this.sheet?.unbatched?null:this.sheet?.batch?.id);this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},virtualCount(count,previous){if(!this.sheet||!this.virtualized)return;const end=Math.max(0,this.visibleRows.length-count),previousEnd=Math.max(0,this.visibleRows.length-previous);if(this.virtualStart>=previousEnd||this.virtualStart>end)this.virtualStart=end},editing(value){if(!value)this._live?.release();if(value){this.snapshotView();this.batchDetailsOpen=!this.sheet?.unbatched&&(!this.sheet?.batch.id||!this.sheet?.batch.expenseCategoryId||!this.batchProject.value&&!this.batchProject.mixed)}else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},editCell(value){if(!value&&!this._liveRebasing)this._live?.release()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
async created(){this.changedKeys=new Set();this.headerDirty=false;this.structureDirty=false;this._editor=createSheetEditor(this);this._live=createPurchaseLive(this);this.loading=true;try{this.refreshDrafts();await this.references();if(this.embedded||this.$route.path!=='/procurement/details')await this.loadBatches();else await this.applyRoute()}finally{this.loading=false}},
async activated(){this._pageInactive=false;this._live?.start(this.sheet?.unbatched?null:this.sheet?.batch?.id);if(this._routeStamp===undefined||this.loading||this.creating)return;const identity=this._routeIdentity;await this.applyRoute();if(!this._refreshOnActivate)return;this._refreshOnActivate=false;if(identity!==this._routeIdentity||this.saving||this.editing||this.dirty)return;if(this.sheet){const filter=this.rowFilter;if(this.sheet.unbatched){if(this.sheet.rows.length)await this.openUnbatched(this.sheet.rows,false)}else await this.openBatch(this.sheet.batch);this.rowFilter=filter}else if(this.viewMode==='batches')await this.loadBatches();else await this.$refs.lookup?.load()},
watch:{sheet(){this.cellSelection=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pasteContext=null;this._insertContext=null},density(){this.resetGridScroll();this.layout()},virtualCount(count,previous){if(!this.sheet||!this.virtualized)return;const end=Math.max(0,this.visibleRows.length-count),previousEnd=Math.max(0,this.visibleRows.length-previous);if(this.virtualStart>=previousEnd||this.virtualStart>end)this.virtualStart=end},editing(value){if(value){this.snapshotView();this.batchDetailsOpen=!this.sheet?.unbatched&&(!this.sheet?.batch.id||!this.sheet?.batch.expenseCategoryId||!this.batchProject.value&&!this.batchProject.mixed)}else{this.viewSnapshot=null;this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false}this.layout()},extras(){this.cellSelection=null;this.layout()},rowFilter(){this.rowViewChanged()},rowQueue(){this.rowViewChanged()},rowSort(){this.rowViewChanged()},onlyInvalid(){this.cellSelection=null;this.resetGridScroll()},'sheet.rows.length'(){this.virtualStart=0;this.layout()},'$route.fullPath'(){if(this._routeStamp!==undefined&&!this._pageInactive)this.applyRoute()}},
async created(){this.changedKeys=new Set();this.headerDirty=false;this.structureDirty=false;this._editor=createSheetEditor(this);this.loading=true;try{this.refreshDrafts();await this.references();if(this.embedded||this.$route.path!=='/procurement/details')await this.loadBatches();else await this.applyRoute()}finally{this.loading=false}},
async activated(){this._pageInactive=false;if(this._routeStamp===undefined||this.loading||this.creating)return;const identity=this._routeIdentity;await this.applyRoute();if(!this._refreshOnActivate)return;this._refreshOnActivate=false;if(identity!==this._routeIdentity||this.saving||this.editing||this.dirty)return;if(this.sheet){const filter=this.rowFilter;if(this.sheet.unbatched){if(this.sheet.rows.length)await this.openUnbatched(this.sheet.rows,false)}else await this.openBatch(this.sheet.batch);this.rowFilter=filter}else if(this.viewMode==='batches')await this.loadBatches();else await this.$refs.lookup?.load()},
unmounted(){this.endCellSelection()},
deactivated(){this.persistDraft();this._live?.stop();this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pageInactive=true;this._creationEpoch=(this._creationEpoch||0)+1;this._refreshOnActivate=true;this.endCellSelection()},
deactivated(){this.persistDraft();this.rowMenu=null;this.insertRowsOpen=false;this.pastePreviewOpen=false;this._pageInactive=true;this._creationEpoch=(this._creationEpoch||0)+1;this._refreshOnActivate=true;this.endCellSelection()},
mounted(){this._guardPath=this.$route.path;this._unregisterPageGuard=registerPageGuard(this._guardPath,navigation=>this.checkNavigation(navigation));window.addEventListener('pointerdown',this.dismissRowMenu,true);window.addEventListener('keydown',this.dismissRowMenu);window.addEventListener('resize',this.resize);window.addEventListener('beforeunload',this.beforeUnload);window.addEventListener('pagehide',this.persistDraft);window.addEventListener('offline',this.persistDraft);document.addEventListener('visibilitychange',this.persistDraft)},
beforeUnmount(){this._purchaseDisposed=true;this._live?.stop();this._creationEpoch=(this._creationEpoch||0)+1;this._unregisterPageGuard?.();this.persistDraft();this._editor?.stop();window.removeEventListener('pointerdown',this.dismissRowMenu,true);window.removeEventListener('keydown',this.dismissRowMenu);window.removeEventListener('resize',this.resize);window.removeEventListener('beforeunload',this.beforeUnload);window.removeEventListener('pagehide',this.persistDraft);window.removeEventListener('offline',this.persistDraft);document.removeEventListener('visibilitychange',this.persistDraft)},
beforeUnmount(){this._purchaseDisposed=true;this._creationEpoch=(this._creationEpoch||0)+1;this._unregisterPageGuard?.();this.persistDraft();this._editor?.stop();window.removeEventListener('pointerdown',this.dismissRowMenu,true);window.removeEventListener('keydown',this.dismissRowMenu);window.removeEventListener('resize',this.resize);window.removeEventListener('beforeunload',this.beforeUnload);window.removeEventListener('pagehide',this.persistDraft);window.removeEventListener('offline',this.persistDraft);document.removeEventListener('visibilitychange',this.persistDraft)},
methods:{formatDateTime,
liveHeaderChanged(){if(!this._liveRebasing)this._live?.scheduleSave()},
liveRowChanged(row){if(row&&!this._liveRebasing)this._live?.rowChanged(row)},
liveTyping(row,field,value,raw=false){this._live?.typing(row,field,value,raw)},
liveCommitted(){this._live?.committed()},
liveCommitting(row,field,value,task){return this._live?this._live.commit(row,field,value,task):task},
liveLocalText(row,field){return this.sheet?.liveText?.[row._key+'|'+field]?.value},
livePeer(row,field){return this._live?.peer(row,field)||null},
liveBusy(row,field){return !!this._live?.peer(row,field,true)},
liveColor:livePresenceColor,
liveCellHint(row,field){const peer=this._live?.peer(row,field,true),ghost=this._live?.ghost(row,field);return peer?peer.name+' 正在编辑'+(peer.field===field?'此单元格':'关联的物品信息'):ghost?ghost.name+' 的输入草稿,尚未保存':''},
async openBatchCategories(){
if(!this.isEditing||this.saving)return
await this.finishCellEdit()
@ -330,9 +304,9 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
},
exportTemplate(){this.download('warehouse/purchase/importTemplate',{},`采购申请导入模板_${Date.now()}.xlsx`)},
async importedPurchases(){this.viewMode='unbatched';await this.references();await this.$nextTick();await this.$refs.lookup?.load()},
canReopen(row){return row.editable!==false&&canReopenPurchase(row)},
canReopen:canReopenPurchase,
async reopen(row){
if(this.saving||this.isEditing||this.dirty||!this.canEdit||!this.canReopen(row))return
if(this.saving||this.isEditing||this.dirty||!this.canEdit||!canReopenPurchase(row))return
try{await this.$confirm('撤销后返回待确认,释放本行锁定费用;数量、报价及拒收记录保留。是否继续?','撤销采购确认');this.saving=true;await updatePurchaseStatus(row.id,{purchaseStatus:0,progressRemark:'撤销采购确认,保留原报价及到货历史'});this.install((await getPurchaseSheet(this.sheet.batch.id)).data);this.$modal.msgSuccess('已撤销确认,锁定费用已释放')}catch{/* The shared handler displays server errors. */}finally{this.saving=false}
},
viewReference(row){return this.editing&&this.viewSnapshot?.[row._key]||row},
@ -345,7 +319,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
draftId(){const rows=this.sheet?.unbatched&&this.baseline?JSON.parse(this.baseline).rows:this.sheet?.rows||[];return this.sheet?.unbatched?'unbatched-'+(rows.filter(r=>r.id).map(r=>r.id).sort().join('-')||'new'):(this.sheet?.batch.id||'new')},
async openUnbatched(rows,edit=true){this.loading=true;try{await loadAmountDisplay();this.install((await getUnbatchedSheet(rows.map(r=>r.id))).data);this.editing=edit&&this.canEdit;this.layout()}finally{this.loading=false}},
checkNavigation(navigation){if(!navigation)return this.checkLeave();const {to,from}=navigation;if(to.path===this._guardPath){if(this.embedded||to.path!=='/procurement/details'||purchaseRouteStamp(to)===this._routeIdentity)return true;return this.checkLeave()}return from.path===this._guardPath?this.checkLeave():true},
async checkLeave(){if(this.saving||this.live?.saving){this.$modal.msgWarning('正在保存,请稍候');return false}if(!this.dirty)return true;try{await this.$confirm('有未保存修改,是否保留草稿并离开?','离开采购');return this.persistDraft()}catch{return false}},
async checkLeave(){if(this.saving){this.$modal.msgWarning('正在保存,请稍候');return false}if(!this.dirty)return true;try{await this.$confirm('有未保存修改,是否保留草稿并离开?','离开采购');return this.persistDraft()}catch{return false}},
draftPrefix(){return 'purchase-sheet-draft:'+String(this.$store.getters.userId || this.$store.getters.name)+':'},
refreshDrafts(){if(this.isEditing)return;try{this.drafts=listSheetDrafts(localStorage,this.draftPrefix()).map(data=>({key:data.key,title:(data.sheet.unbatched?'未组批明细':data.sheet.batch.batchNo||'新采购清单')+' · '+this.parseTime(data.savedAt,'{m}-{d} {h}:{i}')}))}catch{this.drafts=[]}},
persistDraft(){try{const saved=this._editor?.persist();if(saved){this.draftSavedAt=Date.now();this.draftError=''}return !this.draftError}catch(e){this.draftError='本机草稿保存失败(存储空间或浏览器权限),请勿关闭页面。可重试保存清单;失败时内容仍在当前页面。';return false}},
@ -356,7 +330,7 @@ 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;const id=this.sheet.batch.id;await delPurchaseBatch(id);this.clearDraft(this.draftId());this._sheetSequence=(this._sheetSequence||0)+1;this._live?.stop();this.sheet=null;this.editing=false;this.baseline='';this.moveOutcome=null;if(!this.embedded&&this.$route.path==='/procurement/details'&&String(this.$route.query.purchaseBatchId)===String(id)){const target={path:this.$route.path,query:{...this.$route.query}};delete target.query.purchaseBatchId;this._routeIdentity=purchaseRouteStamp(target);await this.$router.replace(target)}await this.loadBatches();this.$modal.msgSuccess('空批次已删除')}catch{}finally{this.saving=false}},
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}},
async loadLoans(row){
const requests=this._loanRequests||(this._loanRequests=new Map()),request={projectId:row.projectId,itemId:row.productId}
requests.set(row._key,request)
@ -436,9 +410,9 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
actualAmount:purchaseActualAmount,
referenceOnly(row){return referenceOnlyChange(row,this.baselineRowMap.get(row._key))},
serialize(value){return JSON.stringify(value)},hasPrice(r){return r.quoteAvailable===true || r.finalUnitPrice!==null && r.finalUnitPrice!==undefined && r.finalUnitPrice!==''},
readonly(r){return !this.isEditing || r.editable===false || !!r.historical || Number(r.purchaseStatus)===5},
readonly(r){return !this.isEditing || !!r.historical || Number(r.purchaseStatus)===5},
linkUrl(value){try{const url=new URL(clean(value));return ['http:','https:'].includes(url.protocol)?url.href:''}catch(e){return ''}},
canArrive(r){return r.editable!==false && this.sheet && this.sheet.batch.supplierId && r.id && r.priceLocked && !r.historical && Number(r.purchaseStatus)!==5 && Number(r.remainingQuantity)>0},
canArrive(r){return this.sheet && this.sheet.batch.supplierId && r.id && r.priceLocked && !r.historical && Number(r.purchaseStatus)!==5 && Number(r.remainingQuantity)>0},
batchProgress,
rowState(r){if(r.historical)return {label:'历史已完成',type:'info'};if(Number(r.purchaseStatus)===5)return {label:'已取消',type:'info'};if(Number(r.pendingArrivalQuantity)>0)return {label:'待验收',type:'warning'};if(Number(r.purchaseStatus)===4)return {label:'已到齐',type:'success'};if(Number(r.acceptedQuantity)>0)return {label:'部分到货',type:'warning'};if(r.priceLocked)return {label:'已确认采购',type:''};if(!r.productId)return {label:'保存时建档',type:'info'};return {label:this.hasPrice(r)?'待确认':'待报价',type:'info'}},
cellError(row,field){return this.errorFields[row._key+'|'+field]||''},
@ -459,7 +433,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
else if(command==='cancel')this.$refs.cancelPurchase.open(row)
},
async focusError(error){if(!error)return;if(error.field==='projectId'&&!this.sheet.unbatched&&!this.batchProject.mixed){this.batchDetailsOpen=true;await this.$nextTick();this.$refs.batchProjectSelect?.focus();return}this.rowFilter='';if(['loanId','purchasePurpose','productionTaskId','remark'].includes(error.field))this.extras=true;await this.$nextTick();const row=this.sheet.rows.find(r=>r._key===error.rowKey);if(row)await this.activateCell(row,error.field)},
editableCell(row,field){if(this.liveBusy?.(row,field))return false;if(field==='actualUnitPrice')return row.editable!==false&&this.isEditing&&!this.saving&&!this.compactAmounts;return !this.saving&&!this.readonly(row)&&!this.fieldLocked(row,field)&&!(row.id&&field==='productionTaskId')&&!(row.id&&row.productionTaskId&&field==='projectId')&&!(row.productId&&field==='unit')&&!(field==='category'&&!this.canEditCategory(row))&&!(field==='loanId'&&row.purchasePurpose!=='REPAY')},
editableCell(row,field){if(field==='actualUnitPrice')return this.isEditing&&!this.saving&&!this.compactAmounts;return !this.saving&&!this.readonly(row)&&!this.fieldLocked(row,field)&&!(row.id&&field==='productionTaskId')&&!(row.id&&row.productionTaskId&&field==='projectId')&&!(row.productId&&field==='unit')&&!(field==='category'&&!this.canEditCategory(row))&&!(field==='loanId'&&row.purchasePurpose!=='REPAY')},
isGridSelected(row,field){const range=this.cellRange;if(!range)return false;const r=this.visibleRowIndexMap.get(row._key),c=this.columns.findIndex(column=>column.field===field);return r>=range.top&&r<=range.bottom&&c>=range.left&&c<=range.right},
focusGridCell(row,field){if(this._gridDragging)return;if(this._pasteContinuation&&(this._pasteContinuation.key!==row._key||this._pasteContinuation.field!==field))this._pasteContinuation=null;if(!this.cellSelection)this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}}},
startCellSelection(row,field,event){if(event.button!==0||this.saving)return;if(this.editCell===row._key+'|'+field&&!event.shiftKey&&event.target.closest('input,textarea,button,a,[role="button"],.el-select,.el-cascader'))return;event.preventDefault();document.activeElement?.blur?.();this._editor?.flush();this.editCell=null;this.activeMenu=null;this.nameMenuRow=null;const point={key:row._key,field};this.cellSelection={anchor:event.shiftKey&&this.cellSelection?this.cellSelection.anchor:point,focus:point};this._gridDragging=true;window.addEventListener('mouseup',this.endCellSelection,{once:true});event.currentTarget.focus({preventScroll:true})},
@ -473,7 +447,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
selectionText(){return selectedGridText(this.cellRange,this.visibleRows,this.columns,(row,field)=>this.displayCell(row,field)==='—'?'':this.displayCell(row,field))},
copyGridEvent(event){if(!this.cellRange)return;const target=event.target,one=this.cellRange.top===this.cellRange.bottom&&this.cellRange.left===this.cellRange.right;if(one&&target.matches('input,textarea')&&target.selectionStart!==target.selectionEnd)return;event.preventDefault();event.clipboardData?.setData('text/plain',this.selectionText())},
async copySelection(){if(!this.cellRange||this.saving)return;await this.finishCellEdit();try{await writeClipboardText(this.selectionText());this.$modal.msgSuccess('选区已复制,可粘贴到 Excel')}catch(error){this.$modal.msgWarning(error.message)}},
async activateCell(row,field,openDropdown=false,event){if(!this.editableCell(row,field))return;if(this._live&&!await this._live.claim(row,field)){this.$modal.msgWarning(this.live.issue||'此单元格正在被编辑');return}await this.revealRow(row);const key=row._key+'|'+field,wasActive=this.editCell===key;this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}};this.rememberCell(this.originalIndex(row),field);this.editCell=key;await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]');if(!cell)return;cell.scrollIntoView({block:'nearest',inline:'nearest'});const input=cell.querySelector('input:not([disabled]),textarea:not([disabled])');if(input&&!cell.contains(document.activeElement)){input.focus({preventScroll:true});if(['materialName','materialBrand','materialParams','purchaseLink','remark'].includes(field))input.setSelectionRange?.(input.value.length,input.value.length);else input.select()}if(openDropdown&&!wasActive&&input?.getAttribute('aria-expanded')!=='true')cell.querySelector('.el-select__wrapper')?.click()},
async activateCell(row,field,openDropdown=false,event){if(!this.editableCell(row,field))return;await this.revealRow(row);const key=row._key+'|'+field,wasActive=this.editCell===key;this.cellSelection={anchor:{key:row._key,field},focus:{key:row._key,field}};this.rememberCell(this.originalIndex(row),field);this.editCell=key;await this.$nextTick();const cell=this.$el.querySelector('.sheet-cell[data-row="'+this.originalIndex(row)+'"][data-field="'+field+'"]');if(!cell)return;cell.scrollIntoView({block:'nearest',inline:'nearest'});const input=cell.querySelector('input:not([disabled]),textarea:not([disabled])');if(input&&!cell.contains(document.activeElement)){input.focus({preventScroll:true});if(['materialName','materialBrand','materialParams','purchaseLink','remark'].includes(field))input.setSelectionRange?.(input.value.length,input.value.length);else input.select()}if(openDropdown&&!wasActive&&input?.getAttribute('aria-expanded')!=='true')cell.querySelector('.el-select__wrapper')?.click()},
originalIndex(row){return this.rowIndexMap.get(row._key)??-1},
fieldLocked(row,field){if(field==='finalUnitPrice'&&!this.canViewQuotes)return true;const received=Number(row.receivedQuantity||0)>0,arrived=received||Number(row.acceptedQuantity||0)>0||Number(row.pendingArrivalQuantity||0)>0;return (received&&['projectId','expenseCategoryId','purchasePurpose','loanId'].includes(field))||(arrived&&['materialName','materialBrand','materialParams','unit','category','finalUnitPrice'].includes(field))},
mergeItems(items){const map=new Map(this.items.map(r=>[String(r.id),r]));items.forEach(r=>{const old=map.get(String(r.id))||{};map.set(String(r.id),{...old,...r,unit:r.unit||old.unit,category:r.category||old.category})});this.items=[...map.values()]},
@ -494,13 +468,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
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(){
if(this.saving||this.live?.saving||!this.sheet)return
if(this.live?.enabled){
await this.finishCellEdit()
if(!await this._live.settle())return this.$modal.msgWarning('上次自动保存结果尚未确认,请等待重连后核对')
if(this.dirty){await this.save();if(this.dirty)return}
this.editing=false;this.editCell=null;this.layout();return
}
if(this.saving||!this.sheet)return
const creating=!this.sheet.batch.id&&!this.sheet.version
if(this.dirty){try{await this.$confirm('是否放弃本次未保存的修改?如需保留草稿,请选择继续编辑,再使用返回列表。','取消编辑',{confirmButtonText:'放弃修改',cancelButtonText:'继续编辑'})}catch(e){return}}
this.clearDraft(this.draftId())
@ -510,12 +478,12 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
if(creating)await this.loadBatches()
this.layout()
},
async back(){if(this.saving||this.live?.saving)return this.$modal.msgWarning('正在自动保存,请稍候');if(this.dirty){try{await this.$confirm('清单有未保存修改,是否保留草稿并返回?','返回批次列表')}catch(e){return}if(!this.persistDraft())return}this._sheetSequence=(this._sheetSequence||0)+1;if(this.sheet?.unbatched)this.viewMode='unbatched';this.sheet=null;this.editing=false;this.refreshDrafts?.();this.history=[];this.redoHistory=[];this.moveOutcome=null;this.cellSelection=null;if(!this.embedded&&this.$route.path==='/procurement/details'&&this.$route.query.purchaseBatchId){const query={...this.$route.query};delete query.purchaseBatchId;await this.$router.replace({path:this.$route.path,query});return}await this.loadBatches();this.layout()},
async back(){if(this.saving)return;if(this.dirty){try{await this.$confirm('清单有未保存修改,是否保留草稿并返回?','返回批次列表')}catch(e){return}if(!this.persistDraft())return}this._sheetSequence=(this._sheetSequence||0)+1;if(this.sheet?.unbatched)this.viewMode='unbatched';this.sheet=null;this.editing=false;this.refreshDrafts?.();this.history=[];this.redoHistory=[];this.moveOutcome=null;this.cellSelection=null;if(!this.embedded&&this.$route.path==='/procurement/details'&&this.$route.query.purchaseBatchId){const query={...this.$route.query};delete query.purchaseBatchId;await this.$router.replace({path:this.$route.path,query});return}await this.loadBatches();this.layout()},
remember(rows=[]){this._editor.remember(rows)},
async finishCellEdit(cancel=false){const editingKey=this.editCell,active=document.activeElement;if(this.$el.contains(active))active?.blur?.();await this.$nextTick();if(cancel){this._identityEditor?.invalidate(this.sheet.rows);this._editor?.cancelCell();if(editingKey&&this.sheet.liveText)delete this.sheet.liveText[editingKey]}else this._editor?.flush();this.editCell=null;this.activeMenu=null;this.nameMenuRow=null;await this.$nextTick()},
async finishCellEdit(cancel=false){const active=document.activeElement;if(this.$el.contains(active))active?.blur?.();await this.$nextTick();if(cancel){this._identityEditor?.invalidate(this.sheet.rows);this._editor?.cancelCell()}else this._editor?.flush();this.editCell=null;this.activeMenu=null;this.nameMenuRow=null;await this.$nextTick()},
async undo(){if(!this.isEditing||this.saving)return;await this.finishCellEdit();this._identityEditor?.invalidate(this.sheet.rows);this._editor.undo();this.$el.focus({preventScroll:true});await this.focusSelectedCell()},
async redo(){if(!this.isEditing||this.saving)return;await this.finishCellEdit();this._identityEditor?.invalidate(this.sheet.rows);this._editor.redo();this.$el.focus({preventScroll:true});await this.focusSelectedCell()},
rememberHeader(event){if(this.isEditing&&!this.saving){void this._live?.claim(null,'batch');this._editor.beginHeader(event?.target?.id||event?.target?.closest?.('.el-form-item')?.textContent||'header')}},
rememberHeader(event){if(this.isEditing&&!this.saving)this._editor.beginHeader(event?.target?.id||event?.target?.closest?.('.el-form-item')?.textContent||'header')},
editorShortcut(e){if(!this.isEditing||this.saving||e.isComposing||!(e.ctrlKey||e.metaKey)||e.altKey)return;if(e.target!==this.$el&&!e.target?.closest?.('.sheet-cell,.batch-form,.sheet-toolbar,.sheet-heading'))return;const key=e.key.toLowerCase();if(!['s','z','y'].includes(key))return;e.preventDefault();e.stopPropagation();if(e.repeat)return;if(key==='s'){this.finishCellEdit().then(()=>this.save())}else if(key==='y'||e.shiftKey)this.redo();else this.undo()},
rememberCell(index,field){const row=this.sheet.rows[index];if(row&&this.editableCell(row,field))this._editor.beginCell(row,field)},
// Mount the full catalog only for the open cell, not once per row (and fixed-pane copy).
@ -532,20 +500,20 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
remove(){if(!this.canRemoveSelection)return;this.remember(this.selected);const keys=new Set(this.selected.map(r=>r._key));this.sheet.deletedIds.push(...this.selected.filter(r=>r.id).map(r=>r.id));this.sheet.rows=this.sheet.rows.filter(r=>!keys.has(r._key));this.selected=[]},
removeOne(row){if(this.readonly(row) || row.id || !this.canAdd || this.saving)return;this.remember([row]);this.sheet.rows=this.sheet.rows.filter(r=>r._key!==row._key)},
setProjects(id){if(!id || !this.isEditing || this.saving || this.selected.some(r=>this.readonly(r)||this.fieldLocked(r,'projectId')))return;if(this.selected.some(r=>r.id && r.productionTaskId && String(r.projectId)!==String(id)))return this.$modal.msgWarning('已关联生产计划的明细不能更换项目');this.remember(this.selected);this.selected.forEach(r=>{if(String(r.projectId)!==String(id))this.projectChanged(r);r.projectId=id})},
setBatchCategory(id){if(!this.isEditing||this.saving||this.sheet.batch.editable===false)return;this.remember(this.sheet.rows);this.sheet.batch.expenseCategoryId=id;this.commonCategory=id;this.sheet.rows.filter(r=>r.purchaseStatus!==5).forEach(r=>r.expenseCategoryId=id)},
setBatchCategory(id){if(!this.isEditing||this.saving||this.sheet.batch.id&&!this.$can(['warehouse:purchase:manage']))return;this.remember(this.sheet.rows);this.sheet.batch.expenseCategoryId=id;this.commonCategory=id;this.sheet.rows.filter(r=>r.purchaseStatus!==5).forEach(r=>r.expenseCategoryId=id)},
setCategories(id){if(!id || !this.isEditing || this.saving || this.selected.some(r=>this.readonly(r)||this.fieldLocked(r,'expenseCategoryId')))return;this.remember(this.selected);this.selected.forEach(r=>{r.expenseCategoryId=id})},
clearLoan(row){row.loanId=null;this.loans[row._key]=[];this._loanRequests?.delete(row._key)},
projectChanged(row){row.productionTaskId=null;this.clearLoan(row)},
brands(row){return [...new Set(candidates(this.items,row,'brand').map(i=>i.brand).filter(Boolean))]},specs(row){return candidates(this.items,row,'spec')},
async searchPlans(row,keyword){const result=await purchasePlanOptions({projectId:row.projectId,keyword});const map=new Map(this.plans.map(p=>[p.id,p]));(result.data||[]).forEach(p=>map.set(p.id,p));this.plans=[...map.values()]},
rowPlans(row){return this.plans.filter(p=>String(p.projectId)===String(row.projectId))},rowUnits(row){return [...new Set([...this.units,...(row.productId&&row.unit?[row.unit]:[])])]},
canEditCategory(row){const item=this.itemMap.get(String(row.productId));return !item || !clean(item.category) || this.canViewQuotes || this.$auth.hasPermiOr(['warehouse:product:edit'])},
canEditCategory(row){const item=this.itemMap.get(String(row.productId));return !item || !clean(item.category) || this.$auth.hasPermiOr(['warehouse:product:edit'])},
identityEditor(){return this._identityEditor||(this._identityEditor=createRowIdentityEditor({getItems:()=>this.items,loadName:name=>this.loadName(name),isCurrentRow:row=>this.isEditing&&!!this.sheet?.rows.includes(row),onDetach:row=>this.clearLoan(row)}))},
nameChanged(row,value=row.materialName){return this.identityEditor().nameChanged(row,value)},
brandChanged(row){this.identityEditor().brandChanged(row)},
specChanged(row,value){this.identityEditor().specChanged(row,value)},
projectName(id){return this.projectMap.get(String(id))?.projectName || '未选项目'},
displayCell(row,field){const mine=this.liveLocalText?.(row,field),ghost=this._live?.ghost(row,field);if(mine!==undefined)row={...row,[field]:mine};else if(ghost)row={...row,[field]:ghost.value};if(field==='projectId')return this.projectName(row.projectId);if(field==='expenseCategoryId')return this.categories.find(c=>String(c.id)===String(row[field]))?.categoryName || row.expenseCategoryName || '—';if(field==='productionTaskId')return this.plans.find(p=>String(p.id)===String(row[field]))?.taskNo || row.productionTaskNo || '—';return row[field]==null||row[field]===''?'—':row[field]},
displayCell(row,field){if(field==='projectId')return this.projectName(row.projectId);if(field==='expenseCategoryId')return this.categories.find(c=>String(c.id)===String(row[field]))?.categoryName || row.expenseCategoryName || '—';if(field==='productionTaskId')return this.plans.find(p=>String(p.id)===String(row[field]))?.taskNo || row.productionTaskNo || '—';return row[field]==null||row[field]===''?'—':row[field]},
async paste(event,index,field){
const text=event.clipboardData?.getData('text/plain');if(!text||!this.isEditing||this.saving||this.pasteApplying)return
const matrix=text.includes('\t')||/[\r\n]/.test(text);if(!matrix&&event.target.matches('input:not(.sheet-keyboard-input),textarea')){this._pasteContinuation=null;return}
@ -626,15 +594,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
this.finishCellEdit().then(()=>this.focusSelectedCell())
},
activeRows(){return this.sheet.rows.filter(r=>r.id||clean(r.materialName)||clean(r.materialBrand)||clean(r.materialParams)||clean(r.purchaseLink))},
resolveConflicts(){
const draft=resolvePurchaseSheetConflicts(this.conflictData,this.conflictChoices)
this.install(this.conflictData.latest)
draft.rows=draft.rows.map((row,index)=>({...this.emptyRow(),...row,_key:row.id?'saved-'+row.id:'merge-new-'+index+'-'+Date.now()}))
this.sheet=draft;this.editing=true;this.conflictOpen=false;this.persistDraft();this.live.blocked=false;this._live?.scheduleSave();this.$modal.msgSuccess('已合并到编辑草稿,核对后自动保存')
},
conflictText(value){return Object.entries(value).filter(([key])=>!['productId','productCode','projectCode','expenseCategoryCode'].includes(key)).map(([key,v])=>key==='projectId'?this.projectName(v):key==='expenseCategoryId'?(this.categories.find(c=>String(c.id)===String(v))?.categoryName||v||'空'):v??'空').join(' / ')},
async save(){
if(this._live&&!await this._live.settle())return this.$modal.msgWarning('上次自动保存结果尚未确认,请等待重连后核对')
if(this.saving || !this.isEditing || !this.dirty)return
if(!this.sheet.unbatched&&!this.sheet.batch.expenseCategoryId){this.batchDetailsOpen=true;await this.$nextTick();this.$refs.batchCategorySelect?.focus();return this.$modal.msgWarning('请先选择批次费用类别')}
this.validationEnabled=true
@ -647,7 +607,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
validateRows(changed,this.items,changed.map(r=>this.sheet.rows.findIndex(o=>o._key===r._key)+1))
for(const row of rows){
if(!this.referenceOnly(row)&&!row.productId&&!this.units.some(u=>same(u,row.unit)))throw new Error('新物品请使用字典中的单位')
row.finalUnitPrice=this.canViewQuotes&&row.finalUnitPrice!=null&&row.finalUnitPrice!==''?Number(row.finalUnitPrice):null
row.finalUnitPrice=this.canViewQuotes&&this.hasPrice(row)?Number(row.finalUnitPrice):null
row.actualUnitPrice=row.actualUnitPrice===''||row.actualUnitPrice===undefined?null:row.actualUnitPrice
}
this.saving=true
@ -658,11 +618,11 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
this.persistDraft()
if(JSON.parse(localStorage.getItem(this.draftPrefix()+draftId)||'null')?.sheet?.submissionKey!==this.sheet.submissionKey)
throw new Error('无法保留安全重试标识,请检查浏览器存储空间或权限后再保存')
const result=await savePurchaseSheet({...this.sheet,rows:rows.map(row=>({...row,clientRowKey:row._key})),liveClientId:this.live.connected?this.live.clientId:null,liveSequence:this._live?.sequence||0})
const result=await savePurchaseSheet({...this.sheet,rows})
this.clearDraft(draftId);this.install(result.data);if(result.data.unbatched){this.viewMode='unbatched';this.sheet=null;this.editing=false;this.baseline='';await this.$nextTick()}
await this.references()
this.$modal.msgSuccess(result.data.collaborationMerged?'清单已保存,已合并其他人的修改':'清单已保存')
}catch(e){if(e.code===409&&e.data?.conflicts){this.sheet.submissionKey=null;this.conflictData=e.data;this.conflictChoices=e.data.conflicts.map(()=>null);this.conflictOpen=true;this.persistDraft()}else if(e.message&&!e.message.includes('status code'))this.$modal.msgError(e.message)}
this.$modal.msgSuccess('清单已保存')
}catch(e){if(e.message&&!e.message.includes('status code'))this.$modal.msgError(e.message)}
finally{this.saving=false}
},
async recoverSubmission(){
@ -678,20 +638,18 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
}catch{/* Cancellation keeps all local changes; request failures are shown globally. */}
finally{this.saving=false}
},
async confirm(){if(this.saving || this.isEditing || !this.canConfirm)return;if(!this.sheet.batch.supplierId)return this.$modal.msgWarning('清单可以先保存;请编辑并补选供应商后再确认采购');const id=this.sheet.batch.id,version=this.sheet.version,rowIds=this.confirmationRows.map(r=>r.id),count=this.confirmationRows.length;this.saving=true;try{await this.$confirm(`确认${this.selected.length?'选中':rowIds?'当前筛选':'整批'} ${count} 行报价并开始采购?费用按明细所属项目和批次费用类别计入,未选行不变,重复确认不会重复计费。`,'确认采购');this.install((await confirmPurchaseSheet(id,version,rowIds)).data);this.$modal.msgSuccess('已确认采购')}catch(e){/* Request handler displays server errors. */}finally{this.saving=false}},
async confirm(){if(this.saving || this.isEditing || !this.canConfirm)return;if(!this.sheet.batch.supplierId)return this.$modal.msgWarning('清单可以先保存;请编辑并补选供应商后再确认采购');const id=this.sheet.batch.id,version=this.sheet.version,rowIds=(this.selected.length||this.rowQueue!=='all'||this.rowFilter||this.onlyInvalid)?this.confirmationRows.map(r=>r.id):undefined,count=this.confirmationRows.length;this.saving=true;try{await this.$confirm(`确认${this.selected.length?'选中':rowIds?'当前筛选':'整批'} ${count} 行报价并开始采购?费用按明细所属项目和批次费用类别计入,未选行不变,重复确认不会重复计费。`,'确认采购');this.install((await confirmPurchaseSheet(id,version,rowIds)).data);this.$modal.msgSuccess('已确认采购')}catch(e){/* Request handler displays server errors. */}finally{this.saving=false}},
exportBatch(){this.download('warehouse/purchase/supplier-export',{purchaseBatchId:this.sheet.batch.id},`${this.sheet.batch.batchNo}.xlsx`)},
async batchArrival(batch){const loaded=(await getPurchaseSheet(batch.id)).data;if(!loaded.batch.supplierId)return this.$modal.msgWarning('请先选择供应商');await this.arrival(loaded.rows.filter(r=>r.id&&r.priceLocked&&!r.historical&&Number(r.purchaseStatus)!==5&&Number(r.remainingQuantity)>0))},
async arrival(rows){if(this.isEditing || this.dirty)return this.$modal.msgWarning('请先保存或取消编辑,再登记到货');if(rows.some(r=>!r.priceLocked))return this.$modal.msgWarning('请先确认采购报价,再登记到货');await this.$refs.arrival.open(rows,'arrival')},
async arrivalChanged(){if(this.sheet&&!this.dirty)await this.openBatch(this.sheet.batch);else if(!this.sheet)await this.loadBatches()},
async records(row){this.recordsRequest=row;this.recordsItem=[row.materialName,row.materialBrand,row.materialParams,row.unit].filter(Boolean).join(' / ');this.arrivalRecords=(await listPurchaseArrival(row.id)).data||[];this.recordsOpen=true},
async records(row){this.recordsItem=[row.materialName,row.materialBrand,row.materialParams,row.unit].filter(Boolean).join(' / ');this.arrivalRecords=(await listPurchaseArrival(row.id)).data||[];this.recordsOpen=true},
goArrival(){this.recordsOpen=false;this.$router.push({path:'/procurement/arrival',query:{purchaseBatchNo:this.sheet.batch.batchNo}})}
}
}
</script>
<style scoped>
.sheet-project-note{margin:0 0 10px;font-size:12px;line-height:1.6;color:var(--el-text-color-secondary)}.sheet-list-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:16px}.sheet-list-tabs>.el-radio-group{margin:0!important}.batch-form .table-text{max-width:220px}
<style scoped>.sheet-project-note{margin:0 0 10px;font-size:12px;line-height:1.6;color:var(--el-text-color-secondary)}.sheet-list-tabs{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:16px}.sheet-list-tabs>.el-radio-group{margin:0!important}.batch-form .table-text{max-width:220px}
.purchase-sheet{display:flex;flex-direction:column;flex:1;min-height:0;min-width:0;overflow:hidden}
.sheet-save-notice{flex:none;margin-bottom:10px}
.purchase-sheet>.el-form,.purchase-sheet>.el-row,.purchase-sheet>.sheet-list-tabs,.purchase-sheet>.pagination-container{flex:none}
@ -767,9 +725,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.sheet-grid :deep(.el-input__wrapper){ padding:1px 8px; }
.sheet-grid :deep(.el-select__wrapper){ min-height:var(--cmvr-grid-height); padding:2px 8px; font-size:var(--cmvr-grid-font); }
.sheet-grid :deep(.el-select__input), .sheet-grid :deep(.el-input__inner){ padding:0; font-size:var(--cmvr-grid-font); }
.sheet-grid :deep(.sheet-cell),.sheet-grid :deep(.sheet-cell .sheet-value){text-align:center}
.sheet-grid :deep(.sheet-pending-category>.sheet-value){width:auto}
.sheet-grid :deep(.sheet-cell .el-input__inner),.sheet-grid :deep(.sheet-cell .el-select__wrapper){text-align:left}
.sheet-grid :deep(.sheet-cell),.sheet-grid :deep(.sheet-cell .sheet-value),.sheet-grid :deep(.sheet-cell .el-input__inner),.sheet-grid :deep(.sheet-cell .el-select__wrapper){text-align:left}
.sheet-grid :deep(td.el-table__cell){ padding:var(--cmvr-grid-padding) 0 !important; }
.sheet-footer { display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; flex:none; padding:12px 0; font-size:var(--cmvr-grid-font); }
.secondary { display:block; color:var(--el-text-color-secondary); font-size:12px; }
@ -781,10 +737,10 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.sheet-heading{display:flex;align-items:center;flex-wrap:wrap;gap:6px 10px;flex:none;min-width:0;margin-bottom:8px}
.sheet-heading__back{flex:none;margin:0}
.sheet-heading__identity{display:flex;align-items:center;gap:10px;flex:1 1 360px;min-width:min(100%,360px);overflow:hidden}.sheet-heading h2{flex:0 1 auto;min-width:80px;font-size:15px;line-height:24px;margin:0;color:var(--el-text-color-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sheet-heading__identity{display:flex;align-items:center;gap:10px;flex:1 1 180px;min-width:0;overflow:hidden}.sheet-heading h2{flex:0 1 auto;min-width:0;font-size:15px;line-height:24px;margin:0;color:var(--el-text-color-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.sheet-heading__meta{flex:0 3 auto;min-width:0;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--el-text-color-secondary);font-size:12px;line-height:24px}
.sheet-heading>.sheet-toolbar{flex:0 1 auto;gap:6px;margin-left:auto;min-width:0}
.sheet-heading__identity>.sheet-presence{margin-left:auto}.sheet-heading__state{flex:none}.batch-form{padding:10px 12px 0;background:var(--el-fill-color-extra-light);border-radius:5px;border-bottom:0;margin-bottom:10px;column-gap:14px}
.sheet-heading__state{flex:none}.batch-form{padding:10px 12px 0;background:var(--el-fill-color-extra-light);border-radius:5px;border-bottom:0;margin-bottom:10px;column-gap:14px}
.sheet-filters{gap:8px;margin-bottom:10px}.sheet-filters>.el-input{width:230px}.sheet-filters>.el-select{width:145px}.sheet-filters>.el-button{margin:0}.sheet-filters>.el-checkbox{margin:0 4px}
.sheet-filters>.sheet-selection{display:flex;align-items:center;gap:10px;flex-wrap:nowrap;margin:0 0 0 auto;padding:0;font-size:12px;color:var(--el-text-color-secondary)}
.sheet-grid :deep(.row-more){vertical-align:middle;margin-left:8px}.sheet-grid :deep(.business-operation-cell .cell){white-space:nowrap}

View File

@ -59,6 +59,7 @@ manage/
流程画布的共享布局方案、数据边界、接口和验证记录见 [流程共享布局](docs/shared-flow-layout.md)。节点坐标、分区和排版结果按项目、迭代共用,仅由迭代创建者维护;节点生成、连线、框选/多选及分组也限定该创建者,其他成员(含其他项目管理者)只读数据库布局。阶段组父子关系、执行连线及回退记录继续由现有业务表保存。流程视图不再恢复或写入浏览器缓存,旧流程缓存直接清理;所有成员可临时平移、缩放、展开折叠及查看详情,浏览动作不保存。页面刷新或显式重新加载成功后恢复数据库坐标、统一展开及默认视口,后台静默同步保留当前浏览状态。
- 阶段节点展示已有描述的两行摘要,完整说明在阶段抽屉查看;拖入新阶段时可填写描述。
- 所有成员单击阶段节点(含阶段组、子阶段和数量区域)仅临时选中,双击才打开详情;单击空白取消选中。历史版本、审批、编辑及折叠等明确操作按钮保留单击行为,选择不保存到数据库或浏览器缓存;普通成员仍不能框选、多选或修改布局。
- 采购当前执行版本记录实际开始后即放行直接下游,蓝色连线标注“开始即放行”;采购仍须验收及人工确认才算完成。绿色表示真实完成,历史沿用保持琥珀色;多条入边须全部满足,阶段组仍须全部子阶段完成。详情展示服务端完整准入条件(含继承门禁),排期分别标示采购开始至开始、其他执行边结束至开始边界。
- 流程画布左侧节点库提供阶段组、需求、方案、采购、设计、加工、组装、调试、研发、测试和自定义,支持搜索与拖放。普通类型拖入组内(包括子节点上方)自动归属,组本身仍只支持根画布;未执行及历史保护规则保持不变。自定义类型按普通工作阶段要求交付齐备后提审,不支持承载子阶段。
- 节点分类创建后固定,名称、负责人和说明可编辑;只有阶段组承载子阶段,其余分类沿用工作阶段规则。组内快捷创建可在提交前选择工作分类;复制迭代保留来源分类,回退换版沿用同一节点身份。

View File

@ -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 共同控制编辑能力,不能依赖项目管理角色;新建阶段后坐标须等最新阶段摘要到达才能保存,避免尚未加载的节点身份被错误拒绝。

View File

@ -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')
}
/** 当前或历史版本共用同一阶段抽屉,零号虚拟节点只展示未分配当前工作项。 */

View File

@ -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>

View 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;

View File

@ -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