package com.example.rzgb.files; import com.example.rzgb.common.*; import com.example.rzgb.config.AppProperties; import com.example.rzgb.evidence.EvidenceService; import java.sql.Timestamp; import java.time.Instant; import java.util.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.multipart.MultipartFile; /** * 上传只允许 BID_PROJECT 用途。原件、全文和临时图片统一存储与删除, * 文件第一次绑定任务后不可转移;报告中的必要摘录按审计期限保留,不谎称随原件删除。 */ @Service public class BidFileService { private final JdbcTemplate jdbc; private final Json json; private final BidFileParser parser; private final AppProperties p; private final TransactionTemplate tx; private final EvidenceService evidence; public BidFileService(JdbcTemplate jdbc,Json json,BidFileParser parser,AppProperties p,TransactionTemplate tx,EvidenceService evidence) { this.jdbc=jdbc; this.json=json; this.parser=parser; this.p=p; this.tx=tx; this.evidence=evidence; } public Map upload(String owner,String purpose,MultipartFile file) { if(!"BID_PROJECT".equals(purpose)) throw new ApiException(400,"FILE_PURPOSE","文件仅用于投标项目,不支持公司档案导入"); if(file.isEmpty()||file.getSize()>p.maxFileBytes()) throw new ApiException(413,"FILE_LIMIT","文件为空或超过大小保护值,请拆分后上传"); try { String name=Objects.toString(file.getOriginalFilename(),"投标文件").replace('\\','/'); name=name.substring(name.lastIndexOf('/')+1).replaceAll("[\\p{Cntrl}]",""); if(name.length()>200||!name.contains(".")) throw new ApiException(400,"INVALID_FILENAME","文件名需包含后缀且不超过 200 字符"); byte[] bytes=file.getBytes(); var parsed=parser.parse(name,bytes); String id=UUID.randomUUID().toString(); jdbc.update("INSERT INTO temporary_file(id,user_id,purpose,media_type,sha256,status,expires_at,filename,original_bytes,segments_json) VALUES(?,?,'BID_PROJECT',?,?,'READY',?,?,?,?)", id,owner,parsed.mediaType(),EvidenceService.hash(Base64.getEncoder().encodeToString(bytes)),Timestamp.from(Instant.now().plusSeconds(p.fileRetentionHours()*3600L)),name,bytes,json.write(parsed.segments())); return get(owner,id); } catch(java.io.IOException e) { throw new ApiException(422,"FILE_READ_FAILED","文件读取失败,请重新上传"); } } public Map get(String owner,String id) { var row=tx.execute(s->{ var current=owned(owner,id,true); // 到期后即使定时清理尚未运行,也不能再把提取全文返回浏览器。 if("READY".equals(current.get("status"))&&!((Timestamp)current.get("expires_at")).toInstant().isAfter(Instant.now())) { wipe(owner,id,"EXPIRED"); return owned(owner,id,false); } return current; }); Map out=new LinkedHashMap<>(); for(String key:List.of("id","filename","purpose","media_type","status","task_id","expires_at","deleted_at")) out.put(key,row.get(key)); var segments=segments(row); out.put("segments",segments.stream().map(s->Map.of("locator",s.locator(),"text",s.text(),"needsVision",s.image()!=null)).toList()); out.put("notice","原件/全文/临时图片到期或手动删除;已写入报告的必要摘录和费用记录保留。图片与必要正文将发送后端配置的 DeepSeek 用于本次解析。"); return out; } /** 调用方已经锁定任务,锁文件后原子绑定,防止两个并发任务复用同一文件。 */ public List bind(String owner,String file,String task) { return tx.execute(s->{ var row=owned(owner,file,true); if(!"READY".equals(row.get("status"))||((Timestamp)row.get("expires_at")).toInstant().isBefore(Instant.now())) throw new ApiException(410,"FILE_EXPIRED","文件已删除或过期,请重新上传"); if(row.get("task_id")!=null&&!task.equals(row.get("task_id"))) throw new ApiException(409,"FILE_ALREADY_BOUND","文件已绑定其他项目任务,不能跨任务使用"); jdbc.update("UPDATE temporary_file SET task_id=? WHERE id=?",task,file); return segments(row); }); } @org.springframework.transaction.annotation.Transactional public String record(String owner,String file,String task) { var segments=bind(owner,file,task); String call=UUID.randomUUID().toString(); jdbc.update("INSERT INTO tool_call(id,task_id,provider,tool_name,client_version,status,cost_units) VALUES(?,?,'LOCAL','FILE_PARSE','D3','SUCCEEDED',0)",call,task); // 提取全文只留在有期限的 temporary_file;长期报告只留逐段必要摘录,不能把全文复制进审计表后声称已清理。 var visible=segments.stream().map(s->Map.of("locator",s.locator(),"text",s.text().substring(0,Math.min(2000,s.text().length())),"excerptOnly",s.text().length()>2000,"needsVision",s.image()!=null)).toList(); String name=owned(owner,file,false).get("filename").toString(); String ref=evidence.record(task,call,null,"文件 "+file,name,"用户上传投标文件;未经站内公告核实。每段仅保留最多 2000 字摘录,超出部分不属于报告证据。",json.read(json.write(Map.of("filename",name,"segments",visible)))); jdbc.update("UPDATE evidence SET source_type='USER_FILE' WHERE id=?",ref); return ref; } public void delete(String owner,String id) { tx.executeWithoutResult(s->{ owned(owner,id,true); wipe(owner,id,"MANUAL"); }); } @Scheduled(fixedDelay=60_000) public void expire() { // 查询只取标识,不载入可能较大的原件;每次最多清理 100 条,避免长事务。 for(var row:jdbc.queryForList("SELECT id,user_id FROM temporary_file WHERE status='READY' AND expires_at<=CURRENT_TIMESTAMP ORDER BY expires_at,id LIMIT 100")) tx.executeWithoutResult(s->{ var current=owned(row.get("user_id").toString(),row.get("id").toString(),true); if(!((Timestamp)current.get("expires_at")).toInstant().isAfter(Instant.now())) wipe(row.get("user_id").toString(),row.get("id").toString(),"EXPIRED"); }); } private void wipe(String owner,String id,String reason) { if(jdbc.update("UPDATE temporary_file SET status='DELETED',original_bytes=NULL,segments_json=NULL,storage_path=NULL,deleted_at=CURRENT_TIMESTAMP WHERE id=? AND status<>'DELETED'",id)>0) jdbc.update("INSERT INTO file_deletion_audit(id,file_id,user_id,reason) VALUES(?,?,?,?)",UUID.randomUUID().toString(),id,owner,reason); } private Map owned(String owner,String id,boolean lock) { var rows=jdbc.queryForList("SELECT * FROM temporary_file WHERE id=? AND user_id=?"+(lock?" FOR UPDATE":""),id,owner); if(rows.isEmpty()) throw new ApiException(404,"NOT_FOUND","文件不存在"); return rows.getFirst(); } private List segments(Map row) { if(row.get("segments_json")==null) return List.of(); return Arrays.asList(json.convert(row.get("segments_json").toString(),BidFileParser.Segment[].class)); } }