2026-10-12 16:41:42 +08:00
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 {
2026-10-20 10:04:17 +08:00
@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 ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var draft = f . draft ( ) ; draft . getRows ( ) . get ( 1 ) . setProjectId ( draft . getRows ( ) . get ( 0 ) . getProjectId ( ) ) ; var sheet = f . save ( draft ) ; var first = sheet . getRows ( ) . get ( 0 ) ; var second = sheet . getRows ( ) . get ( 1 ) ;
f . jdbc . update ( " update purchase_request set purchase_status=4,historical=1 where purchase_batch_id=? " , sheet . getBatch ( ) . getId ( ) ) ;
var history = f . history ( ) ; var a = new PurchaseHistoryCorrectionService . Entry ( first . getId ( ) , Map . of ( " quantity " , 3 , " actualUnitPrice " , 7 , " finalUnitPrice " , 4 , " category " , " 更正类别 " , " remark " , " 核对历史附件 " ) , null ) ;
var b = new PurchaseHistoryCorrectionService . Entry ( second . getId ( ) , Map . of ( " remark " , " 另一条更正 " ) , null ) ;
var preview = history . preview ( new PurchaseHistoryCorrectionService . Command ( null , " 历史附件核对 " , List . of ( a , b ) , false ) ) ; assertEquals ( true , preview . get ( " ready " ) , preview . toString ( ) ) ;
var rows = ( List < Map < String , Object > > ) preview . get ( " rows " ) ; a = new PurchaseHistoryCorrectionService . Entry ( a . id ( ) , a . changes ( ) , rows . get ( 0 ) . get ( " version " ) . toString ( ) ) ; b = new PurchaseHistoryCorrectionService . Entry ( b . id ( ) , b . changes ( ) , rows . get ( 1 ) . get ( " version " ) . toString ( ) ) ;
var stale = new PurchaseHistoryCorrectionService . Entry ( b . id ( ) , b . changes ( ) , " stale " ) ; var reviewedA = a ;
assertThrows ( ServiceException . class , ( ) - > history . correct ( new PurchaseHistoryCorrectionService . Command ( " history-stale-key " , " 历史附件核对 " , List . of ( reviewedA , stale ) , false ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 1.25 " ) . compareTo ( f . purchaseRows . selectPurchaseRequestById ( first . getId ( ) , null ) . getFinalUnitPrice ( ) ) ) ;
var command = new PurchaseHistoryCorrectionService . Command ( " history-test- " + UUID . randomUUID ( ) , " 历史附件核对 " , List . of ( a , b ) , false ) ; var result = history . correct ( command ) ; assertEquals ( 2L , result . get ( " changed " ) ) ;
var after = f . purchaseRows . selectPurchaseRequestById ( first . getId ( ) , null ) ; assertEquals ( 0 , new BigDecimal ( " 21 " ) . compareTo ( after . getActualAmount ( ) ) ) ; assertEquals ( 0 , new BigDecimal ( " 12 " ) . compareTo ( after . getEstimatedAmount ( ) ) ) ; assertEquals ( first . getMaterialName ( ) , after . getMaterialName ( ) ) ; assertEquals ( first . getPurchaseBatchId ( ) , after . getPurchaseBatchId ( ) ) ; assertEquals ( 4 , after . getPurchaseStatus ( ) ) ;
assertEquals ( " 更正类别 " , f . jdbc . queryForObject ( " select category from product_info where id=? " , String . class , first . getProductId ( ) ) ) ;
int audit = f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger where purchase_request_id=? " , Integer . class , first . getId ( ) ) ;
assertEquals ( ( ( Number ) result . get ( " changed " ) ) . longValue ( ) , ( ( Number ) history . correct ( command ) . get ( " changed " ) ) . longValue ( ) ) ; assertEquals ( audit , f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger where purchase_request_id=? " , Integer . class , first . getId ( ) ) ) ;
var wrong = new PurchaseHistoryCorrectionService . Command ( command . submissionKey ( ) , " 另一个原因 " , command . rows ( ) , false ) ; assertThrows ( ServiceException . class , ( ) - > history . correct ( wrong ) ) ;
} ) ;
} assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_request where material_name=? " , Integer . class , f . name ) ) ;
}
@Test void historyReclassifiesOnlyTraceableUnusedReceiptsAndNeverRewritesReceivedQuantity ( ) throws Exception {
Fixture f = new Fixture ( ) ; try ( var security = mockStatic ( SecurityUtils . class ) ) {
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ; security . when ( SecurityUtils : : getUsername ) . thenReturn ( " history-stock-rollback-test " ) ; security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var sheet = f . save ( f . draft ( ) ) ; var first = sheet . getRows ( ) . get ( 0 ) ; var history = f . history ( ) ; var journal = f . historyJournal ;
Long area = f . jdbc . queryForObject ( " select id from warehouse_area where status=0 order by id limit 1 " , Long . class ) ;
var receipt = journal . append ( InventoryCostJournal . event ( first . getProjectId ( ) , first . getProductId ( ) , area , " RECEIPT " , new BigDecimal ( " 2 " ) , new BigDecimal ( " 2.50 " ) , null , f . name + " -history-receipt " ) ) ;
f . jdbc . update ( " insert into in_record(in_no,area_id,product_id,purchase_request_id,source_project_id,in_type,in_num,in_status,cost_event_id,receipt_unit_cost,receipt_root) values(?,?,?,?,?,1,2,1,?,1.25,0) " , f . name + " -history-in " , area , first . getProductId ( ) , first . getId ( ) , first . getProjectId ( ) , receipt . getId ( ) ) ;
var insufficient = history . preview ( new PurchaseHistoryCorrectionService . Command ( null , " 核对数量 " , List . of ( new PurchaseHistoryCorrectionService . Entry ( first . getId ( ) , Map . of ( " quantity " , 1 ) , null ) ) , false ) ) ; assertEquals ( false , insufficient . get ( " ready " ) ) ;
var patch = Map . < String , Object > of ( " materialName " , f . name + " -更正物品 " , " quantity " , 3 ) ; var preview = history . preview ( new PurchaseHistoryCorrectionService . Command ( null , " 原物品名称录错 " , List . of ( new PurchaseHistoryCorrectionService . Entry ( first . getId ( ) , patch , null ) ) , false ) ) ; assertEquals ( true , preview . get ( " ready " ) , preview . toString ( ) ) ;
String version = ( ( List < Map < String , Object > > ) preview . get ( " rows " ) ) . get ( 0 ) . get ( " version " ) . toString ( ) ; history . correct ( new PurchaseHistoryCorrectionService . Command ( " history-stock- " + UUID . randomUUID ( ) , " 原物品名称录错 " , List . of ( new PurchaseHistoryCorrectionService . Entry ( first . getId ( ) , patch , version ) ) , false ) ) ;
var after = f . purchaseRows . selectPurchaseRequestById ( first . getId ( ) , null ) ; assertNotEquals ( first . getProductId ( ) , after . getProductId ( ) ) ; assertEquals ( 0 , new BigDecimal ( " 2 " ) . compareTo ( f . jdbc . queryForObject ( " select in_num from in_record where purchase_request_id=? " , BigDecimal . class , first . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 2 " ) . compareTo ( journal . balance ( after . getProjectId ( ) , after . getProductId ( ) ) . getQuantity ( ) ) ) ; assertEquals ( 0 , BigDecimal . ZERO . compareTo ( journal . balance ( first . getProjectId ( ) , first . getProductId ( ) ) . getQuantity ( ) ) ) ;
journal . append ( InventoryCostJournal . event ( after . getProjectId ( ) , after . getProductId ( ) , area , " ISSUE " , BigDecimal . ONE , null , null , f . name + " -history-issue " ) ) ;
var blocked = history . preview ( new PurchaseHistoryCorrectionService . Command ( null , " 重新核对物品 " , List . of ( new PurchaseHistoryCorrectionService . Entry ( first . getId ( ) , Map . of ( " materialName " , f . name + " -不能猜测 " ) , null ) ) , false ) ) ; assertEquals ( false , blocked . get ( " ready " ) ) ; assertTrue ( blocked . get ( " errors " ) . toString ( ) . contains ( " 领用 " ) ) ;
assertEquals ( after . getProductId ( ) , f . purchaseRows . selectPurchaseRequestById ( first . getId ( ) , null ) . getProductId ( ) ) ;
} ) ;
} assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from inventory_cost_event where event_key like ? " , Integer . class , f . name + " % " ) ) ;
}
@Test void assistantReferencePriceCopiesEachQuoteThroughNativeSaveAndDoesNotChangeCostLedger ( ) throws Exception {
Fixture f = new Fixture ( ) ; try ( var security = mockStatic ( SecurityUtils . class ) ) {
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ; security . when ( SecurityUtils : : getUsername ) . thenReturn ( " assistant-reference-rollback-test " ) ; security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var saved = f . save ( f . draft ( ) ) ; var locked = f . service . confirm ( saved . getBatch ( ) . getId ( ) , saved . getVersion ( ) ) ;
int ledger = f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger " , Integer . class ) ; int events = f . jdbc . queryForObject ( " select count(*) from inventory_cost_event " , Integer . class ) ;
var adapter = new com . ruoyi . web . service . assistant . AssistantReferencePriceService ( ) ; f . set ( adapter , " sheets " , f . service ) ; f . set ( adapter , " requests " , f . purchaseRows ) ; f . set ( adapter , " projects " , mock ( IProjectInfoService . class ) ) ;
var input = new LinkedHashMap < String , Object > ( ) ; input . put ( " purchaseBatchId " , locked . getBatch ( ) . getId ( ) ) ; input . put ( " mode " , " COPY_QUOTE " ) ; input . put ( " referenceVersion " , adapter . preview ( input ) . get ( " version " ) ) ;
var result = adapter . apply ( input , " assistant-reference-rollback- " + UUID . randomUUID ( ) ) ; assertEquals ( locked . getRows ( ) . size ( ) , result . get ( " changed " ) ) ;
var after = f . service . load ( locked . getBatch ( ) . getId ( ) ) ;
for ( var row : after . getRows ( ) ) { assertEquals ( 0 , row . getActualUnitPrice ( ) . compareTo ( row . getFinalUnitPrice ( ) ) ) ; assertEquals ( 0 , row . getActualAmount ( ) . compareTo ( row . getQuantity ( ) . multiply ( row . getFinalUnitPrice ( ) ) . setScale ( 2 ) ) ) ; }
assertEquals ( ledger , f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger " , Integer . class ) ) ; assertEquals ( events , f . jdbc . queryForObject ( " select count(*) from inventory_cost_event " , Integer . class ) ) ;
assertThrows ( ServiceException . class , ( ) - > adapter . apply ( input , " assistant-reference-rollback-stale " ) ) ;
} ) ;
} assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_request where material_name=? " , Integer . class , f . name ) ) ;
}
@Test void batchPriceCorrectionChecksAllBaselinesAndHandlesSharedItemCostVersionsAtomically ( ) throws Exception {
Fixture f = new Fixture ( ) ; try ( var security = mockStatic ( SecurityUtils . class ) ) {
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ; security . when ( SecurityUtils : : getUsername ) . thenReturn ( " price-batch-rollback-test " ) ; security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var draft = f . draft ( ) ; draft . getRows ( ) . get ( 1 ) . setProjectId ( draft . getRows ( ) . get ( 0 ) . getProjectId ( ) ) ;
var sheet = f . save ( draft ) ; var first = sheet . getRows ( ) . get ( 0 ) ; var second = sheet . getRows ( ) . get ( 1 ) ; assertEquals ( first . getProductId ( ) , second . getProductId ( ) ) ;
var config = new Configuration ( ) ; config . getTypeAliasRegistry ( ) . registerAliases ( " com.ruoyi.warehouse.domain " ) ; config . setEnvironment ( new Environment ( " quote-batch-rollback " , new SpringManagedTransactionFactory ( ) , f . jdbc . getDataSource ( ) ) ) ;
for ( String name : List . of ( " InventoryCost " , " WarehouseArea " , " ProductInfo " ) ) { String resource = " mapper/warehouse/ " + name + " Mapper.xml " ; try ( var input = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resource ) ) { new XMLMapperBuilder ( input , config , resource , config . getSqlFragments ( ) ) . parse ( ) ; } catch ( Exception error ) { throw new IllegalStateException ( error ) ; } }
var session = new SqlSessionTemplate ( new SqlSessionFactoryBuilder ( ) . build ( config ) ) ; var access = mock ( IProjectInfoService . class ) ; var journal = new InventoryCostJournal ( ) ;
f . set ( journal , " mapper " , session . getMapper ( InventoryCostMapper . class ) ) ; f . set ( journal , " projects " , access ) ; f . set ( journal , " items " , session . getMapper ( ProductInfoMapper . class ) ) ; f . set ( journal , " areas " , session . getMapper ( WarehouseAreaMapper . class ) ) ; f . set ( journal , " adjustmentDatabase " , f . jdbc ) ; f . set ( journal , " businessNumbers " , AuthorizedDatabaseTestSupport . numbers ( f . jdbc , f . manager ) ) ;
Long area = f . jdbc . queryForObject ( " select id from warehouse_area where status=0 order by id limit 1 " , Long . class ) ;
for ( var row : sheet . getRows ( ) ) {
var receipt = journal . append ( InventoryCostJournal . event ( row . getProjectId ( ) , row . getProductId ( ) , area , " RECEIPT " , new BigDecimal ( " 2 " ) , new BigDecimal ( " 2.50 " ) , null , f . name + " -receipt- " + row . getId ( ) ) ) ;
f . jdbc . update ( " insert into in_record(in_no,area_id,product_id,purchase_request_id,source_project_id,in_type,in_num,in_status,cost_event_id,receipt_unit_cost,receipt_root) values(?,?,?,?,?,1,2,1,?,1.25,0) " , f . name + " -in- " + row . getId ( ) , area , row . getProductId ( ) , row . getId ( ) , row . getProjectId ( ) , receipt . getId ( ) ) ;
}
var issue = journal . append ( InventoryCostJournal . event ( first . getProjectId ( ) , first . getProductId ( ) , area , " ISSUE " , BigDecimal . ONE , null , null , f . name + " -issue " ) ) ;
var target = new PurchasePriceCorrectionService ( ) ; f . set ( target , " db " , f . jdbc ) ; f . set ( target , " requests " , f . purchaseRows ) ; f . set ( target , " projects " , access ) ; f . set ( target , " journal " , journal ) ; f . set ( target , " prices " , f . priceService ) ; f . set ( target , " logs " , mock ( IPurchaseOperationLogService . class ) ) ; f . set ( target , " production " , mock ( com . ruoyi . production . service . ProductionService . class ) ) ; var corrections = f . proxy ( target ) ;
var a = new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 2 " ) , " 第一项供应商报价 " , null , false ) ; var b = new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 3 " ) , " 第二项供应商报价 " , null , false ) ;
var av = corrections . preview ( first . getId ( ) , a ) . get ( " version " ) . toString ( ) ; var bv = corrections . preview ( second . getId ( ) , b ) . get ( " version " ) . toString ( ) ;
var entryA = new PurchasePriceCorrectionService . Entry ( first . getId ( ) , new PurchasePriceCorrectionService . Correction ( a . finalUnitPrice ( ) , a . reason ( ) , av , false ) ) ;
assertThrows ( ServiceException . class , ( ) - > corrections . correctBatch ( List . of ( entryA , new PurchasePriceCorrectionService . Entry ( second . getId ( ) , new PurchasePriceCorrectionService . Correction ( b . finalUnitPrice ( ) , b . reason ( ) , " stale " , false ) ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 1.25 " ) . compareTo ( f . jdbc . queryForObject ( " select final_unit_price from purchase_request where id=? " , BigDecimal . class , first . getId ( ) ) ) ) ;
assertThrows ( ServiceException . class , ( ) - > corrections . correctBatch ( List . of ( entryA , entryA ) ) ) ;
var results = corrections . correctBatch ( List . of ( entryA , new PurchasePriceCorrectionService . Entry ( second . getId ( ) , new PurchasePriceCorrectionService . Correction ( b . finalUnitPrice ( ) , b . reason ( ) , bv , false ) ) ) ) ; assertEquals ( 2 , results . size ( ) ) ;
assertEquals ( 0 , new BigDecimal ( " 7.50 " ) . compareTo ( journal . balance ( first . getProjectId ( ) , first . getProductId ( ) ) . getAmount ( ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 2.50 " ) . compareTo ( f . jdbc . queryForObject ( " select effective_cost from inventory_cost_event where id=? " , BigDecimal . class , issue . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 4 " ) . compareTo ( f . jdbc . queryForObject ( " select estimated_amount from purchase_request where id=? " , BigDecimal . class , first . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 6 " ) . compareTo ( f . jdbc . queryForObject ( " select estimated_amount from purchase_request where id=? " , BigDecimal . class , second . getId ( ) ) ) ) ;
} ) ;
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_batch where batch_name=? " , Integer . class , f . name ) ) ;
}
}
@Test void explicitPriceCorrectionReplaysReceiptIssueAndBalanceWithoutChangingReferenceAmounts ( ) throws Exception {
Fixture f = new Fixture ( ) ; try ( var security = mockStatic ( SecurityUtils . class ) ) {
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ; security . when ( SecurityUtils : : getUsername ) . thenReturn ( " correction-rollback-test " ) ; security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var draft = f . draft ( ) ; draft . getRows ( ) . get ( 0 ) . setActualUnitPrice ( new BigDecimal ( " 7 " ) ) ; var sheet = f . save ( draft ) ; sheet = f . service . confirm ( sheet . getBatch ( ) . getId ( ) , sheet . getVersion ( ) ) ;
// Even confirmed quotes remain editable before any arrival.
sheet . getRows ( ) . get ( 0 ) . setFinalUnitPrice ( new BigDecimal ( " 4 " ) ) ; sheet = f . save ( sheet ) ; var row = sheet . getRows ( ) . get ( 0 ) ; Long id = row . getId ( ) , item = row . getProductId ( ) , project = row . getProjectId ( ) ;
assertEquals ( 0 , new BigDecimal ( " 8 " ) . compareTo ( f . jdbc . queryForObject ( " select locked_amount from purchase_request where id=? " , BigDecimal . class , id ) ) ) ;
var config = new Configuration ( ) ; config . getTypeAliasRegistry ( ) . registerAliases ( " com.ruoyi.warehouse.domain " ) ; config . setEnvironment ( new Environment ( " correction-rollback " , new SpringManagedTransactionFactory ( ) , f . jdbc . getDataSource ( ) ) ) ;
for ( String name : List . of ( " InventoryCost " , " WarehouseArea " , " ProductInfo " ) ) { String resource = " mapper/warehouse/ " + name + " Mapper.xml " ; try ( var input = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resource ) ) { new XMLMapperBuilder ( input , config , resource , config . getSqlFragments ( ) ) . parse ( ) ; } catch ( Exception error ) { throw new IllegalStateException ( error ) ; } }
var session = new SqlSessionTemplate ( new SqlSessionFactoryBuilder ( ) . build ( config ) ) ; var access = mock ( IProjectInfoService . class ) ; var journal = new InventoryCostJournal ( ) ; f . set ( journal , " mapper " , session . getMapper ( InventoryCostMapper . class ) ) ; f . set ( journal , " projects " , access ) ; f . set ( journal , " items " , session . getMapper ( ProductInfoMapper . class ) ) ; f . set ( journal , " areas " , session . getMapper ( WarehouseAreaMapper . class ) ) ; f . set ( journal , " adjustmentDatabase " , f . jdbc ) ; f . set ( journal , " businessNumbers " , AuthorizedDatabaseTestSupport . numbers ( f . jdbc , f . manager ) ) ;
Long area = f . jdbc . queryForObject ( " select id from warehouse_area where status=0 order by id limit 1 " , Long . class ) ;
var receipt = journal . append ( InventoryCostJournal . event ( project , item , area , " RECEIPT " , new BigDecimal ( " 2 " ) , new BigDecimal ( " 8 " ) , null , f . name + " -receipt " ) ) ;
f . jdbc . update ( " insert into in_record(in_no,area_id,product_id,purchase_request_id,source_project_id,in_type,in_num,in_status,cost_event_id,receipt_unit_cost,receipt_root) values(?,?,?,?,?,1,2,1,?,4,0) " , f . name + " -in " , area , item , id , project , receipt . getId ( ) ) ;
var issue = journal . append ( InventoryCostJournal . event ( project , item , area , " ISSUE " , BigDecimal . ONE , null , null , f . name + " -issue " ) ) ;
var target = new PurchasePriceCorrectionService ( ) ; f . set ( target , " db " , f . jdbc ) ; f . set ( target , " requests " , f . purchaseRows ) ; f . set ( target , " projects " , access ) ; f . set ( target , " journal " , journal ) ; f . set ( target , " prices " , f . priceService ) ; f . set ( target , " logs " , mock ( IPurchaseOperationLogService . class ) ) ; var production = mock ( com . ruoyi . production . service . ProductionService . class ) ; f . set ( target , " production " , production ) ; var corrections = f . proxy ( target ) ;
var input = new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 5 " ) , " 纠正原报价 " , null , false ) ; var preview = corrections . preview ( id , input ) ;
assertEquals ( 1 , preview . get ( " costSourceCount " ) ) ; assertEquals ( 0 , preview . get ( " archiveOnlyCount " ) ) ;
String reviewedVersion = preview . get ( " version " ) . toString ( ) ; assertThrows ( ServiceException . class , ( ) - > corrections . correct ( id , new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 9 " ) , input . reason ( ) , reviewedVersion , false ) ) ) ;
// A concurrent cost change invalidates the preview instead of silently recalculating another baseline.
journal . append ( InventoryCostJournal . event ( project , item , area , " ISSUE " , new BigDecimal ( " 0.25 " ) , null , null , f . name + " -later " ) ) ;
String stale = preview . get ( " version " ) . toString ( ) ; assertThrows ( ServiceException . class , ( ) - > corrections . correct ( id , new PurchasePriceCorrectionService . Correction ( input . finalUnitPrice ( ) , input . reason ( ) , stale , false ) ) ) ;
preview = corrections . preview ( id , input ) ; corrections . correct ( id , new PurchasePriceCorrectionService . Correction ( input . finalUnitPrice ( ) , input . reason ( ) , preview . get ( " version " ) . toString ( ) , false ) ) ;
assertEquals ( 0 , new BigDecimal ( " 5 " ) . compareTo ( f . jdbc . queryForObject ( " select final_unit_price from purchase_request where id=? " , BigDecimal . class , id ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 10 " ) . compareTo ( f . jdbc . queryForObject ( " select estimated_amount from purchase_request where id=? " , BigDecimal . class , id ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 10 " ) . compareTo ( f . jdbc . queryForObject ( " select locked_amount from purchase_request where id=? " , BigDecimal . class , id ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 7 " ) . compareTo ( f . jdbc . queryForObject ( " select actual_unit_price from purchase_request where id=? " , BigDecimal . class , id ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 5 " ) . compareTo ( f . jdbc . queryForObject ( " select receipt_unit_cost from in_record where purchase_request_id=? " , BigDecimal . class , id ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 5 " ) . compareTo ( f . jdbc . queryForObject ( " select effective_cost from inventory_cost_event where id=? " , BigDecimal . class , issue . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 3.75 " ) . compareTo ( f . jdbc . queryForObject ( " select amount from project_item_cost where project_id=? and item_id=? " , BigDecimal . class , project , item ) ) ) ;
verify ( production ) . recalculateSettled ( ) ;
assertEquals ( 1 , f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger where purchase_request_id=? and operation='PRICE_CORRECTION' " , Integer . class , id ) ) ;
// An unlinked old receipt is never silently treated as a modern cost source.
var legacy = sheet . getRows ( ) . get ( 1 ) ; f . jdbc . update ( " update purchase_request set historical=1 where id=? " , legacy . getId ( ) ) ;
f . jdbc . update ( " insert into in_record(in_no,product_id,purchase_request_id,source_project_id,in_type,in_num,in_status,receipt_unit_cost,receipt_root) values(?,?,?,?,1,2,1,1.25,0) " , f . name + " -legacy-in " , item , legacy . getId ( ) , legacy . getProjectId ( ) ) ;
var oldInput = new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 6 " ) , " 旧价格录入有误 " , null , false ) ; var oldPreview = corrections . preview ( legacy . getId ( ) , oldInput ) ;
assertEquals ( 1 , oldPreview . get ( " archiveOnlyCount " ) ) ; assertEquals ( 0 , oldPreview . get ( " costSourceCount " ) ) ;
String oldVersion = oldPreview . get ( " version " ) . toString ( ) ; assertThrows ( ServiceException . class , ( ) - > corrections . correct ( legacy . getId ( ) , new PurchasePriceCorrectionService . Correction ( oldInput . finalUnitPrice ( ) , oldInput . reason ( ) , oldVersion , false ) ) ) ;
corrections . correct ( legacy . getId ( ) , new PurchasePriceCorrectionService . Correction ( oldInput . finalUnitPrice ( ) , oldInput . reason ( ) , oldVersion , true ) ) ;
assertEquals ( 0 , new BigDecimal ( " 12 " ) . compareTo ( f . jdbc . queryForObject ( " select estimated_amount from purchase_request where id=? " , BigDecimal . class , legacy . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 6 " ) . compareTo ( f . jdbc . queryForObject ( " select receipt_unit_cost from in_record where purchase_request_id=? " , BigDecimal . class , legacy . getId ( ) ) ) ) ;
assertEquals ( 0 , new BigDecimal ( " 3.75 " ) . compareTo ( f . jdbc . queryForObject ( " select amount from project_item_cost where project_id=? and item_id=? " , BigDecimal . class , project , item ) ) ) ;
// A cutover opening is matched by the immutable lot id, never by same-name item guesses.
Long legacyIn = f . jdbc . queryForObject ( " select id from in_record where purchase_request_id=? " , Long . class , legacy . getId ( ) ) ;
f . jdbc . update ( " insert into stock_lot(lot_no,area_id,product_id,source_project_id,purchase_request_id,in_record_id,received_quantity,available_quantity,unit_cost,lot_status) values(?,?,?,?,?,?,2,1,6,0) " , f . name + " -lot " , area , item , legacy . getProjectId ( ) , legacy . getId ( ) , legacyIn ) ;
Long lot = f . jdbc . queryForObject ( " select id from stock_lot where lot_no=? " , Long . class , f . name + " -lot " ) ;
var opening = journal . append ( InventoryCostJournal . event ( legacy . getProjectId ( ) , item , area , " RECEIPT " , BigDecimal . ONE , new BigDecimal ( " 6 " ) , null , " LEGACY-STOCK: " + lot ) ) ;
var openingInput = new PurchasePriceCorrectionService . Correction ( new BigDecimal ( " 7.123456 " ) , " 更正期初来源价格 " , null , true ) ; var openingPreview = corrections . preview ( legacy . getId ( ) , openingInput ) ;
assertEquals ( 1 , openingPreview . get ( " costSourceCount " ) ) ; corrections . correct ( legacy . getId ( ) , new PurchasePriceCorrectionService . Correction ( openingInput . finalUnitPrice ( ) , openingInput . reason ( ) , openingPreview . get ( " version " ) . toString ( ) , true ) ) ;
assertEquals ( 0 , openingInput . finalUnitPrice ( ) . compareTo ( f . jdbc . queryForObject ( " select effective_cost from inventory_cost_event where id=? " , BigDecimal . class , opening . getId ( ) ) ) ) ;
assertEquals ( 0 , openingInput . finalUnitPrice ( ) . compareTo ( f . jdbc . queryForObject ( " select unit_cost from stock_lot where id=? " , BigDecimal . class , lot ) ) ) ;
} ) ;
} assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_request where material_name=? " , Integer . class , f . name ) ) ;
}
@Test void referenceOnlyEditsPersistAfterConfirmationWithoutTouchingCostsAndDisplayFilteringIsReversible ( ) throws Exception {
Fixture f = new Fixture ( ) ; try ( var security = mockStatic ( SecurityUtils . class ) ) {
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ; security . when ( SecurityUtils : : getUsername ) . thenReturn ( " reference-rollback-test " ) ; security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ;
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ;
var draft = f . draft ( ) ; draft . getRows ( ) . get ( 0 ) . setFinalUnitPrice ( BigDecimal . ZERO ) ; draft . getRows ( ) . get ( 0 ) . setActualUnitPrice ( new BigDecimal ( " 7.25 " ) ) ;
var saved = f . save ( draft ) ; var locked = f . service . confirm ( saved . getBatch ( ) . getId ( ) , saved . getVersion ( ) ) ; var first = locked . getRows ( ) . get ( 0 ) ;
int prices = f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger where purchase_request_id=? " , Integer . class , first . getId ( ) ) ;
int events = f . jdbc . queryForObject ( " select count(*) from inventory_cost_event " , Integer . class ) ;
first . setActualUnitPrice ( new BigDecimal ( " 8.50 " ) ) ; var changed = f . save ( locked ) ; var reloaded = changed . getRows ( ) . get ( 0 ) ;
assertEquals ( 0 , reloaded . getActualAmount ( ) . compareTo ( new BigDecimal ( " 17 " ) ) ) ; assertEquals ( 0 , reloaded . getFinalUnitPrice ( ) . signum ( ) ) ; assertEquals ( 0 , reloaded . getLockedAmount ( ) . signum ( ) ) ; assertTrue ( reloaded . getPriceLocked ( ) ) ;
assertEquals ( prices , f . jdbc . queryForObject ( " select count(*) from purchase_price_ledger where purchase_request_id=? " , Integer . class , first . getId ( ) ) ) ;
assertEquals ( events , f . jdbc . queryForObject ( " select count(*) from inventory_cost_event " , Integer . class ) ) ;
f . jdbc . update ( " update purchase_request set historical=1 where id=? " , first . getId ( ) ) ; var historical = f . service . load ( changed . getBatch ( ) . getId ( ) ) ; historical . getRows ( ) . get ( 0 ) . setActualUnitPrice ( new BigDecimal ( " 9 " ) ) ; assertEquals ( new BigDecimal ( " 18.00 " ) , f . save ( historical ) . getRows ( ) . get ( 0 ) . getActualAmount ( ) ) ;
String key = com . ruoyi . warehouse . util . AmountDisplayPolicy . KEY ;
if ( f . jdbc . update ( " update sys_config set config_value='true' where config_key=? " , key ) = = 0 ) f . jdbc . update ( " insert into sys_config(config_name,config_key,config_value,config_type) values('测试展示开关',?,'true','Y') " , key ) ;
f . purchaseRows . selectPurchaseSheetRows ( changed . getBatch ( ) . getId ( ) ) ; var query = new PurchaseRequest ( ) ; query . setPurchaseBatchId ( changed . getBatch ( ) . getId ( ) ) ;
assertEquals ( 2 , f . purchaseRows . selectPurchaseRequestList ( query ) . size ( ) ) ; com . ruoyi . warehouse . util . AmountDisplayPolicy . forView ( query ) ; assertEquals ( 1 , f . purchaseRows . selectPurchaseRequestList ( query ) . size ( ) ) ;
// Editor snapshots remain complete; hidden rows must never be dropped by save.
assertEquals ( 2 , f . service . load ( changed . getBatch ( ) . getId ( ) ) . getRows ( ) . size ( ) ) ;
var maps = referenceViewMappers ( f ) ; Long area = f . jdbc . queryForObject ( " select min(id) from warehouse_area " , Long . class ) , item = first . getProductId ( ) ; assertNotNull ( area ) ;
for ( int n = 0 ; n < 2 ; n + + ) {
var r = changed . getRows ( ) . get ( n ) ; BigDecimal cost = n = = 0 ? BigDecimal . ZERO : new BigDecimal ( " 5 " ) ;
f . jdbc . update ( " insert into project_stock_balance(project_id,item_id,area_id,quantity) values(?,?,?,2) " , r . getProjectId ( ) , item , area ) ;
f . jdbc . update ( " insert into project_item_cost(project_id,item_id,quantity,amount) values(?,?,2,?) " , r . getProjectId ( ) , item , cost ) ;
f . jdbc . update ( " insert into in_record(in_no,product_id,purchase_request_id,source_project_id,in_type,in_num,in_status) values(?,?,?,?,1,1,0) " , f . name + " -in " + n , item , r . getId ( ) , r . getProjectId ( ) ) ;
f . jdbc . update ( " insert into inventory_cost_event(project_id,item_id,area_id,event_key,event_type,quantity,effective_cost) values(?,?,?,?,'ISSUE',1,?) " , r . getProjectId ( ) , item , area , f . name + " -event " + n , cost ) ;
Long event = f . jdbc . queryForObject ( " select id from inventory_cost_event where event_key=? " , Long . class , f . name + " -event " + n ) ;
f . jdbc . update ( " insert into out_record(out_no,product_id,area_id,usage_project_id,out_type,out_num,cost_event_id) values(?,?,?,?,4,1,?) " , f . name + " -out " + n , item , area , r . getProjectId ( ) , event ) ;
}
var stock = new StockInfo ( ) ; stock . setProductId ( item ) ; var in = new InRecord ( ) ; in . setProductId ( item ) ; var out = new OutRecord ( ) ; out . setProductId ( item ) ;
assertEquals ( 2 , maps . getMapper ( StockInfoMapper . class ) . selectStockInfoList ( stock ) . size ( ) ) ;
com . ruoyi . warehouse . util . AmountDisplayPolicy . forView ( stock ) ; com . ruoyi . warehouse . util . AmountDisplayPolicy . forView ( in ) ; com . ruoyi . warehouse . util . AmountDisplayPolicy . forView ( out ) ;
assertEquals ( 1 , maps . getMapper ( StockInfoMapper . class ) . selectStockInfoList ( stock ) . size ( ) ) ; assertEquals ( 1 , maps . getMapper ( InRecordMapper . class ) . selectInRecordList ( in ) . size ( ) ) ; assertEquals ( 1 , maps . getMapper ( OutRecordMapper . class ) . selectOutRecordList ( out ) . size ( ) ) ;
var pending = new PendingReceiptService ( ) ; f . set ( pending , " db " , f . jdbc ) ; f . set ( pending , " records " , maps . getMapper ( InRecordMapper . class ) ) ; var pendingQuery = new InRecord ( ) ; pendingQuery . setKeyword ( f . name ) ; assertEquals ( 1L , pending . page ( pendingQuery , 1 , 20 ) . get ( " itemTotal " ) ) ;
f . jdbc . update ( " update project_item_cost set amount=null where project_id=? and item_id=? " , first . getProjectId ( ) , item ) ; maps . clearCache ( ) ; assertEquals ( 2 , maps . getMapper ( StockInfoMapper . class ) . selectStockInfoList ( stock ) . size ( ) ) ;
f . jdbc . update ( " update sys_config set config_value='false' where config_key=? " , key ) ; f . purchaseRows . selectPurchaseSheetRows ( changed . getBatch ( ) . getId ( ) ) ; assertEquals ( 2 , f . purchaseRows . selectPurchaseRequestList ( query ) . size ( ) ) ;
maps . clearCache ( ) ; assertEquals ( 2 , maps . getMapper ( InRecordMapper . class ) . selectInRecordList ( in ) . size ( ) ) ; assertEquals ( 2 , maps . getMapper ( OutRecordMapper . class ) . selectOutRecordList ( out ) . size ( ) ) ;
var invalid = f . service . load ( changed . getBatch ( ) . getId ( ) ) ; invalid . getRows ( ) . get ( 0 ) . setActualUnitPrice ( new BigDecimal ( " -1 " ) ) ; assertThrows ( ServiceException . class , ( ) - > f . save ( invalid ) ) ;
} ) ;
} assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_request where material_name=? " , Integer . class , f . name ) ) ;
}
private static SqlSessionTemplate referenceViewMappers ( Fixture f ) {
var config = new Configuration ( ) ; config . getTypeAliasRegistry ( ) . registerAliases ( " com.ruoyi.warehouse.domain " ) ; config . setEnvironment ( new Environment ( " view-rollback " , new SpringManagedTransactionFactory ( ) , f . jdbc . getDataSource ( ) ) ) ;
for ( String name : List . of ( " InRecord " , " OutRecord " , " StockInfo " ) ) { String resource = " mapper/warehouse/ " + name + " Mapper.xml " ; try ( var input = PurchaseSheetDatabaseTest . class . getClassLoader ( ) . getResourceAsStream ( resource ) ) { new XMLMapperBuilder ( input , config , resource , config . getSqlFragments ( ) ) . parse ( ) ; } catch ( Exception error ) { throw new IllegalStateException ( error ) ; } }
return new SqlSessionTemplate ( new SqlSessionFactoryBuilder ( ) . build ( config ) ) ;
}
2026-10-16 17:17:06 +08:00
@Test void savedPurchaseCategoryCanBeCorrectedWithoutChangingIdentityOrQuotesAndOldRowsDoNotUndoIt ( ) 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 . save ( f . draft ( ) ) ; var before = f . copy ( saved ) ; Long productId = saved . getRows ( ) . get ( 0 ) . getProductId ( ) ;
saved . getRows ( ) . get ( 0 ) . setCategory ( " 更正类别 " ) ; var changed = f . save ( saved ) ; var reopened = f . service . load ( changed . getBatch ( ) . getId ( ) ) ;
assertEquals ( " 更正类别 " , reopened . getRows ( ) . get ( 0 ) . getCategory ( ) ) ;
assertEquals ( " 更正类别 " , f . jdbc . queryForObject ( " select category from product_info where id=? " , String . class , productId ) ) ;
for ( int i = 0 ; i < 2 ; i + + ) { assertEquals ( before . getRows ( ) . get ( i ) . getProductId ( ) , reopened . getRows ( ) . get ( i ) . getProductId ( ) ) ; assertEquals ( before . getRows ( ) . get ( i ) . getQuantity ( ) , reopened . getRows ( ) . get ( i ) . getQuantity ( ) ) ; assertEquals ( before . getRows ( ) . get ( i ) . getFinalUnitPrice ( ) , reopened . getRows ( ) . get ( i ) . getFinalUnitPrice ( ) ) ; }
reopened . getRows ( ) . get ( 1 ) . setRemark ( " 仅修改备注,不撤销档案类别更正 " ) ; f . save ( reopened ) ;
assertEquals ( " 更正类别 " , f . jdbc . queryForObject ( " select category from product_info where id=? " , String . class , productId ) ) ;
var invalid = f . service . load ( changed . getBatch ( ) . getId ( ) ) ; invalid . getRows ( ) . get ( 0 ) . setCategory ( " 不存在的类别 " ) ; assertThrows ( ServiceException . class , ( ) - > f . save ( invalid ) ) ;
assertEquals ( " 更正类别 " , f . jdbc . queryForObject ( " select category from product_info where id=? " , String . class , productId ) ) ;
} ) ;
}
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from product_info where product_name=? " , Integer . class , f . name ) ) ;
}
2026-10-16 15:30:10 +08:00
@Test void supplierInquiryRoundTripSavesOnlyConfirmedPreviewPricesThroughNativeSheetService ( ) 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 . save ( f . draft ( ) ) ; var before = f . copy ( saved ) ;
try ( var book = com . ruoyi . web . controller . warehouse . SupplierInquiryExport . workbook ( saved ) ; var bytes = new java . io . ByteArrayOutputStream ( ) ) {
book . getSheetAt ( 0 ) . getRow ( 6 ) . getCell ( 6 ) . setCellValue ( 9 . 123456 ) ; book . write ( bytes ) ;
var preview = com . ruoyi . web . controller . warehouse . SupplierQuoteImport . preview ( new java . io . ByteArrayInputStream ( bytes . toByteArray ( ) ) , saved ) ;
assertEquals ( 1 , preview . size ( ) ) ; assertNull ( preview . get ( 0 ) . get ( " error " ) ) ;
assertEquals ( 0 , new BigDecimal ( " 1.25 " ) . compareTo ( f . service . load ( saved . getBatch ( ) . getId ( ) ) . getRows ( ) . get ( 0 ) . getFinalUnitPrice ( ) ) , " Preview must not save quotes " ) ;
@SuppressWarnings ( " unchecked " ) var ids = ( List < Long > ) preview . get ( 0 ) . get ( " rowIds " ) ;
for ( var row : saved . getRows ( ) ) if ( ids . contains ( row . getId ( ) ) ) row . setFinalUnitPrice ( ( BigDecimal ) preview . get ( 0 ) . get ( " unitPrice " ) ) ;
var applied = f . save ( saved ) ;
for ( int i = 0 ; i < applied . getRows ( ) . size ( ) ; i + + ) {
var row = applied . getRows ( ) . get ( i ) ; assertEquals ( 0 , new BigDecimal ( " 9.123456 " ) . compareTo ( row . getFinalUnitPrice ( ) ) ) ;
assertEquals ( 0 , before . getRows ( ) . get ( i ) . getQuantity ( ) . compareTo ( row . getQuantity ( ) ) ) ; assertEquals ( before . getRows ( ) . get ( i ) . getProjectId ( ) , row . getProjectId ( ) ) ; assertFalse ( Boolean . TRUE . equals ( row . getPriceLocked ( ) ) , " Quote import must not confirm purchase " ) ;
}
} catch ( Exception error ) { throw new RuntimeException ( error ) ; }
} ) ;
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_batch where batch_name=? " , Integer . class , f . name ) ) ;
}
}
2026-10-14 09:11:33 +08:00
@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 ( ) ;
2026-10-15 11:30:55 +08:00
var saved = f . save ( f . draft ( ) ) ;
2026-10-14 09:11:33 +08:00
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 ) ) ;
}
}
2026-10-12 16:41:42 +08:00
@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 ( ) ;
2026-10-15 11:30:55 +08:00
PurchaseSheet saved = f . save ( draft ) ;
2026-10-12 16:41:42 +08:00
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 ) ;
2026-10-15 11:30:55 +08:00
PurchaseSheet second = f . save ( another ) ;
2026-10-12 16:41:42 +08:00
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 " ) ) ;
2026-10-15 11:30:55 +08:00
saved = f . save ( saved ) ;
2026-10-12 16:41:42 +08:00
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 ) ;
2026-10-15 11:30:55 +08:00
saved = f . save ( saved ) ;
2026-10-12 16:41:42 +08:00
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 " ) ) ;
2026-10-15 11:30:55 +08:00
saved = f . save ( saved ) ;
2026-10-12 16:41:42 +08:00
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 " ) ) ;
2026-10-15 11:30:55 +08:00
PurchaseSheet maintained = f . save ( locked ) ;
2026-10-13 09:41:46 +08:00
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 " ) ) ) ;
2026-10-12 16:41:42 +08:00
} 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 ( " 箱 " ) ;
2026-10-15 11:30:55 +08:00
return f . save ( draft ) ;
2026-10-12 16:41:42 +08:00
} ) ) ;
}
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 {
2026-10-15 11:30:55 +08:00
PurchaseSheet saved = f . save ( f . draft ( ) ) ;
saved . setVersion ( " stale " ) ; assertThrows ( ServiceException . class , ( ) - > f . save ( saved ) ) ;
2026-10-12 16:41:42 +08:00
PurchaseSheet omitted = f . service . load ( saved . getBatch ( ) . getId ( ) ) ;
omitted . setRows ( List . of ( omitted . getRows ( ) . get ( 0 ) ) ) ;
2026-10-15 11:30:55 +08:00
assertThrows ( ServiceException . class , ( ) - > f . save ( omitted ) ) ;
2026-10-12 16:41:42 +08:00
PurchaseSheet cleared = f . service . load ( saved . getBatch ( ) . getId ( ) ) ;
cleared . setDeletedIds ( cleared . getRows ( ) . stream ( ) . map ( PurchaseRequest : : getId ) . toList ( ) ) ;
cleared . setRows ( List . of ( ) ) ;
2026-10-15 11:30:55 +08:00
assertTrue ( f . save ( cleared ) . getRows ( ) . isEmpty ( ) ) ;
2026-10-12 16:41:42 +08:00
} 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 ) ;
2026-10-15 11:30:55 +08:00
PurchaseSheet saved = f . save ( draft ) ;
2026-10-12 16:41:42 +08:00
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 ( ) ) ) ) ;
2026-10-15 11:30:55 +08:00
saved . getBatch ( ) . setSupplierId ( supplier ) ; PurchaseSheet assigned = f . save ( saved ) ;
2026-10-12 16:41:42 +08:00
PurchaseSheet locked = f . service . confirm ( assigned . getBatch ( ) . getId ( ) , assigned . getVersion ( ) ) ;
assertTrue ( locked . getRows ( ) . stream ( ) . allMatch ( r - > Boolean . TRUE . equals ( r . getPriceLocked ( ) ) ) ) ;
2026-10-15 11:30:55 +08:00
locked . getBatch ( ) . setSupplierId ( null ) ; assertThrows ( ServiceException . class , ( ) - > f . save ( locked ) ) ;
2026-10-12 16:41:42 +08:00
} 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 - > {
2026-10-15 11:30:55 +08:00
PurchaseSheet draft = f . draft ( ) ; draft . getRows ( ) . get ( 0 ) . setCategory ( " " ) ; return f . save ( draft ) ;
2026-10-12 16:41:42 +08:00
} ) ) ; 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 ) ) ;
}
2026-10-20 10:04:17 +08:00
@Test void confirmedTransfersKeepFeesRejectChangedSupplierAndAllowExistingArrival ( ) throws Exception {
2026-10-13 09:41:46 +08:00
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 {
2026-10-15 11:30:55 +08:00
var saved = f . save ( f . draft ( ) ) ; var locked = f . service . confirm ( saved . getBatch ( ) . getId ( ) , saved . getVersion ( ) ) ; var row = locked . getRows ( ) . get ( 0 ) ; Long supplier = locked . getBatch ( ) . getSupplierId ( ) ;
2026-10-13 09:41:46 +08:00
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 ( ) ) ;
2026-10-20 10:04:17 +08:00
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 . save ( appended ) ; assertEquals ( 3 , updated . getRows ( ) . get ( 0 ) . getPurchaseStatus ( ) ) ; assertEquals ( 0 , new BigDecimal ( " 3.75 " ) . compareTo ( updated . getRows ( ) . get ( 0 ) . getLockedAmount ( ) ) ) ;
var numbers = mock ( PurchaseBatchNumber . class ) ; when ( numbers . reserve ( any ( ) , any ( ) ) ) . thenReturn ( f . name + " -new " ) ; f . set ( raw , " batchNumbers " , numbers ) ; var suppliers = new SupplierService ( ) ; f . set ( suppliers , " db " , f . jdbc ) ; f . set ( raw , " suppliers " , suppliers ) ;
var create = new PurchaseBatchAssignRequest ( ) ; create . setRequestIds ( new Long [ ] { row . getId ( ) } ) ; create . setRequestKey ( " rollback-transfer-123 " ) ; var batch = new PurchaseBatch ( ) ; batch . setSupplierId ( supplier ) ; batch . setBatchName ( f . name + " -new " ) ; batch . setBusinessDate ( java . time . LocalDate . now ( ) ) ; create . setNewBatch ( batch ) ;
assertEquals ( 1 , service . assignPurchaseBatch ( create ) ) ; Long destination = create . getBatchId ( ) ; assertNotNull ( destination ) ; var after = f . purchaseRows . selectPurchaseRequestById ( row . getId ( ) , null ) ; assertEquals ( destination , after . getPurchaseBatchId ( ) ) ; assertTrue ( after . getPriceLocked ( ) ) ; assertEquals ( 3 , after . getPurchaseStatus ( ) ) ; assertEquals ( 0 , new BigDecimal ( " 3.75 " ) . compareTo ( after . getLockedAmount ( ) ) ) ; assertEquals ( 1 , f . jdbc . queryForObject ( " select count(*) from purchase_arrival where purchase_request_id=? " , Integer . class , row . getId ( ) ) ) ;
var retry = new PurchaseBatchAssignRequest ( ) ; retry . setRequestIds ( new Long [ ] { row . getId ( ) } ) ; retry . setRequestKey ( create . getRequestKey ( ) ) ; retry . setNewBatch ( batch ) ; assertEquals ( 1 , service . assignPurchaseBatch ( retry ) ) ; assertEquals ( destination , retry . getBatchId ( ) ) ; assertEquals ( 1 , f . jdbc . queryForObject ( " select count(*) from purchase_batch where batch_no=? " , Integer . class , f . name + " -new " ) ) ;
2026-10-13 09:41:46 +08:00
} 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 ) ;
2026-10-15 11:30:55 +08:00
new TransactionTemplate ( f . manager ) . executeWithoutResult ( status - > { status . setRollbackOnly ( ) ; var initial = f . save ( f . draft ( ) ) ; Long [ ] ids = initial . getRows ( ) . stream ( ) . map ( PurchaseRequest : : getId ) . toArray ( Long [ ] : : new ) ;
2026-10-13 09:41:46 +08:00
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 ) ) ;
} ) ;
}
}
2026-10-14 09:11:33 +08:00
@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 ) ) ;
2026-10-15 11:30:55 +08:00
var saved = f . save ( draft ) ; assertTrue ( saved . isUnbatched ( ) ) ; assertNull ( saved . getBatch ( ) . getId ( ) ) ; assertEquals ( batchCount , f . jdbc . queryForObject ( " select count(*) from purchase_batch " , Long . class ) ) ;
2026-10-14 09:11:33 +08:00
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 ) ;
2026-10-15 11:30:55 +08:00
var stale = f . service . loadUnbatched ( ids ) ; saved . getRows ( ) . get ( 0 ) . setQuantity ( new BigDecimal ( " 7 " ) ) ; f . save ( saved ) ;
stale . getRows ( ) . get ( 0 ) . setQuantity ( BigDecimal . TEN ) ; assertThrows ( ServiceException . class , ( ) - > f . save ( stale ) ) ;
2026-10-14 09:11:33 +08:00
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 ) ) ;
2026-10-15 11:30:55 +08:00
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 . save ( more ) ; var deleted = deletion . getRows ( ) . stream ( ) . map ( PurchaseRequest : : getId ) . toList ( ) ; deletion . setDeletedIds ( deleted ) ; deletion . setRows ( List . of ( ) ) ; assertTrue ( f . save ( deletion ) . getRows ( ) . isEmpty ( ) ) ;
2026-10-14 09:11:33 +08:00
} finally { status . setRollbackOnly ( ) ; } return null ; } ) ;
}
}
2026-10-15 11:30:55 +08:00
@Test void completedSheetSubmissionsReplayWithoutDuplicatingBatchesOrUnbatchedRows ( ) throws Exception {
Fixture f = new Fixture ( ) ; String prefix = " sheet-replay- " + UUID . randomUUID ( ) ;
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 draft = f . draft ( ) ; draft . setSubmissionKey ( prefix ) ;
var retry = f . copy ( draft ) ; var saved = f . service . save ( draft ) ;
long batches = f . jdbc . queryForObject ( " select count(*) from purchase_batch " , Long . class ) ;
long rows = f . jdbc . queryForObject ( " select count(*) from purchase_request " , Long . class ) ;
var replay = f . service . save ( retry ) ;
assertEquals ( saved . getBatch ( ) . getId ( ) , replay . getBatch ( ) . getId ( ) ) ;
assertEquals ( saved . getVersion ( ) , replay . getVersion ( ) ) ; assertNull ( replay . getSubmissionKey ( ) ) ;
assertEquals ( rows , f . jdbc . queryForObject ( " select count(*) from purchase_request " , Long . class ) ) ;
assertEquals ( batches , f . jdbc . queryForObject ( " select count(*) from purchase_batch " , Long . class ) ) ;
var unbatched = f . copy ( retry ) ; unbatched . setUnbatched ( true ) ; unbatched . setBatch ( new PurchaseBatch ( ) ) ; unbatched . setSubmissionKey ( prefix + " -unbatched " ) ;
var pending = f . copy ( unbatched ) ; var first = f . service . save ( unbatched ) ;
var second = f . service . save ( pending ) ;
assertEquals ( first . getRows ( ) . stream ( ) . map ( PurchaseRequest : : getId ) . toList ( ) , second . getRows ( ) . stream ( ) . map ( PurchaseRequest : : getId ) . toList ( ) ) ;
assertEquals ( rows + 2 , f . jdbc . queryForObject ( " select count(*) from purchase_request " , Long . class ) ) ;
assertEquals ( batches , f . jdbc . queryForObject ( " select count(*) from purchase_batch " , Long . class ) ) ;
assertEquals ( first . getVersion ( ) , f . service . savedSubmission ( prefix + " -unbatched " ) . getVersion ( ) ) ;
} ) ;
}
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_sheet_submission where submission_key like ? " , Integer . class , prefix + " % " ) ) ;
}
@Test void addingRowsToExistingSheetReplaysAndRejectsChangedContentOrAnotherAccount ( ) throws Exception {
Fixture f = new Fixture ( ) ; String key = " sheet-edit-replay- " + UUID . randomUUID ( ) ;
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 . save ( f . draft ( ) ) ;
var editing = f . copy ( saved ) ; var added = f . copy ( saved ) . getRows ( ) . get ( 0 ) ; added . setId ( null ) ; editing . getRows ( ) . add ( added ) ; editing . setSubmissionKey ( key ) ;
var retry = f . copy ( editing ) ; var first = f . service . save ( editing ) ; assertEquals ( 3 , first . getRows ( ) . size ( ) ) ;
// Display aggregates and decimal scale are not new business content.
retry . getRows ( ) . get ( 0 ) . setQuantity ( new BigDecimal ( " 2.0000 " ) ) ; retry . getBatch ( ) . setRequestCount ( 999 ) ;
var replay = f . service . save ( retry ) ; assertEquals ( 3 , replay . getRows ( ) . size ( ) ) ; assertEquals ( first . getVersion ( ) , replay . getVersion ( ) ) ;
assertEquals ( 3 , f . service . load ( saved . getBatch ( ) . getId ( ) ) . getRows ( ) . size ( ) ) ;
retry . getRows ( ) . get ( 0 ) . setQuantity ( new BigDecimal ( " 9 " ) ) ;
assertTrue ( assertThrows ( ServiceException . class , ( ) - > f . service . save ( retry ) ) . getMessage ( ) . contains ( " 本次内容不同 " ) ) ;
assertEquals ( first . getVersion ( ) , f . service . savedSubmission ( key ) . getVersion ( ) ) ;
security . when ( SecurityUtils : : getUserId ) . thenReturn ( 2L ) ;
assertThrows ( ServiceException . class , ( ) - > f . service . savedSubmission ( key ) ) ;
assertThrows ( ServiceException . class , ( ) - > f . service . save ( retry ) ) ;
security . when ( SecurityUtils : : getUserId ) . thenReturn ( 1L ) ; security . when ( SecurityUtils : : isAdmin ) . thenReturn ( false ) ;
assertThrows ( ServiceException . class , ( ) - > f . service . savedSubmission ( key ) ) ;
assertThrows ( ServiceException . class , ( ) - > f . service . save ( retry ) ) ;
security . when ( SecurityUtils : : isAdmin ) . thenReturn ( true ) ;
} ) ;
}
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_sheet_submission where submission_key=? " , Integer . class , key ) ) ;
}
@Test void failedSheetDoesNotLeaveSuccessfulSubmissionAndCanBeCorrectedWithSameKey ( ) throws Exception {
Fixture f = new Fixture ( ) ; String key = " sheet-correction- " + UUID . randomUUID ( ) ;
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 draft = f . draft ( ) ; draft . setSubmissionKey ( key ) ; var fixed = f . copy ( draft ) ;
draft . getRows ( ) . get ( 1 ) . setUnit ( " 箱 " ) ; assertThrows ( ServiceException . class , ( ) - > f . service . save ( draft ) ) ;
assertNull ( f . service . savedSubmission ( key ) ) ;
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_batch where batch_name=? " , Integer . class , f . name ) ) ;
var saved = f . service . save ( fixed ) ; assertNotNull ( saved . getBatch ( ) . getId ( ) ) ;
assertEquals ( saved . getBatch ( ) . getId ( ) , f . service . savedSubmission ( key ) . getBatch ( ) . getId ( ) ) ;
fixed . setSubmissionKey ( null ) ; assertThrows ( ServiceException . class , ( ) - > f . service . save ( fixed ) ) ;
} ) ;
}
assertEquals ( 0 , f . jdbc . queryForObject ( " select count(*) from purchase_sheet_submission where submission_key=? " , Integer . class , key ) ) ;
}
2026-10-12 16:41:42 +08:00
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 ;
2026-10-13 09:41:46 +08:00
final PurchaseBatchMapper batchMapper ;
2026-10-20 10:04:17 +08:00
final PurchasePriceService priceService ;
InventoryCostJournal historyJournal ;
PurchaseHistoryCorrectionService history ( ) {
var config = new Configuration ( ) ; config . getTypeAliasRegistry ( ) . registerAliases ( " com.ruoyi.warehouse.domain " ) ; config . setEnvironment ( new Environment ( " history-rollback " , new SpringManagedTransactionFactory ( ) , jdbc . getDataSource ( ) ) ) ;
for ( String name : List . of ( " InventoryCost " , " WarehouseArea " , " ProductInfo " ) ) { String resource = " mapper/warehouse/ " + name + " Mapper.xml " ; try ( var input = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( resource ) ) { new XMLMapperBuilder ( input , config , resource , config . getSqlFragments ( ) ) . parse ( ) ; } catch ( Exception error ) { throw new IllegalStateException ( error ) ; } }
var session = new SqlSessionTemplate ( new SqlSessionFactoryBuilder ( ) . build ( config ) ) ; var access = mock ( IProjectInfoService . class ) ; historyJournal = new InventoryCostJournal ( ) ; set ( historyJournal , " mapper " , session . getMapper ( InventoryCostMapper . class ) ) ; set ( historyJournal , " projects " , access ) ; set ( historyJournal , " items " , session . getMapper ( ProductInfoMapper . class ) ) ; set ( historyJournal , " areas " , session . getMapper ( WarehouseAreaMapper . class ) ) ; set ( historyJournal , " adjustmentDatabase " , jdbc ) ; set ( historyJournal , " businessNumbers " , AuthorizedDatabaseTestSupport . numbers ( jdbc , manager ) ) ;
var price = new PurchasePriceCorrectionService ( ) ; set ( price , " db " , jdbc ) ; set ( price , " requests " , purchaseRows ) ; set ( price , " projects " , access ) ; set ( price , " journal " , historyJournal ) ; set ( price , " prices " , priceService ) ; set ( price , " logs " , mock ( IPurchaseOperationLogService . class ) ) ; set ( price , " production " , mock ( com . ruoyi . production . service . ProductionService . class ) ) ;
var history = new PurchaseHistoryCorrectionService ( ) ; set ( history , " db " , jdbc ) ; set ( history , " json " , new ObjectMapper ( ) . findAndRegisterModules ( ) ) ; set ( history , " requests " , purchaseRows ) ; set ( history , " products " , session . getMapper ( ProductInfoMapper . class ) ) ; set ( history , " projects " , access ) ; set ( history , " journal " , historyJournal ) ; set ( history , " prices " , proxy ( price ) ) ; set ( history , " commitments " , priceService ) ; set ( history , " logs " , mock ( IPurchaseOperationLogService . class ) ) ; set ( history , " production " , mock ( com . ruoyi . production . service . ProductionService . class ) ) ;
for ( var field : Map . of ( " catalog " , " products " , " categories " , " itemCategories " , " dictionaries " , " dictTypes " , " catalogLock " , " catalogLock " , " nativePurchases " , " purchases " ) . entrySet ( ) ) set ( history , field . getKey ( ) , ReflectionTestUtils . getField ( service , field . getValue ( ) ) ) ;
return proxy ( history ) ;
}
2026-10-12 16:41:42 +08:00
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 ;
2026-10-13 09:41:46 +08:00
batchMapper = session . getMapper ( PurchaseBatchMapper . class ) ;
2026-10-12 16:41:42 +08:00
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 ) ;
2026-10-20 10:04:17 +08:00
priceService = prices ;
2026-10-12 16:41:42 +08:00
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 ) ) ;
2026-10-16 17:17:06 +08:00
set ( productTarget , " dictTypes " , dict ) ; var itemCategories = mock ( ItemCategoryService . class ) ; when ( itemCategories . labels ( ) ) . thenReturn ( List . of ( " 测试类别 " , " 更正类别 " ) ) ; set ( productTarget , " itemCategories " , itemCategories ) ;
2026-10-12 16:41:42 +08:00
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 ) ;
2026-10-13 09:41:46 +08:00
set ( target , " batchNumbers " , numbers ) ; set ( target , " operationLogs " , logs ) ; service = proxy ( target ) ;
2026-10-16 17:17:06 +08:00
set ( target , " itemCategories " , itemCategories ) ;
2026-10-12 16:41:42 +08:00
}
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 ;
}
2026-10-15 11:30:55 +08:00
PurchaseSheet save ( PurchaseSheet sheet ) {
// Existing tests describe distinct user saves; explicit retry cases call
// service.save directly with the same stable submission key.
sheet . setSubmissionKey ( " sheet-test- " + UUID . randomUUID ( ) ) ; return service . save ( sheet ) ;
}
PurchaseSheet copy ( PurchaseSheet sheet ) {
return new ObjectMapper ( ) . findAndRegisterModules ( ) . convertValue ( sheet , PurchaseSheet . class ) ;
}
2026-10-12 16:41:42 +08:00
// 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 ) ) ; }
}