| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578 |
- 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";
- public static String run(Db db, String groupFile, String memberFile,
- String batchId, boolean execute) throws Exception {
- List<GroupRow> groups = rdGroups(Path.of(groupFile));
- List<MemberRow> 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("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');
- if (!execute) {
- report.append("DRY_RUN_OK\n");
- return report.toString();
- }
- Field connField = Db.class.getDeclaredField("conn");
- connField.setAccessible(true);
- Connection connection = (Connection) connField.get(db);
- String user = scalarString(connection, "select user from dual");
- if (!"PMS_TEST".equals(user)) {
- throw new IllegalStateException("refusing import: current user is " + user);
- }
- 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<GroupKey, Long> 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<GroupRow> rdGroups(Path path) throws Exception {
- List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
- Map<String, Integer> idx = indexes(lines.get(0));
- List<GroupRow> 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<MemberRow> rdMembers(
- Path path, List<GroupRow> groups) throws Exception {
- Map<GroupKey, GroupRow> groupMap = new LinkedHashMap<>();
- for (GroupRow group : groups)
- groupMap.put(group.key(), group);
- List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
- Map<String, Integer> idx = indexes(lines.get(0));
- List<MemberRow> 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<String, Integer> indexes(String header) {
- String[] names = header.split("\t", -1);
- Map<String, Integer> result = new LinkedHashMap<>();
- for (int i = 0; i < names.length; i++)
- result.put(names[i], i);
- return result;
- }
- private static void validate(
- List<GroupRow> groups, List<MemberRow> 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<String> 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 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<GroupKey, Long> importGroups(
- Connection connection, List<GroupRow> groups,
- ImportCounts counts) throws Exception {
- Map<GroupKey, Long> 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<MemberRow> members,
- Map<GroupKey, Long> 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<MemberRow> 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;
- }
- }
|