✨ 毛利分析订单支持异步导出
This commit is contained in:
+22
-12
@@ -8,6 +8,7 @@ import java.nio.file.Paths;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -17,6 +18,7 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.bms.common.annotation.Log;
|
||||
@@ -39,6 +41,7 @@ import com.bms.price.domain.vo.PrcProfitReportProductRow;
|
||||
import com.bms.price.domain.vo.PrcProfitReportQuery;
|
||||
import com.bms.price.domain.vo.PrcProfitReportSummary;
|
||||
import com.bms.price.service.IPrcProfitReportService;
|
||||
import com.bms.price.task.PrcProfitReportExportRunner;
|
||||
|
||||
/** 产品/订单维度毛利报表。 */
|
||||
@RestController
|
||||
@@ -51,6 +54,9 @@ public class PrcProfitReportController extends BaseController
|
||||
@Autowired
|
||||
private OssStorage ossStorage;
|
||||
|
||||
@Autowired
|
||||
private PrcProfitReportExportRunner exportRunner;
|
||||
|
||||
/** 客户筛选选项,沿用毛利报表的访问权限和查询范围。 */
|
||||
@PreAuthorize("@ss.hasPermi('report:profit:list')")
|
||||
@GetMapping("/customer-options")
|
||||
@@ -124,19 +130,23 @@ public class PrcProfitReportController extends BaseController
|
||||
@Log(title = "毛利报表-订单维度", businessType = BusinessType.EXPORT)
|
||||
@PreAuthorize("@ss.hasPermi('report:profit:export')")
|
||||
@PostMapping("/orders/export")
|
||||
public AjaxResult exportOrders(PrcProfitReportQuery query)
|
||||
public AjaxResult exportOrders(@RequestBody PrcProfitReportQuery query)
|
||||
{
|
||||
PrcProfitReportExport export = beginExport("ORDER", "订单维度毛利分析");
|
||||
try
|
||||
{
|
||||
List<PrcProfitReportOrderRow> rows = profitReportService.selectOrderRows(query);
|
||||
return finishExport(export, rows, PrcProfitReportOrderRow.class, "订单毛利报表", query.getProfitRule());
|
||||
}
|
||||
catch (RuntimeException e)
|
||||
{
|
||||
failExport(export, e);
|
||||
throw e;
|
||||
}
|
||||
return success(Map.of("taskId", exportRunner.submit(query, getUserId())));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('report:profit:export')")
|
||||
@GetMapping("/orders/export/task/{taskId}")
|
||||
public AjaxResult orderExportTask(@PathVariable String taskId)
|
||||
{
|
||||
return success(exportRunner.getTask(taskId, getUserId()));
|
||||
}
|
||||
|
||||
@PreAuthorize("@ss.hasPermi('report:profit:export')")
|
||||
@GetMapping("/orders/export/download/{taskId}")
|
||||
public void downloadOrderExport(@PathVariable String taskId, HttpServletResponse response) throws Exception
|
||||
{
|
||||
exportRunner.download(taskId, getUserId(), response);
|
||||
}
|
||||
|
||||
@Log(title = "毛利报表-产品维度", businessType = BusinessType.EXPORT)
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package com.bms.report;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.FileTime;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Function;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.usermodel.WorkbookFactory;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.core.task.TaskRejectedException;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
import com.bms.common.config.BmsConfig;
|
||||
import com.bms.common.core.redis.RedisCache;
|
||||
import com.bms.common.exception.ServiceException;
|
||||
import com.bms.price.domain.PrcProfitReportExportTask;
|
||||
import com.bms.price.domain.vo.PrcProfitReportOrderRow;
|
||||
import com.bms.price.domain.vo.PrcProfitReportQuery;
|
||||
import com.bms.price.enums.ProfitAreaRule;
|
||||
import com.bms.price.service.IPrcProfitReportService;
|
||||
import com.bms.price.task.PrcProfitReportExportRunner;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
|
||||
class ProfitReportAsyncExportTest
|
||||
{
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
private String previousProfile;
|
||||
|
||||
@BeforeEach
|
||||
void useTempProfile()
|
||||
{
|
||||
previousProfile = BmsConfig.getProfile();
|
||||
new BmsConfig().setProfile(tempDir.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreProfile()
|
||||
{
|
||||
new BmsConfig().setProfile(previousProfile);
|
||||
PageHelper.clearPage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void submissionQueuesWorkAndExportsAllRowsUsingTheSubmittedFiltersAndRegionColumns() throws Exception
|
||||
{
|
||||
for (String area : List.of("C", "GZ"))
|
||||
{
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
HoldingExecutor executor = new HoldingExecutor();
|
||||
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> {
|
||||
calls.incrementAndGet();
|
||||
assertNull(PageHelper.getLocalPage());
|
||||
assertEquals(area, query.getCustomerArea());
|
||||
assertEquals("UNBILLED", query.getArBillStatus());
|
||||
assertEquals("P1", query.getProductCode());
|
||||
query.setProfitRule(ProfitAreaRule.fromCustomerArea(area).name());
|
||||
return List.of(row("ORDER-A"), row("ORDER-B"));
|
||||
}), new MemoryRedis(), executor);
|
||||
PrcProfitReportQuery query = query(area);
|
||||
query.setProductCode("P1");
|
||||
String taskId = runner.submit(query, 1L);
|
||||
|
||||
assertEquals(0, calls.get());
|
||||
assertEquals("PENDING", runner.getTask(taskId, 1L).getStatus());
|
||||
assertThrows(ServiceException.class, () -> runner.download(taskId, 1L, new MockHttpServletResponse()));
|
||||
query.setProductCode("CHANGED-AFTER-SUBMIT");
|
||||
PageHelper.startPage(2, 1);
|
||||
executor.work.run();
|
||||
|
||||
PrcProfitReportExportTask task = runner.getTask(taskId, 1L);
|
||||
assertEquals("SUCCESS", task.getStatus());
|
||||
assertEquals(100, task.getPercent());
|
||||
assertEquals(2, task.getRowCount());
|
||||
assertEquals(1, calls.get());
|
||||
assertNull(PageHelper.getLocalPage());
|
||||
assertThrows(ServiceException.class, () -> runner.getTask(taskId, 2L));
|
||||
assertThrows(ServiceException.class, () -> runner.download(taskId, 2L, new MockHttpServletResponse()));
|
||||
Path file = tempDir.resolve("download").resolve(task.getStorageKey());
|
||||
try (InputStream input = Files.newInputStream(file); Workbook workbook = WorkbookFactory.create(input))
|
||||
{
|
||||
var sheet = workbook.getSheetAt(0);
|
||||
assertEquals(2, sheet.getLastRowNum());
|
||||
Row header = sheet.getRow(0);
|
||||
assertEquals(area.equals("C"), hasColumn(header, "产品价(目录价)"));
|
||||
assertEquals(area.equals("C"), hasColumn(header, "红线毛利"));
|
||||
assertTrue(hasColumn(header, "销售价"));
|
||||
}
|
||||
MockHttpServletResponse response = new MockHttpServletResponse();
|
||||
runner.download(taskId, 1L, response);
|
||||
assertArrayEquals(Files.readAllBytes(file), response.getContentAsByteArray());
|
||||
assertTrue(response.getHeader("Content-Disposition").contains(".xlsx"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedExecutionAndQueryFailuresBecomeVisibleFailedTasks() throws Exception
|
||||
{
|
||||
ThreadPoolTaskExecutor rejected = new ThreadPoolTaskExecutor() {
|
||||
@Override
|
||||
public void execute(Runnable task) { throw new TaskRejectedException("busy"); }
|
||||
};
|
||||
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> {
|
||||
fail("Rejected tasks must not query orders");
|
||||
return List.of();
|
||||
}), new MemoryRedis(), rejected);
|
||||
String rejectedId = runner.submit(query("C"), 1L);
|
||||
assertEquals("FAIL", runner.getTask(rejectedId, 1L).getStatus());
|
||||
assertEquals("导出任务较多,请稍后重试", runner.getTask(rejectedId, 1L).getError());
|
||||
|
||||
HoldingExecutor executor = new HoldingExecutor();
|
||||
PrcProfitReportExportRunner failing = new PrcProfitReportExportRunner(service(query -> {
|
||||
throw new ServiceException("该客户区域未配置毛利规则");
|
||||
}), new MemoryRedis(), executor);
|
||||
String failedId = failing.submit(query("INVALID"), 1L);
|
||||
executor.work.run();
|
||||
PrcProfitReportExportTask failed = failing.getTask(failedId, 1L);
|
||||
assertEquals("FAIL", failed.getStatus());
|
||||
assertEquals("该客户区域未配置毛利规则", failed.getError());
|
||||
assertNull(failed.getStorageKey());
|
||||
assertThrows(ServiceException.class, () -> failing.download(failedId, 1L, new MockHttpServletResponse()));
|
||||
assertFalse(Files.exists(tempDir.resolve("download/profitReportExport/" + failedId + ".xlsx")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void cleanupRemovesOnlyExpiredExportFiles() throws Exception
|
||||
{
|
||||
Path dir = Files.createDirectories(tempDir.resolve("download/profitReportExport"));
|
||||
Path old = Files.writeString(dir.resolve("a".repeat(32) + ".xlsx"), "old");
|
||||
Path recent = Files.writeString(dir.resolve("b".repeat(32) + ".xlsx"), "new");
|
||||
Path other = Files.writeString(dir.resolve("unrelated.xlsx"), "other");
|
||||
FileTime expired = FileTime.from(Instant.now().minusSeconds(TimeUnit.HOURS.toSeconds(25)));
|
||||
Files.setLastModifiedTime(old, expired);
|
||||
Files.setLastModifiedTime(other, expired);
|
||||
PrcProfitReportExportRunner runner = new PrcProfitReportExportRunner(service(query -> List.of()),
|
||||
new MemoryRedis(), new HoldingExecutor());
|
||||
runner.cleanupExpiredFiles();
|
||||
assertFalse(Files.exists(old));
|
||||
assertTrue(Files.exists(recent));
|
||||
assertTrue(Files.exists(other));
|
||||
}
|
||||
|
||||
@Test
|
||||
void jsonSubmissionRetainsTheListDateRangeAndFilters() throws Exception
|
||||
{
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
|
||||
PrcProfitReportQuery query = mapper.readValue("""
|
||||
{"customerArea":"C", "beginBizDate":"2026-10-18 00:00:00",
|
||||
"endBizDate":"2026-11-17 23:59:59", "arBillStatus":"UNBILLED", "orderNo":"A\\nB"}
|
||||
""", PrcProfitReportQuery.class);
|
||||
assertEquals(Instant.parse("2026-10-17T16:00:00Z"), query.getBeginBizDate().toInstant());
|
||||
assertEquals(Instant.parse("2026-11-17T15:59:59Z"), query.getEndBizDate().toInstant());
|
||||
assertEquals("A\nB", query.getOrderNo());
|
||||
assertEquals("UNBILLED", query.getArBillStatus());
|
||||
}
|
||||
|
||||
private static PrcProfitReportQuery query(String area)
|
||||
{
|
||||
PrcProfitReportQuery query = new PrcProfitReportQuery();
|
||||
query.setCustomerArea(area);
|
||||
query.setArBillStatus("UNBILLED");
|
||||
return query;
|
||||
}
|
||||
|
||||
private static PrcProfitReportOrderRow row(String orderNo)
|
||||
{
|
||||
PrcProfitReportOrderRow row = new PrcProfitReportOrderRow();
|
||||
row.setOrderNo(orderNo);
|
||||
row.setSalesAmount(new BigDecimal("26.60"));
|
||||
row.setArBillStatus("UNBILLED");
|
||||
return row;
|
||||
}
|
||||
|
||||
private static boolean hasColumn(Row header, String name)
|
||||
{
|
||||
for (var cell : header) if (name.equals(cell.getStringCellValue())) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static IPrcProfitReportService service(Function<PrcProfitReportQuery, List<PrcProfitReportOrderRow>> query)
|
||||
{
|
||||
return (IPrcProfitReportService) Proxy.newProxyInstance(ProfitReportAsyncExportTest.class.getClassLoader(),
|
||||
new Class<?>[] { IPrcProfitReportService.class }, (proxy, method, args) -> {
|
||||
if ("selectOrderRows".equals(method.getName())) return query.apply((PrcProfitReportQuery) args[0]);
|
||||
throw new AssertionError("Unexpected service call: " + method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
private static class HoldingExecutor extends ThreadPoolTaskExecutor
|
||||
{
|
||||
private Runnable work;
|
||||
@Override
|
||||
public void execute(Runnable task) { work = task; }
|
||||
}
|
||||
|
||||
private static class MemoryRedis extends RedisCache
|
||||
{
|
||||
private final Map<String, Object> values = new HashMap<>();
|
||||
@Override
|
||||
public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit unit)
|
||||
{
|
||||
values.put(key, value);
|
||||
}
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T getCacheObject(String key) { return (T) values.get(key); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user