TeamImportRunner.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. package tools.team_import;
  2. import java.io.PrintWriter;
  3. import java.lang.reflect.Field;
  4. import java.nio.charset.StandardCharsets;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.sql.Connection;
  8. import java.sql.Date;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.Statement;
  12. import java.sql.Timestamp;
  13. import java.time.LocalDate;
  14. import java.util.ArrayList;
  15. import java.util.LinkedHashMap;
  16. import java.util.LinkedHashSet;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.Set;
  20. import ss.db.Db;
  21. /**
  22. * 沙溪团体信息一次性导入工具。
  23. *
  24. * 由临时 JSP 在应用容器内调用,以复用 JNDI 数据源。
  25. */
  26. public class TeamImportRunner {
  27. private static final long TEACHER_ID = 111148350L;
  28. private static final String EFFECTIVE_DATE = "2026-11-01";
  29. private static final String SCHOOL_YEAR = "2026-2027";
  30. public static String run(Db db, String groupFile, String memberFile,
  31. String batchId, boolean execute) throws Exception {
  32. List<GroupRow> groups = rdGroups(Path.of(groupFile));
  33. List<MemberRow> members = rdMembers(Path.of(memberFile), groups);
  34. validate(groups, members);
  35. StringBuilder report = new StringBuilder();
  36. report.append("mode=").append(execute ? "EXECUTE" : "DRY_RUN")
  37. .append('\n');
  38. report.append("batch=").append(batchId).append('\n');
  39. report.append("TT=").append(groups.size()).append('\n');
  40. report.append("TTCY=").append(members.size()).append('\n');
  41. report.append("TTWCY=").append(members.stream()
  42. .filter(row -> row.memberTable.equals("TTWCY")).count())
  43. .append('\n');
  44. if (!execute) {
  45. report.append("DRY_RUN_OK\n");
  46. return report.toString();
  47. }
  48. Field connField = Db.class.getDeclaredField("conn");
  49. connField.setAccessible(true);
  50. Connection connection = (Connection) connField.get(db);
  51. String user = scalarString(connection, "select user from dual");
  52. if (!"PMS_TEST".equals(user)) {
  53. throw new IllegalStateException("refusing import: current user is " + user);
  54. }
  55. ensureImportTables(connection);
  56. backupTables(connection, report);
  57. if (count(connection,
  58. "select count(*) from XJB_TT_IMPORT_BATCH where IMPORT_BATCH_ID=?",
  59. batchId) > 0) {
  60. throw new IllegalStateException("import batch already exists: " + batchId);
  61. }
  62. connection.setAutoCommit(false);
  63. try {
  64. insertBatch(connection, batchId, "RUNNING", groups.size(),
  65. members.size(), (int) countRoleRows(members), 4);
  66. ImportCounts counts = new ImportCounts();
  67. Map<GroupKey, Long> groupIds =
  68. importGroups(connection, groups, counts);
  69. importMembers(connection, batchId, members, groupIds, counts);
  70. updateBatch(connection, batchId, "SUCCESS", counts);
  71. connection.commit();
  72. report.append("createdTT=").append(counts.createdGroups).append('\n');
  73. report.append("reusedTT=").append(counts.reusedGroups).append('\n');
  74. report.append("createdTTCY=").append(counts.createdMembers).append('\n');
  75. report.append("reusedTTCY=").append(counts.reusedMembers).append('\n');
  76. report.append("createdTTWCY=").append(counts.createdRoles).append('\n');
  77. report.append("reusedTTWCY=").append(counts.reusedRoles).append('\n');
  78. report.append("IMPORT_OK\n");
  79. return report.toString();
  80. } catch (Exception error) {
  81. connection.rollback();
  82. throw error;
  83. }
  84. }
  85. private static List<GroupRow> rdGroups(Path path) throws Exception {
  86. List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
  87. Map<String, Integer> idx = indexes(lines.get(0));
  88. List<GroupRow> result = new ArrayList<>();
  89. for (int i = 1; i < lines.size(); i++) {
  90. if (lines.get(i).isBlank())
  91. continue;
  92. String[] cols = lines.get(i).split("\t", -1);
  93. result.add(new GroupRow(
  94. cols[idx.get("group_name")],
  95. Integer.parseInt(cols[idx.get("ttlbm")]),
  96. Long.parseLong(cols[idx.get("fzbmid")])));
  97. }
  98. return result;
  99. }
  100. private static List<MemberRow> rdMembers(
  101. Path path, List<GroupRow> groups) throws Exception {
  102. Map<GroupKey, GroupRow> groupMap = new LinkedHashMap<>();
  103. for (GroupRow group : groups)
  104. groupMap.put(group.key(), group);
  105. List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
  106. Map<String, Integer> idx = indexes(lines.get(0));
  107. List<MemberRow> result = new ArrayList<>();
  108. for (int i = 1; i < lines.size(); i++) {
  109. if (lines.get(i).isBlank())
  110. continue;
  111. String[] cols = lines.get(i).split("\t", -1);
  112. GroupKey key = new GroupKey(
  113. cols[idx.get("group_name")],
  114. Integer.parseInt(cols[idx.get("ttlbm")]),
  115. Long.parseLong(cols[idx.get("fzbmid")]));
  116. if (!groupMap.containsKey(key))
  117. throw new IllegalArgumentException(
  118. "group missing in manifest: " + key);
  119. String memberTable = cols[idx.get("member_table")];
  120. int roleCode = 0;
  121. if ("TTWCY".equals(memberTable)) {
  122. roleCode = Integer.parseInt(cols[idx.get("role_code")]);
  123. } else if (!"TTCY".equals(memberTable)) {
  124. throw new IllegalArgumentException(
  125. "invalid member table: " + memberTable);
  126. }
  127. result.add(new MemberRow(
  128. cols[idx.get("source_id")],
  129. key,
  130. Long.parseLong(cols[idx.get("ryid")]),
  131. Long.parseLong(cols[idx.get("bjid")]),
  132. cols[idx.get("source_student_name")],
  133. cols[idx.get("matched_name")],
  134. cols[idx.get("role_name")],
  135. cols[idx.get("role_category")],
  136. roleCode,
  137. memberTable,
  138. cols[idx.get("match_basis")]));
  139. }
  140. return result;
  141. }
  142. private static Map<String, Integer> indexes(String header) {
  143. String[] names = header.split("\t", -1);
  144. Map<String, Integer> result = new LinkedHashMap<>();
  145. for (int i = 0; i < names.length; i++)
  146. result.put(names[i], i);
  147. return result;
  148. }
  149. private static void validate(
  150. List<GroupRow> groups, List<MemberRow> members) {
  151. if (groups.size() != 15)
  152. throw new IllegalArgumentException("expected 15 groups");
  153. if (members.size() != 919)
  154. throw new IllegalArgumentException("expected 919 members");
  155. long roleCount = members.stream()
  156. .filter(row -> row.memberTable.equals("TTWCY")).count();
  157. if (roleCount != 892)
  158. throw new IllegalArgumentException("expected 892 role records");
  159. Set<String> memberKeys = new LinkedHashSet<>();
  160. for (MemberRow row : members) {
  161. String key = row.group + "|" + row.ryid;
  162. if (!memberKeys.add(key))
  163. throw new IllegalArgumentException(
  164. "duplicate group member: " + key);
  165. }
  166. }
  167. private static void ensureImportTables(Connection connection)
  168. throws Exception {
  169. executeIfMissing(connection, "table", "XJB_TT_IMPORT_BATCH",
  170. "create table XJB_TT_IMPORT_BATCH("
  171. + "IMPORT_BATCH_ID varchar2(32) primary key,"
  172. + "STATUS varchar2(16) not null,"
  173. + "TT_COUNT number not null,"
  174. + "TTCY_COUNT number not null,"
  175. + "TTWCY_COUNT number not null,"
  176. + "EXCLUDED_COUNT number not null,"
  177. + "CREATED_AT date not null,"
  178. + "FINISHED_AT date,"
  179. + "MSG varchar2(500))");
  180. executeIfMissing(connection, "table", "XJB_TT_IMPORT_MAP",
  181. "create table XJB_TT_IMPORT_MAP("
  182. + "MAP_ID number primary key,"
  183. + "IMPORT_BATCH_ID varchar2(32) not null,"
  184. + "SOURCE_ID varchar2(32) not null,"
  185. + "GROUP_NAME varchar2(100) not null,"
  186. + "TTID number not null,"
  187. + "TTCYID number not null,"
  188. + "TTWCYID number,"
  189. + "RYID number not null,"
  190. + "STATUS varchar2(16) not null,"
  191. + "CREATED_AT date not null)");
  192. executeIfMissing(connection, "sequence", "XJB_TT_IMPORT_MAP_SEQ",
  193. "create sequence XJB_TT_IMPORT_MAP_SEQ start with 1 increment by 1");
  194. }
  195. private static void backupTables(
  196. Connection connection, StringBuilder report) throws Exception {
  197. for (String table : List.of("TT", "TTCY", "TTWCY")) {
  198. String backup = "BAK_20261109_GROUP_IMPORT_" + table;
  199. if (count(connection,
  200. "select count(*) from user_tables where table_name=?",
  201. backup) == 0) {
  202. try (Statement statement = connection.createStatement()) {
  203. statement.execute("create table " + backup
  204. + " as select * from " + table);
  205. }
  206. }
  207. report.append(backup).append('=')
  208. .append(scalarLong(
  209. connection, "select count(*) from " + backup))
  210. .append('\n');
  211. }
  212. }
  213. private static void executeIfMissing(
  214. Connection connection, String type, String name, String sql)
  215. throws Exception {
  216. long exists;
  217. if ("sequence".equals(type)) {
  218. exists = count(connection,
  219. "select count(*) from user_sequences where sequence_name=?", name);
  220. } else {
  221. exists = count(connection,
  222. "select count(*) from user_tables where table_name=?", name);
  223. }
  224. if (exists == 0) {
  225. try (Statement statement = connection.createStatement()) {
  226. statement.execute(sql);
  227. }
  228. }
  229. }
  230. private static void insertBatch(
  231. Connection connection, String batchId, String status,
  232. int ttCount, int ttcyCount, int ttwcyCount, int excludedCount)
  233. throws Exception {
  234. try (PreparedStatement statement = connection.prepareStatement(
  235. "insert into XJB_TT_IMPORT_BATCH("
  236. + "IMPORT_BATCH_ID,STATUS,TT_COUNT,TTCY_COUNT,"
  237. + "TTWCY_COUNT,EXCLUDED_COUNT,CREATED_AT)"
  238. + " values(?,?,?,?,?,?,?)")) {
  239. statement.setString(1, batchId);
  240. statement.setString(2, status);
  241. statement.setInt(3, ttCount);
  242. statement.setInt(4, ttcyCount);
  243. statement.setInt(5, ttwcyCount);
  244. statement.setInt(6, excludedCount);
  245. statement.setTimestamp(7, new Timestamp(System.currentTimeMillis()));
  246. statement.executeUpdate();
  247. }
  248. }
  249. private static void updateBatch(
  250. Connection connection, String batchId, String status,
  251. ImportCounts counts) throws Exception {
  252. try (PreparedStatement statement = connection.prepareStatement(
  253. "update XJB_TT_IMPORT_BATCH set STATUS=?,FINISHED_AT=?,MSG=?"
  254. + " where IMPORT_BATCH_ID=?")) {
  255. statement.setString(1, status);
  256. statement.setTimestamp(2, new Timestamp(System.currentTimeMillis()));
  257. statement.setString(3,
  258. "createdTT=" + counts.createdGroups
  259. + ",reusedTT=" + counts.reusedGroups
  260. + ",createdTTCY=" + counts.createdMembers
  261. + ",reusedTTCY=" + counts.reusedMembers
  262. + ",createdTTWCY=" + counts.createdRoles
  263. + ",reusedTTWCY=" + counts.reusedRoles);
  264. statement.setString(4, batchId);
  265. statement.executeUpdate();
  266. }
  267. }
  268. private static Map<GroupKey, Long> importGroups(
  269. Connection connection, List<GroupRow> groups,
  270. ImportCounts counts) throws Exception {
  271. Map<GroupKey, Long> result = new LinkedHashMap<>();
  272. for (GroupRow group : groups) {
  273. long id = findGroup(connection, group);
  274. if (id == 0) {
  275. try (PreparedStatement statement = connection.prepareStatement(
  276. "insert into TT(MC,TTLBM,FZBMID,FZRYID,KSRQ,XNDM,"
  277. + "JLZTM,CJRYID,GLRYID,GLBMID,MS)"
  278. + " values(?,?,?,?,?,?,?,?,?,?,?)")) {
  279. statement.setString(1, group.name);
  280. statement.setInt(2, group.ttlbm);
  281. statement.setLong(3, group.fzbmid);
  282. statement.setLong(4, TEACHER_ID);
  283. statement.setDate(5, Date.valueOf(EFFECTIVE_DATE));
  284. statement.setString(6, SCHOOL_YEAR);
  285. statement.setInt(7, 51);
  286. statement.setLong(8, TEACHER_ID);
  287. statement.setLong(9, TEACHER_ID);
  288. statement.setLong(10, group.fzbmid);
  289. statement.setString(11, "团体信息导入");
  290. statement.executeUpdate();
  291. }
  292. id = findGroup(connection, group);
  293. counts.createdGroups++;
  294. } else {
  295. counts.reusedGroups++;
  296. }
  297. if (id == 0)
  298. throw new IllegalStateException("TT insert failed: " + group);
  299. result.put(group.key(), id);
  300. }
  301. return result;
  302. }
  303. private static long findGroup(Connection connection, GroupRow group)
  304. throws Exception {
  305. try (PreparedStatement statement = connection.prepareStatement(
  306. "select TTID from TT where MC=? and TTLBM=? and FZBMID=?"
  307. + " order by TTID")) {
  308. statement.setString(1, group.name);
  309. statement.setInt(2, group.ttlbm);
  310. statement.setLong(3, group.fzbmid);
  311. try (ResultSet result = statement.executeQuery()) {
  312. if (!result.next())
  313. return 0L;
  314. long id = result.getLong(1);
  315. if (result.next())
  316. throw new IllegalStateException(
  317. "multiple TT rows for " + group);
  318. return id;
  319. }
  320. }
  321. }
  322. private static void importMembers(
  323. Connection connection, String batchId, List<MemberRow> members,
  324. Map<GroupKey, Long> groupIds, ImportCounts counts) throws Exception {
  325. for (MemberRow row : members) {
  326. long ttid = groupIds.get(row.group);
  327. long ttcyid = findTtcy(connection, ttid, row.ryid);
  328. if (ttcyid == 0) {
  329. try (PreparedStatement statement = connection.prepareStatement(
  330. "insert into TTCY(TTID,RYID,KSRQ,XNDM,JLZTM,"
  331. + "CJRYID,GLRYID,GLBMID)"
  332. + " values(?,?,?,?,?,?,?,?)")) {
  333. statement.setLong(1, ttid);
  334. statement.setLong(2, row.ryid);
  335. statement.setDate(3, Date.valueOf(EFFECTIVE_DATE));
  336. statement.setString(4, SCHOOL_YEAR);
  337. statement.setInt(5, 51);
  338. statement.setLong(6, TEACHER_ID);
  339. statement.setLong(7, TEACHER_ID);
  340. statement.setLong(8, row.group.fzbmid);
  341. statement.executeUpdate();
  342. }
  343. ttcyid = findTtcy(connection, ttid, row.ryid);
  344. counts.createdMembers++;
  345. } else {
  346. counts.reusedMembers++;
  347. }
  348. if (ttcyid == 0)
  349. throw new IllegalStateException("TTCY insert failed: " + row.sourceId);
  350. Long ttwcyid = null;
  351. if ("TTWCY".equals(row.memberTable)) {
  352. long roleId = findTtwcy(
  353. connection, ttid, row.ryid, row.roleCode);
  354. if (roleId == 0) {
  355. try (PreparedStatement statement = connection.prepareStatement(
  356. "insert into TTWCY(TTID,RYID,TTWCYLBM,ZWMC,"
  357. + "KSRQ,XNDM,JLZTM,CJRYID,GLRYID,GLBMID)"
  358. + " values(?,?,?,?,?,?,?,?,?,?)")) {
  359. statement.setLong(1, ttid);
  360. statement.setLong(2, row.ryid);
  361. statement.setInt(3, row.roleCode);
  362. statement.setString(4, row.roleName);
  363. statement.setDate(5, Date.valueOf(EFFECTIVE_DATE));
  364. statement.setString(6, SCHOOL_YEAR);
  365. statement.setInt(7, 51);
  366. statement.setLong(8, TEACHER_ID);
  367. statement.setLong(9, TEACHER_ID);
  368. statement.setLong(10, row.group.fzbmid);
  369. statement.executeUpdate();
  370. }
  371. roleId = findTtwcy(
  372. connection, ttid, row.ryid, row.roleCode);
  373. counts.createdRoles++;
  374. } else {
  375. counts.reusedRoles++;
  376. }
  377. if (roleId == 0)
  378. throw new IllegalStateException(
  379. "TTWCY insert failed: " + row.sourceId);
  380. ttwcyid = roleId;
  381. }
  382. try (PreparedStatement statement = connection.prepareStatement(
  383. "insert into XJB_TT_IMPORT_MAP("
  384. + "MAP_ID,IMPORT_BATCH_ID,SOURCE_ID,GROUP_NAME,"
  385. + "TTID,TTCYID,TTWCYID,RYID,STATUS,CREATED_AT)"
  386. + " values(XJB_TT_IMPORT_MAP_SEQ.nextval,?,?,?,?,?,?,?,?,?)")) {
  387. statement.setString(1, batchId);
  388. statement.setString(2, row.sourceId);
  389. statement.setString(3, row.group.name);
  390. statement.setLong(4, ttid);
  391. statement.setLong(5, ttcyid);
  392. if (ttwcyid == null)
  393. statement.setNull(6, java.sql.Types.NUMERIC);
  394. else
  395. statement.setLong(6, ttwcyid);
  396. statement.setLong(7, row.ryid);
  397. statement.setString(8,
  398. ttwcyid == null ? "TTCY_ONLY" : "TTCY_TTWCY");
  399. statement.setTimestamp(9,
  400. new Timestamp(System.currentTimeMillis()));
  401. statement.executeUpdate();
  402. }
  403. }
  404. }
  405. private static long findTtcy(
  406. Connection connection, long ttid, long ryid) throws Exception {
  407. try (PreparedStatement statement = connection.prepareStatement(
  408. "select TTCYID from TTCY where TTID=? and RYID=? and JLZTM=51")) {
  409. statement.setLong(1, ttid);
  410. statement.setLong(2, ryid);
  411. try (ResultSet result = statement.executeQuery()) {
  412. return result.next() ? result.getLong(1) : 0L;
  413. }
  414. }
  415. }
  416. private static long findTtwcy(
  417. Connection connection, long ttid, long ryid, int roleCode)
  418. throws Exception {
  419. try (PreparedStatement statement = connection.prepareStatement(
  420. "select TTWCYID from TTWCY where TTID=? and RYID=?"
  421. + " and TTWCYLBM=? and JLZTM=51")) {
  422. statement.setLong(1, ttid);
  423. statement.setLong(2, ryid);
  424. statement.setInt(3, roleCode);
  425. try (ResultSet result = statement.executeQuery()) {
  426. return result.next() ? result.getLong(1) : 0L;
  427. }
  428. }
  429. }
  430. private static long countRoleRows(List<MemberRow> members) {
  431. return members.stream()
  432. .filter(row -> "TTWCY".equals(row.memberTable)).count();
  433. }
  434. private static long count(
  435. Connection connection, String sql, String value) throws Exception {
  436. try (PreparedStatement statement = connection.prepareStatement(sql)) {
  437. statement.setString(1, value);
  438. try (ResultSet result = statement.executeQuery()) {
  439. result.next();
  440. return result.getLong(1);
  441. }
  442. }
  443. }
  444. private static long scalarLong(Connection connection, String sql)
  445. throws Exception {
  446. try (Statement statement = connection.createStatement();
  447. ResultSet result = statement.executeQuery(sql)) {
  448. result.next();
  449. return result.getLong(1);
  450. }
  451. }
  452. private static String scalarString(Connection connection, String sql)
  453. throws Exception {
  454. try (Statement statement = connection.createStatement();
  455. ResultSet result = statement.executeQuery(sql)) {
  456. result.next();
  457. return result.getString(1);
  458. }
  459. }
  460. private static final class GroupKey {
  461. final String name;
  462. final int ttlbm;
  463. final long fzbmid;
  464. GroupKey(String name, int ttlbm, long fzbmid) {
  465. this.name = name;
  466. this.ttlbm = ttlbm;
  467. this.fzbmid = fzbmid;
  468. }
  469. @Override
  470. public boolean equals(Object other) {
  471. if (!(other instanceof GroupKey))
  472. return false;
  473. GroupKey key = (GroupKey) other;
  474. return name.equals(key.name)
  475. && ttlbm == key.ttlbm && fzbmid == key.fzbmid;
  476. }
  477. @Override
  478. public int hashCode() {
  479. return java.util.Objects.hash(name, ttlbm, fzbmid);
  480. }
  481. @Override
  482. public String toString() {
  483. return name + "/" + ttlbm + "/" + fzbmid;
  484. }
  485. }
  486. private static final class GroupRow {
  487. final String name;
  488. final int ttlbm;
  489. final long fzbmid;
  490. GroupRow(String name, int ttlbm, long fzbmid) {
  491. this.name = name;
  492. this.ttlbm = ttlbm;
  493. this.fzbmid = fzbmid;
  494. }
  495. GroupKey key() {
  496. return new GroupKey(name, ttlbm, fzbmid);
  497. }
  498. }
  499. private static final class MemberRow {
  500. final String sourceId;
  501. final GroupKey group;
  502. final long ryid;
  503. final long bjid;
  504. final String sourceName;
  505. final String matchedName;
  506. final String roleName;
  507. final String roleCategory;
  508. final int roleCode;
  509. final String memberTable;
  510. final String matchBasis;
  511. MemberRow(String sourceId, GroupKey group, long ryid, long bjid,
  512. String sourceName, String matchedName, String roleName,
  513. String roleCategory, int roleCode, String memberTable,
  514. String matchBasis) {
  515. this.sourceId = sourceId;
  516. this.group = group;
  517. this.ryid = ryid;
  518. this.bjid = bjid;
  519. this.sourceName = sourceName;
  520. this.matchedName = matchedName;
  521. this.roleName = roleName;
  522. this.roleCategory = roleCategory;
  523. this.roleCode = roleCode;
  524. this.memberTable = memberTable;
  525. this.matchBasis = matchBasis;
  526. }
  527. }
  528. private static final class ImportCounts {
  529. int createdGroups;
  530. int reusedGroups;
  531. int createdMembers;
  532. int reusedMembers;
  533. int createdRoles;
  534. int reusedRoles;
  535. }
  536. }