import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.nio.file.*; import java.sql.*; import java.math.BigDecimal; import java.util.*; /** Compares the frozen source with UI-created target records. SELECT only. */ public class ReadOnlyReplayAudit { static final ObjectMapper JSON=new ObjectMapper(); @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception{ if(args.length!=1||!args[0].matches("[a-zA-Z0-9_-]+"))throw new IllegalArgumentException("report basename required"); var root=JSON.readValue(Files.readAllBytes(Path.of(".codex-tmp/real-data-replay/wms-dev-20261015-ui-reentry-inventory.json")),new TypeReference>(){}); if(!"wms-dev".equals(root.get("database"))||!Boolean.TRUE.equals(root.get("readOnly")))throw new IllegalStateException("Unverified source"); var tables=(Map>)root.get("tables"); Map config=new HashMap<>();boolean master=false; for(String line:Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml"))){if(line.trim().equals("master:")){master=true;continue;}if(line.trim().equals("slave:"))break;if(master&&line.indexOf(':')>0){int colon=line.indexOf(':');config.put(line.substring(0,colon).trim(),DatabaseTool.value(line.substring(colon+1).trim()));}} String url=config.get("url");if(url==null||!url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/cmvr-project-dev(?:\\?.*)?$"))throw new IllegalStateException("Target mismatch"); var props=new Properties();props.setProperty("user",config.get("username"));props.setProperty("password",config.get("password"));props.setProperty("socketTimeout","60000");props.setProperty("connectTimeout","5000");props.setProperty("tinyInt1isBit","false"); try(var c=DriverManager.getConnection(url,props)){ c.setReadOnly(true);c.setAutoCommit(false);try(var s=c.createStatement()){s.execute("START TRANSACTION READ ONLY");} if(!"cmvr-project-dev".equals(BackupReplayTarget.scalar(c,"select database()")))throw new IllegalStateException("Target mismatch"); var report=new LinkedHashMap();report.put("target","cmvr-project-dev");report.put("source","wms-dev frozen read-only snapshot");report.put("readOnly",true); var items=index(rows(tables,"product_info"));var areas=index(rows(tables,"warehouse_area"));var projects=index(rows(tables,"project_info")); var expected=new TreeMap(); for(var lot:rows(tables,"stock_lot")){var item=items.get(id(lot.get("product_id")));var area=areas.get(id(lot.get("area_id")));var project=projects.get(id(lot.get("source_project_id")));add(expected,key(project.get("project_name"),area.get("area_name"),item),decimal(lot.get("available_quantity")));} var actual=new TreeMap(); var balances=BackupReplayTarget.records(c,"select p.project_name,a.area_name,i.product_name,i.brand,i.spec,i.category,b.quantity from project_stock_balance b join project_info p on p.id=b.project_id join warehouse_area a on a.id=b.area_id join product_info i on i.id=b.item_id"); for(var balance:balances){var normalized=new TreeMap(String.CASE_INSENSITIVE_ORDER);normalized.putAll(balance);add(actual,key(normalized.get("project_name"),normalized.get("area_name"),normalized),decimal(normalized.get("quantity")));} var differences=new ArrayList>();var all=new TreeSet();all.addAll(expected.keySet());all.addAll(actual.keySet()); for(String key:all){var before=expected.getOrDefault(key,BigDecimal.ZERO);var after=actual.getOrDefault(key,BigDecimal.ZERO);if(before.compareTo(after)!=0)differences.add(Map.of("identity",key,"expected",before,"actual",after));} report.put("stockDifferences",differences);report.put("sourceStockGroups",expected.values().stream().filter(q->q.signum()!=0).count());report.put("targetStockGroups",actual.values().stream().filter(q->q.signum()!=0).count()); var expectedCosts=new TreeMap();var unknownCosts=new HashSet(); for(var lot:rows(tables,"stock_lot")){if(decimal(lot.get("available_quantity")).signum()<=0)continue;var item=items.get(id(lot.get("product_id")));var project=projects.get(id(lot.get("source_project_id")));String identity=key(project.get("project_name"),"",item);var price=decimal(lot.get("unit_cost"));if(price.signum()<=0)unknownCosts.add(identity);else add(expectedCosts,identity,decimal(lot.get("available_quantity")).multiply(price));} var actualCosts=new TreeMap(); for(var balance:BackupReplayTarget.records(c,"select p.project_name,i.product_name,i.brand,i.spec,i.category,b.amount from project_item_cost b join project_info p on p.id=b.project_id join product_info i on i.id=b.item_id")){var normalized=new TreeMap(String.CASE_INSENSITIVE_ORDER);normalized.putAll(balance);if(normalized.get("amount")!=null)actualCosts.put(key(normalized.get("project_name"),"",normalized),decimal(normalized.get("amount")));} var costDifferences=new ArrayList>();int knownCostGroups=0; for(var entry:expectedCosts.entrySet()){if(unknownCosts.contains(entry.getKey()))continue;knownCostGroups++;var amount=actualCosts.get(entry.getKey());if(amount==null||amount.compareTo(entry.getValue())!=0)costDifferences.add(Map.of("identity",entry.getKey(),"expected",entry.getValue(),"actual",amount==null?"unknown":amount));} report.put("knownCostGroupsChecked",knownCostGroups);report.put("knownCostDifferences",costDifferences);report.put("sourceUnknownCostGroups",unknownCosts.size()); var counts=new LinkedHashMap();for(String table:List.of("warehouse_area","product_info","expense_category","project_budget","purchase_request","purchase_arrival","in_record","out_record","stock_info","stock_lot","inventory_cost_event","project_stock_balance","history_entry_receipt","project_fund_ledger","wms_batch_job","wms_batch_item","sys_oper_log","sys_logininfor","sys_notice_read"))counts.put(table,BackupReplayTarget.scalar(c,"select count(*) from `"+table+"`")); counts.put("confirmedPhysicalReceipts",BackupReplayTarget.scalar(c,"select count(*) from in_record where in_status=1 and receipt_root=0")); counts.put("purchaseLockedAmount",BackupReplayTarget.scalar(c,"select coalesce(sum(locked_amount),0) from purchase_request where del_flag='0'")); report.put("counts",counts); report.put("historyReceipts",BackupReplayTarget.records(c,"select source_table,count(*) recorded from history_entry_receipt group by source_table order by source_table")); report.put("duplicateNativeSourceReceipts",BackupReplayTarget.records(c,"select substring_index(remark,';',1) marker,count(*) n from in_record where receipt_root=0 and remark like 'SRC:in_record:%' group by marker having count(*)<>1")); var cleanup=JSON.readValue(Files.readAllBytes(Path.of(".codex-tmp/database-backups/cmvr-project-dev-20261015-051442/cleanup-result.json")),new TypeReference>(){}); report.put("cleanupProtection",cleanup); var manifest=JSON.readTree(Path.of(".codex-tmp/database-backups/cmvr-project-dev-20261015-051442/manifest.json").toFile()); var protectedChanges=new ArrayList();int protectedCount=0; for(var names=manifest.path("tables").fieldNames();names.hasNext();){String table=names.next();if(!table.startsWith("pm_")&&!table.equals("project_member"))continue;protectedCount++;var definition=manifest.path("tables").path(table);if(!fingerprint(c,table,definition).equals(definition.path("rowFingerprint").asText()))protectedChanges.add(table);} report.put("protectedCollaborationTablesChecked",protectedCount);report.put("protectedCollaborationChanges",protectedChanges); report.put("historyContent",auditHistory(c,tables)); report.put("sharedIdentityCoverage",auditShared(c,tables)); report.put("businessContent",auditBusiness(c,tables)); c.rollback();Path output=Path.of(".codex-tmp/real-data-replay",args[0]+".json");Files.writeString(output,JSON.writerWithDefaultPrettyPrinter().writeValueAsString(report)); System.out.println("Read-only audit: stock differences="+differences.size()+", source positive groups="+report.get("sourceStockGroups")+", target positive groups="+report.get("targetStockGroups")+"; report="+output); System.out.println("Counts: "+counts); } } @SuppressWarnings("unchecked") static List> rows(Map> tables,String name){return (List>)tables.get(name).get("rows");} static Map> index(List> rows){var result=new HashMap>();for(var row:rows)result.put(id(row.get("id")),row);return result;} static long id(Object value){return Long.parseLong(value.toString());} static BigDecimal decimal(Object value){return value==null?BigDecimal.ZERO:new BigDecimal(value.toString());} static void add(Map values,String key,BigDecimal value){values.merge(key,value,BigDecimal::add);} static String text(Object value){return Objects.toString(value,"").trim();} static String key(Object project,Object area,Map item){return String.join(" | ",text(project),text(area),text(item.get("product_name")),text(item.get("brand")),text(item.get("spec")),text(item.get("category")));} static String fingerprint(Connection c,String table,com.fasterxml.jackson.databind.JsonNode definition)throws Exception{ var columns=new ArrayList();for(var node:definition.path("columns"))columns.add(node.asText());String list=String.join(",",columns.stream().map(BackupReplayTarget::id).toList());var hashes=new ArrayList(); try(var statement=c.createStatement();var result=statement.executeQuery("select "+list+" from "+BackupReplayTarget.id(table))){var meta=result.getMetaData();while(result.next()){var values=new StringJoiner(",");for(int i=1;i<=meta.getColumnCount();i++)values.add(BackupReplayTarget.literal(result,meta,i));String insert="INSERT INTO "+BackupReplayTarget.id(table)+" ("+list+") VALUES ("+values+");\n";hashes.add(BackupReplayTarget.hash(insert.getBytes(java.nio.charset.StandardCharsets.UTF_8)));}} Collections.sort(hashes);return BackupReplayTarget.hash(String.join("\n",hashes).getBytes(java.nio.charset.StandardCharsets.UTF_8)); } static Map auditHistory(Connection c,Map> tables)throws Exception{ var keys=Map.of("sys_oper_log","oper_id","sys_logininfor","info_id","sys_job_log","job_log_id","wms_batch_job","id","wms_batch_item","id","sys_notice_read","read_id","project_fund_ledger","id","out_record","id"); var remapped=Map.of("wms_batch_item",Set.of("job_id","ref_id"),"sys_notice_read",Set.of("user_id","notice_id"),"project_fund_ledger",Set.of("project_id","expense_category_id","biz_id"),"out_record",Set.of("area_id","product_id","usage_project_id")); var receipts=BackupReplayTarget.records(c,"select source_table,source_id,target_key,row_hash from history_entry_receipt"); var mismatches=new ArrayList>();var checked=new TreeMap(); for(var definition:keys.entrySet()){ String table=definition.getKey(),primary=definition.getValue();var original=indexBy(rows(tables,table),primary);var targets=new HashMap>(); for(var row:BackupReplayTarget.records(c,"select * from "+BackupReplayTarget.id(table))){var normalized=new TreeMap(String.CASE_INSENSITIVE_ORDER);normalized.putAll(row);targets.put(id(normalized.get(primary)),normalized);} int verified=0; for(var receipt:receipts){if(!table.equals(receipt.get("SOURCE_TABLE")))continue;long sourceId=id(receipt.get("SOURCE_ID"));var source=original.get(sourceId);var target=targets.get(id(receipt.get("TARGET_KEY"))); if(source==null||target==null){mismatches.add(Map.of("table",table,"sourceId",sourceId,"field","missing source or target"));continue;} if(!BackupReplayTarget.hash(JSON.writeValueAsBytes(new TreeMap<>(source))).equals(receipt.get("ROW_HASH")))mismatches.add(Map.of("table",table,"sourceId",sourceId,"field","source fingerprint")); for(var field:source.entrySet()){if(field.getKey().equals(primary)||remapped.getOrDefault(table,Set.of()).contains(field.getKey()))continue;if(!same(field.getValue(),target.get(field.getKey())))mismatches.add(Map.of("table",table,"sourceId",sourceId,"field",field.getKey()));} verified++; } checked.put(table,verified); } return Map.of("verifiedRecords",checked,"contentDifferences",mismatches,"note","Original fields compared except remapped foreign keys; these were validated against exact native records on each individual form save."); } static Map> indexBy(List> rows,String primary){var result=new HashMap>();for(var row:rows)result.put(id(row.get(primary)),row);return result;} static boolean same(Object source,Object target){ if(source==null||target==null)return source==target; if(target instanceof java.sql.Timestamp t)return java.time.LocalDateTime.parse(source.toString().replace(' ','T')).equals(t.toLocalDateTime()); if(target instanceof java.time.LocalDateTime t)return java.time.LocalDateTime.parse(source.toString().replace(' ','T')).equals(t); if(target instanceof java.sql.Date t)return java.time.LocalDate.parse(source.toString()).equals(t.toLocalDate()); if(target instanceof Number){try{return decimal(source).compareTo(decimal(target))==0;}catch(Exception e){return false;}} return source.toString().equals(target.toString()); } static Map auditShared(Connection c,Map> tables)throws Exception{ var identities=Map.of("sys_user","user_name","sys_role","role_key","sys_dept","dept_name","sys_post","post_code","sys_notice","notice_title","sys_config","config_key","sys_job","job_name"); var coverage=new TreeMap(); for(var entry:identities.entrySet()){ var targets=new HashMap>(); for(var row:BackupReplayTarget.records(c,"select * from "+BackupReplayTarget.id(entry.getKey()))){var normalized=new TreeMap(String.CASE_INSENSITIVE_ORDER);normalized.putAll(row);targets.put(text(normalized.get(entry.getValue())),normalized);} var missing=new ArrayList();var passwordDifferences=new ArrayList();int present=0; for(var source:rows(tables,entry.getKey())){String identity=text(source.get(entry.getValue()));var target=targets.get(identity);if(target==null)missing.add(identity);else{present++;if(entry.getKey().equals("sys_user")&&!same(source.get("password"),target.get("password")))passwordDifferences.add(identity);}} coverage.put(entry.getKey(),Map.of("sourceRecords",rows(tables,entry.getKey()).size(),"present",present,"missing",missing,"passwordDifferences",passwordDifferences)); } var sourceUsers=indexBy(rows(tables,"sys_user"),"user_id");var sourceRoles=indexBy(rows(tables,"sys_role"),"role_id"); var userRoles=new HashSet();for(var row:BackupReplayTarget.records(c,"select u.user_name,r.role_key from sys_user_role ur join sys_user u on u.user_id=ur.user_id join sys_role r on r.role_id=ur.role_id"))userRoles.add(text(row.get("USER_NAME"))+"|"+text(row.get("ROLE_KEY"))); var missingGrants=new ArrayList();for(var row:rows(tables,"sys_user_role")){String identity=text(sourceUsers.get(id(row.get("user_id"))).get("user_name"))+"|"+text(sourceRoles.get(id(row.get("role_id"))).get("role_key"));if(!userRoles.contains(identity))missingGrants.add(identity);} coverage.put("sys_user_role",Map.of("sourceRecords",rows(tables,"sys_user_role").size(),"missing",missingGrants)); return coverage; } static Map auditBusiness(Connection c,Map> tables)throws Exception{ var differences=new ArrayList>();var checked=new TreeMap(); var sourceItems=index(rows(tables,"product_info"));var sourceAreas=index(rows(tables,"warehouse_area"));var sourceProjects=index(rows(tables,"project_info")); var targetItems=new HashMap>();var targetAreas=new HashMap>();var targetProjects=new HashMap>(); for(var row:ciRows(c,"product_info"))targetItems.put(id(row.get("id")),row); for(var row:ciRows(c,"warehouse_area"))targetAreas.put(id(row.get("id")),row); for(var row:ciRows(c,"project_info"))targetProjects.put(id(row.get("id")),row); var itemKeys=new HashSet();for(var row:targetItems.values())itemKeys.add(key("","",row)); for(var row:sourceItems.values())if(!itemKeys.contains(key("","",row)))differences.add(Map.of("table","product_info","sourceId",row.get("id"),"field","item identity")); checked.put("product_info",sourceItems.size()); var nativePurchases=marked(ciRows(c,"purchase_request"),"purchase_request"); var prices=new HashMap();for(var row:rows(tables,"purchase_arrival"))prices.put(id(row.get("purchase_request_id")),row.get("actual_unit_price")); for(var source:rows(tables,"purchase_request")){ long sourceId=id(source.get("id"));var target=nativePurchases.get(sourceId);if(target==null){differences.add(Map.of("table","purchase_request","sourceId",sourceId,"field","missing"));continue;} verify(differences,"purchase_request",sourceId,"quantity",source.get("quantity"),target.get("quantity")); verify(differences,"purchase_request",sourceId,"project",sourceProjects.get(id(source.get("project_id"))).get("project_name"),targetProjects.get(id(target.get("project_id"))).get("project_name")); Object expected=prices.getOrDefault(sourceId,source.get("estimated_unit_price"));if(decimal(expected).signum()>0)verify(differences,"purchase_request",sourceId,"price",expected,target.get("final_unit_price")); } checked.put("purchase_request",rows(tables,"purchase_request").size()); var targetPurchaseSources=new HashMap();nativePurchases.forEach((sourceId,row)->targetPurchaseSources.put(id(row.get("id")),sourceId)); var arrivals=marked(ciRows(c,"purchase_arrival"),"purchase_arrival"); for(var source:rows(tables,"purchase_arrival")){long sourceId=id(source.get("id"));var target=arrivals.get(sourceId);if(target==null){differences.add(Map.of("table","purchase_arrival","sourceId",sourceId,"field","missing"));continue;}for(String field:List.of("arrival_quantity","actual_unit_price","arrival_date","acceptance_status"))verify(differences,"purchase_arrival",sourceId,field,source.get(field),target.get(field));verify(differences,"purchase_arrival",sourceId,"purchase source",source.get("purchase_request_id"),targetPurchaseSources.get(id(target.get("purchase_request_id"))));} checked.put("purchase_arrival",arrivals.size()); for(String table:List.of("in_record","out_record")){ var targets=marked(ciRows(c,table),table); if(table.equals("out_record"))for(var receipt:ciRows(c,"history_entry_receipt"))if(table.equals(receipt.get("source_table")))for(var row:ciRows(c,table))if(id(row.get("id"))==id(receipt.get("target_key")))targets.put(id(receipt.get("source_id")),row); for(var source:rows(tables,table)){long sourceId=id(source.get("id"));var target=targets.get(sourceId);if(target==null){differences.add(Map.of("table",table,"sourceId",sourceId,"field","missing"));continue;} String quantity=table.equals("in_record")?"in_num":"out_num",project=table.equals("in_record")?"source_project_id":"usage_project_id"; verify(differences,table,sourceId,quantity,source.get(quantity),target.get(quantity)); verify(differences,table,sourceId,"area",sourceAreas.get(id(source.get("area_id"))).get("area_name"),targetAreas.get(id(target.get("area_id"))).get("area_name")); verify(differences,table,sourceId,"item",key("","",sourceItems.get(id(source.get("product_id")))),key("","",targetItems.get(id(target.get("product_id"))))); verify(differences,table,sourceId,"project",sourceProjects.get(id(source.get(project))).get("project_name"),targetProjects.get(id(target.get(project))).get("project_name")); Object originalDate=table.equals("in_record")?Objects.requireNonNullElse(source.get("confirm_time"),source.get("create_time")):source.get("out_time"); String sourceDate=originalDate.toString().substring(0,10),targetDate=target.get(table.equals("in_record")?"business_date":"out_time").toString().substring(0,10);if(!sourceDate.equals(targetDate))differences.add(Map.of("table",table,"sourceId",sourceId,"field","business date","expected",sourceDate,"actual",targetDate)); } checked.put(table,targets.size()); } return Map.of("checked",checked,"differences",differences,"note","Native identifiers intentionally regenerated; original identifiers and operators are retained in provenance remarks or exact historical records. Original purchase estimates copied without confirmation."); } static List> ciRows(Connection c,String table)throws Exception{var rows=new ArrayList>();for(var row:BackupReplayTarget.records(c,"select * from "+BackupReplayTarget.id(table))){var normalized=new TreeMap(String.CASE_INSENSITIVE_ORDER);normalized.putAll(row);rows.add(normalized);}return rows;} static Map> marked(List> rows,String table){var result=new HashMap>();var pattern=java.util.regex.Pattern.compile("SRC:"+table+":(\\d+)");for(var row:rows){var match=pattern.matcher(text(row.get("remark")));if(match.find())result.put(Long.parseLong(match.group(1)),row);}return result;} static void verify(List> differences,String table,long sourceId,String field,Object source,Object target){if(!same(source,target))differences.add(Map.of("table",table,"sourceId",sourceId,"field",field));} }