- 在 .env.production 中新增 VITE_AUTH_COOKIE_NAME 配置项用于设置认证cookie名称 - 将 AcceptanceException.vue 中的表单标签宽度从固定90px改为自动适配 - 在 ActionDialog.vue 中将多个表单项标记为必填项并调整标签宽度为自动适配 - 重构 ActionHistory.vue 中的按钮布局结构并添加表格列样式类名 - 更新 api-contract-audit.cjs 添加生产任务和BOM相关接口的契约测试 - 修改 auth.js 使用动态认证cookie键名替换硬编码的Admin-Token - 调整系统角色授权用户页面的表单布局和表格样式类名 - 优化 ReceiptDialog Batch 组件的对话框尺寸、表单验证和分页功能
413 lines
37 KiB
Java
413 lines
37 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 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));
|
|
}
|
|
}
|
|
@Test void batchCombinedFiltersKeepWholeBatchTotalsAndDateBoundaries() throws Exception {
|
|
Fixture f=new Fixture();
|
|
try(var security=mockStatic(SecurityUtils.class)) {
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
|
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
|
security.when(SecurityUtils::getUserId).thenReturn(1L);
|
|
new TransactionTemplate(f.manager).executeWithoutResult(status->{
|
|
status.setRollbackOnly();
|
|
var saved=f.save(f.draft());
|
|
var filter=new PurchaseBatch();
|
|
filter.setKeyword(saved.getBatch().getBatchNo());
|
|
filter.setSupplierId(saved.getBatch().getSupplierId());
|
|
filter.setProjectId(saved.getRows().get(0).getProjectId());
|
|
filter.setMaterialName(f.name);
|
|
filter.setBeginDate(saved.getBatch().getBusinessDate());
|
|
filter.setEndDate(saved.getBatch().getBusinessDate());
|
|
filter.setProgress("confirm");
|
|
var result=f.batchMapper.selectPurchaseBatchList(filter);
|
|
assertEquals(1,result.size());
|
|
assertEquals(saved.getBatch().getId(),result.get(0).getId());
|
|
assertEquals(2,result.get(0).getRequestCount(),"Filtering by one project must not remove other projects from batch totals");
|
|
assertEquals(0,new BigDecimal("5.00").compareTo(result.get(0).getTotalAmount()));
|
|
filter.setBeginDate(saved.getBatch().getBusinessDate().plusDays(1));
|
|
assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty());
|
|
filter.setBeginDate(null);filter.setEndDate(saved.getBatch().getBusinessDate().minusDays(1));
|
|
assertTrue(f.batchMapper.selectPurchaseBatchList(filter).isEmpty());
|
|
});
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
|
|
}
|
|
}
|
|
|
|
@Test void mixedProjectSaveDedupQuotesAndLockingAreAtomic() throws Exception {
|
|
Fixture f = new Fixture();
|
|
try (var security = mockStatic(SecurityUtils.class)) {
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
|
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
|
security.when(SecurityUtils::getUserId).thenReturn(1L);
|
|
new TransactionTemplate(f.manager).execute(status -> {
|
|
try {
|
|
PurchaseSheet draft = f.draft();
|
|
PurchaseSheet saved = f.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.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.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.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.save(saved);
|
|
PurchaseSheet locked = f.service.confirm(saved.getBatch().getId(),saved.getVersion());
|
|
assertTrue(locked.getRows().stream().allMatch(r->Boolean.TRUE.equals(r.getPriceLocked())));
|
|
assertEquals(0, locked.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("3.75")));
|
|
f.service.confirm(locked.getBatch().getId(),locked.getVersion());
|
|
assertEquals(2,f.jdbc.queryForObject("select count(*) from purchase_price_ledger where purchase_request_id in (?,?)",Integer.class,locked.getRows().get(0).getId(),locked.getRows().get(1).getId()));
|
|
locked.getRows().get(0).setQuantity(new BigDecimal("10"));
|
|
PurchaseSheet maintained=f.save(locked);
|
|
assertTrue(maintained.getRows().get(0).getPriceLocked());
|
|
assertEquals(0,maintained.getRows().get(0).getLockedAmount().compareTo(new BigDecimal("12.50")));
|
|
assertEquals(0,f.jdbc.queryForObject("select quantity from purchase_request where id=?",BigDecimal.class,locked.getRows().get(0).getId()).compareTo(new BigDecimal("10")));
|
|
} finally { status.setRollbackOnly(); }
|
|
return null;
|
|
});
|
|
}
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
|
}
|
|
|
|
@Test void invalidSecondRowRollsBackBatchArchiveAndFirstRow() throws Exception {
|
|
Fixture f = new Fixture();
|
|
try(var security=mockStatic(SecurityUtils.class)) {
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);
|
|
security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
|
security.when(SecurityUtils::getUserId).thenReturn(1L);
|
|
assertThrows(ServiceException.class,()->new TransactionTemplate(f.manager).execute(status->{
|
|
PurchaseSheet draft=f.draft();draft.getRows().get(1).setUnit("箱");
|
|
return f.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.save(f.draft());
|
|
saved.setVersion("stale");assertThrows(ServiceException.class,()->f.save(saved));
|
|
PurchaseSheet omitted=f.service.load(saved.getBatch().getId());
|
|
omitted.setRows(List.of(omitted.getRows().get(0)));
|
|
assertThrows(ServiceException.class,()->f.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.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.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.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.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.save(draft);
|
|
}));assertTrue(error.getMessage().contains("物品类别"));
|
|
}
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from product_info where product_name=?",Integer.class,f.name));
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_name=?",Integer.class,f.name));
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_request where material_name=?",Integer.class,f.name));
|
|
}
|
|
|
|
@Test void confirmedTransfersKeepFeesAndRejectChangedSupplierOrExistingArrival()throws Exception {
|
|
Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)) {
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUserId).thenReturn(1L);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");
|
|
new TransactionTemplate(f.manager).execute(status->{try {
|
|
var saved=f.save(f.draft());var locked=f.service.confirm(saved.getBatch().getId(),saved.getVersion());var row=locked.getRows().get(0);Long supplier=locked.getBatch().getSupplierId();
|
|
f.jdbc.update("insert into purchase_batch(batch_no,batch_name,supplier_id,purchase_status,business_date) values(?,?,?,1,current_date())",f.name+"-target",f.name+"-target",supplier);Long target=f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-target");
|
|
var raw=new PurchaseBatchServiceImpl();f.set(raw,"purchaseBatchMapper",f.batchMapper);f.set(raw,"purchaseRequestMapper",f.purchaseRows);f.set(raw,"purchaseOperationLogService",mock(IPurchaseOperationLogService.class));var lock=new CatalogWriteLock();f.set(lock,"jdbc",f.jdbc);f.set(raw,"catalogWriteLock",lock);var service=f.proxy(raw);
|
|
var command=new PurchaseBatchAssignRequest();command.setRequestIds(new Long[]{row.getId()});command.setBatchId(target);assertEquals(1,service.assignPurchaseBatch(command));var moved=f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId());assertEquals(target,moved.getPurchaseBatchId());assertTrue(moved.getPriceLocked());assertEquals(row.getLockedAmount(),moved.getLockedAmount());
|
|
f.jdbc.update("insert into supplier_info(name,active) values(?,1)",f.name+"-other");Long other=f.jdbc.queryForObject("select id from supplier_info where name=?",Long.class,f.name+"-other");f.jdbc.update("insert into purchase_batch(batch_no,supplier_id,purchase_status) values(?,?,1)",f.name+"-wrong",other);command.setBatchId(f.jdbc.queryForObject("select id from purchase_batch where batch_no=?",Long.class,f.name+"-wrong"));assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId());
|
|
f.jdbc.update("insert into purchase_arrival(arrival_no,purchase_request_id,arrival_quantity,arrival_date,acceptance_status,create_by) values(?,?,2,current_date(),1,'sheet-rollback-test')","ARR-"+UUID.randomUUID(),row.getId());f.jdbc.update("update purchase_request set purchase_status=4 where id=?",row.getId());var appended=f.service.load(target);appended.getRows().get(0).setQuantity(new BigDecimal("3"));var updated=f.save(appended);assertEquals(3,updated.getRows().get(0).getPurchaseStatus());assertEquals(0,new BigDecimal("3.75").compareTo(updated.getRows().get(0).getLockedAmount()));command.setBatchId(locked.getBatch().getId());assertThrows(ServiceException.class,()->service.assignPurchaseBatch(command));assertEquals(target,f.purchaseRows.selectPurchaseRequestByIdForUpdate(row.getId()).getPurchaseBatchId());
|
|
} finally{status.setRollbackOnly();}return null;});
|
|
}
|
|
assertEquals(0,f.jdbc.queryForObject("select count(*) from purchase_batch where batch_no like ?",Integer.class,f.name+"%"));
|
|
}
|
|
@Test void preparingUnbatchedRowsIsAtomicAndPreservesIds()throws Exception{
|
|
Fixture f=new Fixture();try(var security=mockStatic(SecurityUtils.class)){
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
|
new TransactionTemplate(f.manager).executeWithoutResult(status->{status.setRollbackOnly();var initial=f.save(f.draft());Long[] ids=initial.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new);
|
|
for(Long id:ids)f.jdbc.update("update purchase_request set purchase_batch_id=null,purchase_batch_no=null where id=?",id);
|
|
var prepared=f.service.prepare(ids);assertEquals(2,prepared.getRows().size());assertNull(prepared.getBatch().getSupplierId());assertEquals(Set.of(ids),new HashSet<>(prepared.getRows().stream().map(PurchaseRequest::getId).toList()));
|
|
long count=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class);assertThrows(ServiceException.class,()->f.service.prepare(ids));assertEquals(count,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class));
|
|
});
|
|
}
|
|
}
|
|
|
|
@Test void unbatchedSaveEditDeleteAndGroupingPreserveAtomicity() throws Exception {
|
|
Fixture f=new Fixture();
|
|
try(var security=mockStatic(SecurityUtils.class)){
|
|
security.when(SecurityUtils::isAdmin).thenReturn(true);security.when(SecurityUtils::getUsername).thenReturn("sheet-rollback-test");security.when(SecurityUtils::getUserId).thenReturn(1L);
|
|
new TransactionTemplate(f.manager).execute(status->{try{
|
|
long batchCount=f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class);
|
|
var draft=f.draft();draft.setUnbatched(true);draft.getBatch().setSupplierId(null);draft.getRows().forEach(r->r.setFinalUnitPrice(null));
|
|
var saved=f.save(draft);assertTrue(saved.isUnbatched());assertNull(saved.getBatch().getId());assertEquals(batchCount,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class));
|
|
assertTrue(saved.getRows().stream().allMatch(r->r.getPurchaseBatchId()==null&&!Boolean.TRUE.equals(r.getPriceLocked())));
|
|
var ids=saved.getRows().stream().map(PurchaseRequest::getId).toArray(Long[]::new);
|
|
var stale=f.service.loadUnbatched(ids);saved.getRows().get(0).setQuantity(new BigDecimal("7"));f.save(saved);
|
|
stale.getRows().get(0).setQuantity(BigDecimal.TEN);assertThrows(ServiceException.class,()->f.save(stale));
|
|
var batch=f.service.prepare(new Long[]{ids[0]},null);assertNotNull(batch.getBatch().getId());assertEquals(1,batch.getRows().size());
|
|
assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[0]},batch.getBatch().getId()));
|
|
f.jdbc.update("update purchase_batch set purchase_status=2 where id=?",batch.getBatch().getId());
|
|
assertThrows(ServiceException.class,()->f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId()));
|
|
assertNull(f.service.loadUnbatched(new Long[]{ids[1]}).getRows().get(0).getPurchaseBatchId());
|
|
f.jdbc.update("update purchase_batch set purchase_status=1 where id=?",batch.getBatch().getId());
|
|
assertEquals(2,f.service.prepare(new Long[]{ids[1]},batch.getBatch().getId()).getRows().size());
|
|
assertEquals(batchCount+1,f.jdbc.queryForObject("select count(*) from purchase_batch",Long.class));
|
|
var more=new PurchaseSheet();more.setUnbatched(true);more.setBatch(new PurchaseBatch());more.setRows(draft.getRows());more.getRows().forEach(r->{r.setId(null);r.setPurchaseBatchId(null);});var deletion=f.save(more);var deleted=deletion.getRows().stream().map(PurchaseRequest::getId).toList();deletion.setDeletedIds(deleted);deletion.setRows(List.of());assertTrue(f.save(deletion).getRows().isEmpty());
|
|
}finally{status.setRollbackOnly();}return null;});
|
|
}
|
|
}
|
|
|
|
@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));
|
|
}
|
|
|
|
private static class Fixture {
|
|
final String name="SHEET-CHECK-"+UUID.randomUUID();
|
|
final JdbcTemplate jdbc;
|
|
final DataSourceTransactionManager manager;
|
|
final PurchaseSheetService service;
|
|
final ProjectInfoMapper projects;
|
|
final ProjectBudgetMapper budgets;
|
|
final PurchaseRequestMapper purchaseRows;
|
|
final PurchaseBatchMapper batchMapper;
|
|
Fixture() throws Exception {
|
|
Path root=Path.of(System.getProperty("user.dir"));if(!Files.isDirectory(root.resolve("ruoyi-admin")))root=root.getParent();
|
|
Map<?,?> yaml;try(var input=Files.newInputStream(root.resolve("ruoyi-admin/src/main/resources/application-druid.yml"))){yaml=new Yaml().load(input);}
|
|
Map<?,?> source=(Map<?,?>)((Map<?,?>)((Map<?,?>)((Map<?,?>)yaml.get("spring")).get("datasource")).get("druid")).get("master");
|
|
String url=resolve(String.valueOf(source.get("url")));ProjectDatabaseGuard.assertAllowedUrl(url);
|
|
DriverManagerDataSource ds=new DriverManagerDataSource(url,resolve(String.valueOf(source.get("username"))),resolve(String.valueOf(source.get("password"))));
|
|
jdbc=new JdbcTemplate(ds);assertEquals("cmvr-project-dev",jdbc.queryForObject("select database()",String.class));
|
|
manager=new DataSourceTransactionManager(ds);
|
|
Configuration config=new Configuration();config.getTypeAliasRegistry().registerAliases("com.ruoyi.warehouse.domain");
|
|
config.setEnvironment(new Environment("sheet-rollback",new SpringManagedTransactionFactory(),ds));
|
|
for(String file:List.of("project/ProjectInfo","project/ProjectBudget","warehouse/PurchaseRequest","warehouse/ProductInfo","warehouse/PurchaseBatch","warehouse/PurchaseArrival")) {
|
|
String resource="mapper/"+file+"Mapper.xml";
|
|
try(var input=getClass().getClassLoader().getResourceAsStream(resource)){assertNotNull(input,resource);new XMLMapperBuilder(input,config,resource,config.getSqlFragments()).parse();}
|
|
}
|
|
var session=new SqlSessionTemplate(new SqlSessionFactoryBuilder().build(config));
|
|
projects=session.getMapper(ProjectInfoMapper.class);budgets=session.getMapper(ProjectBudgetMapper.class);
|
|
var purchases=session.getMapper(PurchaseRequestMapper.class);var catalog=session.getMapper(ProductInfoMapper.class);
|
|
purchaseRows=purchases;
|
|
batchMapper=session.getMapper(PurchaseBatchMapper.class);
|
|
IProjectInfoService projectAccess=mock(IProjectInfoService.class);
|
|
IPurchaseOperationLogService logs=mock(IPurchaseOperationLogService.class);
|
|
CatalogWriteLock lock=new CatalogWriteLock();set(lock,"jdbc",jdbc);
|
|
var allocator=AuthorizedDatabaseTestSupport.numbers(jdbc,manager);PurchaseBatchNumber numbers=new PurchaseBatchNumber();set(numbers,"businessNumbers",allocator);
|
|
ProductInfoServiceImpl productTarget=new ProductInfoServiceImpl();set(productTarget,"productInfoMapper",catalog);set(productTarget,"catalogWriteLock",lock);
|
|
set(productTarget,"businessNumbers",allocator);
|
|
var productService=proxy(productTarget);
|
|
PurchasePriceService prices=new PurchasePriceService();set(prices,"purchaseRequestMapper",purchases);set(prices,"projectBudgetMapper",budgets);set(prices,"projectInfoService",projectAccess);set(prices,"operationLogService",logs);
|
|
set(prices,"businessNumbers",allocator);
|
|
PurchaseRequestServiceImpl purchaseTarget=new PurchaseRequestServiceImpl();set(purchaseTarget,"purchaseRequestMapper",purchases);set(purchaseTarget,"productInfoMapper",catalog);set(purchaseTarget,"productInfoService",productService);set(purchaseTarget,"purchaseArrivalMapper",session.getMapper(PurchaseArrivalMapper.class));set(purchaseTarget,"projectInfoMapper",projects);set(purchaseTarget,"projectBudgetMapper",budgets);set(purchaseTarget,"projectInfoService",projectAccess);set(purchaseTarget,"priceService",prices);set(purchaseTarget,"purchaseOperationLogService",logs);set(purchaseTarget,"taskDatabase",jdbc);
|
|
SupplierService supplier=new SupplierService();set(supplier,"db",jdbc);
|
|
set(purchaseTarget,"businessNumbers",allocator);
|
|
ISysDictTypeService dict=mock(ISysDictTypeService.class);SysDictData unit=new SysDictData();unit.setDictLabel("件");unit.setStatus("0");when(dict.selectDictDataByType("wms_item_unit")).thenReturn(List.of(unit));
|
|
set(productTarget,"dictTypes",dict);var itemCategories=mock(ItemCategoryService.class);when(itemCategories.labels()).thenReturn(List.of("测试类别"));set(productTarget,"itemCategories",itemCategories);
|
|
PurchaseSheetService target=new PurchaseSheetService();set(target,"batches",session.getMapper(PurchaseBatchMapper.class));set(target,"requests",purchases);set(target,"catalog",catalog);set(target,"products",productService);set(target,"purchases",proxy(purchaseTarget));set(target,"prices",prices);set(target,"suppliers",supplier);set(target,"catalogLock",lock);set(target,"jdbc",jdbc);set(target,"json",new ObjectMapper().findAndRegisterModules());set(target,"dictTypes",dict);
|
|
set(target,"batchNumbers",numbers);set(target,"operationLogs",logs); service=proxy(target);
|
|
}
|
|
PurchaseSheet draft() {
|
|
jdbc.update("insert into supplier_info(name,active,create_by) values(?,1,'sheet-rollback-test')",name);
|
|
Long supplier=jdbc.queryForObject("select id from supplier_info where name=?",Long.class,name);
|
|
ExpenseCategory category=budgets.selectExpenseCategoryByCode("MATERIAL");assertNotNull(category);
|
|
List<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;
|
|
}
|
|
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);
|
|
}
|
|
// 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));}
|
|
}
|