package com.battery.business.report;
|
|
import java.sql.Timestamp;
|
import java.util.List;
|
import javax.sql.DataSource;
|
import org.springframework.jdbc.core.JdbcTemplate;
|
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
import org.springframework.stereotype.Repository;
|
import com.ruoyi.common.exception.ServiceException;
|
|
/** 报表身份和版本存储;重读只访问报表表,不联查来源测试。 */
|
@Repository
|
public class CompareReportRepository
|
{
|
private final JdbcTemplate jdbc;
|
|
public CompareReportRepository(DataSource dataSource) { jdbc = new JdbcTemplate(dataSource); }
|
|
public record Summary(long id, String name, String creator, long createdAt) { }
|
public record Version(Summary report, int versionNo, String snapshotJson) { }
|
|
/** 查询所有已保存报表摘要,允许授权用户跨创建人查看。 */
|
public List<Summary> list()
|
{
|
return jdbc.query("select report_id, report_name, creator_name, created_at_utc from t_compare_report order by created_at_utc desc, report_id desc",
|
(rs, index) -> new Summary(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4).getTime()));
|
}
|
|
/** 重读首个完整版本;来源不存在不影响结果。 */
|
public Version get(long id)
|
{
|
var rows = jdbc.query("select r.report_id, r.report_name, r.creator_name, r.created_at_utc, v.version_no, v.snapshot_json "
|
+ "from t_compare_report r join t_compare_report_version v on v.report_id=r.report_id and v.version_no=1 where r.report_id=?",
|
(rs, index) -> new Version(new Summary(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getTimestamp(4).getTime()),
|
rs.getInt(5), rs.getString(6)), id);
|
if (rows.isEmpty()) throw new ServiceException("对比报表不存在");
|
return rows.get(0);
|
}
|
|
/** 由业务事务调用,身份与首个版本任一写入失败必须一起回滚。 */
|
public long insert(String name, String snapshot, long operatorId, String operatorName, long createdAt)
|
{
|
var keys = new GeneratedKeyHolder();
|
jdbc.update(connection -> {
|
var statement = connection.prepareStatement("insert into t_compare_report(report_name,creator_id,creator_name,created_at_utc) values(?,?,?,?)", java.sql.Statement.RETURN_GENERATED_KEYS);
|
statement.setString(1, name); statement.setLong(2, operatorId); statement.setString(3, operatorName);
|
statement.setTimestamp(4, new Timestamp(createdAt));
|
return statement;
|
}, keys);
|
long id = keys.getKey().longValue();
|
jdbc.update("insert into t_compare_report_version(report_id,version_no,snapshot_json,operator_id,operator_name,created_at_utc,change_summary) values(?,1,?,?,?,?,?)",
|
id, snapshot, operatorId, operatorName, new Timestamp(createdAt), "首次保存对比报表");
|
return id;
|
}
|
}
|