package tools.team_import; import java.io.PrintWriter; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.sql.Timestamp; import java.time.LocalDate; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import ss.db.Db; /** * 沙溪团体信息一次性导入工具。 * * 由临时 JSP 在应用容器内调用,以复用 JNDI 数据源。 */ public class TeamImportRunner { private static final long TEACHER_ID = 111148350L; private static final String EFFECTIVE_DATE = "2026-11-01"; private static final String SCHOOL_YEAR = "2026-2027"; private static final Set ALLOWED_SCHEMAS = Set.of("PMS_TEST", "C##DC"); public static String run(Db db, String groupFile, String memberFile, String batchId, boolean execute) throws Exception { return run(db, groupFile, memberFile, batchId, execute, "PMS_TEST"); } public static String run(Db db, String groupFile, String memberFile, String batchId, boolean execute, String expectedSchema) throws Exception { if (!ALLOWED_SCHEMAS.contains(expectedSchema)) throw new IllegalArgumentException( "unsupported schema: " + expectedSchema); List groups = rdGroups(Path.of(groupFile)); List members = rdMembers(Path.of(memberFile), groups); validate(groups, members); StringBuilder report = new StringBuilder(); report.append("mode=").append(execute ? "EXECUTE" : "DRY_RUN") .append('\n'); report.append("batch=").append(batchId).append('\n'); report.append("schema=").append(expectedSchema).append('\n'); report.append("TT=").append(groups.size()).append('\n'); report.append("TTCY=").append(members.size()).append('\n'); report.append("TTWCY=").append(members.stream() .filter(row -> row.memberTable.equals("TTWCY")).count()) .append('\n'); Field connField = Db.class.getDeclaredField("conn"); connField.setAccessible(true); Connection connection = (Connection) connField.get(db); String user = scalarString(connection, "select user from dual"); if (!expectedSchema.equals(user)) { throw new IllegalStateException("refusing import: expected schema " + expectedSchema + ", current user is " + user); } if (!execute) { report.append("columns=") .append(importColumnCount(connection)).append('\n'); int existingGroups = 0; for (GroupRow group : groups) { if (findGroup(connection, group) > 0) existingGroups++; } report.append("existingGroups=") .append(existingGroups).append('\n'); if (count(connection, "select count(*) from user_tables where table_name=?", "XJB_TT_IMPORT_BATCH") > 0) { report.append("batchExists=") .append(count(connection, "select count(*) from XJB_TT_IMPORT_BATCH " + "where IMPORT_BATCH_ID=?", batchId)) .append('\n'); } else { report.append("batchExists=table_missing\n"); } report.append("DRY_RUN_OK\n"); return report.toString(); } ensureImportTables(connection); backupTables(connection, report); if (count(connection, "select count(*) from XJB_TT_IMPORT_BATCH where IMPORT_BATCH_ID=?", batchId) > 0) { throw new IllegalStateException("import batch already exists: " + batchId); } connection.setAutoCommit(false); try { insertBatch(connection, batchId, "RUNNING", groups.size(), members.size(), (int) countRoleRows(members), 4); ImportCounts counts = new ImportCounts(); Map groupIds = importGroups(connection, groups, counts); importMembers(connection, batchId, members, groupIds, counts); updateBatch(connection, batchId, "SUCCESS", counts); connection.commit(); report.append("createdTT=").append(counts.createdGroups).append('\n'); report.append("reusedTT=").append(counts.reusedGroups).append('\n'); report.append("createdTTCY=").append(counts.createdMembers).append('\n'); report.append("reusedTTCY=").append(counts.reusedMembers).append('\n'); report.append("createdTTWCY=").append(counts.createdRoles).append('\n'); report.append("reusedTTWCY=").append(counts.reusedRoles).append('\n'); report.append("IMPORT_OK\n"); return report.toString(); } catch (Exception error) { connection.rollback(); throw error; } } private static List rdGroups(Path path) throws Exception { List lines = Files.readAllLines(path, StandardCharsets.UTF_8); Map idx = indexes(lines.get(0)); List result = new ArrayList<>(); for (int i = 1; i < lines.size(); i++) { if (lines.get(i).isBlank()) continue; String[] cols = lines.get(i).split("\t", -1); result.add(new GroupRow( cols[idx.get("group_name")], Integer.parseInt(cols[idx.get("ttlbm")]), Long.parseLong(cols[idx.get("fzbmid")]))); } return result; } private static List rdMembers( Path path, List groups) throws Exception { Map groupMap = new LinkedHashMap<>(); for (GroupRow group : groups) groupMap.put(group.key(), group); List lines = Files.readAllLines(path, StandardCharsets.UTF_8); Map idx = indexes(lines.get(0)); List result = new ArrayList<>(); for (int i = 1; i < lines.size(); i++) { if (lines.get(i).isBlank()) continue; String[] cols = lines.get(i).split("\t", -1); GroupKey key = new GroupKey( cols[idx.get("group_name")], Integer.parseInt(cols[idx.get("ttlbm")]), Long.parseLong(cols[idx.get("fzbmid")])); if (!groupMap.containsKey(key)) throw new IllegalArgumentException( "group missing in manifest: " + key); String memberTable = cols[idx.get("member_table")]; int roleCode = 0; if ("TTWCY".equals(memberTable)) { roleCode = Integer.parseInt(cols[idx.get("role_code")]); } else if (!"TTCY".equals(memberTable)) { throw new IllegalArgumentException( "invalid member table: " + memberTable); } result.add(new MemberRow( cols[idx.get("source_id")], key, Long.parseLong(cols[idx.get("ryid")]), Long.parseLong(cols[idx.get("bjid")]), cols[idx.get("source_student_name")], cols[idx.get("matched_name")], cols[idx.get("role_name")], cols[idx.get("role_category")], roleCode, memberTable, cols[idx.get("match_basis")])); } return result; } private static Map indexes(String header) { String[] names = header.split("\t", -1); Map result = new LinkedHashMap<>(); for (int i = 0; i < names.length; i++) result.put(names[i], i); return result; } private static void validate( List groups, List members) { if (groups.size() != 15) throw new IllegalArgumentException("expected 15 groups"); if (members.size() != 919) throw new IllegalArgumentException("expected 919 members"); long roleCount = members.stream() .filter(row -> row.memberTable.equals("TTWCY")).count(); if (roleCount != 892) throw new IllegalArgumentException("expected 892 role records"); Set memberKeys = new LinkedHashSet<>(); for (MemberRow row : members) { String key = row.group + "|" + row.ryid; if (!memberKeys.add(key)) throw new IllegalArgumentException( "duplicate group member: " + key); } } private static void ensureImportTables(Connection connection) throws Exception { executeIfMissing(connection, "table", "XJB_TT_IMPORT_BATCH", "create table XJB_TT_IMPORT_BATCH(" + "IMPORT_BATCH_ID varchar2(32) primary key," + "STATUS varchar2(16) not null," + "TT_COUNT number not null," + "TTCY_COUNT number not null," + "TTWCY_COUNT number not null," + "EXCLUDED_COUNT number not null," + "CREATED_AT date not null," + "FINISHED_AT date," + "MSG varchar2(500))"); executeIfMissing(connection, "table", "XJB_TT_IMPORT_MAP", "create table XJB_TT_IMPORT_MAP(" + "MAP_ID number primary key," + "IMPORT_BATCH_ID varchar2(32) not null," + "SOURCE_ID varchar2(32) not null," + "GROUP_NAME varchar2(100) not null," + "TTID number not null," + "TTCYID number not null," + "TTWCYID number," + "RYID number not null," + "STATUS varchar2(16) not null," + "CREATED_AT date not null)"); executeIfMissing(connection, "sequence", "XJB_TT_IMPORT_MAP_SEQ", "create sequence XJB_TT_IMPORT_MAP_SEQ start with 1 increment by 1"); } private static int importColumnCount(Connection connection) throws Exception { return (int) scalarLong(connection, "select count(*) from user_tab_columns " + "where (table_name in ('TT','TTCY') " + "and column_name in ('KSRQ','JSRQ','XNDM')) " + "or (table_name='TTWCY' " + "and column_name in ('ZWMC','KSRQ','JSRQ','XNDM'))"); } private static void backupTables( Connection connection, StringBuilder report) throws Exception { for (String table : List.of("TT", "TTCY", "TTWCY")) { String backup = "BAK_20261109_GROUP_IMPORT_" + table; if (count(connection, "select count(*) from user_tables where table_name=?", backup) == 0) { try (Statement statement = connection.createStatement()) { statement.execute("create table " + backup + " as select * from " + table); } } report.append(backup).append('=') .append(scalarLong( connection, "select count(*) from " + backup)) .append('\n'); } } private static void executeIfMissing( Connection connection, String type, String name, String sql) throws Exception { long exists; if ("sequence".equals(type)) { exists = count(connection, "select count(*) from user_sequences where sequence_name=?", name); } else { exists = count(connection, "select count(*) from user_tables where table_name=?", name); } if (exists == 0) { try (Statement statement = connection.createStatement()) { statement.execute(sql); } } } private static void insertBatch( Connection connection, String batchId, String status, int ttCount, int ttcyCount, int ttwcyCount, int excludedCount) throws Exception { try (PreparedStatement statement = connection.prepareStatement( "insert into XJB_TT_IMPORT_BATCH(" + "IMPORT_BATCH_ID,STATUS,TT_COUNT,TTCY_COUNT," + "TTWCY_COUNT,EXCLUDED_COUNT,CREATED_AT)" + " values(?,?,?,?,?,?,?)")) { statement.setString(1, batchId); statement.setString(2, status); statement.setInt(3, ttCount); statement.setInt(4, ttcyCount); statement.setInt(5, ttwcyCount); statement.setInt(6, excludedCount); statement.setTimestamp(7, new Timestamp(System.currentTimeMillis())); statement.executeUpdate(); } } private static void updateBatch( Connection connection, String batchId, String status, ImportCounts counts) throws Exception { try (PreparedStatement statement = connection.prepareStatement( "update XJB_TT_IMPORT_BATCH set STATUS=?,FINISHED_AT=?,MSG=?" + " where IMPORT_BATCH_ID=?")) { statement.setString(1, status); statement.setTimestamp(2, new Timestamp(System.currentTimeMillis())); statement.setString(3, "createdTT=" + counts.createdGroups + ",reusedTT=" + counts.reusedGroups + ",createdTTCY=" + counts.createdMembers + ",reusedTTCY=" + counts.reusedMembers + ",createdTTWCY=" + counts.createdRoles + ",reusedTTWCY=" + counts.reusedRoles); statement.setString(4, batchId); statement.executeUpdate(); } } private static Map importGroups( Connection connection, List groups, ImportCounts counts) throws Exception { Map result = new LinkedHashMap<>(); for (GroupRow group : groups) { long id = findGroup(connection, group); if (id == 0) { try (PreparedStatement statement = connection.prepareStatement( "insert into TT(MC,TTLBM,FZBMID,FZRYID,KSRQ,XNDM," + "JLZTM,CJRYID,GLRYID,GLBMID,MS)" + " values(?,?,?,?,?,?,?,?,?,?,?)")) { statement.setString(1, group.name); statement.setInt(2, group.ttlbm); statement.setLong(3, group.fzbmid); statement.setLong(4, TEACHER_ID); statement.setDate(5, Date.valueOf(EFFECTIVE_DATE)); statement.setString(6, SCHOOL_YEAR); statement.setInt(7, 51); statement.setLong(8, TEACHER_ID); statement.setLong(9, TEACHER_ID); statement.setLong(10, group.fzbmid); statement.setString(11, "团体信息导入"); statement.executeUpdate(); } id = findGroup(connection, group); counts.createdGroups++; } else { counts.reusedGroups++; } if (id == 0) throw new IllegalStateException("TT insert failed: " + group); result.put(group.key(), id); } return result; } private static long findGroup(Connection connection, GroupRow group) throws Exception { try (PreparedStatement statement = connection.prepareStatement( "select TTID from TT where MC=? and TTLBM=? and FZBMID=?" + " order by TTID")) { statement.setString(1, group.name); statement.setInt(2, group.ttlbm); statement.setLong(3, group.fzbmid); try (ResultSet result = statement.executeQuery()) { if (!result.next()) return 0L; long id = result.getLong(1); if (result.next()) throw new IllegalStateException( "multiple TT rows for " + group); return id; } } } private static void importMembers( Connection connection, String batchId, List members, Map groupIds, ImportCounts counts) throws Exception { for (MemberRow row : members) { long ttid = groupIds.get(row.group); long ttcyid = findTtcy(connection, ttid, row.ryid); if (ttcyid == 0) { try (PreparedStatement statement = connection.prepareStatement( "insert into TTCY(TTID,RYID,KSRQ,XNDM,JLZTM," + "CJRYID,GLRYID,GLBMID)" + " values(?,?,?,?,?,?,?,?)")) { statement.setLong(1, ttid); statement.setLong(2, row.ryid); statement.setDate(3, Date.valueOf(EFFECTIVE_DATE)); statement.setString(4, SCHOOL_YEAR); statement.setInt(5, 51); statement.setLong(6, TEACHER_ID); statement.setLong(7, TEACHER_ID); statement.setLong(8, row.group.fzbmid); statement.executeUpdate(); } ttcyid = findTtcy(connection, ttid, row.ryid); counts.createdMembers++; } else { counts.reusedMembers++; } if (ttcyid == 0) throw new IllegalStateException("TTCY insert failed: " + row.sourceId); Long ttwcyid = null; if ("TTWCY".equals(row.memberTable)) { long roleId = findTtwcy( connection, ttid, row.ryid, row.roleCode); if (roleId == 0) { try (PreparedStatement statement = connection.prepareStatement( "insert into TTWCY(TTID,RYID,TTWCYLBM,ZWMC," + "KSRQ,XNDM,JLZTM,CJRYID,GLRYID,GLBMID)" + " values(?,?,?,?,?,?,?,?,?,?)")) { statement.setLong(1, ttid); statement.setLong(2, row.ryid); statement.setInt(3, row.roleCode); statement.setString(4, row.roleName); statement.setDate(5, Date.valueOf(EFFECTIVE_DATE)); statement.setString(6, SCHOOL_YEAR); statement.setInt(7, 51); statement.setLong(8, TEACHER_ID); statement.setLong(9, TEACHER_ID); statement.setLong(10, row.group.fzbmid); statement.executeUpdate(); } roleId = findTtwcy( connection, ttid, row.ryid, row.roleCode); counts.createdRoles++; } else { counts.reusedRoles++; } if (roleId == 0) throw new IllegalStateException( "TTWCY insert failed: " + row.sourceId); ttwcyid = roleId; } try (PreparedStatement statement = connection.prepareStatement( "insert into XJB_TT_IMPORT_MAP(" + "MAP_ID,IMPORT_BATCH_ID,SOURCE_ID,GROUP_NAME," + "TTID,TTCYID,TTWCYID,RYID,STATUS,CREATED_AT)" + " values(XJB_TT_IMPORT_MAP_SEQ.nextval,?,?,?,?,?,?,?,?,?)")) { statement.setString(1, batchId); statement.setString(2, row.sourceId); statement.setString(3, row.group.name); statement.setLong(4, ttid); statement.setLong(5, ttcyid); if (ttwcyid == null) statement.setNull(6, java.sql.Types.NUMERIC); else statement.setLong(6, ttwcyid); statement.setLong(7, row.ryid); statement.setString(8, ttwcyid == null ? "TTCY_ONLY" : "TTCY_TTWCY"); statement.setTimestamp(9, new Timestamp(System.currentTimeMillis())); statement.executeUpdate(); } } } private static long findTtcy( Connection connection, long ttid, long ryid) throws Exception { try (PreparedStatement statement = connection.prepareStatement( "select TTCYID from TTCY where TTID=? and RYID=? and JLZTM=51")) { statement.setLong(1, ttid); statement.setLong(2, ryid); try (ResultSet result = statement.executeQuery()) { return result.next() ? result.getLong(1) : 0L; } } } private static long findTtwcy( Connection connection, long ttid, long ryid, int roleCode) throws Exception { try (PreparedStatement statement = connection.prepareStatement( "select TTWCYID from TTWCY where TTID=? and RYID=?" + " and TTWCYLBM=? and JLZTM=51")) { statement.setLong(1, ttid); statement.setLong(2, ryid); statement.setInt(3, roleCode); try (ResultSet result = statement.executeQuery()) { return result.next() ? result.getLong(1) : 0L; } } } private static long countRoleRows(List members) { return members.stream() .filter(row -> "TTWCY".equals(row.memberTable)).count(); } private static long count( Connection connection, String sql, String value) throws Exception { try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setString(1, value); try (ResultSet result = statement.executeQuery()) { result.next(); return result.getLong(1); } } } private static long scalarLong(Connection connection, String sql) throws Exception { try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { result.next(); return result.getLong(1); } } private static String scalarString(Connection connection, String sql) throws Exception { try (Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql)) { result.next(); return result.getString(1); } } private static final class GroupKey { final String name; final int ttlbm; final long fzbmid; GroupKey(String name, int ttlbm, long fzbmid) { this.name = name; this.ttlbm = ttlbm; this.fzbmid = fzbmid; } @Override public boolean equals(Object other) { if (!(other instanceof GroupKey)) return false; GroupKey key = (GroupKey) other; return name.equals(key.name) && ttlbm == key.ttlbm && fzbmid == key.fzbmid; } @Override public int hashCode() { return java.util.Objects.hash(name, ttlbm, fzbmid); } @Override public String toString() { return name + "/" + ttlbm + "/" + fzbmid; } } private static final class GroupRow { final String name; final int ttlbm; final long fzbmid; GroupRow(String name, int ttlbm, long fzbmid) { this.name = name; this.ttlbm = ttlbm; this.fzbmid = fzbmid; } GroupKey key() { return new GroupKey(name, ttlbm, fzbmid); } } private static final class MemberRow { final String sourceId; final GroupKey group; final long ryid; final long bjid; final String sourceName; final String matchedName; final String roleName; final String roleCategory; final int roleCode; final String memberTable; final String matchBasis; MemberRow(String sourceId, GroupKey group, long ryid, long bjid, String sourceName, String matchedName, String roleName, String roleCategory, int roleCode, String memberTable, String matchBasis) { this.sourceId = sourceId; this.group = group; this.ryid = ryid; this.bjid = bjid; this.sourceName = sourceName; this.matchedName = matchedName; this.roleName = roleName; this.roleCategory = roleCategory; this.roleCode = roleCode; this.memberTable = memberTable; this.matchBasis = matchBasis; } } private static final class ImportCounts { int createdGroups; int reusedGroups; int createdMembers; int reusedMembers; int createdRoles; int reusedRoles; } }