package com.ruoyi.projectdev; import java.math.BigDecimal; import java.nio.file.*; import java.util.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.ruoyi.common.core.domain.entity.SysDictData; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.utils.SecurityUtils; import com.ruoyi.framework.config.ProjectDatabaseGuard; import com.ruoyi.project.domain.*; import com.ruoyi.project.mapper.*; import com.ruoyi.project.service.IProjectInfoService; import com.ruoyi.system.service.ISysDictTypeService; import com.ruoyi.warehouse.domain.*; import com.ruoyi.warehouse.mapper.*; import com.ruoyi.warehouse.service.*; import com.ruoyi.warehouse.service.impl.*; import org.apache.ibatis.builder.xml.XMLMapperBuilder; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.*; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.transaction.SpringManagedTransactionFactory; import org.springframework.aop.framework.ProxyFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionTemplate; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import org.yaml.snakeyaml.Yaml; import static org.junit.jupiter.api.Assertions.*; 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 batchCombinedFiltersKeepWholeBatchTotalsAndDateBoundaries() throws Exception { Fixture f=new Fixture(); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test"); security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).executeWithoutResult(status->{ status.setRollbackOnly(); var saved=f.service.save(f.draft()); var filter=new PurchaseBatch(); filter.setKeyword(saved.getBatch().getBatchNo()); filter.setSupplierId(saved.getBatch().getSupplierId()); filter.setProjectId(saved.getRows().get(0).getProjectId()); filter.setMaterialName(f.name); filter.setBeginDate(saved.getBatch().getBusinessDate()); filter.setEndDate(saved.getBatch().getBusinessDate()); filter.setProgress("confirm"); var result=f.batchMapper.selectPurchaseBatchList(filter); assertEquals(1,result.size()); assertEquals(saved.getBatch().getId(),result.get(0).getId()); assertEquals(2,result.get(0).getRequestCount(),"Filtering by one project must not remove other projects from batch totals"); assertEquals(0,new BigDecimal("5.00").compareTo(result.get(0).getTotalAmount())); filter.setBeginDate(saved.getBatch().getBusinessDate().plusDays(1)); assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty()); filter.setBeginDate(null);filter.setEndDate(saved.getBatch().getBusinessDate().minusDays(1)); assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty()); }); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); } } @Test void mixedProjectSaveDedupQuotesAndLockingAreAtomic() throws Exception { Fixture f = new Fixture(); try (var security = mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test"); security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).execute(status -> { try { PurchaseSheet draft = f.draft(); PurchaseSheet saved = f.service.save(draft); assertTrue(saved.getBatch().getBatchNo().matches("CG"+java.time.LocalDate.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMM"))+"[0-9]{4,}")); PurchaseSheet another=f.service.load(saved.getBatch().getId());another.getBatch().setId(null);another.getRows().forEach(row->row.setId(null));another.setVersion(null); PurchaseSheet second=f.service.save(another); assertEquals(Integer.parseInt(saved.getBatch().getBatchNo().substring(8))+1,Integer.parseInt(second.getBatch().getBatchNo().substring(8)),"Shared day numbering increments without a random suffix"); assertEquals(2, saved.getRows().size()); assertEquals(saved.getRows().get(0).getProductId(), saved.getRows().get(1).getProductId()); assertNotEquals(saved.getRows().get(0).getProjectId(), saved.getRows().get(1).getProjectId()); assertEquals(1, f.jdbc.queryForObject("select count(*) from product_info where product_name=?", Integer.class, f.name)); assertEquals(0, f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)", Integer.class, saved.getRows().get(0).getId(),saved.getRows().get(1).getId())); String stale = saved.getVersion(); saved.getRows().get(0).setQuantity(new BigDecimal("3")); saved = f.service.save(saved); assertEquals(2, saved.getRows().size()); assertNotEquals(stale, saved.getVersion()); assertEquals(1, f.jdbc.queryForObject("select count(*) from product_info where product_name=?", Integer.class, f.name)); saved.getRows().get(0).setFinalUnitPrice(null); saved=f.service.save(saved); assertNull(saved.getRows().get(0).getFinalUnitPrice(),"Clearing a quote must not restore the legacy estimated price"); saved.getRows().get(0).setFinalUnitPrice(new BigDecimal("1.25")); saved=f.service.save(saved); PurchaseSheet locked = f.service.confirm(saved.getBatch().getId(),saved.getVersion()); assertTrue(locked.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked()))); assertEquals(0, locked.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("3.75"))); f.service.confirm(locked.getBatch().getId(),locked.getVersion()); assertEquals(2,f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Integer.class,locked.getRows().get(0).getId(),locked.getRows().get(1).getId())); locked.getRows().get(0).setQuantity(new BigDecimal("10")); PurchaseSheet maintained=f.service.save(locked); assertTrue(maintained.getRows().get(0).getPriceLocked()); assertEquals(0,maintained.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("12.50"))); assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("10"))); } finally { status.setRollbackOnly(); } return null; }); } assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name)); } @Test void invalidSecondRowRollsBackBatchArchiveAndFirstRow() throws Exception { Fixture f = new Fixture(); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test"); security.when(SecurityUtils::getUserId).thenReturn(1L); assertThrows(ServiceException.class,()->new TransactionTemplate(f.manager).execute(status->{ PurchaseSheet draft=f.draft();draft.getRows().get(1).setUnit("箱"); return f.service.save(draft); })); } assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name)); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name)); assertEquals(1,f.jdbc.queryForObject("select get_lock('cmvr-project-dev:catalog-write',0)",Integer.class)); f.jdbc.queryForObject("select release_lock('cmvr-project-dev:catalog-write')",Integer.class); } @Test void staleVersionAndOmittedRowsCannotOverwriteBatch() throws Exception { Fixture f=new Fixture(); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).execute(status->{ try { PurchaseSheet saved=f.service.save(f.draft()); saved.setVersion("stale");assertThrows(ServiceException.class,()->f.service.save(saved)); PurchaseSheet omitted=f.service.load(saved.getBatch().getId()); omitted.setRows(List.of(omitted.getRows().get(0))); assertThrows(ServiceException.class,()->f.service.save(omitted)); PurchaseSheet cleared=f.service.load(saved.getBatch().getId()); cleared.setDeletedIds(cleared.getRows().stream().map(PurchaseRequest::getId).toList()); cleared.setRows(List.of()); assertTrue(f.service.save(cleared).getRows().isEmpty()); }finally{status.setRollbackOnly();}return null; }); } } @Test void supplierCanBeDeferredUntilConfirmationAndUnbatchedFilterIsReal() throws Exception { Fixture f=new Fixture(); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true); security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).execute(status->{ try { PurchaseSheet draft=f.draft();Long supplier=draft.getBatch().getSupplierId();draft.getBatch().setSupplierId(null); PurchaseSheet saved=f.service.save(draft); assertNull(saved.getBatch().getSupplierId());assertEquals(2,saved.getRows().size()); PurchaseRequest unbatched=new PurchaseRequest();unbatched.setUnbatched(true);unbatched.setMaterialName(f.name); assertTrue(f.purchaseRows.selectPurchaseRequestList(unbatched).isEmpty()); assertThrows(ServiceException.class,()->f.service.confirm(saved.getBatch().getId(),saved.getVersion())); assertFalse(f.service.load(saved.getBatch().getId()).getRows().stream().anyMatch(r->Boolean.TRUE.equals(r.getPriceLocked()))); saved.getBatch().setSupplierId(supplier);PurchaseSheet assigned=f.service.save(saved); PurchaseSheet locked=f.service.confirm(assigned.getBatch().getId(),assigned.getVersion()); assertTrue(locked.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked()))); locked.getBatch().setSupplierId(null);assertThrows(ServiceException.class,()->f.service.save(locked)); }finally{status.setRollbackOnly();}return null; }); } assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name)); } @Test void missingCategoryRejectsBeforeCreatingAnyArchiveOrPurchase() throws Exception { Fixture f=new Fixture(); try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); ServiceException error=assertThrows(ServiceException.class,()->new TransactionTemplate(f.manager).execute(status->{ PurchaseSheet draft=f.draft();draft.getRows().get(0).setCategory(" ");return f.service.save(draft); }));assertTrue(error.getMessage().contains("物品类别")); } assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name)); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name)); assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name)); } @Test void confirmedTransfersKeepFeesAndRejectChangedSupplierOrExistingArrival()throws Exception { Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) { security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test"); new TransactionTemplate(f.manager).execute(status->{try { var saved=f.service.save(f.draft());var locked=f.service.confirm(saved.getBatch().getId(),saved.getVersion());var row=locked.getRows().get(0);Long supplier=locked.getBatch().getSupplierId(); f.jdbc.update("insert into purchase_batch(batch_no,batch_name,supplier_id,purchase_status,business_date) values(?,?,?,1,current_date())",f.name+"-target",f.name+"-target",supplier);Long target=f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-target"); var raw=new PurchaseBatchServiceImpl();f.set(raw,"purchaseBatchMapper",f.batchMapper);f.set(raw,"purchaseRequestMapper",f.purchaseRows);f.set(raw,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));var lock=new CatalogWriteLock();f.set(lock,"jdbc",f.jdbc);f.set(raw,"catalogWriteLock",lock);var service=f.proxy(raw); var command=new PurchaseBatchAssignRequest();command.setRequestIds(new Long[]{row.getId()});command.setBatchId(target);assertEquals(1,service.assignPurchaseBatch(command));var moved=f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId());assertEquals(target,moved.getPurchaseBatchId());assertTrue(moved.getPriceLocked());assertEquals(row.getLockedAmount(),moved.getLockedAmount()); f.jdbc.update("insert into supplier_info(name,active) values(?,1)",f.name+"-other");Long other=f.jdbc.queryForObject("select id from supplier_info where name=?",Long.class,f.name+"-other");f.jdbc.update("insert into purchase_batch(batch_no,supplier_id,purchase_status) values(?,?,1)",f.name+"-wrong",other);command.setBatchId(f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-wrong"));assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId()); f.jdbc.update("insert into purchase_arrival(arrival_no,purchase_request_id,arrival_quantity,arrival_date,acceptance_status,create_by) values(?,?,2,current_date(),1,'sheet-rollback-test')","ARR-"+UUID.randomUUID(),row.getId());f.jdbc.update("update purchase_request set purchase_status=4 where id=?",row.getId());var appended=f.service.load(target);appended.getRows().get(0).setQuantity(new BigDecimal("3"));var updated=f.service.save(appended);assertEquals(3,updated.getRows().get(0).getPurchaseStatus());assertEquals(0,new BigDecimal("3.75").compareTo(updated.getRows().get(0).getLockedAmount()));command.setBatchId(locked.getBatch().getId());assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId()); } finally{status.setRollbackOnly();}return null;}); } assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_no like ?",Integer.class,f.name+"%")); } @Test void preparingUnbatchedRowsIsAtomicAndPreservesIds()throws Exception{ Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)){ security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).executeWithoutResult(status->{status.setRollbackOnly();var initial=f.service.save(f.draft());Long[] ids=initial.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new); for(Long id:ids)f.jdbc.update("update purchase_request set purchase_batch_id=null,purchase_batch_no=null where id=?",id); var prepared=f.service.prepare(ids);assertEquals(2,prepared.getRows().size());assertNull(prepared.getBatch().getSupplierId());assertEquals(Set.of(ids),new HashSet<>(prepared.getRows().stream().map(PurchaseRequest::getId).toList())); long count=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class);assertThrows(ServiceException.class,()->f.service.prepare(ids));assertEquals(count,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); }); } } @Test void unbatchedSaveEditDeleteAndGroupingPreserveAtomicity() throws Exception { Fixture f=new Fixture(); try(var security=mockStatic(SecurityUtils.class)){ security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L); new TransactionTemplate(f.manager).execute(status->{try{ long batchCount=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class); var draft=f.draft();draft.setUnbatched(true);draft.getBatch().setSupplierId(null);draft.getRows().forEach(r->r.setFinalUnitPrice(null)); var saved=f.service.save(draft);assertTrue(saved.isUnbatched());assertNull(saved.getBatch().getId());assertEquals(batchCount,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); assertTrue(saved.getRows().stream().allMatch(r->r.getPurchaseBatchId()==null&&!Boolean.TRUE.equals(r.getPriceLocked()))); var ids=saved.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new); var stale=f.service.loadUnbatched(ids);saved.getRows().get(0).setQuantity(new BigDecimal("7"));f.service.save(saved); stale.getRows().get(0).setQuantity(BigDecimal.TEN);assertThrows(ServiceException.class,()->f.service.save(stale)); var batch=f.service.prepare(new Long[]{ids[0]},null);assertNotNull(batch.getBatch().getId());assertEquals(1,batch.getRows().size()); assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[0]},batch.getBatch().getId())); f.jdbc.update("update purchase_batch set purchase_status=2 where id=?",batch.getBatch().getId()); assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId())); assertNull(f.service.loadUnbatched(new Long[]{ids[1]}).getRows().get(0).getPurchaseBatchId()); f.jdbc.update("update purchase_batch set purchase_status=1 where id=?",batch.getBatch().getId()); assertEquals(2,f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId()).getRows().size()); assertEquals(batchCount+1,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class)); var more=new PurchaseSheet();more.setUnbatched(true);more.setBatch(new PurchaseBatch());more.setRows(draft.getRows());more.getRows().forEach(r->{r.setId(null);r.setPurchaseBatchId(null);});var deletion=f.service.save(more);var deleted=deletion.getRows().stream().map(PurchaseRequest::getId).toList();deletion.setDeletedIds(deleted);deletion.setRows(List.of());assertTrue(f.service.save(deletion).getRows().isEmpty()); }finally{status.setRollbackOnly();}return null;}); } } private static class Fixture { final String name="SHEET-CHECK-"+UUID.randomUUID(); final JdbcTemplate jdbc; final DataSourceTransactionManager manager; final PurchaseSheetService service; final ProjectInfoMapper projects; final ProjectBudgetMapper budgets; final PurchaseRequestMapper purchaseRows; final PurchaseBatchMapper batchMapper; Fixture() throws Exception { Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent(); Map yaml;try(var input=Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))){yaml=new Yaml().load(input);} Map source=(Map)((Map)((Map)((Map)yaml.get("spring")).get("datasource")).get("druid")).get("master"); String url=resolve(String.valueOf(source.get("url")));ProjectDatabaseGuard.assertAllowedUrl(url); DriverManagerDataSource ds=new DriverManagerDataSource(url,resolve(String.valueOf(source.get("username"))),resolve(String.valueOf(source.get("password")))); jdbc=new JdbcTemplate(ds);assertEquals("cmvr-project-dev",jdbc.queryForObject("select database()",String.class)); manager=new DataSourceTransactionManager(ds); Configuration config=new Configuration();config.getTypeAliasRegistry().registerAliases("com.ruoyi.warehouse.domain"); config.setEnvironment(new Environment("sheet-rollback",new SpringManagedTransactionFactory(),ds)); for(String file:List.of("project/ProjectInfo","project/ProjectBudget","warehouse/PurchaseRequest","warehouse/ProductInfo","warehouse/PurchaseBatch","warehouse/PurchaseArrival")) { String resource="mapper/"+file+"Mapper.xml"; try(var input=getClass().getClassLoader().getResourceAsStream(resource)){assertNotNull(input,resource);new XMLMapperBuilder(input,config,resource,config.getSqlFragments()).parse();} } var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config)); projects=session.getMapper(ProjectInfoMapper.class);budgets=session.getMapper(ProjectBudgetMapper.class); var purchases=session.getMapper(PurchaseRequestMapper.class);var catalog=session.getMapper(ProductInfoMapper.class); purchaseRows=purchases; batchMapper=session.getMapper(PurchaseBatchMapper.class); IProjectInfoService projectAccess=mock(IProjectInfoService.class); IPurchaseOperationLogService logs=mock(IPurchaseOperationLogService.class); CatalogWriteLock lock=new CatalogWriteLock();set(lock,"jdbc",jdbc); var allocator=AuthorizedDatabaseTestSupport.numbers(jdbc,manager);PurchaseBatchNumber numbers=new PurchaseBatchNumber();set(numbers,"businessNumbers",allocator); ProductInfoServiceImpl productTarget=new ProductInfoServiceImpl();set(productTarget,"productInfoMapper",catalog);set(productTarget,"catalogWriteLock",lock); set(productTarget,"businessNumbers",allocator); var productService=proxy(productTarget); PurchasePriceService prices=new PurchasePriceService();set(prices,"purchaseRequestMapper",purchases);set(prices,"projectBudgetMapper",budgets);set(prices,"projectInfoService",projectAccess);set(prices,"operationLogService",logs); set(prices,"businessNumbers",allocator); PurchaseRequestServiceImpl purchaseTarget=new PurchaseRequestServiceImpl();set(purchaseTarget,"purchaseRequestMapper",purchases);set(purchaseTarget,"productInfoMapper",catalog);set(purchaseTarget,"productInfoService",productService);set(purchaseTarget,"purchaseArrivalMapper",session.getMapper(PurchaseArrivalMapper.class));set(purchaseTarget,"projectInfoMapper",projects);set(purchaseTarget,"projectBudgetMapper",budgets);set(purchaseTarget,"projectInfoService",projectAccess);set(purchaseTarget,"priceService",prices);set(purchaseTarget,"purchaseOperationLogService",logs);set(purchaseTarget,"taskDatabase",jdbc); 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); 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); } PurchaseSheet draft() { jdbc.update("insert into supplier_info(name,active,create_by) values(?,1,'sheet-rollback-test')",name); Long supplier=jdbc.queryForObject("select id from supplier_info where name=?",Long.class,name); ExpenseCategory category=budgets.selectExpenseCategoryByCode("MATERIAL");assertNotNull(category); List rows=new ArrayList<>(); for(int n=0;n<2;n++) { ProjectInfo project=new ProjectInfo();project.setProjectCode(name+"-"+n);project.setProjectName(name+"-"+n);project.setProjectType("RESEARCH");project.setProjectStatus(0);project.setTotalAmount(BigDecimal.TEN);projects.insertProjectInfo(project); PurchaseRequest row=new PurchaseRequest();row.setProjectId(project.getId());row.setExpenseCategoryId(category.getId());row.setMaterialName(name);row.setMaterialBrand("测试品牌");row.setMaterialParams("M4");row.setCategory("测试类别");row.setUnit("件");row.setQuantity(new BigDecimal("2"));row.setFinalUnitPrice(new BigDecimal("1.25"));row.setPurchasePurpose("SELF");rows.add(row); } PurchaseBatch batch=new PurchaseBatch();batch.setSupplierId(supplier);batch.setBatchName(name);batch.setBusinessDate(java.time.LocalDate.now()); PurchaseSheet result=new PurchaseSheet();result.setBatch(batch);result.setRows(rows);result.setDeletedIds(List.of());return result; } // Each simulated HTTP request has a savepoint; a rejected request must not poison // later requests sharing the outer rollback-only fixture transaction. @SuppressWarnings("unchecked") T proxy(T target){var attributes=new org.springframework.transaction.interceptor.MatchAlwaysTransactionAttributeSource();attributes.setTransactionAttribute(new org.springframework.transaction.interceptor.DefaultTransactionAttribute(org.springframework.transaction.TransactionDefinition.PROPAGATION_NESTED));ProxyFactory factory=new ProxyFactory(target);factory.setProxyTargetClass(true);factory.addAdvice(new TransactionInterceptor(manager,attributes));return (T)factory.getProxy();} void set(Object target,String field,Object value){ReflectionTestUtils.setField(target,field,value);} } private static String resolve(String value){if(!value.startsWith("${")||!value.endsWith("}"))return value;String body=value.substring(2,value.length()-1);int pos=body.indexOf(':');return Objects.requireNonNullElse(System.getenv(pos<0?body:body.substring(0,pos)),pos<0?"":body.substring(pos+1));} }