224 lines
19 KiB
Java
224 lines
19 KiB
Java
|
|
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 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"));
|
||
|
|
assertThrows(ServiceException.class,()->f.service.save(locked));
|
||
|
|
assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("3")));
|
||
|
|
} 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));
|
||
|
|
}
|
||
|
|
|
||
|
|
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;
|
||
|
|
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;
|
||
|
|
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));
|
||
|
|
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); 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<PurchaseRequest> 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> 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));}
|
||
|
|
}
|