feat(app): 优化移动端应用配置和功能实现

- 添加生产环境服务器地址配置支持内外网切换
- 实现采购列表只看我创建的功能开关
- 更新构建脚本中的默认生产环境API地址
- 优化采购单表格单元格编辑体验改用自动补全组件
- 调整应用更新检查逻辑增强生产环境兼容性
- 修复开发服务器切换时的一些验证问题
- 增强应用启动时的服务地址配置灵活性
This commit is contained in:
lixiaolong 2026-11-03 09:16:55 +08:00
parent 071994c0e0
commit c9dccdae5c
28 changed files with 429 additions and 138 deletions

View File

@ -5,9 +5,9 @@ module.exports = () => {
return {
name: env.variant === 'prod' ? '设备科综合管理系统' : '设备科综合管理系统·开发',
icon: `./assets/brand/app-icon-blue-${env.variant}.png`,
slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.1', orientation: 'portrait', userInterfaceStyle: 'automatic',
slug: 'cmvr-wms', version: env.variant === 'dev' ? '1.0.5' : '1.0.2', orientation: 'portrait', userInterfaceStyle: 'automatic',
platforms: ['android', 'web'],
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 6,
android: { package: env.variant === 'prod' ? 'cn.cmvr.wms' : 'cn.cmvr.wms.dev', versionCode: env.variant === 'dev' ? 13 : 7,
adaptiveIcon: { foregroundImage: `./assets/brand/app-icon-blue-${env.variant}-adaptive.png`, backgroundColor: '#ffffff' },
permissions: ['android.permission.REQUEST_INSTALL_PACKAGES'], blockedPermissions: ['android.permission.RECORD_AUDIO'] },
plugins: ['./plugins/with-apk-installer.cjs', 'expo-sharing', 'expo-secure-store', 'expo-status-bar', './plugins/with-short-cmake-paths.cjs', './plugins/with-private-build-inputs.cjs', ['./plugins/with-internal-network.cjs', { hosts: cleartextHosts }],

View File

@ -5,6 +5,7 @@ import com.ruoyi.warehouse.domain.PurchaseRequest;
import com.ruoyi.warehouse.domain.PurchaseSheet;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.math.BigDecimal;
import java.math.RoundingMode;
@ -75,7 +76,7 @@ public final class SupplierInquiryExport {
public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts) {
return workbook(purchase,includeActualAmounts,null);
}
private static final Set<String> COLUMN_KEYS=Set.of("name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","remark");
private static final Set<String> COLUMN_KEYS=Set.of("index","name","spec","brand","unit","quantity","quoteUnitPrice","quoteAmount","actualUnitPrice","actualAmount","link","remark");
public static XSSFWorkbook workbook(PurchaseSheet purchase,boolean includeActualAmounts,String selectedColumns) {
Set<String> selected;
if(selectedColumns==null) selected=COLUMN_KEYS;
@ -86,6 +87,7 @@ public final class SupplierInquiryExport {
selected.add(key);
}
}
if(selectedColumns!=null)return selectedWorkbook(purchase,includeActualAmounts,selected);
var items = items(purchase);
if (items.isEmpty()) throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填");
var book = new XSSFWorkbook(); var sheet = book.createSheet("供应商询价单"); sheet.setDisplayGridlines(false);
@ -151,6 +153,60 @@ public final class SupplierInquiryExport {
book.setPrintArea(0,0,remarkColumn,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);
return book;
}
private record Column(String key,String label,int width) { }
private static final List<Column> EXPORT_COLUMNS=List.of(new Column("index","序号",8),new Column("name","物品名称",26),new Column("spec","规格型号",40),new Column("brand","品牌",18),new Column("unit","单位",9),new Column("quantity","采购数量",14),new Column("quoteUnitPrice","报价单价(元)",18),new Column("quoteAmount","报价金额(元)",18),new Column("actualUnitPrice","实际单价(元)",18),new Column("actualAmount","实际金额(元)",18),new Column("link","采购链接",38),new Column("remark","备注",38));
private static XSSFWorkbook selectedWorkbook(PurchaseSheet purchase,boolean includeActual,Set<String> selected){
var columns=EXPORT_COLUMNS.stream().filter(c->selected.contains(c.key())&&(includeActual||!c.key().startsWith("actual"))).toList();
if(columns.isEmpty())throw new ServiceException("请至少选择一个可导出的字段");
var items=items(purchase);if(items.isEmpty())throw new ServiceException("当前批次暂无可询价明细,已入库、历史及取消明细不参与报价回填");
var book=new XSSFWorkbook();var sheet=book.createSheet("供应商询价单");sheet.setDisplayGridlines(false);SupplierInquiryMetadata.mark(book);
var font=book.createFont();font.setFontName("Arial");font.setFontHeightInPoints((short)11);
var body=book.createCellStyle();body.setFont(font);body.setAlignment(HorizontalAlignment.CENTER);body.setVerticalAlignment(VerticalAlignment.CENTER);body.setWrapText(true);
var titleFont=book.createFont();titleFont.setFontName("Arial");titleFont.setFontHeightInPoints((short)16);titleFont.setBold(true);
var title=book.createCellStyle();title.cloneStyleFrom(body);title.setFont(titleFont);
var headerFont=book.createFont();headerFont.setFontName("Arial");headerFont.setColor(IndexedColors.WHITE.getIndex());headerFont.setBold(true);
var headerStyle=book.createCellStyle();headerStyle.cloneStyleFrom(body);headerStyle.setFont(headerFont);headerStyle.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
var numeric=book.createCellStyle();numeric.cloneStyleFrom(body);numeric.setDataFormat(book.createDataFormat().getFormat("#,##0.00####"));
var whole=book.createCellStyle();whole.cloneStyleFrom(body);whole.setDataFormat(book.createDataFormat().getFormat("#,##0"));
var fractional=book.createCellStyle();fractional.cloneStyleFrom(body);fractional.setDataFormat(book.createDataFormat().getFormat("#,##0.####"));
var amount=book.createCellStyle();amount.cloneStyleFrom(body);amount.setDataFormat(book.createDataFormat().getFormat("#,##0.00"));
var input=book.createCellStyle();input.cloneStyleFrom(numeric);input.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());input.setFillPattern(FillPatternType.SOLID_FOREGROUND);input.setLocked(false);
var positions=new HashMap<String,Integer>();for(int c=0;c<columns.size();c++){positions.put(columns.get(c).key(),c);sheet.setColumnWidth(c,columns.get(c).width()*256);}
int last=columns.size()-1;
sheet.createRow(0).setHeightInPoints(8);var titleRow=sheet.createRow(1);titleRow.setHeightInPoints(26);titleRow.createCell(0).setCellValue("供应商询价单");titleRow.getCell(0).setCellStyle(title);
String supplier=clean(purchase.getBatch().getSupplierName());if(supplier.isEmpty())supplier=purchase.getRows().stream().map(r->clean(r.getSupplierName())).filter(s->!s.isEmpty()).findFirst().orElse("待定");
var context=sheet.createRow(2);context.createCell(0).setCellValue("采购批次:"+purchase.getBatch().getBatchNo()+" 供应商:"+supplier);context.getCell(0).setCellStyle(body);context.setHeightInPoints(last<2?60:28);
var note=sheet.createRow(3);note.createCell(0).setCellValue(positions.containsKey("quoteUnitPrice")?"填写说明:仅填写黄色报价单价,未报价留空。请勿修改物品信息及单元格匹配批注,填写后回传原文件。":"说明:本次未导出报价单价填写列;如需报价回填,请重新导出时勾选报价单价。");note.getCell(0).setCellStyle(body);note.setHeightInPoints(last<2?96:44);
for(int r:List.of(1,2,3))if(last>0)sheet.addMergedRegion(new CellRangeAddress(r,r,0,last));
var head=sheet.createRow(5);head.setHeightInPoints(28);for(int c=0;c<columns.size();c++){var cell=head.createCell(c);cell.setCellValue(columns.get(c).label());cell.setCellStyle(headerStyle);}
int index=6;
for(var item:items){
var row=sheet.createRow(index);row.setHeightInPoints(Math.min(409,Math.max(selected.contains("spec")&&item.spec().length()>35||selected.contains("name")&&item.name().length()>20?44:32,selected.contains("remark")?remarkHeight(item.remark()):0)));
for(int c=0;c<columns.size();c++){
var cell=row.createCell(c);cell.setCellStyle(body);
switch(columns.get(c).key()){
case "index" -> cell.setCellValue(index-5);
case "name" -> setText(cell,item.name());case "spec" -> setText(cell,item.spec());case "brand" -> setText(cell,item.brand());case "unit" -> setText(cell,item.unit());
case "quantity" -> {cell.setCellValue(item.quantity().doubleValue());cell.setCellStyle(item.quantity().stripTrailingZeros().scale()<=0?whole:fractional);}
case "quoteUnitPrice" -> cell.setCellStyle(input);
case "quoteAmount" -> {cell.setCellStyle(amount);if(positions.containsKey("quoteUnitPrice")){String price=CellReference.convertNumToColString(positions.get("quoteUnitPrice"))+(index+1),quantity=positions.containsKey("quantity")?CellReference.convertNumToColString(positions.get("quantity"))+(index+1):item.quantity().toPlainString();cell.setCellFormula("IF(ISNUMBER("+price+"),ROUND("+quantity+"*"+price+",2),\"\")");}}
case "actualUnitPrice" -> {cell.setCellStyle(numeric);if(item.mixedActualPrices())setText(cell,"多种实际单价");else if(item.actualUnitPrice()!=null)cell.setCellValue(item.actualUnitPrice().doubleValue());}
case "actualAmount" -> {cell.setCellStyle(amount);if(item.actualAmount()!=null)cell.setCellValue(item.actualAmount().doubleValue());}
case "link" -> setText(cell,item.link());case "remark" -> setText(cell,item.remark());
}
}
SupplierInquiryMetadata.write(row,0,new SupplierInquiryMetadata.Match(purchase.getBatch().getBatchNo(),item.snapshot(),item.rowIds()));index++;
}
if(positions.containsKey("quoteUnitPrice")){int c=positions.get("quoteUnitPrice");var helper=sheet.getDataValidationHelper();var validation=helper.createValidation(helper.createDecimalConstraint(DataValidationConstraint.OperatorType.BETWEEN,"0","999999999999.999999"),new org.apache.poi.ss.util.CellRangeAddressList(6,index-1,c,c));validation.setEmptyCellAllowed(true);validation.setShowErrorBox(true);validation.createErrorBox("请填写有效单价","报价单价需为非负数,最多6位小数;不报价请留空。");sheet.addValidationData(validation);}
sheet.setAutoFilter(new CellRangeAddress(5,index-1,0,last));
if(positions.containsKey("actualAmount")){
int c=positions.get("actualAmount");if(last==0){var label=sheet.createRow(index++).createCell(0);label.setCellValue("实际金额合计");label.setCellStyle(body);SupplierInquiryMetadata.total(label);}
var total=sheet.createRow(index);total.setHeightInPoints(36);if(last>0){var label=total.createCell(c==0?1:0);label.setCellValue("实际金额合计");label.setCellStyle(body);}
var cell=total.createCell(c);String range=CellReference.convertNumToColString(c)+"7:"+CellReference.convertNumToColString(c)+(items.size()+6);cell.setCellFormula("IF(COUNT("+range+")="+items.size()+",SUM("+range+"),\"\")");cell.setCellStyle(amount);SupplierInquiryMetadata.total(cell);index++;
}
sheet.createFreezePane(last>0?1:0,6);sheet.setRepeatingRows(new CellRangeAddress(5,5,-1,-1));sheet.getPrintSetup().setLandscape(true);sheet.getPrintSetup().setPaperSize(PrintSetup.A3_PAPERSIZE);sheet.getPrintSetup().setFitWidth((short)1);sheet.getPrintSetup().setFitHeight((short)0);sheet.setFitToPage(true);
book.setPrintArea(0,0,last,0,index-1);book.getCreationHelper().createFormulaEvaluator().evaluateAll();book.setForceFormulaRecalculation(true);return book;
}
private static float remarkHeight(String remark) {
int lines=0;
for(String line:remark.split("\n",-1)) {

View File

@ -15,7 +15,8 @@ public final class SupplierQuoteImport {
public static List<Map<String,Object>> preview(InputStream input, PurchaseSheet sheet) throws Exception {
var current = SupplierInquiryExport.items(sheet);
try (var workbook=WorkbookFactory.create(input)) {
var formatter=new DataFormatter(Locale.ROOT); Header header=findHeader(workbook,formatter);
boolean metadataRequired=SupplierInquiryMetadata.required(workbook);
var formatter=new DataFormatter(Locale.ROOT); Header header=findHeader(workbook,formatter,metadataRequired);
Sheet tab=header.sheet();Map<String,Integer> columns=header.columns();
if(tab.getLastRowNum()-header.row()>2000)throw new ServiceException("报价文件最多2000行,请按批次分别回传");
String contextBatch=contextBatch(tab,header.row(),formatter);
@ -23,15 +24,18 @@ public final class SupplierQuoteImport {
var evaluator=workbook.getCreationHelper().createFormulaEvaluator();
for(int n=header.row()+1;n<=tab.getLastRowNum();n++) {
var row=tab.getRow(n);if(row==null)continue;
if(metadataRequired&&SupplierInquiryMetadata.isTotal(row))continue;
SupplierInquiryMetadata.Match metadata=null;String error=null;
if(metadataRequired)try{metadata=SupplierInquiryMetadata.read(row);if(metadata==null)error="所选采购明细匹配标记缺失,请重新导出询价单";}catch(ServiceException invalid){error=invalid.getMessage();}
String code=text(row,columns.get("物品编码"),formatter), name=text(row,columns.get("物品名称"),formatter), rawPrice=text(row,columns.get("最终单价"),formatter);
if(code.isEmpty()&&name.isEmpty()&&rawPrice.isEmpty())continue;
String batch=text(row,columns.get("采购批次"),formatter);if(batch.isEmpty())batch=contextBatch;
if(code.isEmpty()&&name.isEmpty()&&rawPrice.isEmpty()&&metadata==null){boolean content=false;for(var cell:row)if(!formatter.formatCellValue(cell).isBlank()){content=true;break;}if(!metadataRequired||!content)continue;}
String batch=metadata==null?text(row,columns.get("采购批次"),formatter):metadata.batch();if(batch.isEmpty())batch=contextBatch;
var item=new LinkedHashMap<String,Object>();item.put("line",n+1);item.put("productCode",code);item.put("name",name);item.put("spec",text(row,columns.get("规格型号"),formatter));item.put("brand",text(row,columns.get("品牌"),formatter));item.put("unit",text(row,columns.get("单位"),formatter));item.put("price",rawPrice);item.put("rowIds",List.of());item.put("unitPrice",null);item.put("skipped",rawPrice.isEmpty());
String error=null;
var candidates=current;
if(columns.containsKey("采购明细标识")) {
if(metadataRequired||columns.containsKey("采购明细标识")) {
try {
var ids=Arrays.stream(text(row,columns.get("采购明细标识"),formatter).split(",",-1)).map(String::trim).map(Long::valueOf).toList();
if(metadataRequired&&(metadata==null||error!=null))throw new IllegalArgumentException();
var ids=metadataRequired?metadata.rowIds():Arrays.stream(text(row,columns.get("采购明细标识"),formatter).split(",",-1)).map(String::trim).map(Long::valueOf).toList();
if(new HashSet<>(ids).size()!=ids.size())throw new IllegalArgumentException();
var subset=SupplierInquiryExport.selected(sheet,ids);
if(subset.getRows().stream().anyMatch(value->!SupplierInquiryExport.eligible(value)))throw new IllegalArgumentException();
@ -39,15 +43,15 @@ public final class SupplierQuoteImport {
if(candidates.size()!=1)throw new IllegalArgumentException();
}catch(Exception invalid){error="所选采购明细已变化或匹配信息缺失,请重新导出询价单";candidates=List.of();}
}
var matches=candidates.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList();
var matches=metadataRequired?candidates:candidates.stream().filter(value->!code.isEmpty()?code.equals(value.productCode()):name.equals(value.name())&&identityMatches(row,columns,formatter,value)).toList();
SupplierInquiryExport.Item match=matches.size()==1?matches.get(0):null;
if(error!=null) { /* Keep the selection error; never widen to the whole batch. */ }
else if(!Objects.equals(batch,sheet.getBatch().getBatchNo()))error="采购批次不一致,请回传当前批次的询价单";
else if(match==null)error=matches.size()>1?"存在同名物品,请保留原表隐藏列,或补全品牌、规格和单位":"当前批次找不到可回填的物品,或该物品已入库、为历史/取消明细";
else if(match==null)error=matches.size()>1?"存在同名物品,请回传原表,或补全品牌、规格和单位":"当前批次找不到可回填的物品,或该物品已入库、为历史/取消明细";
else {
item.put("productCode",match.productCode());item.put("name",match.name());item.put("spec",match.spec());item.put("brand",match.brand());item.put("unit",match.unit());item.put("quantity",match.quantity());item.put("previousPrice",match.previousPrice());item.put("rowIds",match.rowIds());
if(!identityMatches(row,columns,formatter,match))error="物品名称、规格、品牌或单位与采购清单不一致,请勿修改询价单物品信息";
String snapshot=text(row,columns.get("清单校验"),formatter);
String snapshot=metadata==null?text(row,columns.get("清单校验"),formatter):metadata.snapshot();
if(error==null&&!snapshot.isEmpty()&&!snapshot.equals(match.snapshot()))error="采购清单已变化,请重新导出当前批次询价单后报价";
if(error==null&&columns.containsKey("采购数量")) {
try { if(number(row.getCell(columns.get("采购数量")),evaluator).compareTo(match.quantity())!=0)error="采购数量与当前清单不一致,请重新导出询价单"; }
@ -66,7 +70,7 @@ public final class SupplierQuoteImport {
return result;
}
}
private static Header findHeader(Workbook workbook,DataFormatter formatter) {
private static Header findHeader(Workbook workbook,DataFormatter formatter,boolean metadataRequired) {
List<Header> found=new ArrayList<>();
if(workbook.getNumberOfSheets()>50)throw new ServiceException("报价工作表过多,请仅保留本批次询价单");
for(int s=0;s<workbook.getNumberOfSheets();s++) {
@ -74,7 +78,7 @@ public final class SupplierQuoteImport {
for(int r=tab.getFirstRowNum();r<=Math.min(tab.getLastRowNum(),24);r++) {
var row=tab.getRow(r);if(row==null)continue;Map<String,Integer> columns=new HashMap<>();Set<String> duplicates=new HashSet<>();
for(var cell:row) {String key=canonical(formatter.formatCellValue(cell).trim());if(key!=null&&columns.putIfAbsent(key,cell.getColumnIndex())!=null)duplicates.add(key);}
if(columns.containsKey("最终单价")&&(columns.containsKey("物品编码")||columns.containsKey("物品名称"))){if(!duplicates.isEmpty())throw new ServiceException("报价表存在重复列:"+String.join("、",duplicates));found.add(new Header(tab,r,columns));break;}
if(columns.containsKey("最终单价")&&(metadataRequired||columns.containsKey("物品编码")||columns.containsKey("物品名称"))){if(!duplicates.isEmpty())throw new ServiceException("报价表存在重复列:"+String.join("、",duplicates));found.add(new Header(tab,r,columns));break;}
}
}
var preferred=found.stream().filter(header->"供应商询价单".equals(header.sheet().getSheetName())).toList();

View File

@ -38,6 +38,44 @@ import static org.mockito.Mockito.*;
/** Real MySQL saves/locks run inside a rollback-only transaction, never against another database. */
@EnabledIfSystemProperty(named="projectDbTests", matches="true")
class PurchaseSheetDatabaseTest {
@Test void provisionalCategoryCanSaveAndConfirmPurchasesThenReclassifiesOnlyLinkedRecords()throws Exception {
Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) {
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("category-flow-rollback");security.when(SecurityUtils::getUserId).thenReturn(1L);
new TransactionTemplate(f.manager).executeWithoutResult(status->{status.setRollbackOnly();
var raw=(PurchaseSheetService)org.springframework.test.util.AopTestUtils.getUltimateTargetObject(f.service);
var categories=new ItemCategoryService();f.set(categories,"jdbc",f.jdbc);f.set(categories,"catalogLock",ReflectionTestUtils.getField(raw,"catalogLock"));
f.set(raw,"itemCategories",categories);
f.set(org.springframework.test.util.AopTestUtils.getUltimateTargetObject(ReflectionTestUtils.getField(raw,"products")),"itemCategories",categories);
f.set(org.springframework.test.util.AopTestUtils.getUltimateTargetObject(ReflectionTestUtils.getField(raw,"purchases")),"itemCategories",categories);
var dictionaries=mock(com.ruoyi.system.service.ISysDictDataService.class);
var applications=new ItemCategoryApplicationService();f.set(applications,"jdbc",f.jdbc);f.set(applications,"catalogLock",ReflectionTestUtils.getField(raw,"catalogLock"));f.set(applications,"categories",categories);f.set(applications,"dictionaries",dictionaries);
var parent=applications.groups().get(0);long group=((Number)parent.get("id")).longValue();String temporary=f.name+"临时分类",temporaryGroup=parent.get("label").toString();
long application=((Number)applications.submit(new ItemCategoryApplicationService.Application("LEAF",temporary,group,"先使用,后确认",f.name,"")).get("id")).longValue();
var draft=f.draft();draft.getRows().get(1).setProjectId(draft.getRows().get(0).getProjectId());draft.getRows().forEach(row->row.setCategory(temporary));
var saved=f.save(draft);assertEquals(2,saved.getRows().size());assertTrue(saved.getRows().stream().allMatch(row->temporary.equals(row.getCategory())));
assertEquals(3,f.jdbc.queryForObject("select count(*) from item_category_usage where application_id=?",Integer.class,application));
assertEquals(temporaryGroup,categories.options().stream().filter(row->temporary.equals(row.get("label"))).findFirst().orElseThrow().get("parentLabel"));
assertEquals(temporaryGroup,((com.ruoyi.warehouse.service.IProductInfoService)ReflectionTestUtils.getField(raw,"products")).selectProductInfoById(saved.getRows().get(0).getProductId()).getCategoryGroupName());
var purchased=f.service.confirm(saved.getBatch().getId(),saved.getVersion());assertTrue(purchased.getRows().stream().allMatch(row->Boolean.TRUE.equals(row.getPriceLocked())));
var before=f.jdbc.queryForList("select id,quantity,final_unit_price,estimated_amount,purchase_status,price_locked,product_id from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId());
int events=f.jdbc.queryForObject("select count(*) from inventory_cost_event",Integer.class);
f.jdbc.update("insert into product_info(product_code,product_name,category,unit) values(?,?,?,'件')",f.name+"unlinked",f.name+"unlinked",temporary);
var target=categories.confirmedOptions().get(0);long targetId=((Number)target.get("id")).longValue();String targetName=(String)target.get("label");
assertThrows(ServiceException.class,()->applications.review(application,new ItemCategoryApplicationService.Review(false,null,null,"分类整理",targetId,"outdated")));
var version=(String)applications.usage(application,1,20).get("version");
var result=applications.review(application,new ItemCategoryApplicationService.Review(false,null,null,"归入已有分类",targetId,version));assertEquals("ADJUSTED",result.get("status"));assertEquals(2,result.get("purchaseCount"));assertEquals(1,result.get("productCount"));
assertTrue(f.service.load(saved.getBatch().getId()).getRows().stream().allMatch(row->targetName.equals(row.getCategory())));
assertEquals(targetName,f.jdbc.queryForObject("select category from product_info where id=?",String.class,saved.getRows().get(0).getProductId()));
assertEquals(temporary,f.jdbc.queryForObject("select category from product_info where product_code=?",String.class,f.name+"unlinked"));
assertEquals(before,f.jdbc.queryForList("select id,quantity,final_unit_price,estimated_amount,purchase_status,price_locked,product_id from purchase_request where purchase_batch_id=? order by id",saved.getBatch().getId()));
assertEquals(events,f.jdbc.queryForObject("select count(*) from inventory_cost_event",Integer.class));
assertEquals(3,f.jdbc.queryForObject("select count(*) from item_category_adjustment where application_id=?",Integer.class,application));
assertThrows(ServiceException.class,()->f.save(f.copy(purchased)));
});
}
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
}
@Test void historyCorrectionChecksEveryBaselineAndRetriesWithoutDuplicateWrites()throws Exception {
Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) {
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("history-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
@ -603,7 +641,7 @@ class PurchaseSheetDatabaseTest {
SupplierService supplier=new SupplierService();set(supplier,"db",jdbc);
set(purchaseTarget,"businessNumbers",allocator);
ISysDictTypeService dict=mock(ISysDictTypeService.class);SysDictData unit=new SysDictData();unit.setDictLabel("件");unit.setStatus("0");when(dict.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));
set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别","更正类别"));set(productTarget,"itemCategories",itemCategories);
set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别","更正类别"));set(productTarget,"itemCategories",itemCategories);set(purchaseTarget,"itemCategories",itemCategories);
PurchaseSheetService target=new PurchaseSheetService();set(target,"batches",session.getMapper(PurchaseBatchMapper.class));set(target,"requests",purchases);set(target,"catalog",catalog);set(target,"products",productService);set(target,"purchases",proxy(purchaseTarget));set(target,"prices",prices);set(target,"suppliers",supplier);set(target,"catalogLock",lock);set(target,"jdbc",jdbc);set(target,"json",new ObjectMapper().findAndRegisterModules());set(target,"dictTypes",dict);
set(target,"batchNumbers",numbers);set(target,"operationLogs",logs); service=proxy(target);
set(target,"itemCategories",itemCategories);

View File

@ -127,30 +127,28 @@ class SupplierInquiryRoundTripTest {
var result=preview(bytes.toByteArray(),purchase);assertTrue(ready(result.get(0)));assertEquals(List.of(1L,2L),result.get(0).get("rowIds"));
}
}
@Test void selectedColumnsHideRequiredIdentityButNeverWriteUnselectedOptionalValues() throws Exception {
@Test void selectedColumnsOnlyExistInTheFileAndNeverWriteUnselectedValues() throws Exception {
var purchase=purchase();purchase.getRows().forEach(r->{r.setRemark("敏感备注");r.setActualUnitPrice(BigDecimal.TEN);});
for(boolean includeActual:List.of(true,false))try(var book=SupplierInquiryExport.workbook(purchase,includeActual,"name,quoteUnitPrice");var bytes=new ByteArrayOutputStream()) {
var tab=book.getSheetAt(0);int link=includeActual?10:8,remark=includeActual?14:12;
assertTrue(tab.isColumnHidden(2));assertFalse(tab.isColumnHidden(1));assertFalse(tab.isColumnHidden(6));
assertEquals(CellType.BLANK,tab.getRow(6).getCell(link).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(remark).getCellType());
assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType());
if(includeActual){assertEquals(CellType.BLANK,tab.getRow(6).getCell(8).getCellType());assertEquals(CellType.BLANK,tab.getRow(6).getCell(9).getCellType());}
tab.getRow(6).getCell(6).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0)));
var tab=book.getSheetAt(0);assertEquals(2,tab.getRow(5).getLastCellNum());assertEquals("物品名称",tab.getRow(5).getCell(0).getStringCellValue());assertEquals("报价单价(元)",tab.getRow(5).getCell(1).getStringCellValue());
for(var row:tab){assertTrue(row.getLastCellNum()<=2);for(var cell:row)if(cell.getCellType()==CellType.STRING)assertFalse(cell.getStringCellValue().contains("敏感备注"));}
for(int c=0;c<16;c++)assertFalse(tab.isColumnHidden(c));
tab.getRow(6).getCell(1).setCellValue(5);book.write(bytes);assertTrue(ready(preview(bytes.toByteArray(),purchase).get(0)));
}
try(var book=SupplierInquiryExport.workbook(purchase,true,"name")){assertTrue(book.getSheetAt(0).isColumnHidden(6));assertEquals(CellType.BLANK,book.getSheetAt(0).getRow(6).getCell(7).getCellType());}
try(var book=SupplierInquiryExport.workbook(purchase,true,"name")){assertEquals(1,book.getSheetAt(0).getRow(5).getLastCellNum());assertNull(book.getSheetAt(0).getRow(6).getCell(1));assertFalse(book.getSheetAt(0).isColumnHidden(0));}
assertThrows(ServiceException.class,()->SupplierInquiryExport.workbook(purchase,true,"quoteUnitPrice,bogus"));
}
@Test void totalLabelRemainsVisibleWhenActualUnitPriceIsOmitted() throws Exception {
var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN));
try(var book=SupplierInquiryExport.workbook(purchase,true,"name,quoteUnitPrice,actualAmount,remark")) {
var sheet=book.getSheetAt(0);assertTrue(sheet.isColumnHidden(8));assertFalse(sheet.isColumnHidden(6));
assertEquals("实际金额合计",sheet.getRow(8).getCell(6).getStringCellValue());
assertEquals(60,sheet.getRow(8).getCell(9).getNumericCellValue());
assertEquals("A6:O8",sheet.getCTWorksheet().getAutoFilter().getRef());
var sheet=book.getSheetAt(0);assertEquals(4,sheet.getRow(5).getLastCellNum());
assertEquals("实际金额合计",sheet.getRow(8).getCell(0).getStringCellValue());
assertEquals(60,sheet.getRow(8).getCell(2).getNumericCellValue());
assertEquals("A6:D8",sheet.getCTWorksheet().getAutoFilter().getRef());
}
try(var book=SupplierInquiryExport.workbook(purchase,false,"name,quoteUnitPrice,remark")) {
assertEquals("A6:M8",book.getSheetAt(0).getCTWorksheet().getAutoFilter().getRef());
assertEquals("A6:C8",book.getSheetAt(0).getCTWorksheet().getAutoFilter().getRef());
}
}
@ -173,7 +171,7 @@ class SupplierInquiryRoundTripTest {
@Test void exportedCellsAreCenteredAndQuoteInputIsOptional() throws Exception {
var purchase=purchase();purchase.getRows().forEach(r->r.setActualUnitPrice(BigDecimal.TEN));
try(var book=SupplierInquiryExport.workbook(purchase,true,"name,actualAmount")) {
var tab=book.getSheetAt(0);assertTrue(tab.isColumnHidden(6));assertTrue(tab.isColumnHidden(7));assertEquals(CellType.BLANK,tab.getRow(6).getCell(7).getCellType());assertFalse(tab.isColumnHidden(1));assertEquals("实际金额合计",tab.getRow(8).getCell(1).getStringCellValue());
var tab=book.getSheetAt(0);assertEquals(2,tab.getRow(5).getLastCellNum());assertEquals("实际金额合计",tab.getRow(8).getCell(0).getStringCellValue());assertFalse(tab.isColumnHidden(0));assertFalse(tab.isColumnHidden(1));
for(var row:tab)for(var cell:row){assertEquals(HorizontalAlignment.CENTER,cell.getCellStyle().getAlignment());assertEquals(VerticalAlignment.CENTER,cell.getCellStyle().getVerticalAlignment());}
}
}
@ -183,7 +181,7 @@ class SupplierInquiryRoundTripTest {
try(var security=org.mockito.Mockito.mockStatic(com.ruoyi.warehouse.util.PurchaseQuoteAccess.class,org.mockito.Mockito.CALLS_REAL_METHODS)) {
security.when(com.ruoyi.warehouse.util.PurchaseQuoteAccess::allowed).thenReturn(true);
var response=new org.springframework.mock.web.MockHttpServletResponse();controller.inquiryExport(1L,"snapshot-1","name,quantity",new PurchaseRequestController.InquiryExportSelection(List.of(2L)),response);
try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){assertEquals(2,book.getSheetAt(0).getRow(6).getCell(5).getNumericCellValue());assertNull(book.getSheetAt(0).getRow(7));assertTrue(book.getSheetAt(0).isColumnHidden(6));}
try(var book=new XSSFWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()))){assertEquals(2,book.getSheetAt(0).getRow(6).getCell(1).getNumericCellValue());assertNull(book.getSheetAt(0).getRow(7));assertEquals(2,book.getSheetAt(0).getRow(5).getLastCellNum());assertFalse(book.getSheetAt(0).isColumnHidden(0));assertFalse(book.getSheetAt(0).isColumnHidden(1));}
assertThrows(ServiceException.class,()->controller.inquiryExport(1L,"snapshot-1","name",new PurchaseRequestController.InquiryExportSelection(List.of(999L)),new org.springframework.mock.web.MockHttpServletResponse()));
}
}

View File

@ -72,7 +72,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService
SysDictData data = selectDictDataById(dictCode);
dictDataMapper.deleteDictDataById(dictCode);
List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
DictUtils.setDictCache(data.getDictType(), dictDatas);
cacheAfterCategoryCommit(data.getDictType(), dictDatas);
}
}
@ -91,7 +91,7 @@ public class SysDictDataServiceImpl implements ISysDictDataService
if (row > 0)
{
List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
DictUtils.setDictCache(data.getDictType(), dictDatas);
cacheAfterCategoryCommit(data.getDictType(), dictDatas);
}
return row;
}
@ -111,8 +111,18 @@ public class SysDictDataServiceImpl implements ISysDictDataService
if (row > 0)
{
List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(data.getDictType());
DictUtils.setDictCache(data.getDictType(), dictDatas);
cacheAfterCategoryCommit(data.getDictType(), dictDatas);
}
return row;
}
/** A category approved in a transaction must not leak through the dictionary cache before commit. */
private void cacheAfterCategoryCommit(String type, List<SysDictData> rows)
{
if (itemCategories.managed(type) && org.springframework.transaction.support.TransactionSynchronizationManager.isSynchronizationActive()) {
org.springframework.transaction.support.TransactionSynchronizationManager.registerSynchronization(new org.springframework.transaction.support.TransactionSynchronization() {
@Override public void afterCommit() { DictUtils.setDictCache(type, rows); }
});
} else DictUtils.setDictCache(type, rows);
}
}

View File

@ -44,7 +44,21 @@ public class ItemCategoryService {
return jdbc.queryForObject("select (select count(*) from product_info where category=?)+(select count(*) from purchase_request where category=?)",Long.class,label,label)>0;
}
public List<Map<String,Object>> options() {
return jdbc.queryForList("select c.dict_code as id,c.dict_label as label,c.parent_code as parentId,g.dict_label as parentLabel from sys_dict_data c left join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type=? where c.dict_type=? and c.status='0' and (c.parent_code is null or g.status='0') order by coalesce(g.dict_sort,2147483647),g.dict_code,c.dict_sort,c.dict_code",GROUP,LEAF);
var result=new ArrayList<>(confirmedOptions());
result.addAll(jdbc.queryForList("select concat('pending-',a.id) as id,a.category_name as label,coalesce(g.dict_code,concat('pending-group-',pg.id)) as parentId,coalesce(g.dict_label,pg.effective_name,pg.category_name) as parentLabel,case when g.dict_code is null then 'PENDING' else 'CONFIRMED' end as parentReviewStatus,a.description,'PENDING' as reviewStatus,a.id as applicationId from item_category_application a left join item_category_application pg on pg.id=a.parent_application_id and pg.category_type='GROUP' left join sys_dict_data g on g.dict_code=coalesce(a.parent_code,pg.resolved_dict_code) and g.dict_type=? where (g.status='0' or pg.status='PENDING' and g.dict_code is null) and a.category_type='LEAF' and a.status='PENDING' and not exists(select 1 from sys_dict_data c where c.dict_type=? and c.dict_label=a.category_name collate utf8mb4_unicode_ci)",GROUP,LEAF));
return result;
}
public List<Map<String,Object>> confirmedOptions() {
return jdbc.queryForList("select c.dict_code as id,c.dict_label as label,c.parent_code as parentId,g.dict_label as parentLabel,c.remark as description,'CONFIRMED' as reviewStatus from sys_dict_data c left join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type=? where c.dict_type=? and c.status='0' and (c.parent_code is null or g.status='0') order by coalesce(g.dict_sort,2147483647),g.dict_code,c.dict_sort,c.dict_code",GROUP,LEAF);
}
public void lockCatalog() { catalogLock.acquire(); }
/** Called inside the same transaction as the actual record save, never from a preview. */
public void recordUsage(String type,Long entityId,String category) {
if(!Set.of("PRODUCT","PURCHASE").contains(type)||entityId==null)throw new IllegalArgumentException("Invalid category usage identity");
catalogLock.acquire();
var pending=jdbc.queryForList("select id from item_category_application where category_type='LEAF' and category_name=? and status='PENDING'",category);
if(!pending.isEmpty())jdbc.update("insert into item_category_usage(entity_type,entity_id,application_id) values(?,?,?) on duplicate key update application_id=values(application_id)",type,entityId,pending.get(0).get("id"));
else jdbc.update("delete u from item_category_usage u join item_category_application a on a.id=u.application_id where u.entity_type=? and u.entity_id=? and coalesce(a.effective_name,a.category_name)<>?",type,entityId,category);
}
public List<String> labels() { return options().stream().map(r->(String)r.get("label")).toList(); }
public List<Map<String,Object>> summary() {

View File

@ -94,7 +94,9 @@ public class ProductInfoServiceImpl implements IProductInfoService
validateProductInfoUnique(productInfo);
productInfo.setProductCode(businessNumbers.reserve("ITEM",null,StringUtils.isBlank(productInfo.getProductCode())?null:"archive:"+productInfo.getProductCode()));
if(!checkProductCodeUnique(productInfo))throw new ServiceException("该物品已建档,请使用已有物品");
return productInfoMapper.insertProductInfo(productInfo);
int rows=productInfoMapper.insertProductInfo(productInfo);
if(rows>0)itemCategories.recordUsage("PRODUCT",productInfo.getId(),productInfo.getCategory());
return rows;
}
@Override
@ -112,6 +114,7 @@ public class ProductInfoServiceImpl implements IProductInfoService
throw new ServiceException("物品已被业务引用,不能更换计量单位;不同单位请分别建档");
validateProductInfoUnique(productInfo);
int rows = productInfoMapper.updateProductInfo(productInfo);
if(rows>0)itemCategories.recordUsage("PRODUCT",productInfo.getId(),productInfo.getCategory());
invalidateCategoryHistory();
return rows;
}

View File

@ -177,6 +177,7 @@ public class PurchaseHistoryCorrectionService {
// Save all other fields first; native audited price correction then sees the final quantity/funding.
next.setFinalUnitPrice(old.getFinalUnitPrice());next.setEstimatedUnitPrice(old.getFinalUnitPrice());next.setEstimatedAmount(old.getFinalUnitPrice()==null?null:PurchasePriceRules.amount(next.getQuantity(),old.getFinalUnitPrice()));next.setUpdateBy(SecurityUtils.getUsername());
if(requests.updatePurchaseRequest(next,null)!=1)throw new ServiceException("采购已变化,更正未完成");
categories.recordUsage("PURCHASE",next.getId(),next.getCategory());
commitments.refreshLockedAmount(old,next,"HISTORY_CORRECTION");
if(changePrice){var input=new PurchasePriceCorrectionService.Correction(targetPrice,command.reason(),null,command.acknowledgeArchiveOnly());var preview=prices.preview(old.getId(),input);prices.correct(old.getId(),new PurchasePriceCorrectionService.Correction(targetPrice,command.reason(),preview.get("version").toString(),command.acknowledgeArchiveOnly()));}
next.setFinalUnitPrice(targetPrice);

View File

@ -90,6 +90,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
@Transactional
public int insertPurchaseRequest(PurchaseRequest purchaseRequest)
{
itemCategories.lockCatalog();
com.ruoyi.warehouse.util.PurchaseQuoteAccess.preserveQuotation(purchaseRequest, null);
normalize(purchaseRequest);
resolveFunding(purchaseRequest);
@ -109,6 +110,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
purchaseRequest.setRequestNo(businessNumbers.reserve("PR",null,StringUtils.isBlank(purchaseRequest.getRequestNo())?null:"request:"+purchaseRequest.getRequestNo()));
if(purchaseRequestMapper.checkRequestNoUnique(purchaseRequest.getRequestNo())!=null)throw new ServiceException("该采购明细已提交,请勿重复导入");
int rows = purchaseRequestMapper.insertPurchaseRequest(purchaseRequest);
if(rows>0)itemCategories.recordUsage("PURCHASE",purchaseRequest.getId(),purchaseRequest.getCategory());
purchaseOperationLogService.record(purchaseRequest.getId(), purchaseRequest.getRequestNo(), "CREATE",
"创建采购申请", "物料:" + purchaseRequest.getMaterialName()
+ ";数量:" + decimalText(purchaseRequest.getQuantity()) + unitText(purchaseRequest.getUnit())
@ -120,6 +122,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
@Transactional
public int updatePurchaseRequest(PurchaseRequest purchaseRequest)
{
itemCategories.lockCatalog();
if (purchaseRequest.getId() == null)
{
throw new ServiceException("采购申请ID不能为空");
@ -181,6 +184,7 @@ public class PurchaseRequestServiceImpl implements IPurchaseRequestService
{
throw new ServiceException("采购明细已变化,请刷新后重试");
}
itemCategories.recordUsage("PURCHASE",purchaseRequest.getId(),purchaseRequest.getCategory());
if(!Integer.valueOf(5).equals(existing.getPurchaseStatus())&&existing.getQuantity().compareTo(purchaseRequest.getQuantity())!=0){
BigDecimal accepted=purchaseArrivalMapper.selectAcceptedQuantityByRequestId(existing.getId());
int progress=accepted.signum()>0?(accepted.compareTo(purchaseRequest.getQuantity())>=0?4:3):

View File

@ -17,7 +17,7 @@
<sql id="selectProductInfoVo">
select id, product_code, product_name, brand, category, spec, unit, remark, create_time, update_time,
coalesce((select g.dict_label from sys_dict_data c join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type='wms_item_category_group' where c.dict_type='wms_item_category' and c.dict_label=product_info.category limit 1),'未分组') as category_group_name from product_info
coalesce((select g.dict_label from sys_dict_data c join sys_dict_data g on g.dict_code=c.parent_code and g.dict_type='wms_item_category_group' where c.dict_type='wms_item_category' and c.dict_label=product_info.category limit 1),(select coalesce(g.dict_label,pg.effective_name,pg.category_name) from item_category_application a left join item_category_application pg on pg.id=a.parent_application_id left join sys_dict_data g on g.dict_code=coalesce(a.parent_code,pg.resolved_dict_code) where a.category_type='LEAF' and a.status='PENDING' and a.category_name collate utf8mb4_unicode_ci=product_info.category limit 1),'未分组') as category_group_name from product_info
</sql>
<select id="selectProductInfoList" parameterType="ProductInfo" resultMap="ProductInfoResult">
@ -32,8 +32,8 @@
<if test="category != null and category != ''">and category = #{category}</if>
<if test="categoryGroupId != null">
<choose>
<when test="categoryGroupId == 0">and not exists(select 1 from sys_dict_data c where c.dict_type='wms_item_category' and c.dict_label=product_info.category and c.parent_code is not null)</when>
<otherwise>and category in (select dict_label from sys_dict_data where dict_type='wms_item_category' and parent_code=#{categoryGroupId})</otherwise>
<when test="categoryGroupId == 0">and not exists(select 1 from sys_dict_data c where c.dict_type='wms_item_category' and c.dict_label=product_info.category and c.parent_code is not null) and not exists(select 1 from item_category_application a where a.category_type='LEAF' and a.status='PENDING' and a.category_name collate utf8mb4_unicode_ci=product_info.category and (a.parent_code is not null or a.parent_application_id is not null))</when>
<otherwise>and (category in (select dict_label from sys_dict_data where dict_type='wms_item_category' and parent_code=#{categoryGroupId}) or category collate utf8mb4_unicode_ci in (select a.category_name from item_category_application a left join item_category_application pg on pg.id=a.parent_application_id where a.category_type='LEAF' and a.status='PENDING' and coalesce(a.parent_code,pg.resolved_dict_code)=#{categoryGroupId}))</otherwise>
</choose>
</if>
<if test="spec != null and spec != ''">and spec like concat('%', #{spec}, '%')</if>

View File

@ -1,12 +1,29 @@
<template>
<el-cascader :model-value="modelValue" :options="options" :props="{emitPath:false}" filterable clearable :placeholder="loading?'加载分类…':placeholder" :disabled="disabled" @update:model-value="$emit('update:modelValue',$event||'')" @change="$emit('change',$event||'')" @visible-change="opened" style="width:100%" />
<div class="item-category-select" @keydown="categoryKeydown">
<el-cascader :model-value="modelValue" :options="options" :props="{emitPath:false}" :show-all-levels="false" filterable clearable :placeholder="loading?'加载分类…':placeholder" :disabled="disabled" @update:model-value="emit('update:modelValue',$event||'')" @change="emit('change',$event||'')" @visible-change="opened"><template #default="{data}"><span :title="data.description||data.label">{{ data.label }}<el-tag v-if="data.reviewStatus==='PENDING'" type="warning" size="small" class="category-pending-tag">待确认</el-tag></span></template></el-cascader>
<el-tag v-if="pendingSelection" type="warning" size="small" class="category-pending-tag">待确认</el-tag>
<el-popover v-if="itemName" v-model:visible="recommendOpen" trigger="click" placement="bottom-end" :width="370" :popper-style="{maxWidth:'calc(100vw - 24px)'}" @show="recommend">
<template #reference><el-button link type="primary" :disabled="disabled" aria-label="AI推荐物品分类">AI 推荐</el-button></template>
<div class="category-recommendations" v-loading="recommending" element-loading-text="AI 正在判断…"><strong>AI 分类建议</strong><p class="category-recommendations__hint">结合物品名称、规格和现有分类判断,点击选用。</p><el-alert v-if="recommendError" :title="recommendError" type="error" :closable="false"/><button v-for="item in recommendations" :key="item.id" type="button" class="category-recommendation" @click="choose(item.label)"><span><b>{{ item.label }}<el-tag v-if="item.reviewStatus==='PENDING'" size="small" type="warning">待确认</el-tag></b><small>{{ item.parentLabel }}</small></span><small>{{ item.reason }}</small></button><p v-if="!recommending&&!recommendations.length&&!recommendError" class="category-recommendations__empty">AI 未找到合适的已有分类,可申请新增后先使用。</p><div v-for="item in suggestions" :key="item.label" class="category-new-suggestion"><span>AI 建议新增:<b>{{ item.label }}</b></span><small>所属大类:{{ item.group }}</small><small>{{ item.reason }}</small><el-button v-if="canApply" size="small" @click="apply(item)">申请并使用</el-button></div><div v-if="canApply" class="category-recommendations__footer"><el-button link type="primary" @click="apply()">申请新分类并使用</el-button><el-button link @click="applications.open({list:true})">我的申请</el-button></div></div>
</el-popover>
<category-applications v-if="itemName&&canApply" ref="applications" @selected="choose"/>
</div>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { itemCategories, loadItemCategories, categoryTree } from '@/utils/item-categories'
const props=defineProps({modelValue:String,disabled:Boolean,placeholder:{type:String,default:'选择大类 / 小类'}})
defineEmits(['update:modelValue','change'])
import { computed, defineAsyncComponent, getCurrentInstance, onMounted, onBeforeUnmount, ref } from 'vue'
import { itemCategories, loadItemCategories, categoryTree,isPendingItemCategory } from '@/utils/item-categories'
import {recommendCategory} from '@/api/warehouse/item-category'
const CategoryApplications=defineAsyncComponent(()=>import('./Applications.vue'))
const props=defineProps({modelValue:String,disabled:Boolean,itemName:String,itemSpec:String,itemBrand:String,placeholder:{type:String,default:'选择大类 / 小类'}})
const emit=defineEmits(['update:modelValue','change']),instance=getCurrentInstance(),applications=ref(),recommendOpen=ref(false),recommending=ref(false),recommendError=ref(''),recommendations=ref([]),suggestions=ref([])
const canApply=computed(()=>!!instance?.proxy.$can?.(['warehouse:product:add','warehouse:product:edit','warehouse:purchase:add','warehouse:purchase:edit','warehouse:purchase:manage']))
const loading=ref(false)
const pendingSelection=computed(()=>isPendingItemCategory(props.modelValue))
let generation=0
async function recommend(){const stamp=++generation,identity=[props.itemName,props.itemSpec,props.itemBrand].join('|');recommending.value=true;recommendError.value='';recommendations.value=[];suggestions.value=[];try{const {data}=await recommendCategory({name:props.itemName,spec:props.itemSpec,brand:props.itemBrand});if(stamp!==generation||identity!==[props.itemName,props.itemSpec,props.itemBrand].join('|'))return;recommendations.value=data.recommendations||[];suggestions.value=data.suggestions||[]}catch{if(stamp===generation)recommendError.value='推荐加载失败,请重试或手动选择'}finally{if(stamp===generation)recommending.value=false}}
function choose(value){if(props.disabled)return;emit('update:modelValue',value);emit('change',value);recommendOpen.value=false}
function apply(item){recommendOpen.value=false;applications.value?.open({name:item?.label||'',group:item?.group,reason:item?.reason,exampleName:props.itemName,exampleSpec:props.itemSpec})}
function categoryKeydown(event){if(event.target.closest('button')&&['Enter',' ','ArrowDown','ArrowUp'].includes(event.key))event.stopPropagation()}
const options=computed(()=>{
const rows=categoryTree(itemCategories.value)
if(props.modelValue&&!itemCategories.value.some(c=>c.label===props.modelValue))rows.push({value:'history',label:'历史分类',children:[{value:props.modelValue,label:props.modelValue,disabled:true}]})
@ -14,4 +31,9 @@ const options=computed(()=>{
})
async function opened(visible){if(!visible)return;loading.value=true;try{await loadItemCategories()}catch(_){/* request handler reports failure; reopening retries */}finally{loading.value=false}}
onMounted(()=>opened(true))
onBeforeUnmount(()=>generation++)
</script>
<style scoped>
.item-category-select{display:flex;align-items:center;flex:1;gap:6px;width:100%;min-width:0}.item-category-select>.el-cascader{flex:1;min-width:0;width:100%}.item-category-select>.el-button{flex:none;margin:0;font-size:12px}.category-pending-tag{flex:none;margin-left:4px;font-size:11px;padding:0 4px}
.category-recommendations>strong{color:var(--el-text-color-primary)}.category-recommendations__hint{font-size:12px;color:var(--el-text-color-secondary);margin:7px 0 10px;line-height:1.6}.category-recommendation{display:flex;flex-direction:column;gap:5px;width:100%;text-align:left;cursor:pointer;border:1px solid var(--el-border-color-lighter);background:var(--el-bg-color);border-radius:5px;padding:10px;margin:7px 0;color:var(--el-text-color-primary);font:inherit}.category-recommendation:hover{border-color:var(--el-color-primary);background:var(--el-color-primary-light-9)}.category-recommendation>span{display:flex;align-items:center;justify-content:space-between;gap:10px}.category-recommendation small,.category-new-suggestion small{font-size:12px;line-height:1.5;color:var(--el-text-color-secondary)}.category-recommendations__empty{font-size:13px;line-height:1.6;color:var(--el-text-color-secondary)}.category-new-suggestion{display:flex;flex-direction:column;align-items:flex-start;gap:7px;background:var(--el-fill-color-light);padding:10px;border-radius:5px;margin:8px 0}.category-recommendations__footer{display:flex;justify-content:space-between;padding-top:8px;margin-top:10px;border-top:1px solid var(--el-border-color-lighter)}
</style>

View File

@ -1,8 +1,9 @@
<template>
<div :class="['sheet-cell', {'cell-numeric':['quantity','actualUnitPrice','finalUnitPrice'].includes(column.field),'cell-invalid':owner.cellError(row,column.field),'cell-editable':owner.editableCell(row,column.field),'cell-active':active&&owner.editableCell(row,column.field),'cell-selected':owner.isGridSelected?.(row,column.field)}]" tabindex="0" @mousedown="owner.startCellSelection?.(row,column.field,$event)" @mouseenter="owner.extendCellSelection?.(row,column.field,$event)" @focus="owner.focusGridCell?.(row,column.field)" @dblclick="owner.activateCell(row,column.field,true,$event)" :data-row="index" :data-field="column.field" :aria-label="'第'+(index+1)+'行 '+column.label" :title="owner.cellError(row,column.field) || (owner.isEditing&&owner.fieldLocked(row,column.field)?column.field==='finalUnitPrice'?'已有到货,请退出编辑后选择该行,使用更正价格同步关联金额':'已有到货或入库,请先按流程退回后修改':String(owner.displayCell(row,column.field) ?? ''))" @focusin="active&&owner.rememberCell(index,column.field)" @focusout="commitDraft" @copy="owner.copyGridEvent?.($event)" @paste="owner.paste($event,index,column.field)" @keydown.esc.capture.stop="owner.navigate($event,index,column.field)" @keydown="owner.navigate($event,index,column.field)">
<input v-if="!active && owner.isGridTypingCell?.(row,column.field)" class="sheet-keyboard-input" :aria-label="'输入第'+(index+1)+'行 '+column.label" autocomplete="off" @compositionstart="composing=true" @compositionend="compositionEnd" @input="typeInput" />
<div :class="['sheet-cell', {'cell-numeric':['quantity','actualUnitPrice','finalUnitPrice'].includes(column.field),'cell-invalid':owner.cellError(row,column.field),'cell-editable':owner.editableCell(row,column.field),'cell-active':active&&owner.editableCell(row,column.field),'cell-selected':selected}]" tabindex="0" @mousedown="owner.startCellSelection?.(row,column.field,$event)" @mouseenter="owner.extendCellSelection?.(row,column.field,$event)" @focus="owner.focusGridCell?.(row,column.field)" @dblclick="owner.activateCell(row,column.field,true,$event)" :data-row="index" :data-field="column.field" :aria-label="'第'+(index+1)+'行 '+column.label" :title="owner.cellError(row,column.field) || (owner.isEditing&&owner.fieldLocked(row,column.field)?column.field==='finalUnitPrice'?'已有到货,请退出编辑后选择该行,使用更正价格同步关联金额':'已有到货或入库,请先按流程退回后修改':String(owner.displayCell(row,column.field) ?? ''))" @focusin="active&&owner.rememberCell(index,column.field)" @focusout="commitDraft" @copy="owner.copyGridEvent?.($event)" @paste="owner.paste($event,index,column.field)" @keydown.esc.capture.stop="owner.navigate($event,index,column.field)" @keydown="owner.navigate($event,index,column.field)">
<input v-if="!active && typing" class="sheet-keyboard-input" :aria-label="'输入第'+(index+1)+'行 '+column.label" autocomplete="off" @compositionstart="composing=true" @compositionend="compositionEnd" @input="typeInput" />
<template v-if="!owner.editableCell(row,column.field) || !active">
<a v-if="owner.readonly(row) && column.field==='purchaseLink' && owner.linkUrl(row.purchaseLink)" class="sheet-link" :href="owner.linkUrl(row.purchaseLink)" :title="row.purchaseLink" target="_blank" rel="noopener noreferrer" @click.stop>{{ purchaseLinkLabel(row.purchaseLink) }}</a>
<span v-else-if="column.field==='category'&&pendingCategory" class="sheet-pending-category"><span class="sheet-value">{{ row.category }}</span><el-tag type="warning" size="small">待确认</el-tag></span>
<span v-else class="sheet-value" :title="String(owner.displayCell(row,column.field))">{{ column.field==='purchaseLink' && row.purchaseLink ? purchaseLinkLabel(row.purchaseLink) : owner.displayCell(row,column.field) }}</span>
</template>
<el-select v-else-if="column.field==='projectId'" v-model="row.projectId" filterable :disabled="owner.saving || owner.fieldLocked(row,column.field) || !!(row.id && row.productionTaskId)" @visible-change="owner.menu(row,column.field,$event)" @change="owner.projectChanged(row)"><el-option v-for="p in owner.menuOpen(row,column.field)?owner.projects:owner.projects.filter(p=>String(p.id)===String(row.projectId))" :key="p.id" :value="p.id" :label="p.projectName" /></el-select>
@ -17,7 +18,7 @@
<el-input v-else-if="column.field==='actualUnitPrice'" v-model="row.actualUnitPrice" maxlength="21" placeholder="内部参考,选填" :disabled="owner.saving" />
<el-select v-else-if="column.field==='productionTaskId'" v-model="row.productionTaskId" filterable remote :remote-method="q=>owner.searchPlans(row,q)" clearable :disabled="owner.saving || !!row.id" placeholder="自研可不选" @visible-change="owner.menu(row,column.field,$event)"><el-option v-for="p in owner.menuOpen(row,column.field)?owner.rowPlans(row):owner.plans.filter(p=>String(p.id)===String(row.productionTaskId))" :key="p.id" :value="p.id" :label="[p.taskNo,p.productName].filter(Boolean).join(' / ')" /></el-select>
<span v-else-if="column.field==='category' && !owner.canEditCategory(row)" class="sheet-value">{{ row.category }}</span>
<item-category-select v-else-if="column.field==='category'" v-model="row.category" :disabled="owner.saving || owner.fieldLocked(row,column.field)" />
<item-category-select v-else-if="column.field==='category'" v-model="row.category" :item-name="row.materialName" :item-spec="row.materialParams" :item-brand="row.materialBrand" :disabled="owner.saving || owner.fieldLocked(row,column.field)" />
<el-select v-else-if="column.field==='purchasePurpose'" v-model="row.purchasePurpose" :disabled="owner.saving || owner.fieldLocked(row,column.field)" @change="owner.loadLoans(row)"><el-option label="本项目使用" value="SELF"/><el-option label="归还借用" value="REPAY"/></el-select>
<el-select v-else-if="column.field==='loanId'" v-model="row.loanId" filterable :disabled="owner.saving || row.purchasePurpose!=='REPAY' || owner.fieldLocked(row,column.field)" @visible-change="$event&&owner.loadLoans(row)"><el-option v-for="loan in owner.loans[row._key]||[]" :key="loan.id" :value="loan.id" :label="loan.loanNo+' / 待还 '+loan.outstandingQuantity"/></el-select>
<el-input v-else v-model="row[column.field]" :disabled="owner.saving || owner.fieldLocked(row,column.field)" :maxlength="column.field==='remark'?500:1000" />
@ -26,7 +27,7 @@
<script setup>
import { ref, watch } from 'vue'
import { purchaseLinkLabel } from '@/utils/purchase-link-label'
const props=defineProps({row:Object,column:Object,index:Number,owner:Object,active:Boolean})
const props=defineProps({row:Object,column:Object,index:Number,owner:Object,active:Boolean,selected:Boolean,typing:Boolean,pendingCategory:Boolean})
const composing=ref(false)
const specDraft=ref(props.row?.materialParams || '')
const nameDraft=ref(props.row?.materialName || ''),brandDraft=ref(props.row?.materialBrand || '')
@ -63,7 +64,7 @@ watch(()=>props.active, active=>{if(active && props.column.field==='materialName
watch(()=>props.active,active=>{if(active&&props.column.field==='materialName')props.owner._openedName=null},{flush:'sync'})
</script>
<style scoped>
.cell-numeric{font-variant-numeric:tabular-nums;text-align:right}
.cell-numeric .sheet-value,.cell-numeric :deep(.el-input__inner){text-align:right}
.sheet-pending-category{display:flex;align-items:center;gap:5px;width:100%;min-width:0}.sheet-pending-category>.sheet-value{flex:1;min-width:0}.sheet-pending-category>.el-tag{flex:none;font-size:11px;padding:0 3px}
.cell-numeric{font-variant-numeric:tabular-nums}
.sheet-keyboard-input{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none;padding:0;border:0}
</style>

View File

@ -42,7 +42,7 @@
<el-checkbox-group v-model="selectedColumns" class="inquiry-options__grid">
<el-checkbox v-for="column in availableColumns" :key="column.key" :value="column.key">{{ column.label }}</el-checkbox>
</el-checkbox-group>
<p class="supplier-quotation__hint">报价单价可按需勾选,供供应商填写。必要的物品匹配信息保存在隐藏列中;已入库、历史及取消明细不参与导出。</p>
<p class="supplier-quotation__hint">仅导出勾选字段,未勾选字段不写入文件。报价单价可按需选择;回填时请保留原文件中的匹配批注。已入库、历史及取消明细不参与导出。</p>
</div>
<template #footer><el-button :disabled="exporting" @click="exportOptionsOpen=false">取消</el-button><el-button type="primary" :disabled="!selectedColumns.length || !exportRowIds.length" :loading="exporting" @click="downloadInquiry">导出询价单</el-button></template>
</el-dialog>
@ -62,7 +62,7 @@ const emit=defineEmits(['update:modelValue','apply','busy'])
const results=ref([]),fileName=ref(''),exporting=ref(false),uploading=ref(false),allowPartial=ref(false)
const exportOptionsOpen=ref(false),selectedColumns=ref([])
const exportRowIds=ref([]),exportItemCount=ref(0)
const columns=[{key:'name',label:'物品名称'},{key:'spec',label:'规格型号'},{key:'brand',label:'品牌'},{key:'unit',label:'单位'},{key:'quantity',label:'采购数量'},{key:'quoteUnitPrice',label:'报价单价'},{key:'quoteAmount',label:'报价金额'},{key:'actualUnitPrice',label:'实际单价',actual:true},{key:'actualAmount',label:'实际金额',actual:true},{key:'link',label:'采购链接'},{key:'remark',label:'备注'}]
const columns=[{key:'index',label:'序号'},{key:'name',label:'物品名称'},{key:'spec',label:'规格型号'},{key:'brand',label:'品牌'},{key:'unit',label:'单位'},{key:'quantity',label:'采购数量'},{key:'quoteUnitPrice',label:'报价单价'},{key:'quoteAmount',label:'报价金额'},{key:'actualUnitPrice',label:'实际单价',actual:true},{key:'actualAmount',label:'实际金额',actual:true},{key:'link',label:'采购链接'},{key:'remark',label:'备注'}]
const availableColumns=computed(()=>columns.filter(column=>!column.actual||!props.compactAmounts))
function selectAllColumns(){selectedColumns.value=availableColumns.value.map(column=>column.key)}
function resetColumns(){selectAllColumns()}

View File

@ -51,8 +51,35 @@
</template>
</template>
<template v-else>
<el-form inline size="small" label-width="84px" class="batch-form" :disabled="saving" @focusin="rememberHeader">
<el-form-item><el-button icon="el-icon-back" @click="back">{{ sheet.unbatched?'待组批列表':'批次列表' }}</el-button></el-form-item><el-form-item v-if="sheet.unbatched"><strong>未组批采购明细</strong></el-form-item>
<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="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" @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>
<el-button type="danger" plain size="small" icon="el-icon-delete" @click="remove" :disabled="saving || !canRemoveSelection">删除</el-button>
<el-button size="small" icon="el-icon-refresh-left" title="Ctrl / ⌘ + Z" @mousedown.prevent @click="undo" :disabled="saving || !canUndo || !canEdit">撤销</el-button>
<el-button size="small" title="Ctrl + Y / ⌘ + Shift + Z" @mousedown.prevent @click="redo" :disabled="saving || !canRedo || !canEdit">重做</el-button>
<el-button size="small" :disabled="saving" @click="openBatchCategories">批量 AI 分类</el-button>
<el-popover trigger="click" width="320" placement="bottom"><template #reference><el-button size="small" :disabled="saving||!selected.length">批量设置<business-icon name="arrow-down"/></el-button></template><el-form label-width="80px" size="small"><el-form-item v-if="sheet.unbatched || batchProject.mixed" label="项目"><el-select v-model="commonProject" filterable clearable placeholder="选择项目" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'projectId')||r.id&&r.productionTaskId)" @change="setProjects"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item><el-form-item label="费用分类"><el-select v-model="commonCategory" filterable clearable placeholder="选择费用分类" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'expenseCategoryId'))" @change="setCategories"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select></el-form-item></el-form></el-popover>
</template>
<el-button v-if="!isEditing&&canExportInquiry && !sheet.unbatched" size="small" icon="el-icon-download" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryExportRows.length" @click="$refs.quotation.exportInquiry()">导出询价单</el-button>
<el-button v-if="!isEditing&&canEdit && canViewQuotes && !sheet.unbatched" size="small" icon="el-icon-upload" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="quoteImportOpen=true">回填供应商报价</el-button>
<el-button v-if="cellRange" size="small" :disabled="saving" @mousedown.prevent @click="copySelection">复制选区</el-button>
<el-dropdown v-if="isEditing" trigger="click" :disabled="saving||!cellRange" @command="command=>command==='clear'?clearGridSelection():fillGrid(command)"><el-button size="small" :disabled="saving||!cellRange">选区操作<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item command="clear">清空内容(Delete)</el-dropdown-item><el-dropdown-item command="down" :disabled="!cellRange||cellRange.top===cellRange.bottom">向下填充(Ctrl/⌘+D)</el-dropdown-item><el-dropdown-item command="right" :disabled="!cellRange||cellRange.left===cellRange.right">向右填充(Ctrl/⌘+R)</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
<el-dropdown v-if="!sheet.unbatched&&!isEditing" trigger="click" @command="kind=>$refs.documents.open('batch',sheet.batch.id,sheet.batch.batchNo+(sheet.batch.batchName?' / '+sheet.batch.batchName:''),kind)"><el-button :disabled="saving||!sheet.batch.id">批次资料<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item v-for="document in documentKinds" :key="document.kind" :command="document.kind">{{ document.label }}</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
<el-button v-if="!isEditing&&canViewQuotes&&selected.length" size="small" title="选择一条已保存且未取消的明细,预览并更正报价及关联金额" :disabled="saving||dirty||selected.length!==1||!selected[0]?.id||Number(selected[0]?.purchaseStatus)===5" @click="$refs.priceCorrection.open(selected[0])">更正价格</el-button>
<el-button v-if="!isEditing&&canViewQuotes&&selected.length" size="small" title="选择1至100条明细,预览并更正历史字段及关联金额" :disabled="saving||dirty||!selected.length||selected.length>100||selected.some(row=>!row.id||Number(row.purchaseStatus)===5)" @click="$refs.historyCorrection.open(selected)">历史更正</el-button>
<el-dropdown v-if="!isEditing&&canEdit&&!sheet.unbatched" trigger="click"><el-button :disabled="saving">更多操作<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item :disabled="saving||selected.length!==1||!canReopen(selected[0])" @click="reopen(selected[0])">撤销确认</el-dropdown-item><el-dropdown-item v-if="$can(['warehouse:purchase:manage'])" :disabled="saving||dirty||!canMoveSelection" @click="openMove">转批次</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
</div>
</div>
<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>
@ -60,64 +87,39 @@
<el-form-item v-if="isEditing" 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-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>
<p v-if="!sheet.unbatched&&!isEditing" class="sheet-project-note">{{ batchProject.mixed?'该历史批次包含多个项目,继续按明细核算,不会自动合并或改动归属。':'本批次统一使用上方项目,新增明细自动沿用,无需逐行选择。' }}</p>
<el-alert v-if="moveOutcome&&!isEditing" type="success" :closable="false" class="mb8"><template #title>明细已转入目标批次,原报价、确认、到货和入库记录保留。</template><el-button link type="primary" @click="viewMoveTarget">查看目标批次</el-button></el-alert>
<el-alert v-if="sheet.batch.id&&!sheet.rows.length" type="info" :closable="false" class="mb8"><template #title>这是空批次,默认保留。批次附件和流程编号不会随明细移动;有资料请保留用于追溯。</template><el-button link type="primary" :disabled="saving||isEditing" @click="deleteEmptyBatch">删除无资料的空批次</el-button></el-alert>
<el-alert v-if="sheet.submissionKey && !saving" class="sheet-save-notice" type="warning" :closable="false" show-icon>
<template #title>上次保存结果未确认。原内容可直接重试;修改前建议先核对保存结果。</template>
<el-button link type="primary" @click="recoverSubmission">核对上次保存</el-button>
</el-alert>
<div v-if="!sheet.unbatched&&!isEditing" class="sheet-documents" aria-label="采购批次资料">
<span>批次资料</span><el-button v-for="document in documentKinds" :key="document.kind" size="small" :disabled="saving || !sheet.batch.id" @click="$refs.documents.open('batch',sheet.batch.id,sheet.batch.batchNo+(sheet.batch.batchName?' / '+sheet.batch.batchName:''),document.kind)">{{ document.label }}</el-button><span class="sheet-documents__hint">{{ sheet.batch.id?'选填,不影响业务流程':'保存批次后可维护附件及编号' }}</span>
</div>
<el-row :gutter="10" class="mb8">
<el-col :span="24" class="sheet-toolbar">
<el-button v-if="canEdit && !editing" type="primary" plain size="small" icon="el-icon-edit" :disabled="saving" @click="startEditing">编辑</el-button>
<el-button v-if="!isEditing&&canViewQuotes" size="small" title="选择一条已保存且未取消的明细,预览并更正报价及关联金额" :disabled="saving||dirty||selected.length!==1||!selected[0]?.id||Number(selected[0]?.purchaseStatus)===5" @click="$refs.priceCorrection.open(selected[0])">更正价格</el-button>
<el-button v-if="!isEditing&&canViewQuotes" size="small" title="选择1至100条明细,预览并更正历史字段及关联金额" :disabled="saving||dirty||!selected.length||selected.length>100||selected.some(row=>!row.id||Number(row.purchaseStatus)===5)" @click="$refs.historyCorrection.open(selected)">历史更正</el-button>
<el-button v-if="canEdit && !isEditing && !sheet.unbatched" size="small" :disabled="saving||selected.length!==1||!canReopen(selected[0])" title="选择一条未到货的已确认采购,撤销后保留数量和报价" @click="reopen(selected[0])">撤销确认</el-button>
<template v-if="isEditing">
<el-button size="small" :disabled="saving" @click="cancelEditing">取消编辑</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>
<el-button type="danger" plain size="small" icon="el-icon-delete" @click="remove" :disabled="saving || !canRemoveSelection">删除</el-button>
<el-button size="small" icon="el-icon-refresh-left" title="Ctrl / ⌘ + Z" @mousedown.prevent @click="undo" :disabled="saving || !canUndo || !canEdit">撤销</el-button>
<el-button size="small" title="Ctrl + Y / ⌘ + Shift + Z" @mousedown.prevent @click="redo" :disabled="saving || !canRedo || !canEdit">重做</el-button>
<el-popover trigger="click" width="320" placement="bottom"><template #reference><el-button size="small" :disabled="saving||!selected.length">批量设置<business-icon name="arrow-down"/></el-button></template><el-form label-width="80px" size="small"><el-form-item v-if="sheet.unbatched || batchProject.mixed" label="项目"><el-select v-model="commonProject" filterable clearable placeholder="选择项目" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'projectId')||r.id&&r.productionTaskId)" @change="setProjects"><el-option v-for="p in projects" :key="p.id" :value="p.id" :label="p.projectName" /></el-select></el-form-item><el-form-item label="费用分类"><el-select v-model="commonCategory" filterable clearable placeholder="选择费用分类" :disabled="saving || !selected.length || selected.some(r=>readonly(r)||fieldLocked(r,'expenseCategoryId'))" @change="setCategories"><el-option v-for="c in categories" :key="c.id" :value="c.id" :label="c.categoryName" /></el-select></el-form-item></el-form></el-popover>
</template>
<el-button v-if="!isEditing&&canExportInquiry && !sheet.unbatched" size="small" icon="el-icon-download" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryExportRows.length" @click="$refs.quotation.exportInquiry()">导出询价单</el-button>
<el-button v-if="!isEditing&&canEdit && canViewQuotes && !sheet.unbatched" size="small" icon="el-icon-upload" :disabled="saving || quoteLoading || dirty || !sheet.batch.id || !inquiryRows.length" @click="quoteImportOpen=true">回填供应商报价</el-button>
<el-button size="small" :disabled="saving||!cellRange" @mousedown.prevent @click="copySelection">复制选区</el-button>
<el-dropdown v-if="isEditing" trigger="click" :disabled="saving||!cellRange" @command="command=>command==='clear'?clearGridSelection():fillGrid(command)"><el-button size="small" :disabled="saving||!cellRange">选区操作<business-icon name="arrow-down"/></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item command="clear">清空内容(Delete)</el-dropdown-item><el-dropdown-item command="down" :disabled="!cellRange||cellRange.top===cellRange.bottom">向下填充(Ctrl/⌘+D)</el-dropdown-item><el-dropdown-item command="right" :disabled="!cellRange||cellRange.left===cellRange.right">向右填充(Ctrl/⌘+R)</el-dropdown-item></el-dropdown-menu></template></el-dropdown>
<div class="sheet-toolbar__view"><el-checkbox v-model="extras">更多列</el-checkbox></div>
<el-button size="small" :disabled="saving || dirty || !canMoveSelection" v-if="!isEditing&&(!sheet.unbatched) && ($can(['warehouse:purchase:manage']))" @click="openMove" >转批次</el-button>
</el-col>
</el-row>
<div class="sheet-filters">
<el-radio-group v-model="rowQueue" class="sheet-queues" aria-label="采购处理筛选" :disabled="saving"><el-radio-button v-for="queue in queueOptions" :key="queue.value" :value="queue.value">{{ queue.label }} <span class="queue-count">{{ queue.count }}</span></el-radio-button></el-radio-group>
<div class="sheet-filter-inputs"><el-input v-model="rowFilter" clearable placeholder="搜索物品、规格或项目" :disabled="saving"/><el-select v-model="rowSort" aria-label="采购明细排序" :disabled="saving"><el-option v-for="sort in sortOptions" :key="sort.value" :value="sort.value" :label="sort.label"/></el-select><el-button :disabled="saving" @click="resetRowView">重置</el-button></div>
<el-input v-model="rowFilter" clearable placeholder="搜索物品、规格或项目" aria-label="搜索采购明细" :disabled="saving" class="sheet-filter-search"/>
<el-select v-model="rowQueue" class="sheet-queues" aria-label="采购处理筛选" :disabled="saving"><el-option v-for="queue in queueOptions" :key="queue.value" :value="queue.value" :label="queue.label+'('+queue.count+')'"/></el-select>
<el-select v-model="rowSort" aria-label="采购明细排序" :disabled="saving"><el-option v-for="sort in sortOptions" :key="sort.value" :value="sort.value" :label="sort.label"/></el-select><el-button :disabled="saving" @click="resetRowView">重置</el-button>
<el-checkbox v-model="extras" :disabled="saving">更多列</el-checkbox>
<div class="sheet-selection"><span>{{ selected.length?'已选 '+selected.length+' 项':'共 '+visibleRows.length+' 项' }}</span><el-button v-if="rowQueue==='arrival'" link type="primary" :disabled="saving||isEditing" @click="selectEligible">选择可到货项</el-button><el-button v-if="selected.length" link :disabled="saving" @click="selected=[]">清空选择</el-button></div>
</div>
<div class="sheet-selection"><span>{{ selected.length?'已选 '+selected.length+' 项':'筛选结果 '+visibleRows.length+' 项' }}</span><el-button v-if="rowQueue==='arrival'" link type="primary" :disabled="saving||isEditing" @click="selectEligible">选择可到货项</el-button><el-button v-if="selected.length" link :disabled="saving" @click="selected=[]">清空选择</el-button></div>
<div ref="tableStage" class="sheet-table" data-viewport-explicit>
<el-table key="batch-sheet" ref="grid" :data="renderedRows" border size="small" :height="gridHeight" class="sheet-grid" :style="virtualStyle" @scroll="scrollGrid" row-key="_key" :empty-text="'没有符合当前筛选的数据'">
<el-table-column key="selection" width="45" fixed="left" class-name="business-control-cell"><template #header><el-checkbox :model-value="allGridSelected" :indeterminate="someGridSelected" aria-label="选择全部筛选结果" @change="selectAllRows"/></template><template #default="s"><el-checkbox :model-value="selectedKeys.has(s.row._key)" :aria-label="'选择第'+(originalIndex(s.row)+1)+'行'" @change="toggleGridRow(s.row,$event)"/></template></el-table-column>
<el-table-column key="index" label="#" width="45" fixed="left"><template #default="s"><button type="button" class="sheet-row-index" :class="{'is-selected':selectedKeys.has(s.row._key)}" :data-row-key="s.row._key" :disabled="saving" :aria-label="'第'+(originalIndex(s.row)+1)+'行,单击选择,右键打开行操作'" :aria-haspopup="isEditing?'menu':undefined" title="单击选择整行,Shift 扩选;编辑时右键或 Shift+F10 打开行操作" @click="selectRowHeader(s.row,$event)" @contextmenu="openRowMenu(s.row,$event)" @keydown.shift.f10.prevent="openRowMenu(s.row,$event)" @keydown.context-menu.prevent="openRowMenu(s.row,$event)">{{ originalIndex(s.row)+1 }}</button></template></el-table-column>
<el-table-column key="index" label="#" width="45" fixed="left" align="center"><template #default="s"><button type="button" class="sheet-row-index" :class="{'is-selected':selectedKeys.has(s.row._key)}" :data-row-key="s.row._key" :disabled="saving" :aria-label="'第'+(originalIndex(s.row)+1)+'行,单击选择,右键打开行操作'" :aria-haspopup="isEditing?'menu':undefined" title="单击选择整行,Shift 扩选;编辑时右键或 Shift+F10 打开行操作" @click="selectRowHeader(s.row,$event)" @contextmenu="openRowMenu(s.row,$event)" @keydown.shift.f10.prevent="openRowMenu(s.row,$event)" @keydown.context-menu.prevent="openRowMenu(s.row,$event)">{{ originalIndex(s.row)+1 }}</button></template></el-table-column>
<template v-for="column in columns" :key="column.field">
<el-table-column :label="column.label" :min-width="column.width" :align="['quantity','actualUnitPrice','finalUnitPrice'].includes(column.field)?'right':'left'" class-name="business-control-cell">
<el-table-column :label="column.label" :min-width="column.width" align="left" class-name="business-control-cell">
<template #header><button type="button" class="sheet-column-select" :aria-label="'选择'+column.label+'列'" :title="column.field==='category'?'单击选择整列,Shift 扩选;更正类别将在保存时同步修改物品档案':'单击选择整列,Shift 扩选多列'" @click="selectColumn(column.field,$event)"><span v-if="column.required" class="required-mark">*</span>{{ column.label }}</button></template>
<template #default="s">
<purchase-cell :row="s.row" :column="column" :index="originalIndex(s.row)" :owner="cellOwner" :active="editCell===s.row._key+'|'+column.field"/>
<purchase-cell :row="s.row" :column="column" :index="originalIndex(s.row)" :owner="cellOwner" :pending-category="column.field==='category'&&pendingCategory(s.row.category)" :selected="isGridSelected(s.row,column.field)" :typing="isGridTypingCell(s.row,column.field)" :active="editCell===s.row._key+'|'+column.field"/>
</template>
</el-table-column>
<el-table-column v-if="column.field==='actualUnitPrice'" key="actual-amount" label="实际金额" width="115" align="right" show-overflow-tooltip><template #default="s">{{ actualAmount(s.row)==null?'—':money(actualAmount(s.row)) }}</template></el-table-column>
<el-table-column v-if="column.field==='finalUnitPrice'" key="amount" label="报价金额" width="115" align="right" show-overflow-tooltip><template #default="s">{{ hasPrice(s.row)?money(Number(s.row.quantity)*Number(s.row.finalUnitPrice)):'—' }}</template></el-table-column>
<el-table-column v-if="column.field==='actualUnitPrice'" key="actual-amount" label="实际金额" width="115" align="left" show-overflow-tooltip><template #default="s">{{ actualAmount(s.row)==null?'—':money(actualAmount(s.row)) }}</template></el-table-column>
<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="!isEditing" key="documents" label="附件" width="85" fixed="right" align="center" class-name="business-control-cell"><template #default="s"><el-button link type="primary" size="small" :disabled="saving || !s.row.id" :title="s.row.id?'查看或上传本条采购明细的附件':'保存明细后可上传附件'" @click="$refs.documents.open('detail',s.row.id,s.row.materialName+(s.row.materialParams?' / '+s.row.materialParams:''))">{{ s.row.id?'附件':'保存后上传' }}</el-button></template></el-table-column>
<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="status" label="状态" width="104" 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="270" fixed="right" align="center" class-name="business-operation-cell"><template #default="s"><el-button v-if="(canArrive(s.row)) && ($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="!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="canEdit && canArrive(s.row) && !isEditing" link type="primary" size="small" @click="$refs.cancelPurchase.open(s.row)">取消剩余</el-button></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.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">
@ -135,6 +137,7 @@
<teleport to="body"><div v-if="rowMenu&&isEditing" class="sheet-row-context" role="menu" aria-label="采购明细行操作" :style="{left:rowMenu.x+'px',top:rowMenu.y+'px'}" @contextmenu.prevent @keydown="rowMenuKeydown"><div class="sheet-row-context__heading">第 {{ contextRow?originalIndex(contextRow)+1:'—' }} 行 · 已选 {{ selected.length }} 行</div><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('before')">在上方插入一行</button><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('after')">在下方插入一行</button><button role="menuitem" type="button" :disabled="!canAdd||saving||sheet.rows.length>=2000" @click="rowCommand('many')">连续插入多行…</button><button role="menuitem" type="button" :disabled="!canAdd||saving||!selected.length||sheet.rows.length+selected.length>2000" @click="rowCommand('duplicate')">复制选中行到下方</button><div class="sheet-row-context__separator"/><button role="menuitem" type="button" class="is-danger" :disabled="saving||!canRemoveSelection" @click="rowCommand('remove')">删除选中行</button></div></teleport>
<el-dialog v-model="insertRowsOpen" title="连续插入多行" width="min(400px,94vw)" append-to-body :close-on-click-modal="false"><el-form label-position="top"><el-form-item label="插入位置"><span>第 {{ insertRowsLine }} 行下方,仅新增编辑草稿</span></el-form-item><el-form-item label="新增行数"><el-input-number v-model="insertRowsCount" :min="1" :max="Math.min(100,2000-(sheet?.rows.length||0))" :precision="0" :controls="false" aria-label="新增行数"/></el-form-item></el-form><template #footer><el-button @click="insertRowsOpen=false">取消</el-button><el-button type="primary" :disabled="saving||!isEditing||!canAdd" @click="insertManyRows">插入</el-button></template></el-dialog>
<paste-preview v-model:visible="pastePreviewOpen" :text="pasteText" :columns="columns" :start-field="pasteStartField" :busy="pasteApplying" :units="units" :issues="pasteIssues" @clear-issues="pasteIssues=[]" @apply="applyPastePreview"/>
<batch-category ref="batchCategory" :apply="applyBatchCategories"/>
<purchase-documents ref="documents"/>
<price-correction ref="priceCorrection" @changed="arrivalChanged"/>
<history-correction ref="historyCorrection" :projects="projects" :categories="categories" :units="units" :plans="plans" @changed="arrivalChanged"/>
@ -179,6 +182,10 @@ import PriceCorrection from './PriceCorrection.vue'
import HistoryCorrection from './HistoryCorrection.vue'
import PurchaseDocuments from '@/components/PurchaseDocuments'
import { canViewPurchaseQuotes } from '@/utils/purchase-quote-permission'
import { itemCategories,loadItemCategories,isPendingItemCategory,invalidateItemCategories } from '@/utils/item-categories'
import {submitCategoryApplications} from '@/api/warehouse/item-category'
import {categoryBatchSource,checkCategoryBatch} from '@/utils/purchase-category-batch'
import BatchCategory from './BatchCategory.vue'
import SupplierQuotation from './SupplierQuotation.vue'
import { supplierInquiryRows, quotationReady } from '@/utils/supplier-quotation'
import { purchaseDocumentKinds } from '@/utils/purchase-documents'
@ -204,14 +211,15 @@ 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}, dicts:['wms_item_category'],
components:{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 {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:[]}},
name:'PurchaseBatchSheet', props:{projectId:Number,embedded:Boolean},
components:{BatchCategory,ArrivalPhotos:defineAsyncComponent(()=>import('@/components/ArrivalPhotos')),PurchaseCell,PriceCorrection,HistoryCorrection,PurchaseDocuments,SupplierQuotation,PastePreview,PurchaseLookup:defineAsyncComponent(()=>import('./Lookup')),SupplierPicker:defineAsyncComponent(()=>import('@/components/SupplierPicker')),BatchArrival:defineAsyncComponent(()=>import('@/components/ReceiptDialog/Batch')),CancelPurchase:defineAsyncComponent(()=>import('@/components/ReceiptDialog/CancelPurchase')),ExcelImportDialog:defineAsyncComponent(()=>import('@/components/ExcelImportDialog'))},
data(){return {batchDetailsOpen:false,rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLine:0,pastePreviewOpen:false,pasteText:'',pasteStartField:'',pasteApplying:false,moveAttempted:false,draftError:'',draftSavedAt:null,redoHistory:[],moveOutcome:null,moveMode:'existing',moveLoading:false,moveNew:{batchName:'',supplierId:null,businessDate:''},rowQueue:'all',rowSort:'original',viewSnapshot:null,quoteImportOpen:false,onlyMine:false,viewMode:'batches',loading:true,creating:false,saving:false,editing:false,validationEnabled:false,onlyInvalid:false,editCell:null,showSearch:true,nameMenuRow:null,nameOptions:null,nameLoading:false,categoryMenuRow:null,activeMenu:null,remarkRowId:null,remarkDraft:'',remarkSaving:false,batches:[],total:0,summary:null,query:{pageNum:1,pageSize:20,projectId:this.projectId,keyword:'',progress:null,supplierId:null,materialName:''},queryDates:[],rowFilter:'',drafts:[],quoteLoading:false,moveOpen:false,moveBatches:[],moveBatchId:null,loans:{},projects:[],categories:[],items:[],units:[],plans:[],sheet:null,baseline:'',selected:[],history:[],extras:false,commonProject:null,commonCategory:null,recordsOpen:false,recordsItem:'',arrivalRecords:[]}},
computed:{
documentKinds(){return purchaseDocumentKinds.filter(item=>item.kind!=='QUOTE'||this.canViewQuotes)},
canViewQuotes(){const user=this.$store.getters;return canViewPurchaseQuotes(user.userId,user.roles)},
compactAmounts(){return this.canViewQuotes&&amountDisplay.enabled},
actualTotal(){return purchaseActualTotal(this.sheet?.rows||[])},
activeCategoryLabels(){return itemCategories.value.map(category=>category.label)},
baselineRowMap(){return new Map((this.baseline?JSON.parse(this.baseline).rows||[]:[]).map(row=>[row._key,row]))},
inquiryRows(){return supplierInquiryRows(this.sheet?.rows?.filter(row=>visibleAmountRow(row,this.compactAmounts)))},
inquiryExportSourceRows(){return (this.selected.length?this.selected:this.visibleRows).filter(row=>visibleAmountRow(row,this.compactAmounts))},
@ -222,7 +230,7 @@ data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLin
cellRange(){return purchaseGridRange(this.cellSelection,this.sheet?this.visibleRows:[],this.columns)},
selectionStats(){return this.sheet&&this.isEditing?purchaseSelectionStats({rows:this.visibleRows,columns:this.columns,range:this.cellRange,compactAmounts:this.compactAmounts}):null},
contextRow(){return this.sheet?.rows.find(row=>row._key===this.rowMenu?.key)},
virtualized(){return this.visibleRows.length>150},
virtualized(){return this.visibleRows.length>50},
selectedKeys(){return new Set(this.selected.map(r=>r._key))},
allGridSelected(){return this.visibleRows.length>0&&this.visibleRows.every(r=>this.selectedKeys.has(r._key))},
someGridSelected(){return !this.allGridSelected&&this.visibleRows.some(r=>this.selectedKeys.has(r._key))},
@ -239,7 +247,7 @@ data(){return {rowMenu:null,insertRowsOpen:false,insertRowsCount:5,insertRowsLin
sortOptions(){return this.canViewQuotes?sheetSorts:sheetSorts.filter(sort=>!['priceAsc','priceDesc','amountDesc'].includes(sort.value))},
quoteCandidates(){return (this.sheet?.rows||[]).filter(r=>!r.historical&&Number(r.purchaseStatus)!==5&&!r.priceLocked&&!this.hasPrice(r))},
visibleRows(){const q=clean(this.rowFilter).toLowerCase();const rows=(this.sheet?.rows||[]).filter(r=>this.amountRowVisible(r)&&queueMatches(this.viewReference(r),this.rowQueue)&&(!q||[r.materialName,r.materialBrand,r.materialParams,r.requestNo,this.projectName(r.projectId)].join(' ').toLowerCase().includes(q))&&(!this.onlyInvalid||this.errorKeys.has(r._key)));return sortSheetRows(rows,this.rowSort,this.viewReference)},
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.dict.type.wms_item_category||[]).map(d=>d.label)),...changed.filter(row=>referencePriceError(row)).map(row=>({rowKey:row._key,line:this.originalIndex(row)+1,field:'actualUnitPrice',message:referencePriceError(row)}))]},
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.id&&Number(r.purchaseStatus)!==5)&&new Set(this.selected.map(r=>String(r.projectId))).size===1},
@ -252,13 +260,13 @@ rowErrors(){if(!this.validationEnabled||!this.sheet||!this.isEditing)return [];c
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:'materialParams',label:'规格型号',width:170},{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:'materialBrand',label:'品牌',width:120},{field:'category',label:'物品类别',width:140,required:true},{field:'purchaseLink',label:'链接',width:190}];if(!this.compactAmounts)columns.splice(4,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))},
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))},
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.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.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();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()}},
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.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()},
@ -266,6 +274,33 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
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._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,
async openBatchCategories(){
if(!this.isEditing||this.saving)return
await this.finishCellEdit()
const source=categoryBatchSource(this.selected.length?this.selected:this.visibleRows,row=>this.editableCell(row,'category'),row=>this.originalIndex(row))
if(!source.rows.length)return this.$modal.msgWarning('当前范围没有可修改分类的明细,请先填写名称并检查权限或锁定状态')
this._batchCategorySheet=this.sheet
await this.$refs.batchCategory.open({...source,scope:this.selected.length?'所选明细':'当前筛选结果'})
},
async applyBatchCategories(entries){
const assertCurrent=()=>{if(!this.isEditing||this.saving||this.sheet!==this._batchCategorySheet)throw new Error('采购清单已变化,请重新打开批量分类');return checkCategoryBatch(entries,this.sheet.rows,row=>this.editableCell(row,'category'))}
assertCurrent();invalidateItemCategories();let options=await loadItemCategories(true)
const labels=new Set(options.map(option=>option.label)),requests=new Map(),normalize=value=>String(value||'').normalize('NFKC').trim()
for(const entry of entries){
if(!entry.proposed){if(!labels.has(entry.value))throw new Error(`第 ${entry.line} 行的分类已失效,请重新选择`);continue}
const name=normalize(entry.proposed.label);if(!name||!entry.proposed.parentCode)throw new Error(`第 ${entry.line} 行请补全新分类`)
if(labels.has(name))continue
const previous=requests.get(name);if(previous&&(previous.parentCode!==entry.proposed.parentCode))throw new Error(`新分类“${name}”选择了不同大类,请统一后再应用`)
requests.set(name,{type:'LEAF',name,parentCode:entry.proposed.parentCode,description:entry.proposed.reason||'批量采购分类:现有分类不适用,申请通用新小类',exampleName:entry.name,exampleSpec:entry.spec})
}
if(requests.size>200)throw new Error('新分类超过200个,请分次勾选应用')
assertCurrent()
if(requests.size){await submitCategoryApplications([...requests.values()]);invalidateItemCategories();options=await loadItemCategories(true)}
const current=assertCurrent(),active=new Set(options.map(option=>option.label)),changes=[]
for(const {row,entry} of current){const category=entry.proposed?normalize(entry.proposed.label):entry.value;if(!active.has(category))throw new Error(`第 ${entry.line} 行分类已变化,请重新选择`);if(row.category!==category)changes.push({row,category})}
if(changes.length){this._identityEditor?.invalidate(changes.map(change=>change.row));this.remember(changes.map(change=>change.row));for(const change of changes)change.row.category=change.category}
this.$modal.msgSuccess(`已应用 ${changes.length} 行分类,请保存采购清单;可一次撤销`)
},
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:canReopenPurchase,
@ -285,7 +320,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
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.$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(){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=[]}},
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}},
clearDraft(id){try{removeSheetDraft(this.draftPrefix()+(id||'new'));this.draftSavedAt=null;this.draftError='';this.refreshDrafts()}catch(e){this.draftError='无法清除本机草稿,请勿重复提交,先核对线上保存结果。'}},
async restoreDraft(key){if(this.dirty){try{await this.$confirm('保留当前草稿并打开所选草稿?','恢复草稿')}catch(e){return}if(!this.persistDraft())return}let draft;try{draft=readSheetDraft(key)}catch(e){return this.$modal.msgError('该草稿内容不完整,已保留原文件,请勿清理浏览器数据')}if(!draft?.sheet)return;this.editing=false;this.sheet=draft.sheet;this.baseline=draft.baseline;this._editor.reset();this.editing=true;this.selected=[];this.history=[];this.redoHistory=[];this.rowFilter='';this.layout();this.$modal.msgSuccess('已恢复本机草稿;保存时仍会核对线上版本,防止覆盖他人修改')},
@ -380,11 +415,27 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
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]||''},
async focusError(error){if(!error)return;if(error.field==='projectId'&&!this.sheet.unbatched&&!this.batchProject.mixed){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)},
pendingCategory(label){return isPendingItemCategory(label)},
rowActions(row){
const actions=[],pending=Number(row.pendingArrivalQuantity)>0,awaitingReceipt=Number(row.acceptedQuantity)>Number(row.receivedQuantity||0)
if(this.canArrive(row)&&(pending||awaitingReceipt)&&this.$can(['warehouse:purchase:edit','warehouse:purchase:manage']))actions.push({command:'arrival',label:'登记到货'})
if(pending&&!row.historical&&awaitingReceipt&&this.$can(['warehouse:in:list']))actions.push({command:'receipt',label:'入库'})
actions.push({command:'attachments',label:'附件',disabled:!row.id})
if(this.canEdit&&this.canArrive(row))actions.push({command:'cancel',label:'取消剩余'})
return actions
},
runRowCommand(command,row){
if(this.saving||!this.rowActions(row).some(action=>action.command===command&&!action.disabled))return
if(command==='attachments')this.$refs.documents.open('detail',row.id,row.materialName+(row.materialParams?' / '+row.materialParams:''))
else if(command==='arrival')this.arrival([row])
else if(command==='receipt')this.$router.push({path:'/warehouse/pending',query:{sourceGroup:'B:'+this.sheet.batch.id,projectId:row.projectId}})
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(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,.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})},
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})},
extendCellSelection(row,field,event){if(!this._gridDragging||event.buttons!==1||!this.cellSelection)return;this.cellSelection={...this.cellSelection,focus:{key:row._key,field}}},
endCellSelection(){const focus=this._gridDragging&&document.activeElement?.closest?.('.sheet-cell');this._gridDragging=false;window.removeEventListener('mouseup',this.endCellSelection);if(focus&&!this.editCell)this.$nextTick(()=>this.focusSelectedCell())},
selectColumn(field,event){if(this.saving||!this.visibleRows.length)return;document.activeElement?.blur?.();this.editCell=null;const anchor=event.shiftKey&&this.cellSelection?this.cellSelection.anchor.field:field;this.cellSelection={anchor:{key:this.visibleRows[0]._key,field:anchor},focus:{key:this.visibleRows.at(-1)._key,field}};this.$nextTick(()=>this.focusSelectedCell())},
@ -401,7 +452,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
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()]},
async searchNames(keyword){const seq=this._nameSequence=(this._nameSequence||0)+1;this.nameLoading=true;try{const r=await purchaseSheetOptions({keyword});if(seq===this._nameSequence){this.mergeItems(r.data.items||[]);this.nameOptions=r.data.items||[]}}finally{if(seq===this._nameSequence)this.nameLoading=false}},
async loadName(name){const r=await purchaseSheetOptions({name});this.mergeItems(r.data.items||[])},
async references(){const [options,projects,categories]=await Promise.all([purchaseSheetOptions(),projectOptions('',true),categoryOptions(),loadAmountDisplay()]);this.mergeItems(options.data.items||[]);this.units=(options.data.units||[]).filter(u=>u.status==='0').map(u=>u.dictLabel);this.plans=options.data.plans||[];this.projects=projects.data||[];this.categories=categories.data||[];if(!this.commonCategory)this.commonCategory=(this.categories.find(c=>c.categoryCode==='MATERIAL')||this.categories[0]||{}).id},
async references(){const [options,projects,categories]=await Promise.all([purchaseSheetOptions(),projectOptions('',true),categoryOptions(),loadAmountDisplay(),loadItemCategories()]);this.mergeItems(options.data.items||[]);this.units=(options.data.units||[]).filter(u=>u.status==='0').map(u=>u.dictLabel);this.plans=options.data.plans||[];this.projects=projects.data||[];this.categories=categories.data||[];if(!this.commonCategory)this.commonCategory=(this.categories.find(c=>c.categoryCode==='MATERIAL')||this.categories[0]||{}).id},
beginBatchRemark(row){if(this.remarkSaving)return;this.remarkDraft=row.progressRemark||'';this.remarkRowId=row.id},
async saveBatchRemark(row){
if(this.remarkSaving)return
@ -413,7 +464,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
emptyRow(){return {_key:'new-'+Date.now()+'-'+Math.random(),id:null,projectId:this.projectId||(this.sheet&&!this.sheet.unbatched?this.batchProject.value:this.commonProject)||null,expenseCategoryId:this.commonCategory||null,materialName:'',materialBrand:'',materialParams:'',productId:null,productCode:null,unit:'',category:'',quantity:1,finalUnitPrice:null,actualUnitPrice:null,purchaseLink:'',remark:'',purchasePurpose:'SELF',productionTaskId:null,purchaseStatus:0}},
async create(unbatched=false){return createPurchaseDraft(this,unbatched)},
async openBatch(batch){const seq=this._sheetSequence=(this._sheetSequence||0)+1;this.loading=true;try{await loadAmountDisplay();const result=(await getPurchaseSheet(batch.id)).data;if(seq===this._sheetSequence)this.install(result)}finally{if(seq===this._sheetSequence)this.loading=false}},
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.layout()},
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.sheet)return
@ -422,17 +473,17 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
this.clearDraft(this.draftId())
if(creating)this._sheetSequence=(this._sheetSequence||0)+1
this.sheet=creating?null:JSON.parse(this.baseline)
this.validationEnabled=false;this.onlyInvalid=false;this.editing=false;this.editCell=null;this.rowFilter='';this.history=[];this.redoHistory=[];this.selected=[];this.commonProject=null;this.commonCategory=null;this._activeCell=null;this.nameMenuRow=null
this.validationEnabled=false;this.onlyInvalid=false;this.editing=false;this.refreshDrafts?.();this.editCell=null;this.rowFilter='';this.history=[];this.redoHistory=[];this.selected=[];this.commonProject=null;this.commonCategory=null;this._activeCell=null;this.nameMenuRow=null
if(creating)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.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 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)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'))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()},
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).
nameMenu(row,visible){if(visible){this.nameMenuRow=row._key;if(this._openedName!==row._key){this._openedName=row._key;this.searchNames(row.materialName||'')}}else if(this.nameMenuRow===row._key)this.nameMenuRow=null},
@ -602,7 +653,6 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.mine-batch-hint{flex:none;margin:0 0 8px;color:var(--el-text-color-secondary);font-size:12px;line-height:20px}
.sheet-table{flex:1;min-height:80px;min-width:0;overflow:hidden}
.purchase-sheet>.pagination-container[style*="display: none"]{display:block!important;visibility:hidden}
.sheet-toolbar{container-type:inline-size}
.purchase-sheet> .el-form:not(.batch-form){margin-bottom:16px}
.sheet-validation{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:8px 0;font-size:13px}
.cell-invalid{outline:1px solid var(--el-color-danger);outline-offset:-1px;background:var(--el-color-danger-light-9)}
@ -620,7 +670,7 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
.sheet-toolbar .el-select { width:160px; }
.sheet-toolbar__view{display:flex;align-items:center;gap:12px;margin-left:auto}
.sheet-filters{display:flex;align-items:center;flex-wrap:wrap;gap:10px 16px;flex:none;margin-bottom:8px}
.sheet-queues{display:flex;flex-wrap:wrap;gap:6px}
.sheet-queues{display:inline-block}
.sheet-queues :deep(.el-radio-button__inner){border:1px solid var(--el-border-color);border-radius:4px!important;box-shadow:none!important;padding:6px 10px}
.queue-count{margin-left:4px;font-variant-numeric:tabular-nums}
.sheet-filter-inputs{display:flex;align-items:center;gap:8px;margin-left:auto;min-width:0}
@ -672,7 +722,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(.el-input-number .el-input__inner){ text-align:right; }
.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; }
@ -681,6 +731,18 @@ unpriced(){return this.sheet.rows.filter(r=>!r.historical&&!this.hasPrice(r)&&Nu
:global(.project-totals-drawer .el-drawer__header){margin-bottom:0;padding:16px 20px;border-bottom:1px solid var(--el-border-color-lighter)}
:global(.project-totals-drawer .el-drawer__body){min-height:0;overflow:hidden}
:global(.project-totals-drawer .el-drawer__footer){border-top:1px solid var(--el-border-color-lighter)}
.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 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__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}
@media(max-width:1100px){.sheet-heading__meta{display:none}}
@media(max-width:1000px){.sheet-filters>.sheet-selection{margin-left:0}.sheet-heading>.sheet-toolbar{flex-basis:100%;margin-left:0}}
</style>
<style scoped>

View File

@ -2,20 +2,26 @@ import { shallowRef } from 'vue'
import request from '@/utils/request'
export const itemCategories = shallowRef([])
let loadedAt=0, pending, generation=0
let loadedAt=0, pending, pendingGeneration=0, generation=0
export function loadItemCategories(force=false) {
if(pending)return pending
if(pending&&pendingGeneration===generation)return pending
if(!force && Date.now()-loadedAt<30000)return Promise.resolve(itemCategories.value)
const current=generation
pending=request({url:'/warehouse/product/category-options',method:'get'}).then(r=>{
const operation=request({url:'/warehouse/product/category-options',method:'get'}).then(r=>{
if(current===generation){itemCategories.value=r.data||[];loadedAt=Date.now()}
return itemCategories.value
}).finally(()=>{pending=null})
}).finally(()=>{if(pending===operation)pending=null})
pending=operation;pendingGeneration=current
return pending
}
export function invalidateItemCategories(){generation++;loadedAt=0}
export function categoryTree(rows) {
const groups=new Map()
for(const row of rows){const key=row.parentId==null?'ungrouped':String(row.parentId);if(!groups.has(key))groups.set(key,{value:'group:'+key,label:row.parentLabel||'未分组',children:[]});groups.get(key).children.push({value:row.label,label:row.label})}
for(const row of rows){const key=row.parentId==null?'ungrouped':String(row.parentId);if(!groups.has(key))groups.set(key,{value:'group:'+key,label:row.parentLabel||'未分组',reviewStatus:row.parentReviewStatus,children:[]});groups.get(key).children.push({value:row.label,label:row.label,reviewStatus:row.reviewStatus,description:String(row.description||'').split(/关键词[::]/)[0].trim()})}
return [...groups.values()]
}
export function isPendingItemCategory(label){return itemCategories.value.some(row=>row.label===label&&row.reviewStatus==='PENDING')}
export function categoryParentFields(value,groups){
const group=groups.find(group=>String(group.id)===String(value))
return {parentCode:group?.reviewStatus==='PENDING'?null:value||null}
}

View File

@ -2,7 +2,7 @@ import { watch, markRaw, ref } from 'vue'
// Each row owns its change observer. Editing one cell never traverses every row.
export function createSheetEditor(vm) {
const subscriptions=new Map(),snapshots=new Map(),draftPending=new Set()
const subscriptions=new Map(),snapshots=new Map(),draftPending=new Set(),cleanedDrafts=new Set()
let baselineRows=new Map(),baselineOrder='',pendingCell=null,queued=false,stopped=false
vm.redoHistory ||= []
const revision=ref(0),touch=()=>{revision.value++}
@ -78,14 +78,20 @@ export function createSheetEditor(vm) {
const generation=globalThis.crypto?.randomUUID?.()||Date.now()+'-'+Math.random().toString(36).slice(2),rowRefs={}
// Immutable fragments + one metadata commit keep the previous snapshot readable
// if quota failure or page termination interrupts this write.
for(const row of vm.sheet.rows){const rowKey=row._key;let ref=prior?.format===3?prior.rowRefs?.[rowKey]:null
if(!ref||draftPending.has(rowKey)){ref=key+':row:'+rowKey+':'+generation;localStorage.setItem(ref,snapshots.get(rowKey)||json(row))}rowRefs[rowKey]=ref}
let baseKey=prior?.format===3?prior.baselineKey:null
if(!baseKey||localStorage.getItem(baseKey)!==vm.baseline){baseKey=key+':baseline:'+generation;localStorage.setItem(baseKey,vm.baseline)}
const {rows,...sheet}=vm.sheet
localStorage.setItem(key,json({format:3,sheet,rowKeys:rows.map(r=>r._key),rowRefs,baselineKey:baseKey,savedAt:Date.now()}));draftPending.clear()
const staged=[];let baseKey=prior?.format===3?prior.baselineKey:null
try {
for(const row of vm.sheet.rows){const rowKey=row._key;let ref=prior?.format===3?prior.rowRefs?.[rowKey]:null
if(!ref||draftPending.has(rowKey)){ref=key+':row:'+rowKey+':'+generation;localStorage.setItem(ref,snapshots.get(rowKey)||json(row));staged.push(ref)}rowRefs[rowKey]=ref}
if(!baseKey||localStorage.getItem(baseKey)!==vm.baseline){baseKey=key+':baseline:'+generation;localStorage.setItem(baseKey,vm.baseline);staged.push(baseKey)}
const {rows,...sheet}=vm.sheet
localStorage.setItem(key,json({format:3,sheet,rowKeys:rows.map(r=>r._key),rowRefs,baselineKey:baseKey,savedAt:Date.now()}));draftPending.clear()
}catch(error){for(const ref of staged)try{localStorage.removeItem(ref)}catch{};throw error}
const retained=new Set([key,baseKey,...Object.values(rowRefs)])
for(const owned of Object.keys(localStorage))if((owned.startsWith(key+':row:')||owned.startsWith(key+':baseline'))&&!retained.has(owned))try{localStorage.removeItem(owned)}catch{}
// Sweep legacy/interrupted fragments once, then retire only the prior commit's
// replaced fragments. Keystrokes must not enumerate every stored draft row.
const owned=cleanedDrafts.has(key)?[...Object.values(prior?.rowRefs||{}),prior?.baselineKey].filter(Boolean):Object.keys(localStorage)
for(const ref of owned)if((ref.startsWith(key+':row:')||ref.startsWith(key+':baseline'))&&!retained.has(ref))try{localStorage.removeItem(ref)}catch{}
cleanedDrafts.add(key)
vm.refreshDrafts();return true
}
})

View File

@ -121,8 +121,7 @@ export default {
{key:'stock',label:'库存操作',icon:'el-icon-takeaway-box',path:'/warehouse/stock',show:this.canStock},
{key:'production',label:'生产任务',icon:'el-icon-setting',path:'/production/tasks',show:this.canProduction},
{key:'project',label:'项目管理',icon:'el-icon-folder-opened',path:'/project/info',show:this.canProjects},
{key:'product',label:'产品档案',icon:'el-icon-files',path:'/businessBasics/products',show:this.$auth.hasPermi('production:product:list')},
{key:'mobile',label:'现场操作',icon:'el-icon-mobile-phone',path:'/mobile',show:this.canStock || this.canPurchase || this.canReceipt}
{key:'product',label:'产品档案',icon:'el-icon-files',path:'/businessBasics/products',show:this.$auth.hasPermi('production:product:list')}
].filter(e=>e.show).map(e=>({...e,target:this.entry(e.path)}))
}
},
@ -135,7 +134,7 @@ export default {
count(value) { return this.loading || value==null ? '—' : String(value) },
amount(value) { if(this.loading || value==null)return '—'; const currency=this.overview.currency; return (currency==='CNY'?'¥ ':currency+' ')+Number(value).toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2}) },
statusWidth(s) { return !this.loading && this.overview.projectCount ? Number(s.count || 0)/this.overview.projectCount*100 : 0 },
entry(path) { return {path,query:['/project/info','/businessBasics/products','/mobile'].includes(path)?{}:(this.projectId?{projectId:this.projectId}:{})} },
entry(path) { return {path,query:['/project/info','/businessBasics/products'].includes(path)?{}:(this.projectId?{projectId:this.projectId}:{})} },
recordIcon(source) { return {purchase:'el-icon-shopping-cart-2',receipt:'el-icon-bottom-left',task:'el-icon-setting',loan:'el-icon-sort'}[source] || 'el-icon-document' },
recordDescription(row) { return [row.item!==row.record?row.record:null,row.supplier!=='—'?row.supplier:null,row.quantityText,row.progress,row.detail].filter(Boolean).join(' · ') },
homeFollowup(key){return homeQueueTarget(key,this.projectId)},

View File

@ -620,7 +620,7 @@
</el-select>
</el-form-item>
<el-form-item label="类别" prop="category">
<item-category-select v-model="form.category" />
<item-category-select v-model="form.category" :item-name="form.productName" :item-spec="form.spec" :item-brand="form.brand" />
</el-form-item>
<el-form-item label="规格" prop="spec">
<el-input v-model="form.spec" placeholder="请输入规格型号" />

View File

@ -9,7 +9,7 @@
<el-tab-pane label="费用分类" name="expense" />
</el-tabs>
<div class="list-actions">
<template v-if="tab==='wms_item_category'"><el-button type="primary" plain icon="el-icon-plus" size="small" @click="edit(null,'wms_item_category_group')" v-if="$can(['system:dict:add'])">新增大类</el-button><el-button size="small" @click="edit()" v-if="$can(['system:dict:add'])">新增小类</el-button></template>
<template v-if="tab==='wms_item_category'"><el-button type="primary" plain icon="el-icon-plus" size="small" @click="edit(null,'wms_item_category_group')" v-if="$can(['system:dict:add'])">新增大类</el-button><el-button size="small" @click="edit()" v-if="$can(['system:dict:add'])">新增小类</el-button><el-button v-if="$can(['system:dict:add'])&&$can(['system:dict:edit'])" size="small" @click="$router.push('/businessBasics/itemCategories')">分类管理<el-tag v-if="pendingCategories" size="small" type="warning" class="pending-category-count">{{ pendingCategories }}</el-tag></el-button></template>
<el-button v-else-if="$can(tab==='expense'?['project:category:edit']:['system:dict:add'])" type="primary" plain icon="el-icon-plus" size="small" @click="edit()" >新增</el-button>
</div>
<el-alert v-if="loadError" :title="loadError" type="error" :closable="false" class="mb8"><el-button link @click="load">重试</el-button></el-alert>
@ -59,9 +59,10 @@ import { runLatest, invalidateQuery, queryError } from '@/utils/query-session'
import useDictStore from '@/store/modules/dict'
import { invalidateItemCategories } from '@/utils/item-categories'
import {amountDisplay,loadAmountDisplay,saveAmountDisplay} from '@/utils/amount-display'
import {listCategoryApplications} from '@/api/warehouse/item-category'
export default {
name: 'BusinessDictionaries',
data: () => ({ displaySaving:false,displayError:false,tab: 'wms_item_category', editTab: 'wms_item_category', loading: false, loadError: '', saving: false, rows: [], groups: [], open: false, form: {}, rules: {} }),
data: () => ({ pendingCategories:0,displaySaving:false,displayError:false,tab: 'wms_item_category', editTab: 'wms_item_category', loading: false, loadError: '', saving: false, rows: [], groups: [], open: false, form: {}, rules: {} }),
computed: {
amountDisplay(){return amountDisplay},
displayRows() {
@ -72,12 +73,13 @@ export default {
return [...groups,...(ungrouped.children.length?[ungrouped]:[])]
}
},
created() { this.load();this.loadDisplay() },
created() { this.load();this.loadDisplay();this.loadCategoryPending() },
watch: { tab() { this.rows = []; this.load() } },
activated() { this.loadDisplay();if (this._needsRefresh) { this._needsRefresh = false; this.load() } },
activated() { this.loadDisplay();this.loadCategoryPending();if (this._needsRefresh) { this._needsRefresh = false; this.load() } },
deactivated() { this._needsRefresh = true; invalidateQuery(this) },
beforeUnmount() { invalidateQuery(this) },
methods: {
async loadCategoryPending(){if(!this.$can(['system:dict:add'])||!this.$can(['system:dict:edit']))return;try{this.pendingCategories=(await listCategoryApplications({all:true,status:'PENDING',pageNum:1,pageSize:1})).data.total}catch{this.pendingCategories=0}},
async loadDisplay(){try{this.displayError=false;await loadAmountDisplay()}catch{this.displayError=true}},
async toggleAmountDisplay(enabled){if(this.displaySaving)return;try{await this.$confirm(enabled?'开启后所有用户的采购、入库、出库、库存展示将隐藏零报价数据和内部实际金额,数据和成本不变。是否开启?':'关闭后所有用户可查看完整金额及零报价数据。是否关闭?','精简金额展示开关');this.displaySaving=true;await saveAmountDisplay(enabled);this.$modal.msgSuccess('展示开关已更新,业务页面刷新后生效')}catch(error){if(error!=='cancel'&&error!=='close')await this.loadDisplay()}finally{this.displaySaving=false}},
categoryReadOnly(row) { return row?.categoryCode === 'LEGACY' },

View File

@ -46,7 +46,7 @@
<el-table-column label="物品名称" prop="productName" show-overflow-tooltip min-width="160"/>
<el-table-column label="品牌" prop="brand" show-overflow-tooltip min-width="100"/>
<el-table-column label="大类" prop="categoryGroupName" show-overflow-tooltip min-width="100"/>
<el-table-column label="小类" prop="category" show-overflow-tooltip min-width="100"/>
<el-table-column label="小类" prop="category" show-overflow-tooltip min-width="150"><template #default="{row}">{{ row.category }}<el-tag v-if="pendingCategory(row.category)" size="small" type="warning" style="margin-left:6px">待确认</el-tag></template></el-table-column>
<el-table-column label="规格型号" prop="spec" show-overflow-tooltip min-width="180"/>
<el-table-column label="单位" prop="unit" show-overflow-tooltip width="70"/>
<el-table-column label="备注" prop="remark" show-overflow-tooltip min-width="160"/>
@ -75,7 +75,7 @@
</el-select>
</el-form-item>
<el-form-item label="类别" prop="category">
<item-category-select v-model="form.category" />
<item-category-select v-model="form.category" :item-name="form.productName" :item-spec="form.spec" :item-brand="form.brand" />
</el-form-item>
<el-form-item label="规格型号" prop="spec"><el-input v-model="form.spec" placeholder="请输入规格型号" /></el-form-item>
<el-form-item label="单位" prop="unit">
@ -107,6 +107,7 @@
import { runLatest, queryError } from '@/utils/query-session'
import request from '@/utils/request'
import { normalizeSearchQuery } from '@/utils/search-query'
import {isPendingItemCategory} from '@/utils/item-categories'
import { defineAsyncComponent } from 'vue'
import { listProduct, getProduct, delProduct, addProduct, updateProduct, optionselectProduct } from '@/api/warehouse/product'
@ -154,6 +155,7 @@ export default {
mounted(){this.openCreateFromRoute()},
watch:{'$route.fullPath'(){this.openCreateFromRoute()}},
methods: {
pendingCategory(label){return isPendingItemCategory(label)},
openCreateFromRoute(){if(this.$route.path==='/businessBasics/product'&&this.$route.query.create==='1'&&!this._createRouteHandled&&!this.open&&!this.saving&&this.$can(['warehouse:product:add'])){this._createRouteHandled=true;this.handleAdd()}},
async openCategorySummary(){this.summaryOpen=true;this.summaryLoading=true;this.summaryRows=[];try{const {data}=await request({url:'/warehouse/product/category-summary',method:'get'});const groups=new Map();for(const row of data||[]){const id=Number(row.parentId||0);if(!groups.has(id))groups.set(id,{key:'group-'+id,label:row.parentLabel,parentId:id,itemCount:0,children:[]});const group=groups.get(id);group.itemCount+=Number(row.itemCount);group.children.push({...row,key:'leaf-'+id+'-'+row.category,label:row.category,itemCount:Number(row.itemCount)})}this.summaryRows=[...groups.values()]}finally{this.summaryLoading=false}},
filterSummary(row){this.resetForm('queryForm');this.queryParams.categoryGroupId=row.children?row.parentId:undefined;this.queryParams.category=row.children?undefined:row.category;this.summaryOpen=false;this.showSearch=true;this.$refs.filters.expand();this.handleQuery()},

View File

@ -377,7 +377,7 @@
<template #default="scope"><el-select v-model="scope.row.materialBrand" filterable clearable allow-create default-first-option @paste="handleGridPaste($event, scope.$index, 4)"><el-option v-for="item in brandOptions" :key="item" :label="item" :value="item" /></el-select></template>
</el-table-column>
<el-table-column label="分类" min-width="130" class-name="business-control-cell">
<template #default="scope"><item-category-select v-model="scope.row.category" @paste="handleGridPaste($event, scope.$index, 5)" /></template>
<template #default="scope"><item-category-select v-model="scope.row.category" :item-name="scope.row.materialName" :item-spec="scope.row.materialParams" :item-brand="scope.row.materialBrand" @paste="handleGridPaste($event, scope.$index, 5)" /></template>
</el-table-column>
<el-table-column label="参数规格" min-width="160" class-name="business-control-cell">
<template #default="scope"><el-select v-model="scope.row.materialParams" filterable clearable allow-create default-first-option @paste="handleGridPaste($event, scope.$index, 6)"><el-option v-for="item in specOptions" :key="item" :label="item" :value="item" /></el-select></template>

View File

@ -26,13 +26,13 @@ it('real purchase columns, batch totals and footer keep actual amounts before qu
const host=defineComponent({template:`<div><el-table class="detail" :data="sheet.rows">${extract(grid)}</el-table><el-table class="batches" :data="sheet.rows">${totals.map(extract).join('')}</el-table><section class="summary">${extract(footer)}</section></div>`,
data:()=>({canViewQuotes:true,compactAmounts:false,extras:false,batchProject:{mixed:false},sheet:{rows:[{_key:'r',quantity:2,unit:'个',actualUnitPrice:3,finalUnitPrice:5,actualTotalAmount:6,totalAmount:10}]},cellOwner:{},editCell:null}),
computed:{columns(){return Sheet.computed.columns.call(this)},visibleRows(){return this.sheet.rows},actualTotal:()=>6,amount:()=>10,unpriced:()=>0},
methods:{selectColumn(){},originalIndex:()=>0,actualAmount:row=>row.quantity*row.actualUnitPrice,hasPrice:()=>true,money:value=>Number(value).toFixed(2)}})
methods:{pendingCategory:()=>false,selectColumn(){},isGridSelected:()=>false,isGridTypingCell:()=>false,originalIndex:()=>0,actualAmount:row=>row.quantity*row.actualUnitPrice,hasPrice:()=>true,money:value=>Number(value).toFixed(2)}})
const wrapper=mount(host,{global:{plugins:[ElementPlus],stubs:{PurchaseCell:true,BusinessIcon:true}}})
const headers=()=>wrapper.findAll('.detail thead th').map(h=>h.text())
const expected=['实际单价','实际金额','报价单价','报价金额']
await flushPromises();await nextTick()
expect(headers().filter(h=>expected.includes(h))).toEqual(expected)
for(const header of wrapper.findAll('.detail thead th').filter(h=>expected.includes(h.text())))expect(header.classes()).toContain('is-right')
for(const header of wrapper.findAll('.detail thead th'))expect(header.classes()).toContain('is-left')
expect(wrapper.findAll('.batches thead th').map(h=>h.text())).toEqual(['实际总金额','报价合计'])
expect(wrapper.get('.summary').text()).toMatch(/实际总金额 ¥ 6\.00.*报价总金额 ¥ 10\.00/)
expect(wrapper.get('.detail tbody').text()).toContain('6.00')

View File

@ -4,6 +4,11 @@ import {parse} from '@vue/compiler-sfc'
import {baseParse} from '@vue/compiler-dom'
import {defineComponent} from 'vue'
import {mount} from '@vue/test-utils'
import Sheet from '../../src/components/PurchaseSheet/index.vue'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
it('purchase keeps template export on the main list only and removes quote-entry shortcuts',()=>{
const template=parse(readFileSync('src/components/PurchaseSheet/index.vue','utf8')).descriptor.template.content
@ -37,17 +42,35 @@ it('purchase editing removes the entire fixed operations column and restores it
find(baseParse(template));expect(column).toBeTruthy()
const actual=template.slice(column.loc.start.offset,column.loc.end.offset)
const records=vi.fn()
const host=defineComponent({template:`<div>${actual}</div>`,data:()=>({isEditing:false,saving:false,canEdit:true}),methods:{canArrive:()=>false,records}})
const host=defineComponent({template:`<div>${actual}</div>`,data:()=>({isEditing:false,saving:false,canEdit:true}),methods:{canArrive:()=>false,records,rowActions:Sheet.methods.rowActions,runRowCommand:Sheet.methods.runRowCommand}})
const tableColumn=defineComponent({props:['label','width'],template:'<section class="operations"><strong>{{label}}</strong><slot :row="row"/></section>',data:()=>({row:{id:1,purchaseStatus:0,pendingArrivalQuantity:0,acceptedQuantity:0}})})
const button=defineComponent({emits:['click'],template:'<button @click="$emit(\'click\')"><slot/></button>'})
const wrapper=mount(host,{global:{stubs:{ElTableColumn:tableColumn,ElButton:button},mocks:{$can:()=>false}}})
expect(wrapper.get('.operations').text()).toContain('操作')
expect(wrapper.findAll('button').map(button=>button.text())).toEqual(['到货记录','附件'])
await wrapper.get('button').trigger('click');expect(records).toHaveBeenCalledOnce()
await wrapper.setData({isEditing:true})
expect(wrapper.find('.operations').exists()).toBe(false)
expect(wrapper.find('button').exists()).toBe(false)
await wrapper.setData({isEditing:false})
expect(wrapper.get('.operations').text()).toContain('到货记录')
expect(wrapper.findComponent(tableColumn).props('width')).toBe('270')
expect(wrapper.findComponent(tableColumn).props('width')).toBe('180')
wrapper.unmount()
})
it('row actions keep concurrent arrival and receipt flows and guard attachment access',()=>{
const vm={saving:false,canEdit:true,canArrive:()=>true,$can:()=>true,sheet:{batch:{id:482}},$refs:{documents:{open:vi.fn()},cancelPurchase:{open:vi.fn()}},arrival:vi.fn(),$router:{push:vi.fn()}}
vm.rowActions=row=>Sheet.methods.rowActions.call(vm,row)
const row={id:12,projectId:4,materialName:'电机',materialParams:'A1',pendingArrivalQuantity:2,acceptedQuantity:3,receivedQuantity:1}
expect(vm.rowActions(row).map(action=>action.command)).toEqual(['arrival','receipt','attachments','cancel'])
const run=command=>Sheet.methods.runRowCommand.call(vm,command,row)
run('attachments');expect(vm.$refs.documents.open).toHaveBeenCalledWith('detail',12,'电机 / A1')
run('arrival');expect(vm.arrival).toHaveBeenCalledWith([row])
run('receipt');expect(vm.$router.push).toHaveBeenCalledWith({path:'/warehouse/pending',query:{sourceGroup:'B:482',projectId:4}})
run('cancel');expect(vm.$refs.cancelPurchase.open).toHaveBeenCalledWith(row)
vm.$can=()=>false;vm.canEdit=false
expect(vm.rowActions(row).map(action=>action.command)).toEqual(['attachments'])
vm.arrival.mockClear();run('arrival');expect(vm.arrival).not.toHaveBeenCalled()
vm.$refs.documents.open.mockClear();vm.saving=true;run('attachments');expect(vm.$refs.documents.open).not.toHaveBeenCalled()
vm.saving=false;row.id=null;run('attachments');expect(vm.$refs.documents.open).not.toHaveBeenCalled()
})

View File

@ -22,7 +22,7 @@ function fixture(){
vm._editor=createSheetEditor(vm)
vm.sheet={batch:{},deletedIds:[],rows:[{_key:'r1',materialName:'原物品',materialBrand:'原品牌',quantity:2,unit:'个',finalUnitPrice:3,actualUnitPrice:4},{_key:'r2',materialName:'第二项',materialBrand:'乙品牌',quantity:5,unit:'个',finalUnitPrice:6,actualUnitPrice:7}]}
vm.baseline=JSON.stringify(vm.sheet)
const wrapper=mount({components:{Cell},setup:()=>({vm}),template:'<div tabindex="-1"><template v-for="(row,index) in vm.sheet.rows" :key="row._key"><Cell v-for="column in vm.columns" :key="column.field" :row="row" :column="column" :index="index" :owner="vm" :active="vm.editCell===row._key+\'|\'+column.field"/></template></div>'},{attachTo:document.body,global:{plugins:[ElementPlus],stubs:{ItemCategorySelect:true}}})
const wrapper=mount({components:{Cell},setup:()=>({vm}),template:'<div tabindex="-1"><template v-for="(row,index) in vm.sheet.rows" :key="row._key"><Cell v-for="column in vm.columns" :key="column.field" :row="row" :column="column" :index="index" :owner="vm" :selected="vm.isGridSelected(row,column.field)" :typing="vm.isGridTypingCell(row,column.field)" :active="vm.editCell===row._key+\'|\'+column.field"/></template></div>'},{attachTo:document.body,global:{plugins:[ElementPlus],stubs:{ItemCategorySelect:true}}})
vm.$el=wrapper.element
Object.defineProperty(Element.prototype,'scrollIntoView',{configurable:true,value:vi.fn()})
cleanup.push(()=>{vm._editor.stop();wrapper.unmount()})

View File

@ -7,6 +7,12 @@ import {writeClipboardText} from '../../src/utils/purchase-grid-clipboard'
vi.mock('@/utils/request',()=>({default:vi.fn()}))
vi.mock('@/store/modules/user',()=>({default:()=>({permissions:['*:*:*']})}))
vi.mock('@/store/modules/app',()=>({default:()=>({size:'default'})}))
it('using an active cell recommendation button does not tear down its editor or start a grid drag',()=>{
const root=document.createElement('div'),button=document.createElement('button');root.append(button)
const event={button:0,shiftKey:false,target:button,currentTarget:root,preventDefault:vi.fn()},vm={editCell:'row|category',saving:false,_editor:{flush:vi.fn()}}
Sheet.methods.startCellSelection.call(vm,{_key:'row'},'category',event)
expect(vm.editCell).toBe('row|category');expect(event.preventDefault).not.toHaveBeenCalled();expect(vm._editor.flush).not.toHaveBeenCalled();expect(vm._gridDragging).toBeUndefined()
})
it.each(['number','text'])('typing into a %s grid input does not invoke unsupported native text selection',async type=>{
const root=document.createElement('div'),cell=document.createElement('div'),input=document.createElement('input')
cell.className='sheet-cell';cell.dataset.row='0';cell.dataset.field='quantity';input.type=type;cell.append(input);root.append(cell)
@ -84,3 +90,17 @@ it('a virtual window at the end retains the last row when density changes its ca
})
it('closing a sheet leaves an empty virtual view without dereferencing its old rows',()=>{expect(Sheet.computed.visibleRows.call({sheet:null,rowFilter:'',rowSort:'original'})).toEqual([]);expect(()=>Sheet.watch.virtualCount.call({sheet:null},24,23)).not.toThrow()})
it('medium-size sheets use a window while their full row and clipboard scope stays available',()=>{
const rows=Array.from({length:100},(_,i)=>({_key:'row-'+i,quantity:i})),vm={visibleRows:rows,virtualStart:20,virtualCount:24}
vm.virtualized=Sheet.computed.virtualized.call(vm)
expect(vm.virtualized).toBe(true);expect(Sheet.computed.renderedRows.call(vm)).toEqual(rows.slice(20,44));expect(vm.visibleRows).toHaveLength(100)
})
it('draft-list discovery waits until leaving editing without deferring the draft write',()=>{
const vm={isEditing:true,drafts:[{key:'old'}],draftPrefix:vi.fn()}
Sheet.methods.refreshDrafts.call(vm);expect(vm.draftPrefix).not.toHaveBeenCalled();expect(vm.drafts).toEqual([{key:'old'}])
})
it('validation opens collapsed batch fields before focusing a missing required project',async()=>{
const focus=vi.fn(),vm={sheet:{unbatched:false},batchProject:{mixed:false},batchDetailsOpen:false,$nextTick:nextTick,$refs:{batchProjectSelect:{focus}}}
await Sheet.methods.focusError.call(vm,{field:'projectId'})
expect(vm.batchDetailsOpen).toBe(true);expect(focus).toHaveBeenCalledOnce()
})

View File

@ -31,6 +31,14 @@ it('captures the selection at dialog opening and never exports the full batch af
api.request.mockRejectedValue(new Error('test response'));button('导出询价单').click();await flushPromises()
expect(api.request.mock.calls[0][0].data.rowIds).toEqual([1])
})
it('sends exactly the two checked fields and lets the serial column be omitted',async()=>{
const w=render();w.vm.exportInquiry();await flushPromises()
expect(document.body.textContent).toContain('仅导出勾选字段,未勾选字段不写入文件')
for(const checkbox of document.querySelectorAll('.inquiry-options__grid .el-checkbox'))if(!['物品名称','采购数量'].includes(checkbox.textContent.trim())){checkbox.querySelector('input').click();await flushPromises()}
await flushPromises();api.request.mockRejectedValue(new Error('test response'));button('导出询价单').click();await flushPromises()
expect(api.request.mock.calls[0][0].params.selectedColumns).toBe('name,quantity')
expect(api.request.mock.calls[0][0].data.rowIds).toEqual([1])
})
it('does not export an empty selection or a stale sheet version',async()=>{
const w=render({exportRows:[]});w.vm.exportInquiry();await flushPromises();expect(api.request).not.toHaveBeenCalled();expect(button('导出询价单')).toBeUndefined()
await w.setProps({exportRows:[{id:1,productCode:'A',quantity:2}]});w.vm.exportInquiry();await flushPromises()

View File

@ -21,6 +21,18 @@ test('interrupted write keeps the previous complete snapshot instead of mixed or
assert.equal(readSheetDraft('durable:1:new').sheet.rows[0].materialName,'原物品')
storage.setItem=original;editor.persist();assert.equal(readSheetDraft('durable:1:new').sheet.rows[0].materialName,'未完成的新版本')
})
test('failed metadata commit retires only new fragments and a retry keeps the old draft recoverable',t=>{
const {vm,editor,storage,values}=fixture(t);editor.persist();const previousKeys=[...values.keys()].sort(),write=storage.setItem
vm.sheet.rows[0].quantity=12;storage.setItem=(key,value)=>{if(key==='durable:1:new')throw Error('quota');write(key,value)}
assert.throws(()=>editor.persist(),/quota/);assert.deepEqual([...values.keys()].sort(),previousKeys);assert.equal(readSheetDraft('durable:1:new').sheet.rows[0].quantity,1)
storage.setItem=write;editor.persist();assert.equal(readSheetDraft('durable:1:new').sheet.rows[0].quantity,12);assert.equal(values.size,previousKeys.length)
})
test('repeated typing retires previous fragments without rescanning unrelated storage',t=>{
const {vm,editor,values}=fixture(t);editor.persist();let scans=0
globalThis.localStorage=new Proxy(globalThis.localStorage,{ownKeys(target){scans++;return Reflect.ownKeys(target)}})
for(let n=2;n<12;n++){vm.sheet.rows[0].quantity=n;editor.persist();assert.equal(readSheetDraft('durable:1:new').sheet.rows[0].quantity,n)}
assert.equal(scans,0);assert.equal(values.size,3)
})
test('old local drafts remain discoverable beyond seven days and stay isolated by account',t=>{
const {storage}=fixture(t);storage.setItem('durable:1:old',JSON.stringify({sheet:{batch:{id:9}},savedAt:Date.now()-30*86400000}));storage.setItem('durable:2:private',JSON.stringify({sheet:{batch:{id:10}},savedAt:Date.now()}))
assert.equal(listSheetDrafts(storage,'durable:1:').length,1)