refactor(phase-3): 3A 拆薄第四笔——结果打包与命名抽出,并补上上一笔声称已加的见证

AppearancePatentTaskService 棘轮读数 3165→3049(本会话累计 3458→3049,净减 409 行);
新落 service/support/AppearancePatentResultPackager 206 行(<800 报警线)。
搬的是「按源文件分组 + zip 打包 + 成品命名」四枚:splitRowsBySourceFile、
packageResultWorkbooksAsZip、uniqueZipEntryName、normalizeZipFilename、writeResultZipEntry、
safeFileStem,连同只有它们用的 SourceRowsBuilder 与 SourceRows/SourceResultWorkbook 两枚 record。
分组键的三级回落(sourceFileKey → sourceFilename → __default__)、条目名去重后缀 (2)(3)…、
Windows 非法字符换下划线、异常文案——判据与字面量逐字带过来。
两处如实说明:① 三个重复出现的字面量(appearance-patent/appearance-patent-result.xlsx/8192)
收成本类常量,值一字未改;② 服务侧留三枚薄委托+一个无状态访问器(与 historyAssembler() 同一先例,
所以本笔不动构造器、不动装配),不是为了保反射接缝——AP 测试按名反射的清单里根本没有这四枚
(那批点名在 writeResultWorkbook/validateCompleteLlmCoverage 那一侧),这条前置扫描是上一笔
栽过之后固定下来的动作。

⚠ 更正上一笔的登记(768f8e05 的 commit message 说了没做):那句「另加两条 anyMatch 点名新落件」
实际没进文件——当时脚本改的是数字、那段追加从未落地。本笔把三枚新件逐枚点名进 witness,
并如实留这句更正:只把分母数字改大,护栏证的还是「数对不对」,不是「扫不扫得到」。

顺带一条既有事实登记(不是本笔引入、本笔没顺手改):文本归一化在 src/main 里有两遍——
Task 93 抽出的 AppearancePatentRowNormalizer(normalize/firstNonBlank/baseId/normalizeDisplayId)
与 AppearancePatentTaskService 自己那两枚同名私有件,服务至今一处没用过 util。扫描件本可以抄第三份,
直接引用 util 了;把服务侧那两枚切过去是纯粹的重复消除(十几处调用点同形),但那是另一笔的账。

门禁:后端全量 mvn -o test 4518 例/0 红/0 错/12 skipped,BUILD SUCCESS(无管道取码);
八条 golden 逐字节相等(git status -- src/test/resources 一字未动);ops 面 ruff All checks passed、
readability 棘轮 9 passed(3049<在册 3458,两枚新件都在报警线以下,基线一格未改)。
This commit is contained in:
2026-10-19 12:28:41 +08:00
parent 768f8e0573
commit ac873b24bf
3 changed files with 244 additions and 149 deletions
@@ -31,6 +31,7 @@ import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParse
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskBatchVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskDetailVo;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentTaskItemVo;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentResultPackager;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentRowOutcome;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentSheetBuilder;
import com.nanri.aiimage.modules.appearancepatent.service.support.AppearancePatentStaleTaskScanner;
@@ -2066,7 +2067,7 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
AppearancePatentParsedPayloadDto parsed = readParsedPayload(task);
List<AppearancePatentParsedRowVo> parsedRows = parsed.getAllItems() == null
? List.of() : parsed.getAllItems();
List<SourceRows> sourceRows = splitRowsBySourceFile(parsed, parsedRows, result.getSourceFilename());
List<AppearancePatentResultPackager.SourceRows> sourceRows = splitRowsBySourceFile(parsed, parsedRows, result.getSourceFilename());
if (sourceRows.isEmpty()) {
throw new BusinessException("外观专利检测结果为空,请稍后重试生成结果文件");
}
@@ -2079,10 +2080,10 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
if (!outputDir.exists() && !outputDir.mkdirs()) {
throw new BusinessException("创建结果目录失败");
}
List<SourceResultWorkbook> workbooks = new ArrayList<>();
List<AppearancePatentResultPackager.SourceResultWorkbook> workbooks = new ArrayList<>();
File zip = null;
try {
for (SourceRows item : sourceRows) {
for (AppearancePatentResultPackager.SourceRows item : sourceRows) {
Map<String, AppearancePatentResultRowDto> resultMap =
loadPersistedResultRowsForRowsWithRetry(task.getId(), item.rows());
// 覆盖率先于「本文件无结果就跳过」判定:整源文件的 LLM 结果全丢(分片被跳过、
@@ -2118,7 +2119,7 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
+ "-result.xlsx";
File xlsx = new File(outputDir, tempFilename);
writeResultWorkbook(xlsx, parsed, receivedRows, resultMap);
workbooks.add(new SourceResultWorkbook(xlsx, filename, receivedRows.size()));
workbooks.add(new AppearancePatentResultPackager.SourceResultWorkbook(xlsx, filename, receivedRows.size()));
resultMap.clear();
}
if (workbooks.isEmpty()) {
@@ -2126,7 +2127,7 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
}
log.info("[appearance-patent] assemble workbook taskId={} parsedRows={} receivedRows={} resultRows={} resolvedRows={} reasonRows={}",
task.getId(), parsedRows.size(), receivedRowCount,
workbooks.stream().mapToInt(SourceResultWorkbook::rowCount).sum(), resolvedRows, reasonRows);
workbooks.stream().mapToInt(AppearancePatentResultPackager.SourceResultWorkbook::rowCount).sum(), resolvedRows, reasonRows);
if (conclusionPropagated > 0) {
log.info("[appearance-patent] group propagate conclusion taskId={} updatedRows={}",
task.getId(), conclusionPropagated);
@@ -2136,7 +2137,7 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
String filename;
String contentType;
if (workbooks.size() == 1) {
SourceResultWorkbook workbook = workbooks.get(0);
AppearancePatentResultPackager.SourceResultWorkbook workbook = workbooks.get(0);
uploadFile = workbook.file();
filename = workbook.filename();
contentType = CONTENT_TYPE_XLSX;
@@ -2161,7 +2162,7 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
result.setRowCount(receivedRowCount);
return deliveryFacts;
} finally {
for (SourceResultWorkbook workbook : workbooks) {
for (AppearancePatentResultPackager.SourceResultWorkbook workbook : workbooks) {
if (workbook.file().exists() && !workbook.file().delete()) {
log.warn("[appearance-patent] delete temp xlsx failed file={}", workbook.file());
}
@@ -2172,100 +2173,30 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
}
}
private List<SourceRows> splitRowsBySourceFile(AppearancePatentParsedPayloadDto parsed,
List<AppearancePatentParsedRowVo> receivedRows,
String fallbackFilename) {
String defaultFilename = firstNonBlank(fallbackFilename, "appearance-patent");
Map<String, SourceRowsBuilder> builders = new LinkedHashMap<>();
if (parsed != null && parsed.getSourceFiles() != null) {
for (AppearancePatentSourceFileDto sourceFile : parsed.getSourceFiles()) {
if (sourceFile == null) {
continue;
}
String sourceFileKey = normalize(sourceFile.getFileKey());
if (sourceFileKey.isBlank()) {
continue;
}
builders.putIfAbsent(sourceFileKey,
new SourceRowsBuilder(sourceFileKey, firstNonBlank(sourceFile.getOriginalFilename(), defaultFilename)));
}
}
for (AppearancePatentParsedRowVo row : receivedRows == null ? List.<AppearancePatentParsedRowVo>of() : receivedRows) {
if (row == null) {
continue;
}
String sourceFileKey = normalize(row.getSourceFileKey());
if (sourceFileKey.isBlank()) {
sourceFileKey = normalize(row.getSourceFilename());
}
if (sourceFileKey.isBlank()) {
sourceFileKey = "__default__";
}
SourceRowsBuilder builder = builders.computeIfAbsent(sourceFileKey,
key -> new SourceRowsBuilder(key, firstNonBlank(row.getSourceFilename(), defaultFilename)));
if (builder.sourceFilename().isBlank() || Objects.equals(builder.sourceFilename(), defaultFilename)) {
builder.setSourceFilename(firstNonBlank(row.getSourceFilename(), defaultFilename));
}
builder.rows().add(row);
}
return builders.values().stream()
.filter(builder -> !builder.rows().isEmpty())
.map(builder -> new SourceRows(builder.sourceFileKey(), firstNonBlank(builder.sourceFilename(), defaultFilename), builder.rows()))
.toList();
/**
* C 聚类·打包与命名住在 {@link AppearancePatentResultPackager}(3A 拆薄第四笔)。
* 无状态、按调用现取,与 {@code historyAssembler()} 同一先例,所以本笔不动构造器、不动装配。
* 三枚薄委托不是为了保住反射接缝(AP 的反射点名在 {@code writeResultWorkbook} 那一侧,
* 本笔搬的四枚方法没有被任何测试按名反射过),而是为了不让六个调用点跟着改形状。
*/
private AppearancePatentResultPackager resultPackager() {
return new AppearancePatentResultPackager();
}
private void packageResultWorkbooksAsZip(File zip, List<SourceResultWorkbook> workbooks) {
Set<String> entryNames = new LinkedHashSet<>();
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip))) {
byte[] buffer = new byte[8192];
for (SourceResultWorkbook workbook : workbooks) {
writeResultZipEntry(zos, buffer, workbook.file(), uniqueZipEntryName(workbook.filename(), entryNames));
}
} catch (IOException ex) {
throw new BusinessException("生成外观专利检测结果压缩包失败");
}
private List<AppearancePatentResultPackager.SourceRows> splitRowsBySourceFile(
AppearancePatentParsedPayloadDto parsed,
List<AppearancePatentParsedRowVo> receivedRows,
String fallbackFilename) {
return resultPackager().splitRowsBySourceFile(parsed, receivedRows, fallbackFilename);
}
private void writeResultZipEntry(ZipOutputStream zos,
byte[] buffer,
File file,
String entryName) throws IOException {
zos.putNextEntry(new ZipEntry(entryName));
try (FileInputStream inputStream = new FileInputStream(file)) {
int len;
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
private void packageResultWorkbooksAsZip(File zip,
List<AppearancePatentResultPackager.SourceResultWorkbook> workbooks) {
resultPackager().packageResultWorkbooksAsZip(zip, workbooks);
}
private String uniqueZipEntryName(String filename, Set<String> entryNames) {
String safeFilename = normalizeZipFilename(filename);
if (entryNames.add(safeFilename)) {
return safeFilename;
}
int dotIndex = safeFilename.lastIndexOf('.');
String stem = dotIndex > 0 ? safeFilename.substring(0, dotIndex) : safeFilename;
String extension = dotIndex > 0 ? safeFilename.substring(dotIndex) : "";
int index = 2;
while (true) {
String candidate = stem + "(" + index + ")" + extension;
if (entryNames.add(candidate)) {
return candidate;
}
index++;
}
}
private String normalizeZipFilename(String filename) {
String normalized = firstNonBlank(filename, "appearance-patent-result.xlsx").replace('\\', '/');
while (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
return normalized.isBlank() ? "appearance-patent-result.xlsx" : normalized;
private String safeFileStem(String filename) {
return resultPackager().safeFileStem(filename);
}
private List<AppearancePatentParsedRowVo> filterReceivedParsedRows(List<AppearancePatentParsedRowVo> parsedRows,
@@ -3015,16 +2946,6 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
return executionFailed ? STATUS_FAILED : STATUS_SUCCESS;
}
private String safeFileStem(String filename) {
String name = filename == null || filename.isBlank() ? "appearance-patent" : filename;
int idx = name.lastIndexOf('.');
if (idx > 0) {
name = name.substring(0, idx);
}
String safe = name.replaceAll("[\\\\/:*?\"<>|]", "_").trim();
return safe.isBlank() ? "appearance-patent" : safe;
}
/** 只读收集任务范围/分片载荷指针,供事务提交后做远端删除。 */
private List<String> collectTransientTaskPayloads(Long taskId) {
if (taskId == null || taskId <= 0) {
@@ -3119,43 +3040,6 @@ public class AppearancePatentTaskService extends AbstractFileTaskPipeline<Appear
String payloadHash) {
}
private static class SourceRowsBuilder {
private final String sourceFileKey;
private String sourceFilename;
private final List<AppearancePatentParsedRowVo> rows = new ArrayList<>();
private SourceRowsBuilder(String sourceFileKey, String sourceFilename) {
this.sourceFileKey = sourceFileKey;
this.sourceFilename = sourceFilename;
}
private String sourceFileKey() {
return sourceFileKey;
}
private String sourceFilename() {
return sourceFilename;
}
private void setSourceFilename(String sourceFilename) {
this.sourceFilename = sourceFilename;
}
private List<AppearancePatentParsedRowVo> rows() {
return rows;
}
}
private record SourceRows(String sourceFileKey,
String sourceFilename,
List<AppearancePatentParsedRowVo> rows) {
}
private record SourceResultWorkbook(File file,
String filename,
int rowCount) {
}
private record ParsedWorkbook(int totalRows, int droppedRows, List<String> headers, List<AppearancePatentParsedRowVo> allRows) {
}
@@ -0,0 +1,205 @@
package com.nanri.aiimage.modules.appearancepatent.service.support;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentParsedPayloadDto;
import com.nanri.aiimage.modules.appearancepatent.model.dto.AppearancePatentSourceFileDto;
import com.nanri.aiimage.modules.appearancepatent.model.vo.AppearancePatentParsedRowVo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 外观专利结果侧的「按源文件分组 + 成品文件打包与命名」,从
* {@code AppearancePatentTaskService} <b>原样搬移</b>(3A 拆薄第四笔)。
*
* <p>搬的是纯形状:分组键的取法({@code sourceFileKey} → 回落 {@code sourceFilename} →
* 再回落 {@code __default__})、zip 条目名的去重后缀 {@code (2)(3)…}、文件名里 Windows
* 非法字符换成下划线、空名兜底成 {@code appearance-patent}。判据、兜底值、异常文案一字未改。
*
* <p><b>为什么这一簇先抽。</b>它是 C 聚类里唯一「零反射接缝、零库表写入」的一段——
* {@code assembleResultWorkbook} 留在服务侧继续编排(要读分片、要落结果行、要挂 OSS),
* 这里只把「给它算出该打包什么、叫什么名、怎么压成 zip」这件事收成一枚无状态件。
* 反面判据也查过:AP 的测试没有按名字反射过这四枚私有方法(反射点名清单里是
* {@code writeResultWorkbook}/{@code validateCompleteLlmCoverage} 那一批),所以本笔
* 不需要为保住接缝而留委托壳——服务侧那三枚薄委托只是为了不让六个调用点改形状。
*
* <p>文本归一化不再抄第三份:分组里用的 {@code normalize}/{@code firstNonBlank} 直接引用
* {@link AppearancePatentRowNormalizer}(该 util 的 javadoc 自陈与服务侧那一版「逐字节一致」,
* 本笔逐条对过,body 相同)。⚠ 顺带登记一条既有事实:服务至今仍有自己那两枚私有同名件,
* Task 93 抽出 util 之后没有将服务侧切过去——那是重复的第二遍,不是本笔引入的。
*/
public class AppearancePatentResultPackager {
private static final String DEFAULT_STEM = "appearance-patent";
private static final String DEFAULT_RESULT_FILENAME = "appearance-patent-result.xlsx";
private static final int ZIP_BUFFER_SIZE = 8192;
/** 一个源文件对应一批待写行的分组(顺序即分组首次出现的顺序)。 */
public record SourceRows(String sourceFileKey,
String sourceFilename,
List<AppearancePatentParsedRowVo> rows) {
}
/** 一份已写好的成品:临时文件、对外文件名、行数(zip 与单文件两条路共用这个形状)。 */
public record SourceResultWorkbook(File file,
String filename,
int rowCount) {
}
/**
* 按源文件把收到的行分组:先按解析载荷里声明的文件建骨架(保持用户上传顺序),
* 再按行自身的 {@code sourceFileKey} 归位——取不到 key 时回落 {@code sourceFilename},
* 两者都空才落 {@code __default__}。空组不输出。
*/
public List<SourceRows> splitRowsBySourceFile(AppearancePatentParsedPayloadDto parsed,
List<AppearancePatentParsedRowVo> receivedRows,
String fallbackFilename) {
String defaultFilename = AppearancePatentRowNormalizer.firstNonBlank(fallbackFilename, DEFAULT_STEM);
Map<String, SourceRowsBuilder> builders = new LinkedHashMap<>();
if (parsed != null && parsed.getSourceFiles() != null) {
for (AppearancePatentSourceFileDto sourceFile : parsed.getSourceFiles()) {
if (sourceFile == null) {
continue;
}
String sourceFileKey = AppearancePatentRowNormalizer.normalize(sourceFile.getFileKey());
if (sourceFileKey.isBlank()) {
continue;
}
builders.putIfAbsent(sourceFileKey, new SourceRowsBuilder(sourceFileKey,
AppearancePatentRowNormalizer.firstNonBlank(sourceFile.getOriginalFilename(), defaultFilename)));
}
}
for (AppearancePatentParsedRowVo row : receivedRows == null
? List.<AppearancePatentParsedRowVo>of() : receivedRows) {
if (row == null) {
continue;
}
String sourceFileKey = AppearancePatentRowNormalizer.normalize(row.getSourceFileKey());
if (sourceFileKey.isBlank()) {
sourceFileKey = AppearancePatentRowNormalizer.normalize(row.getSourceFilename());
}
if (sourceFileKey.isBlank()) {
sourceFileKey = "__default__";
}
SourceRowsBuilder builder = builders.computeIfAbsent(sourceFileKey,
key -> new SourceRowsBuilder(key, AppearancePatentRowNormalizer.firstNonBlank(
row.getSourceFilename(), defaultFilename)));
if (builder.sourceFilename().isBlank() || Objects.equals(builder.sourceFilename(), defaultFilename)) {
builder.setSourceFilename(AppearancePatentRowNormalizer.firstNonBlank(
row.getSourceFilename(), defaultFilename));
}
builder.rows().add(row);
}
return builders.values().stream()
.filter(builder -> !builder.rows().isEmpty())
.map(builder -> new SourceRows(builder.sourceFileKey(),
AppearancePatentRowNormalizer.firstNonBlank(builder.sourceFilename(), defaultFilename),
builder.rows()))
.toList();
}
/** 多份成品压一个 zip;条目名去重,读流失败即整包拒收(文案与原实现同句)。 */
public void packageResultWorkbooksAsZip(File zip, List<SourceResultWorkbook> workbooks) {
Set<String> entryNames = new LinkedHashSet<>();
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip))) {
byte[] buffer = new byte[ZIP_BUFFER_SIZE];
for (SourceResultWorkbook workbook : workbooks) {
writeResultZipEntry(zos, buffer, workbook.file(), uniqueZipEntryName(workbook.filename(), entryNames));
}
} catch (IOException ex) {
throw new BusinessException("生成外观专利检测结果压缩包失败");
}
}
/** 文件名去掉扩展名、把 Windows 非法字符换成下划线;空结果兜底 {@code appearance-patent}。 */
public String safeFileStem(String filename) {
String name = filename == null || filename.isBlank() ? DEFAULT_STEM : filename;
int idx = name.lastIndexOf('.');
if (idx > 0) {
name = name.substring(0, idx);
}
String safe = name.replaceAll("[\\\\/:*?\"<>|]", "_").trim();
return safe.isBlank() ? DEFAULT_STEM : safe;
}
private void writeResultZipEntry(ZipOutputStream zos,
byte[] buffer,
File file,
String entryName) throws IOException {
zos.putNextEntry(new ZipEntry(entryName));
try (FileInputStream inputStream = new FileInputStream(file)) {
int len;
while ((len = inputStream.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
}
zos.closeEntry();
}
private String uniqueZipEntryName(String filename, Set<String> entryNames) {
String safeFilename = normalizeZipFilename(filename);
if (entryNames.add(safeFilename)) {
return safeFilename;
}
int dotIndex = safeFilename.lastIndexOf('.');
String stem = dotIndex > 0 ? safeFilename.substring(0, dotIndex) : safeFilename;
String extension = dotIndex > 0 ? safeFilename.substring(dotIndex) : "";
int index = 2;
while (true) {
String candidate = stem + "(" + index + ")" + extension;
if (entryNames.add(candidate)) {
return candidate;
}
index++;
}
}
private String normalizeZipFilename(String filename) {
String normalized = AppearancePatentRowNormalizer.firstNonBlank(filename, DEFAULT_RESULT_FILENAME)
.replace('\\', '/');
while (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
return normalized.isBlank() ? DEFAULT_RESULT_FILENAME : normalized;
}
private static final class SourceRowsBuilder {
private final String sourceFileKey;
private String sourceFilename;
private final List<AppearancePatentParsedRowVo> rows = new ArrayList<>();
private SourceRowsBuilder(String sourceFileKey, String sourceFilename) {
this.sourceFileKey = sourceFileKey;
this.sourceFilename = sourceFilename;
}
private String sourceFileKey() {
return sourceFileKey;
}
private String sourceFilename() {
return sourceFilename;
}
private void setSourceFilename(String sourceFilename) {
this.sourceFilename = sourceFilename;
}
private List<AppearancePatentParsedRowVo> rows() {
return rows;
}
}
}