RepairSkuDuration.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. import java.io.Console;
  2. import java.io.IOException;
  3. import java.nio.charset.StandardCharsets;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.StandardOpenOption;
  7. import java.sql.Connection;
  8. import java.sql.DriverManager;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.sql.Statement;
  13. import java.time.Duration;
  14. import java.time.LocalDateTime;
  15. import java.time.format.DateTimeFormatter;
  16. import java.util.ArrayList;
  17. import java.util.Arrays;
  18. import java.util.Collections;
  19. import java.util.LinkedHashMap;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Properties;
  23. import java.util.stream.Collectors;
  24. /** Standalone, read-only MySQL inspection. Never starts the Spring application. */
  25. public final class RepairSkuDuration {
  26. private static final DateTimeFormatter SQL_TIME =
  27. DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
  28. private static final String VALID_ORDER = "o.status NOT IN ('close','noPayment','refund')";
  29. static final class Ticket {
  30. long id, groupsId, skuId, userId;
  31. String status;
  32. LocalDateTime start, expiry, updated;
  33. boolean frozen, recover, vip;
  34. int reservedDays, compensationDays;
  35. int aqType = 1;
  36. }
  37. static final class Purchase {
  38. long id, skuId;
  39. int orderType = 1, quantity = 1;
  40. boolean slot;
  41. }
  42. static final class Decision {
  43. final String kind, reason;
  44. final LocalDateTime newExpiry;
  45. final double deltaSeconds;
  46. Decision(String kind, String reason, LocalDateTime newExpiry, double deltaSeconds) {
  47. this.kind = kind;
  48. this.reason = reason;
  49. this.newExpiry = newExpiry;
  50. this.deltaSeconds = deltaSeconds;
  51. }
  52. }
  53. static Decision classify(Ticket ticket, List<Purchase> purchases, int adjustmentCount) {
  54. if (ticket.skuId != 772 && ticket.skuId != 774) {
  55. return new Decision("skipped", "其他规格", null, Double.NaN);
  56. }
  57. if (ticket.start == null || ticket.expiry == null) {
  58. return new Decision("skipped", "未设置完整起止时间", null, Double.NaN);
  59. }
  60. LocalDateTime expected = ticket.start.plusMonths(12);
  61. Duration delta = Duration.between(expected, ticket.expiry);
  62. double deltaSeconds = delta.getSeconds() + delta.getNano() / 1_000_000_000.0;
  63. if (!delta.isZero()) {
  64. // Include small differences straddling midnight, but never silently accept them.
  65. if (Math.abs(deltaSeconds) <= 60
  66. || expected.toLocalDate().equals(ticket.expiry.toLocalDate())) {
  67. return new Decision("review", "接近一年,但时间不精确相等", null, deltaSeconds);
  68. }
  69. return new Decision("skipped", "时长不是12个自然月", null, deltaSeconds);
  70. }
  71. List<String> reasons = new ArrayList<>();
  72. if (ticket.userId <= 0 || !("validity".equals(ticket.status) || "outside".equals(ticket.status))) {
  73. reasons.add("无当前用户或车票状态需核对");
  74. }
  75. if (ticket.frozen || ticket.recover || ticket.reservedDays != 0) {
  76. reasons.add("冻结/恢复/保留天数");
  77. }
  78. if (ticket.compensationDays != 0 || adjustmentCount != 0) {
  79. reasons.add("存在补偿或手工时长调整");
  80. }
  81. if (ticket.vip || ticket.aqType != 1) {
  82. reasons.add("VIP或非普通购买车票");
  83. }
  84. if (purchases.size() != 1) {
  85. reasons.add("有效关联订单不是一笔");
  86. } else {
  87. Purchase purchase = purchases.get(0);
  88. if (purchase.orderType != 1) {
  89. reasons.add("续费或未知订单类型");
  90. }
  91. if (purchase.skuId != ticket.skuId) {
  92. reasons.add("订单规格与当前车票不一致");
  93. }
  94. if (purchase.quantity < 1 || (purchase.quantity > 1 && !purchase.slot)) {
  95. reasons.add("购买数量可能叠加时长");
  96. }
  97. }
  98. if (!reasons.isEmpty()) {
  99. return new Decision("review", String.join(";", reasons), null, deltaSeconds);
  100. }
  101. return new Decision("candidate", "精确一年且未发现续费/补时等情况,需核对后执行SQL",
  102. ticket.expiry.minusMonths(6), deltaSeconds);
  103. }
  104. // The generated update requires the inspected identity, timestamps and state to be unchanged.
  105. static String updateSql(Ticket ticket) {
  106. if ((ticket.skuId != 772 && ticket.skuId != 774) || ticket.start == null || ticket.expiry == null
  107. || !ticket.expiry.equals(ticket.start.plusMonths(12))) {
  108. throw new IllegalArgumentException("只能为精确一年且起止完整的目标规格生成更新");
  109. }
  110. return "UPDATE groups_relation gr\n"
  111. + "JOIN groups_trips gt ON gt.id = gr.groups_id\n"
  112. + "SET gr.expiry_time = " + literal(ticket.expiry.minusMonths(6)) + ", gr.update_time = NOW()\n"
  113. + "WHERE gr.id = " + ticket.id + " AND gr.groups_id = " + ticket.groupsId + "\n"
  114. + " AND gt.sku_id = " + ticket.skuId + " AND gr.user_id = " + ticket.userId + "\n"
  115. + " AND gr.start_time = " + literal(ticket.start) + "\n"
  116. + " AND gr.expiry_time = " + literal(ticket.expiry) + "\n"
  117. + " AND gr.update_time <=> " + literal(ticket.updated) + "\n"
  118. + " AND gr.status = '" + checkedStatus(ticket.status) + "'\n"
  119. + " AND COALESCE(gr.is_frozen, 0) = 0 AND COALESCE(gr.is_recover, 0) = 0\n"
  120. + " AND COALESCE(gr.reserved_days, 0) = 0 AND COALESCE(gr.compensation_days, 0) = 0\n"
  121. + " AND COALESCE(gr.is_vip, 0) = 0 AND gr.aq_type = 1;\n"
  122. + "SELECT " + ticket.id + " AS relation_id, ROW_COUNT() AS updated_rows;\n";
  123. }
  124. private static String checkedStatus(String status) {
  125. if (!"validity".equals(status) && !"outside".equals(status)) {
  126. throw new IllegalArgumentException("非有效车票不能生成更新");
  127. }
  128. return status;
  129. }
  130. private static String literal(LocalDateTime value) {
  131. return value == null ? "NULL" : "'" + SQL_TIME.format(value) + "'";
  132. }
  133. private static LocalDateTime date(ResultSet rs, String name) throws SQLException {
  134. // Reading DATETIME text avoids an unintended JVM/JDBC timezone conversion.
  135. String value = rs.getString(name);
  136. return value == null ? null : LocalDateTime.parse(value.replace(' ', 'T'));
  137. }
  138. private static List<Ticket> tickets(Connection connection) throws SQLException {
  139. String sql = "SELECT gr.id, gr.groups_id, gt.sku_id, gr.user_id, gr.status, "
  140. + "gr.start_time, gr.expiry_time, gr.update_time, gr.is_frozen, gr.is_recover, "
  141. + "gr.reserved_days, gr.compensation_days, gr.aq_type, gr.is_vip "
  142. + "FROM groups_relation gr JOIN groups_trips gt ON gt.id = gr.groups_id "
  143. + "WHERE gt.sku_id IN (772,774) ORDER BY gt.sku_id, gr.id";
  144. List<Ticket> tickets = new ArrayList<>();
  145. try (Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
  146. while (rs.next()) {
  147. Ticket ticket = new Ticket();
  148. ticket.id = rs.getLong("id");
  149. ticket.groupsId = rs.getLong("groups_id");
  150. ticket.skuId = rs.getLong("sku_id");
  151. ticket.userId = rs.getLong("user_id");
  152. ticket.status = rs.getString("status");
  153. ticket.start = date(rs, "start_time");
  154. ticket.expiry = date(rs, "expiry_time");
  155. ticket.updated = date(rs, "update_time");
  156. ticket.frozen = rs.getBoolean("is_frozen");
  157. ticket.recover = rs.getBoolean("is_recover");
  158. ticket.reservedDays = rs.getInt("reserved_days");
  159. ticket.compensationDays = rs.getInt("compensation_days");
  160. ticket.aqType = rs.getInt("aq_type");
  161. ticket.vip = rs.getBoolean("is_vip");
  162. tickets.add(ticket);
  163. }
  164. }
  165. return tickets;
  166. }
  167. private static void loadHistory(Connection connection, List<Ticket> batch,
  168. Map<Long, List<Purchase>> purchases, Map<Long, Integer> adjustments)
  169. throws SQLException {
  170. String marks = String.join(",", Collections.nCopies(batch.size(), "?"));
  171. String columns = "SELECT gr.id AS relation_id, o.id AS order_id, o.sku_id, o.order_type, o.num, ";
  172. String sql = columns + "0 AS via_slot FROM groups_relation gr "
  173. + "JOIN order_don o ON o.relation_id = gr.id AND o.user_id = gr.user_id "
  174. + "WHERE gr.id IN (" + marks + ") AND " + VALID_ORDER
  175. + " UNION ALL " + columns + "1 AS via_slot FROM groups_relation gr "
  176. + "JOIN order_don_ticket_record tr ON tr.relation_id = gr.id AND tr.status = 'success' "
  177. + "JOIN order_don o ON o.id = tr.order_id AND o.user_id = gr.user_id "
  178. + "WHERE gr.id IN (" + marks + ") AND " + VALID_ORDER;
  179. Map<Long, Map<Long, Purchase>> distinct = new LinkedHashMap<>();
  180. try (PreparedStatement stmt = connection.prepareStatement(sql)) {
  181. bindIds(stmt, batch, 1);
  182. bindIds(stmt, batch, batch.size() + 1);
  183. try (ResultSet rs = stmt.executeQuery()) {
  184. while (rs.next()) {
  185. long relationId = rs.getLong("relation_id");
  186. long orderId = rs.getLong("order_id");
  187. Purchase purchase = distinct.computeIfAbsent(relationId, key -> new LinkedHashMap<>())
  188. .computeIfAbsent(orderId, key -> new Purchase());
  189. purchase.id = orderId;
  190. purchase.skuId = rs.getLong("sku_id");
  191. purchase.orderType = rs.getInt("order_type");
  192. purchase.quantity = rs.getInt("num");
  193. purchase.slot |= rs.getBoolean("via_slot");
  194. }
  195. }
  196. }
  197. distinct.forEach((id, records) -> purchases.put(id, new ArrayList<>(records.values())));
  198. String adjustmentSql = "SELECT gr.id, COUNT(*) AS total FROM groups_relation gr "
  199. + "JOIN incr_expiry_time_record r ON r.relation_id = gr.id AND r.user_id = gr.user_id "
  200. + "WHERE gr.id IN (" + marks + ") GROUP BY gr.id";
  201. try (PreparedStatement stmt = connection.prepareStatement(adjustmentSql)) {
  202. bindIds(stmt, batch, 1);
  203. try (ResultSet rs = stmt.executeQuery()) {
  204. while (rs.next()) {
  205. adjustments.put(rs.getLong("id"), rs.getInt("total"));
  206. }
  207. }
  208. }
  209. }
  210. private static void bindIds(PreparedStatement stmt, List<Ticket> batch, int first) throws SQLException {
  211. for (int i = 0; i < batch.size(); i++) {
  212. stmt.setLong(first + i, batch.get(i).id);
  213. }
  214. }
  215. private static String csv(Object value) {
  216. String text = value == null ? "" : value.toString();
  217. return "\"" + text.replace("\"", "\"\"") + "\"";
  218. }
  219. private static void writeReports(Path directory, List<Ticket> tickets,
  220. Map<Long, List<Purchase>> purchases, Map<Long, Integer> adjustments)
  221. throws IOException {
  222. // A fresh output folder prevents overwriting an earlier inspection.
  223. Files.createDirectory(directory);
  224. StringBuilder report = new StringBuilder("\uFEFFrelation_id,sku_id,user_id,groups_id,status,start_time,"
  225. + "old_expiry_time,proposed_expiry_time,update_time,kind,reason,year_delta_seconds,"
  226. + "is_frozen,is_recover,reserved_days,compensation_days,aq_type,is_vip,orders,adjustment_count\n");
  227. StringBuilder sql = new StringBuilder("-- 仅包含候选车票;先核对同目录 preview.csv。\n"
  228. + "-- 这是日期和关联历史筛查,不能证明所有候选都是误设;人工确认错误范围后执行。\n"
  229. + "-- 每条更新使用旧时间和身份校验;updated_rows 应为 1,若为 0 则数据已变化或已修复。\n"
  230. + "-- 本程序未执行数据库写入;SQL 按同一连接分段执行,末尾手动提交或回滚。\n"
  231. + "-- 事务回滚要求 groups_relation 使用 InnoDB 等事务引擎。\n"
  232. + "START TRANSACTION;\n\n");
  233. Map<String, Integer> counts = new LinkedHashMap<>();
  234. for (Ticket ticket : tickets) {
  235. List<Purchase> orders = purchases.getOrDefault(ticket.id, Collections.emptyList());
  236. int adjustmentCount = adjustments.getOrDefault(ticket.id, 0);
  237. Decision decision = classify(ticket, orders, adjustmentCount);
  238. counts.merge(decision.kind, 1, Integer::sum);
  239. String orderInfo = orders.stream().map(order -> order.id + ":sku=" + order.skuId
  240. + ":type=" + order.orderType + ":num=" + order.quantity + ":slot=" + order.slot)
  241. .collect(Collectors.joining(";"));
  242. Object[] fields = {ticket.id, ticket.skuId, ticket.userId, ticket.groupsId, ticket.status,
  243. ticket.start, ticket.expiry, decision.newExpiry, ticket.updated,
  244. decision.kind, decision.reason, Double.isNaN(decision.deltaSeconds) ? "" : decision.deltaSeconds,
  245. ticket.frozen, ticket.recover, ticket.reservedDays, ticket.compensationDays,
  246. ticket.aqType, ticket.vip, orderInfo, adjustmentCount};
  247. report.append(Arrays.stream(fields).map(RepairSkuDuration::csv).collect(Collectors.joining(",")))
  248. .append('\n');
  249. if ("candidate".equals(decision.kind)) {
  250. sql.append(updateSql(ticket)).append('\n');
  251. }
  252. }
  253. sql.append("-- 在同一连接中二选一执行,必须结束上面的事务:\n-- COMMIT;\n-- ROLLBACK;\n");
  254. Files.writeString(directory.resolve("preview.csv"), report, StandardCharsets.UTF_8,
  255. StandardOpenOption.CREATE_NEW);
  256. Files.writeString(directory.resolve("repair.sql"), sql, StandardCharsets.UTF_8,
  257. StandardOpenOption.CREATE_NEW);
  258. System.out.println("只读检查完成,未修改数据库。车票总数:" + tickets.size() + ";分类:" + counts);
  259. System.out.println("输出目录:" + directory.toAbsolutePath());
  260. }
  261. private static String environment(String name) {
  262. String value = System.getenv(name);
  263. if (value == null || value.isBlank()) {
  264. throw new IllegalArgumentException("请设置环境变量 " + name);
  265. }
  266. return value;
  267. }
  268. public static void main(String[] args) throws Exception {
  269. if (args.length != 1 || "--help".equals(args[0])) {
  270. System.out.println("用法:java -cp <MySQL驱动路径> RepairSkuDuration.java <新建输出目录>\n"
  271. + "设置 DURATION_REPAIR_JDBC_URL、DURATION_REPAIR_DB_USER。\n"
  272. + "密码通过终端隐藏输入,或使用 DURATION_REPAIR_DB_PASSWORD。\n"
  273. + "只执行SELECT;生成 preview.csv 和 repair.sql;不修改数据库或规格配置。");
  274. return;
  275. }
  276. Path output = Path.of(args[0]).toAbsolutePath();
  277. if (Files.exists(output)) {
  278. throw new IllegalArgumentException("输出目录已存在,请使用一个新目录");
  279. }
  280. String url = environment("DURATION_REPAIR_JDBC_URL");
  281. if (!url.startsWith("jdbc:mysql:")) {
  282. throw new IllegalArgumentException("仅支持 MySQL JDBC URL");
  283. }
  284. Properties properties = new Properties();
  285. properties.setProperty("user", environment("DURATION_REPAIR_DB_USER"));
  286. String password = System.getenv("DURATION_REPAIR_DB_PASSWORD");
  287. if (password == null) {
  288. Console console = System.console();
  289. if (console == null) {
  290. throw new IllegalArgumentException("无交互终端,请设置 DURATION_REPAIR_DB_PASSWORD");
  291. }
  292. char[] chars = console.readPassword("数据库密码:");
  293. if (chars == null) {
  294. throw new IllegalArgumentException("未输入数据库密码");
  295. }
  296. password = new String(chars);
  297. Arrays.fill(chars, '\0');
  298. }
  299. properties.setProperty("password", password);
  300. properties.setProperty("connectTimeout", "10000");
  301. properties.setProperty("socketTimeout", "60000");
  302. List<Ticket> tickets;
  303. Map<Long, List<Purchase>> purchases = new LinkedHashMap<>();
  304. Map<Long, Integer> adjustments = new LinkedHashMap<>();
  305. try (Connection connection = DriverManager.getConnection(url, properties)) {
  306. connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
  307. connection.setReadOnly(true);
  308. connection.setAutoCommit(false);
  309. try {
  310. // Enforce read-only on the server as well as through JDBC.
  311. try (Statement stmt = connection.createStatement()) {
  312. stmt.execute("START TRANSACTION WITH CONSISTENT SNAPSHOT, READ ONLY");
  313. }
  314. tickets = tickets(connection);
  315. for (int offset = 0; offset < tickets.size(); offset += 200) {
  316. loadHistory(connection, tickets.subList(offset, Math.min(offset + 200, tickets.size())),
  317. purchases, adjustments);
  318. }
  319. } finally {
  320. connection.rollback();
  321. }
  322. }
  323. writeReports(output, tickets, purchases, adjustments);
  324. }
  325. }