HkLeaveAuthServ.java 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125
  1. package biz.kq;
  2. import base.po.RcPo;
  3. import com.google.gson.Gson;
  4. import com.google.gson.JsonElement;
  5. import com.google.gson.JsonObject;
  6. import com.google.gson.JsonParser;
  7. import core.co.haikang.HkApiClient;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.apache.logging.log4j.LogManager;
  10. import org.apache.logging.log4j.Logger;
  11. import ss.db.Db;
  12. import ss.db.SqlCmd;
  13. import ss.serv.Serv;
  14. import ss.serv.ServC;
  15. import java.io.BufferedReader;
  16. import java.io.IOException;
  17. import java.sql.Timestamp;
  18. import java.nio.charset.StandardCharsets;
  19. import java.time.OffsetDateTime;
  20. import java.time.ZoneId;
  21. import java.time.format.DateTimeFormatter;
  22. import java.util.ArrayList;
  23. import java.util.LinkedHashMap;
  24. import java.util.LinkedHashSet;
  25. import java.util.List;
  26. import java.util.Locale;
  27. import java.util.Map;
  28. import java.util.Set;
  29. /**
  30. * 2026-05-26:班主任请假后的海康临时权限同步服务。
  31. * 2026-05-26:请假默认走“特殊人员权限直接下发 + 结果回查”口径,不再依赖 authItemNo。
  32. */
  33. public class HkLeaveAuthServ extends Serv {
  34. private static final Logger log4j = LogManager.getLogger(HkLeaveAuthServ.class);
  35. private static final HkApiClient HK_API_CLIENT = new HkApiClient();
  36. private static final Gson GSON = new Gson();
  37. private static final String CFG_ENABLED = "hk.leaveAuth.enabled";
  38. private static final String CFG_EXECUTE = "hk.leaveAuth.execute";
  39. private static final String CFG_HOST = "hk.host";
  40. private static final String CFG_PORT = "hk.port";
  41. private static final String CFG_APP_KEY = "hk.appKey";
  42. private static final String CFG_APP_SECRET = "hk.appSecret";
  43. private static final String CFG_TAG_ID = "hk.leaveAuth.tagId";
  44. private static final String CFG_CALLBACK_URL = "hk.leaveAuth.callbackUrl";
  45. private static final String CFG_TEMPLATE_ID = "hk.leaveAuth.templateId";
  46. private static final String CFG_TEMPLATE_DIMENSION = "hk.leaveAuth.templateDimension";
  47. private static final String CFG_MODE = "hk.leaveAuth.mode";
  48. private static final String HK_DEF_HOST = "192.168.68.3";
  49. private static final int HK_DEF_PORT = 443;
  50. private static final String HK_DEF_APP_KEY = "25723525";
  51. private static final String HK_DEF_APP_SECRET = "V8KVC0McdY5KVARbIpQv";
  52. private static final String HK_DEF_TAG_ID = "frs";
  53. private static final int HK_DEF_TEMPLATE_DIMENSION = 1;
  54. private static final String HK_DEF_MODE = "platform_config";
  55. private static final int HK_DEF_DOWNLOAD_POLL_COUNT = 4;
  56. private static final int HK_DEF_DOWNLOAD_POLL_SLEEP_MS = 1200;
  57. private static final int RC_WCMSWJ_MAX_BYTES = 4000;
  58. private static final String RC_WCMSWJ_TRUNCATE_SUFFIX = "...";
  59. private static final DateTimeFormatter HK_AUTH_TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
  60. /**
  61. * 2026-05-26:请假保存后执行入口,保持原来的挂点不变。
  62. */
  63. static void syncLeaveAuthAfterCommit(RcPo rcPo) {
  64. if (rcPo == null || rcPo.getRcid() <= 0)
  65. return;
  66. if (!rdBoolCfg(CFG_ENABLED, "HK_LEAVE_AUTH_ENABLED", false))
  67. return;
  68. try {
  69. Map<String, Object> result = buildLeaveAuthSyncResult(rcPo.getRcid(), true, Map.of());
  70. if (!Boolean.TRUE.equals(result.get("ok")) || StringUtils.isNotBlank(rdStr(result.get("skipReason"))))
  71. logSkip(rdStr(result.get("msg")), rcPo.getRcid(), null, null);
  72. } catch (Exception e) {
  73. log4j.error("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 异常,rcid={}", rcPo.getRcid(), e);
  74. persistUnexpectedSyncError(rcPo.getRcid(), e);
  75. }
  76. }
  77. /**
  78. * 2026-05-26:请假权限预览入口,只回显请求和海康组装结果,不影响现网写入。
  79. */
  80. public String previewLeaveAuthSync() {
  81. super.wrJsonByResp(previewLeaveAuthSyncResult());
  82. return ServC.SERV_notByA;
  83. }
  84. /**
  85. * 2026-05-26:请假权限诊断入口,直接回显人员、门禁资源、模板与海康探测结果。
  86. */
  87. public String diagLeaveAuthItem() {
  88. super.wrJsonByResp(diagLeaveAuthItemResult());
  89. return ServC.SERV_notByA;
  90. }
  91. /**
  92. * 2026-05-26:自动探测海康模板编号的诊断入口,只依赖 rcid 和学生身份,不要求先提供 templateId。
  93. */
  94. public String diagLeaveAuthTemplateId() {
  95. super.wrJsonByResp(diagLeaveAuthTemplateIdResult());
  96. return ServC.SERV_notByA;
  97. }
  98. /**
  99. * 2026-05-27:通用海康原始接口探测入口,便于逐个试海康文档候选接口并回收原始响应分析 templateId。
  100. */
  101. public String probeHkTemplateApi() {
  102. super.wrJsonByResp(probeHkTemplateApiResult());
  103. return ServC.SERV_notByA;
  104. }
  105. /**
  106. * 2026-05-26:手工真实下发入口,只在明确传参时执行海康写操作。
  107. */
  108. public String executeLeaveAuthSync() {
  109. super.wrJsonByResp(executeLeaveAuthSyncResult());
  110. return ServC.SERV_notByA;
  111. }
  112. /**
  113. * 2026-05-26:手工查询特殊人员权限下发结果,便于拿到配置后快速回查海康任务状态。
  114. */
  115. public String viewLeaveAuthSyncResult() {
  116. super.wrJsonByResp(viewLeaveAuthSyncResultData());
  117. return ServC.SERV_notByA;
  118. }
  119. /**
  120. * 2026-06-02:海康下载结果回调入口,优先把任务号与下载摘要回写到请假记录,便于现场后补确认。
  121. */
  122. public String recvLeaveAuthDownloadPush() {
  123. String pushBodyStr;
  124. try {
  125. pushBodyStr = rdReqBody();
  126. } catch (Exception e) {
  127. log4j.error("HkLeaveAuthServ.recvLeaveAuthDownloadPush() 读取请求体异常", e);
  128. Map<String, Object> errResp = new LinkedHashMap<>();
  129. errResp.put("ok", false);
  130. errResp.put("msg", e.getMessage());
  131. if (super.resp != null)
  132. super.resp.setStatus(500);
  133. super.wrJsonByResp(errResp);
  134. return ServC.SERV_notByA;
  135. }
  136. boolean showDetail = "1".equals(rdReqStrParm("showDetail", "debug"))
  137. || "true".equalsIgnoreCase(rdReqStrParm("showDetail", "debug"));
  138. if (showDetail) {
  139. Map<String, Object> debugResp = processLeaveAuthDownloadPushAfterAck(pushBodyStr, true);
  140. super.wrJsonByResp(debugResp);
  141. return ServC.SERV_notByA;
  142. }
  143. Map<String, Object> ackResp = new LinkedHashMap<>();
  144. ackResp.put("ok", true);
  145. ackResp.put("accepted", true);
  146. ackResp.put("bodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
  147. super.wrJsonByResp(ackResp);
  148. try {
  149. processLeaveAuthDownloadPushAfterAck(pushBodyStr, false);
  150. } catch (Exception e) {
  151. log4j.error("HkLeaveAuthServ.recvLeaveAuthDownloadPush() 回调已应答,但后续处理异常", e);
  152. }
  153. return ServC.SERV_notByA;
  154. }
  155. /**
  156. * 2026-05-26:预览态统一走同一套组装逻辑,便于和真实下发保持一致。
  157. */
  158. private Map<String, Object> previewLeaveAuthSyncResult() {
  159. long rcid = rdReqLongParm("rcid");
  160. if (rcid <= 0) {
  161. Map<String, Object> result = new LinkedHashMap<>();
  162. result.put("ok", false);
  163. result.put("msg", "缺少有效的 rcid 参数。");
  164. return result;
  165. }
  166. try {
  167. return buildLeaveAuthSyncResult(rcid, false, makeReqOverrideParm());
  168. } catch (Exception e) {
  169. log4j.error("HkLeaveAuthServ.previewLeaveAuthSync() 异常,rcid={}", rcid, e);
  170. Map<String, Object> result = new LinkedHashMap<>();
  171. result.put("ok", false);
  172. result.put("msg", e.getMessage());
  173. return result;
  174. }
  175. }
  176. /**
  177. * 2026-05-26:诊断态直接把权限下发所需的关键拼装链路都回显出来。
  178. */
  179. private Map<String, Object> diagLeaveAuthItemResult() {
  180. long rcid = rdReqLongParm("rcid");
  181. if (rcid <= 0) {
  182. Map<String, Object> result = new LinkedHashMap<>();
  183. result.put("ok", false);
  184. result.put("msg", "缺少有效的 rcid 参数。");
  185. return result;
  186. }
  187. try {
  188. Map<String, Object> result = buildLeaveAuthSyncResult(rcid, false, makeReqOverrideParm());
  189. result.put("diagOnly", true);
  190. return result;
  191. } catch (Exception e) {
  192. log4j.error("HkLeaveAuthServ.diagLeaveAuthItem() 异常,rcid={}", rcid, e);
  193. Map<String, Object> result = new LinkedHashMap<>();
  194. result.put("ok", false);
  195. result.put("msg", e.getMessage());
  196. return result;
  197. }
  198. }
  199. /**
  200. * 2026-05-26:自动探测 templateId,给后续真实下发前先做一轮海康侧可用模板排查。
  201. */
  202. private Map<String, Object> diagLeaveAuthTemplateIdResult() {
  203. long rcid = rdReqLongParm("rcid");
  204. if (rcid <= 0) {
  205. Map<String, Object> result = new LinkedHashMap<>();
  206. result.put("ok", false);
  207. result.put("msg", "缺少有效的 rcid 参数。");
  208. return result;
  209. }
  210. Map<String, Object> result = new LinkedHashMap<>();
  211. result.put("ok", true);
  212. result.put("rcid", rcid);
  213. try (Db gdba = Db.makeConn()) {
  214. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
  215. if (ctx == null) {
  216. result.put("ok", false);
  217. result.put("msg", "未找到对应请假记录。");
  218. return result;
  219. }
  220. result.put("leaveCtx", makeLeaveCtxResp(ctx));
  221. if (StringUtils.isBlank(ctx.jobNo)) {
  222. result.put("ok", false);
  223. result.put("msg", "学生缺少人员号(jobNo/RYH),无法匹配海康人员。");
  224. persistLeaveAuthSyncResult(gdba, ctx, result);
  225. return result;
  226. }
  227. Map<String, Object> hkConnParm = makeHkConnParm();
  228. if (hkConnParm == null) {
  229. result.put("ok", false);
  230. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  231. persistLeaveAuthSyncResult(gdba, ctx, result);
  232. return result;
  233. }
  234. result.put("hkConn", makeSafeHkConnResp(hkConnParm));
  235. Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(
  236. hkConnParm, List.of(ctx.jobNo));
  237. Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
  238. result.put("personQueryJobNo", ctx.jobNo);
  239. result.put("personInfoFound", personInfo != null);
  240. if (personInfo == null) {
  241. result.put("ok", false);
  242. result.put("msg", "海康侧未找到对应人员。");
  243. persistLeaveAuthSyncResult(gdba, ctx, result);
  244. return result;
  245. }
  246. result.put("personInfo", makePersonInfoResp(personInfo));
  247. String personId = rdStr(personInfo.get("personId"));
  248. if (StringUtils.isBlank(personId)) {
  249. result.put("ok", false);
  250. result.put("msg", "海康人员缺少 personId。");
  251. persistLeaveAuthSyncResult(gdba, ctx, result);
  252. return result;
  253. }
  254. int probeLimit = rdReqIntParm("probeLimit", "doorLimit", "limit");
  255. if (probeLimit <= 0)
  256. probeLimit = 3;
  257. List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
  258. List<Map<String, Object>> resourceInfoList = makeResourceInfoList(resourceSourceList);
  259. if (probeLimit > resourceInfoList.size())
  260. probeLimit = resourceInfoList.size();
  261. result.put("resourceCount", resourceInfoList.size());
  262. result.put("probeLimit", probeLimit);
  263. result.put("resourceSourceList", makeMjdRespList(resourceSourceList));
  264. List<Map<String, Object>> probeList = new ArrayList<>();
  265. LinkedHashSet<String> detectedTemplateIdSet = new LinkedHashSet<>();
  266. for (int i = 0; i < probeLimit; i++) {
  267. Map<String, Object> resourceInfo = resourceInfoList.get(i);
  268. Map<String, Object> probeRow = new LinkedHashMap<>();
  269. probeRow.put("resourceInfo", resourceInfo);
  270. probeRow.put("request", makeSingleAuthItemSearchReq(personId, resourceInfo));
  271. try {
  272. Map<String, Object> resp = HK_API_CLIENT.searchSingleAuthItem(hkConnParm, probeRow.get("request") instanceof Map<?, ?> reqMap
  273. ? (Map<String, Object>) reqMap
  274. : makeSingleAuthItemSearchReq(personId, resourceInfo));
  275. probeRow.put("ok", true);
  276. probeRow.put("response", resp);
  277. List<String> templateIdList = extTemplateIdList(resp);
  278. probeRow.put("templateIdCandidates", templateIdList);
  279. if (!templateIdList.isEmpty())
  280. detectedTemplateIdSet.addAll(templateIdList);
  281. } catch (Exception e) {
  282. probeRow.put("ok", false);
  283. probeRow.put("msg", e.getMessage());
  284. }
  285. probeList.add(probeRow);
  286. }
  287. result.put("probeResults", probeList);
  288. result.put("detectedTemplateIds", new ArrayList<>(detectedTemplateIdSet));
  289. result.put("detectedTemplateId", detectedTemplateIdSet.isEmpty() ? null : detectedTemplateIdSet.iterator().next());
  290. result.put("msg", detectedTemplateIdSet.isEmpty()
  291. ? "未探测到 templateId,请海康侧确认该人/门禁是否已有权限模板。"
  292. : "已自动探测到 templateId。");
  293. return result;
  294. } catch (Exception e) {
  295. log4j.error("HkLeaveAuthServ.diagLeaveAuthTemplateId() 异常,rcid={}", rcid, e);
  296. result.put("ok", false);
  297. result.put("msg", e.getMessage());
  298. return result;
  299. }
  300. }
  301. /**
  302. * 2026-05-27:透传海康接口路径和请求体,返回原始请求与响应,作为 templateId 联调诊断口。
  303. */
  304. private Map<String, Object> probeHkTemplateApiResult() {
  305. Map<String, Object> result = new LinkedHashMap<>();
  306. String apiPath = rdReqStrParm("apiPath", "path");
  307. String reqBodyStr = rdReqStrParm("reqBody", "body", "json");
  308. long rcid = rdReqLongParm("rcid");
  309. result.put("ok", false);
  310. result.put("apiPath", apiPath);
  311. result.put("rcid", rcid);
  312. if (StringUtils.isBlank(apiPath)) {
  313. result.put("msg", "缺少 apiPath 参数。");
  314. return result;
  315. }
  316. if (!StringUtils.startsWith(apiPath, "/artemis/api/")) {
  317. result.put("msg", "apiPath 必须以 /artemis/api/ 开头。");
  318. return result;
  319. }
  320. Map<String, Object> reqBodyMap;
  321. try {
  322. reqBodyMap = rdReqBodyMap(reqBodyStr);
  323. } catch (Exception e) {
  324. result.put("msg", "reqBody 不是有效 JSON Object:" + e.getMessage());
  325. return result;
  326. }
  327. result.put("requestBody", reqBodyMap);
  328. try {
  329. Map<String, Object> hkConnParm = makeHkConnParm();
  330. if (hkConnParm == null) {
  331. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  332. return result;
  333. }
  334. result.put("hkConn", makeSafeHkConnResp(hkConnParm));
  335. String tagId = rdCfgOrOverride(makeReqOverrideParm(), "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
  336. if (StringUtils.isNotBlank(tagId))
  337. hkConnParm.put("tagId", tagId);
  338. result.put("tagId", tagId);
  339. result.put("tagIdSource", rdCfgSource(makeReqOverrideParm(), "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
  340. if (rcid > 0) {
  341. try (Db gdba = Db.makeConn()) {
  342. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
  343. if (ctx != null)
  344. result.put("leaveCtx", makeLeaveCtxResp(ctx));
  345. }
  346. }
  347. Map<String, Object> responseMap = HK_API_CLIENT.postProbeApi(hkConnParm, apiPath, reqBodyMap);
  348. result.put("ok", true);
  349. result.put("response", responseMap);
  350. result.put("templateIdCandidates", extTemplateIdList(responseMap));
  351. result.put("msg", "海康接口探测已返回,请把 response 和 templateIdCandidates 一并发我分析。");
  352. return result;
  353. } catch (Exception e) {
  354. log4j.error("HkLeaveAuthServ.probeHkTemplateApi() 异常,apiPath={}", apiPath, e);
  355. result.put("msg", e.getMessage());
  356. return result;
  357. }
  358. }
  359. /**
  360. * 2026-05-26:手工触发真实下发,便于先做一次人工联调确认海康侧能成功接收。
  361. */
  362. private Map<String, Object> executeLeaveAuthSyncResult() {
  363. long rcid = rdReqLongParm("rcid");
  364. if (rcid <= 0) {
  365. Map<String, Object> result = new LinkedHashMap<>();
  366. result.put("ok", false);
  367. result.put("msg", "缺少有效的 rcid 参数。");
  368. return result;
  369. }
  370. try {
  371. return buildLeaveAuthSyncResult(rcid, true, makeReqOverrideParm());
  372. } catch (Exception e) {
  373. log4j.error("HkLeaveAuthServ.executeLeaveAuthSync() 异常,rcid={}", rcid, e);
  374. Map<String, Object> result = new LinkedHashMap<>();
  375. result.put("ok", false);
  376. result.put("msg", e.getMessage());
  377. return result;
  378. }
  379. }
  380. /**
  381. * 2026-05-26:单独开放结果查询口,避免每次都必须先真实下发才能查看海康侧异步结果。
  382. */
  383. private Map<String, Object> viewLeaveAuthSyncResultData() {
  384. long rcid = rdReqLongParm("rcid");
  385. if (rcid <= 0) {
  386. Map<String, Object> result = new LinkedHashMap<>();
  387. result.put("ok", false);
  388. result.put("msg", "缺少有效的 rcid 参数。");
  389. return result;
  390. }
  391. Map<String, Object> overrideParm = makeReqOverrideParm();
  392. try {
  393. Map<String, Object> result = buildLeaveAuthSyncResult(rcid, false, overrideParm);
  394. String modeCfg = normalizeLeaveAuthMode(rdStr(result.get("modeCfg")));
  395. if ("platform_config".equals(modeCfg)) {
  396. try (Db gdba = Db.makeConn()) {
  397. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
  398. if (ctx == null) {
  399. result.put("ok", false);
  400. result.put("msg", "未找到对应请假记录。");
  401. return result;
  402. }
  403. return refreshPlatformConfigLeaveAuthResult(gdba, ctx, overrideParm, result);
  404. }
  405. }
  406. @SuppressWarnings("unchecked")
  407. Map<String, Object> queryReq = (Map<String, Object>) result.get("authDownloadResultQueryReq");
  408. if (queryReq == null) {
  409. result.put("ok", false);
  410. result.put("msg", "未能组装下发结果查询条件。");
  411. return result;
  412. }
  413. Map<String, Object> hkConnParm = rdHkConnParm();
  414. if (hkConnParm == null) {
  415. result.put("ok", false);
  416. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  417. return result;
  418. }
  419. String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
  420. if (StringUtils.isNotBlank(tagId))
  421. hkConnParm.put("tagId", tagId);
  422. result.put("tagId", tagId);
  423. result.put("tagIdSource", rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
  424. result.put("mode", "viewResult");
  425. result.put("authDownloadResultQueryResp",
  426. querySpecialPersonAuthDownloadResultWithRetry(hkConnParm, queryReq));
  427. result.put("downloadResultConfirmed", hasSpecialPersonAuthDownloadResult(result.get("authDownloadResultQueryResp")));
  428. return result;
  429. } catch (Exception e) {
  430. log4j.error("HkLeaveAuthServ.viewLeaveAuthSyncResultData() 异常,rcid={}", rcid, e);
  431. Map<String, Object> result = new LinkedHashMap<>();
  432. result.put("ok", false);
  433. result.put("msg", e.getMessage());
  434. return result;
  435. }
  436. }
  437. /**
  438. * 2026-05-26:统一组装请假权限同步结果,预览和真实执行共用这条链路。
  439. */
  440. private static Map<String, Object> buildLeaveAuthSyncResult(long rcid,
  441. boolean autoTrigger,
  442. Map<String, Object> overrideParm) throws Exception {
  443. Map<String, Object> result = new LinkedHashMap<>();
  444. result.put("ok", true);
  445. result.put("autoTrigger", autoTrigger);
  446. result.put("enabled", rdBoolCfg(CFG_ENABLED, "HK_LEAVE_AUTH_ENABLED", false));
  447. result.put("execute", rdBoolCfg(CFG_EXECUTE, "HK_LEAVE_AUTH_EXECUTE", false));
  448. result.put("modeCfg", rdCfg(CFG_MODE, "HK_LEAVE_AUTH_MODE"));
  449. result.put("rcid", rcid);
  450. try (Db gdba = Db.makeConn()) {
  451. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
  452. if (ctx == null) {
  453. result.put("ok", false);
  454. result.put("msg", "未找到对应请假记录。");
  455. return result;
  456. }
  457. result.put("leaveCtx", makeLeaveCtxResp(ctx));
  458. applyPersistedLeaveAuthSnapshot(ctx, result);
  459. Timestamp now = new Timestamp(System.currentTimeMillis());
  460. result.put("syncTime", makeHkTime(now));
  461. result.put("leaveExpired", ifLeaveEnded(ctx.jssj, now));
  462. if (ifLeaveEnded(ctx.jssj, now)) {
  463. result.put("ok", false);
  464. result.put("mode", "skipExpired");
  465. result.put("skipReason", "请假时间段已结束,跳过海康自动开门。");
  466. result.put("msg", "请假结束时间早于当前时间,不能再下发海康临时权限。");
  467. persistLeaveAuthSyncResult(gdba, ctx, result);
  468. return result;
  469. }
  470. if (StringUtils.isBlank(ctx.jobNo)) {
  471. result.put("ok", false);
  472. result.put("msg", "学生缺少人员号(jobNo/RYH),无法匹配海康人员。");
  473. persistLeaveAuthSyncResult(gdba, ctx, result);
  474. return result;
  475. }
  476. Map<String, Object> hkConnParm = makeHkConnParm();
  477. if (hkConnParm == null) {
  478. result.put("ok", false);
  479. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  480. persistLeaveAuthSyncResult(gdba, ctx, result);
  481. return result;
  482. }
  483. result.put("hkConn", makeSafeHkConnResp(hkConnParm));
  484. Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(
  485. hkConnParm, List.of(ctx.jobNo));
  486. Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
  487. result.put("personQueryJobNo", ctx.jobNo);
  488. result.put("personInfoFound", personInfo != null);
  489. if (personInfo == null) {
  490. result.put("ok", false);
  491. result.put("msg", "海康侧未找到对应人员。");
  492. persistLeaveAuthSyncResult(gdba, ctx, result);
  493. return result;
  494. }
  495. result.put("personInfo", makePersonInfoResp(personInfo));
  496. String personId = rdStr(personInfo.get("personId"));
  497. if (StringUtils.isBlank(personId)) {
  498. result.put("ok", false);
  499. result.put("msg", "海康人员缺少 personId。");
  500. persistLeaveAuthSyncResult(gdba, ctx, result);
  501. return result;
  502. }
  503. List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
  504. List<Map<String, Object>> resourceInfoList = makeResourceInfoList(resourceSourceList);
  505. result.put("resourceSourceList", makeMjdRespList(resourceSourceList));
  506. result.put("resourceInfos", resourceInfoList);
  507. result.put("resourceCount", resourceInfoList.size());
  508. if (resourceInfoList.isEmpty()) {
  509. result.put("ok", false);
  510. result.put("msg", "未找到可下发的有效门禁点。");
  511. persistLeaveAuthSyncResult(gdba, ctx, result);
  512. return result;
  513. }
  514. String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
  515. String callbackUrl = rdCfgOrOverride(overrideParm, "callbackUrl", CFG_CALLBACK_URL, "HK_LEAVE_AUTH_CALLBACK_URL");
  516. Integer templateDimension = rdIntCfgOrOverride(
  517. overrideParm, "templateDimension", CFG_TEMPLATE_DIMENSION, "HK_LEAVE_AUTH_TEMPLATE_DIMENSION", HK_DEF_TEMPLATE_DIMENSION);
  518. String templateId = rdCfgOrOverride(overrideParm, "templateId", CFG_TEMPLATE_ID, "HK_LEAVE_AUTH_TEMPLATE_ID");
  519. String mode = normalizeLeaveAuthMode(rdCfgOrOverride(overrideParm, "mode", CFG_MODE, "HK_LEAVE_AUTH_MODE"));
  520. String tagIdSource = rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
  521. if (StringUtils.isNotBlank(tagId))
  522. hkConnParm.put("tagId", tagId);
  523. // 2026-05-27:当前请假自动开门按“添加权限配置”口径执行,templateId 只在海康侧明确要求时才附带。
  524. Map<String, Object> singleSearchReq = null;
  525. Map<String, Object> singleSearchResp = null;
  526. String probedTemplateId = null;
  527. String templateIdSource = "missing";
  528. if (StringUtils.isBlank(templateId)) {
  529. singleSearchReq = makeSingleAuthItemSearchReq(personId, resourceInfoList.get(0));
  530. result.put("singleSearchReq", singleSearchReq);
  531. try {
  532. singleSearchResp = HK_API_CLIENT.searchSingleAuthItem(hkConnParm, singleSearchReq);
  533. result.put("singleSearchResp", singleSearchResp);
  534. } catch (Exception e) {
  535. result.put("singleSearchError", e.getMessage());
  536. result.put("templateProbeStatus", "failed");
  537. result.put("templateProbeHint", "海康侧 single/search 当前不能稳定用于自动探测 templateId,请改为显式配置。");
  538. }
  539. probedTemplateId = extTemplateId(singleSearchResp);
  540. templateIdSource = StringUtils.isNotBlank(probedTemplateId) ? "singleSearchResp" : "missing";
  541. }
  542. if (StringUtils.isNotBlank(templateId))
  543. templateIdSource = "cfg";
  544. String effectiveTemplateId = StringUtils.defaultIfBlank(templateId, probedTemplateId);
  545. result.put("templateIdSource", templateIdSource);
  546. result.put("templateId", effectiveTemplateId);
  547. result.put("downloadMode", StringUtils.isBlank(effectiveTemplateId) ? "addPermissionConfig" : "addPermissionConfigWithTemplate");
  548. result.put("templateDimension", templateDimension);
  549. result.put("mode", mode);
  550. result.put("tagId", tagId);
  551. result.put("tagIdSource", tagIdSource);
  552. result.put("callbackUrl", callbackUrl);
  553. result.put("configReady", StringUtils.isNotBlank(tagId));
  554. List<String> missingCfgList = new ArrayList<>();
  555. if (StringUtils.isBlank(tagId))
  556. missingCfgList.add("tagId");
  557. result.put("missingConfig", missingCfgList);
  558. result.put("nextSteps", makeNextStepList(missingCfgList));
  559. result.put("tagIdAdvice", "当前项目只做接口下发时,tagId 只要海康侧提供可用值即可;若还要求平台门禁管理可见,再评估是否改成 acs。");
  560. result.put("templateIdAdvice", "templateId 仅在海康侧明确要求模板时再补;当前请假自动开门默认可不传。");
  561. result.put("executeApiPath", "/artemis/api/acps/v1/authDownload/special/person/diy");
  562. result.put("resultApiPath", "/artemis/api/acps/v1/authDownload/special/person/diy/result");
  563. // 2026-05-27:templateId 为空时,不再把 templateConfigInfos 强塞进请求体,避免把新增权限配置卡死。
  564. Map<String, Object> payload = makeSpecialAuthPayload(
  565. ctx, personInfo, personId, resourceInfoList, tagId, callbackUrl, effectiveTemplateId, templateDimension);
  566. result.put("payload", payload);
  567. result.put("authDownloadResultQueryReq", makeAuthDownloadResultQueryReq(personId, resourceInfoList));
  568. if (StringUtils.isBlank(tagId)) {
  569. result.put("skipReason", "缺少海康下发配置 tagId,暂不执行下发。");
  570. result.put("mode", "preview");
  571. persistLeaveAuthSyncResult(gdba, ctx, result);
  572. return result;
  573. }
  574. boolean execute = rdBoolCfg(CFG_EXECUTE, "HK_LEAVE_AUTH_EXECUTE", false);
  575. boolean platformConfigMode = "platform_config".equalsIgnoreCase(mode);
  576. boolean legacyMode = !platformConfigMode;
  577. if (!autoTrigger || !execute) {
  578. result.put("mode", "dryRun");
  579. if (autoTrigger)
  580. logDryRun(ctx, personInfo, payload);
  581. persistLeaveAuthSyncResult(gdba, ctx, result);
  582. return result;
  583. }
  584. if (platformConfigMode) {
  585. return runPlatformConfigMode(gdba, ctx, personInfo, personId, resourceInfoList, tagId, callbackUrl, templateId,
  586. templateDimension, payload, result);
  587. }
  588. if (legacyMode) {
  589. Map<String, Object> authSyncResp = HK_API_CLIENT.downloadSpecialPersonAuth(hkConnParm, payload);
  590. result.put("mode", "execute");
  591. result.put("authSyncResp", authSyncResp);
  592. try {
  593. Map<String, Object> queryReq = makeAuthDownloadResultQueryReq(personId, resourceInfoList);
  594. result.put("authDownloadResultQueryReq", queryReq);
  595. result.put("authDownloadResultQueryResp",
  596. querySpecialPersonAuthDownloadResultWithRetry(hkConnParm, queryReq));
  597. result.put("downloadResultConfirmed", hasSpecialPersonAuthDownloadResult(result.get("authDownloadResultQueryResp")));
  598. } catch (Exception e) {
  599. result.put("authDownloadResultQueryError", e.getMessage());
  600. }
  601. logExecute(ctx, personInfo, payload, authSyncResp);
  602. persistLeaveAuthSyncResult(gdba, ctx, result);
  603. return result;
  604. }
  605. result.put("ok", false);
  606. result.put("msg", "未知的海康请假模式:" + mode);
  607. persistLeaveAuthSyncResult(gdba, ctx, result);
  608. return result;
  609. }
  610. }
  611. /**
  612. * 2026-05-26:把请假记录和人员信息一次性查出来,避免业务层自己拼 SQL。
  613. */
  614. private static LeaveAuthSyncCtx selLeaveAuthSyncCtx(Db gdba, long rcid) throws Exception {
  615. String sql = "select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
  616. + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
  617. + " from RC rc"
  618. + " left join RY on ry.RYID=rc.FZRYID"
  619. + " where rc.RCID=:rcid";
  620. SqlCmd sqlCmd = new SqlCmd(sql);
  621. sqlCmd.wrLongParm("rcid", rcid);
  622. List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
  623. if (rowList == null || rowList.isEmpty())
  624. return null;
  625. Map<String, Object> row = rowList.get(0);
  626. return new LeaveAuthSyncCtx(
  627. rdLong(row.get("rcid")),
  628. rdLong(row.get("bjid")),
  629. rdLong(row.get("ryid")),
  630. rdInt(row.get("rclbm")),
  631. (Timestamp) row.get("kssj"),
  632. (Timestamp) row.get("jssj"),
  633. rdStr(row.get("xm")),
  634. rdStr(row.get("ryh")),
  635. rdStr(row.get("ms")),
  636. rdStr(row.get("mswj")),
  637. rdStr(row.get("wcmswj")));
  638. }
  639. /**
  640. * 2026-05-26:海康连接参数优先读配置,缺失时直接回退到现有默认网关参数。
  641. */
  642. private static Map<String, Object> makeHkConnParm() {
  643. String host = rdCfg(CFG_HOST, "HK_HOST");
  644. String appKey = rdCfg(CFG_APP_KEY, "HK_APP_KEY");
  645. String appSecret = rdCfg(CFG_APP_SECRET, "HK_APP_SECRET");
  646. if (StringUtils.isAnyBlank(host, appKey, appSecret))
  647. return makeDefaultHkConnParm();
  648. Map<String, Object> queryParm = new LinkedHashMap<>();
  649. queryParm.put("host", host);
  650. queryParm.put("port", rdIntCfg(CFG_PORT, "HK_PORT", HK_DEF_PORT));
  651. queryParm.put("appKey", appKey);
  652. queryParm.put("appSecret", appSecret);
  653. return queryParm;
  654. }
  655. /**
  656. * 2026-05-26:回读当前海康连接参数,给手工执行口复用。
  657. */
  658. private static Map<String, Object> rdHkConnParm() {
  659. return makeHkConnParm();
  660. }
  661. /**
  662. * 2026-05-26:请假权限直接按当前所有有效门禁点下发,避免再做班级或住宿点的额外过滤。
  663. */
  664. private static List<Map<String, Object>> makeResourceInfoList(List<Map<String, Object>> mjdList) {
  665. if (mjdList == null || mjdList.isEmpty())
  666. return List.of();
  667. LinkedHashSet<String> resourceIndexCodeSet = new LinkedHashSet<>();
  668. List<Map<String, Object>> resourceInfoList = new ArrayList<>();
  669. for (Map<String, Object> mjd : mjdList) {
  670. String resourceIndexCode = rdStr(mjd.get("sbbs"));
  671. if (StringUtils.isBlank(resourceIndexCode))
  672. continue;
  673. if (!resourceIndexCodeSet.add(resourceIndexCode))
  674. continue;
  675. resourceInfoList.add(makeResourceInfo(resourceIndexCode));
  676. }
  677. return resourceInfoList;
  678. }
  679. /**
  680. * 2026-05-26:把 MJD 记录回显成前端能直接看懂的资源来源列表。
  681. */
  682. private static List<Map<String, Object>> makeMjdRespList(List<Map<String, Object>> mjdList) {
  683. if (mjdList == null || mjdList.isEmpty())
  684. return List.of();
  685. List<Map<String, Object>> respList = new ArrayList<>();
  686. for (Map<String, Object> mjd : mjdList) {
  687. Map<String, Object> row = new LinkedHashMap<>();
  688. row.put("mjdid", rdLong(mjd.get("mjdid")));
  689. row.put("mc", rdStr(mjd.get("mc")));
  690. row.put("sbbs", rdStr(mjd.get("sbbs")));
  691. row.put("cdid", rdLong(mjd.get("cdid")));
  692. row.put("mjdlbm", rdLong(mjd.get("mjdlbm")));
  693. row.put("jcfxm", rdStr(mjd.get("jcfxm")));
  694. row.put("jlztm", rdLong(mjd.get("jlztm")));
  695. respList.add(row);
  696. }
  697. return respList;
  698. }
  699. /**
  700. * 2026-05-26:给海康 special/person/diy 拼单条门禁资源信息。
  701. */
  702. private static Map<String, Object> makeResourceInfo(String resourceIndexCode) {
  703. Map<String, Object> row = new LinkedHashMap<>();
  704. row.put("resourceIndexCode", resourceIndexCode);
  705. row.put("resourceType", "acsDevice");
  706. row.put("channelNos", List.of(1));
  707. row.put("channelIndexCodes", List.of(resourceIndexCode));
  708. return row;
  709. }
  710. /**
  711. * 2026-05-26:按海康文档组装请假特殊权限的真正下发体。
  712. */
  713. private static Map<String, Object> makeSpecialAuthPayload(LeaveAuthSyncCtx ctx,
  714. Map<String, Object> personInfo,
  715. String personId,
  716. List<Map<String, Object>> resourceInfoList,
  717. String tagId,
  718. String callbackUrl,
  719. String templateId,
  720. Integer templateDimension) {
  721. Map<String, Object> payload = new LinkedHashMap<>();
  722. payload.put("priority", 1);
  723. if (StringUtils.isNotBlank(callbackUrl))
  724. payload.put("callbackUrl", callbackUrl);
  725. payload.put("resourceInfos", resourceInfoList);
  726. payload.put("personInfos", List.of(makePersonInfoPayload(ctx, personInfo, personId)));
  727. if (StringUtils.isNotBlank(templateId))
  728. payload.put("templateConfigInfos", makeTemplateConfigInfos(templateId, templateDimension));
  729. return payload;
  730. }
  731. /**
  732. * 2026-05-26:把请假学生信息转成海康 special/person/diy 需要的 personInfos。
  733. */
  734. private static Map<String, Object> makePersonInfoPayload(LeaveAuthSyncCtx ctx,
  735. Map<String, Object> personInfo,
  736. String personId) {
  737. Map<String, Object> row = new LinkedHashMap<>();
  738. row.put("personStatus", "ADD");
  739. row.put("personId", personId);
  740. row.put("beginTime", makeHkTime(ctx.kssj));
  741. row.put("endTime", makeHkTime(ctx.jssj));
  742. row.put("name", rdStr(personInfo.get("personName")));
  743. row.put("personType", "COMMON");
  744. return row;
  745. }
  746. /**
  747. * 2026-05-26:海康权限模板配置只保留最小必要字段。
  748. */
  749. private static List<Map<String, Object>> makeTemplateConfigInfos(String templateId, Integer templateDimension) {
  750. if (StringUtils.isBlank(templateId))
  751. return List.of();
  752. Map<String, Object> row = new LinkedHashMap<>();
  753. row.put("dimension", templateDimension == null || templateDimension <= 0 ? HK_DEF_TEMPLATE_DIMENSION : templateDimension);
  754. row.put("templateId", templateId);
  755. return List.of(row);
  756. }
  757. /**
  758. * 2026-05-28:按平台权限配置模式执行。
  759. * 流程:添加权限配置 -> 查询配置进度 -> 按配置快捷下载 -> 查询下载进度。
  760. */
  761. private static Map<String, Object> runPlatformConfigMode(Db gdba,
  762. LeaveAuthSyncCtx ctx,
  763. Map<String, Object> personInfo,
  764. String personId,
  765. List<Map<String, Object>> resourceInfoList,
  766. String tagId,
  767. String callbackUrl,
  768. String templateId,
  769. Integer templateDimension,
  770. Map<String, Object> legacyPayload,
  771. Map<String, Object> result) throws Exception {
  772. Map<String, Object> hkConnParm = makeHkConnParm();
  773. if (hkConnParm == null) {
  774. result.put("ok", false);
  775. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  776. persistLeaveAuthSyncResult(gdba, ctx, result);
  777. return result;
  778. }
  779. if (StringUtils.isNotBlank(tagId))
  780. hkConnParm.put("tagId", tagId);
  781. Map<String, Object> configAddReq = makeAuthConfigAddReq(personId, resourceInfoList, ctx.kssj, ctx.jssj);
  782. result.put("platformConfigAddReq", configAddReq);
  783. result.put("executeApiPath", "/artemis/api/acps/v1/auth_config/add");
  784. result.put("resultApiPath", "/artemis/api/acps/v1/auth_config/rate/search");
  785. result.put("downloadApiPath", "/artemis/api/acps/v1/authDownload/configuration/person/reset");
  786. result.put("downloadTaskProgressApiPath", "/artemis/api/acps/v1/authDownload/task/progress");
  787. result.put("downloadTaskSearchApiPath", "/artemis/api/acps/v1/authDownload/task/search");
  788. result.put("downloadRecordChannelApiPath", "/artemis/api/acps/v1/download_record/channel/list/search");
  789. result.put("downloadRecordPersonDetailApiPath", "/artemis/api/acps/v2/download_record/person/detail/search");
  790. boolean callbackConfigured = StringUtils.isNotBlank(callbackUrl);
  791. result.put("callbackConfigured", callbackConfigured);
  792. if (callbackConfigured)
  793. result.put("platformCallbackUrl", callbackUrl);
  794. if (StringUtils.isNotBlank(templateId))
  795. result.put("platformTemplateId", templateId);
  796. result.put("platformTemplateDimension", templateDimension);
  797. result.put("payload", legacyPayload);
  798. Map<String, Object> configAddResp = HK_API_CLIENT.addAuthConfig(hkConnParm, configAddReq);
  799. result.put("authSyncResp", configAddResp);
  800. result.put("mode", "execute_platform_config");
  801. String configTaskId = rdTaskId(configAddResp);
  802. result.put("configTaskId", configTaskId);
  803. if (StringUtils.isBlank(configTaskId)) {
  804. result.put("ok", false);
  805. result.put("msg", "平台权限配置返回成功,但未拿到 taskId。");
  806. persistLeaveAuthSyncResult(gdba, ctx, result);
  807. return result;
  808. }
  809. Map<String, Object> configRateReq = Map.of("taskId", configTaskId);
  810. result.put("authConfigRateReq", configRateReq);
  811. try {
  812. result.put("authConfigRateResp", HK_API_CLIENT.searchAuthConfigRate(hkConnParm, configRateReq));
  813. } catch (Exception e) {
  814. result.put("authConfigRateError", e.getMessage());
  815. }
  816. Map<String, Object> configSearchReq = makeAuthConfigSearchReq(personId, resourceInfoList);
  817. result.put("authConfigSearchReq", configSearchReq);
  818. try {
  819. result.put("authConfigSearchResp", HK_API_CLIENT.searchAuthConfig(hkConnParm, configSearchReq));
  820. } catch (Exception e) {
  821. result.put("authConfigSearchError", e.getMessage());
  822. }
  823. boolean autoDownload = rdBoolCfg("hk.leaveAuth.platform.autoDownload", "HK_LEAVE_AUTH_PLATFORM_AUTO_DOWNLOAD", true);
  824. result.put("downloadMode", autoDownload ? "platformConfigAndDownload" : "platformConfigOnly");
  825. if (autoDownload) {
  826. Map<String, Object> resetReq = makeAuthConfigPersonResetReq(personId, resourceInfoList, callbackUrl);
  827. result.put("authDownloadResetReq", resetReq);
  828. Map<String, Object> resetResp = HK_API_CLIENT.resetAuthDownloadByPerson(hkConnParm, resetReq);
  829. result.put("authDownloadResetResp", resetResp);
  830. boolean downloadResetAccepted = isHkRespAccepted(resetResp);
  831. result.put("downloadResetAccepted", downloadResetAccepted);
  832. String downloadTaskId = rdTaskId(resetResp);
  833. String downloadTaskSource = downloadResetAccepted || StringUtils.isNotBlank(downloadTaskId) ? "personReset" : null;
  834. result.put("downloadTaskAccepted", downloadResetAccepted || StringUtils.isNotBlank(downloadTaskId));
  835. result.put("downloadTaskId", downloadTaskId);
  836. result.put("downloadTaskSource", downloadTaskSource);
  837. if (downloadResetAccepted && StringUtils.isBlank(downloadTaskId)) {
  838. result.put("downloadPendingReason",
  839. callbackConfigured ? "resetAcceptedAwaitCallback" : "resetAcceptedWithoutTaskIdOrCallback");
  840. } else if (!downloadResetAccepted) {
  841. result.put("downloadPendingReason", "resetNotAccepted");
  842. }
  843. if (StringUtils.isNotBlank(downloadTaskId)) {
  844. Map<String, Object> taskSearchReq = makeAuthDownloadTaskSearchReq(downloadTaskId);
  845. result.put("authDownloadTaskSearchReq", taskSearchReq);
  846. try {
  847. result.put("authDownloadTaskSearchResp",
  848. queryAuthDownloadTaskSearchWithRetry(hkConnParm, taskSearchReq));
  849. } catch (Exception e) {
  850. result.put("authDownloadTaskSearchError", e.getMessage());
  851. }
  852. Map<String, Object> progressReq = Map.of("taskId", downloadTaskId);
  853. result.put("authDownloadTaskProgressReq", progressReq);
  854. try {
  855. result.put("authDownloadTaskProgressResp",
  856. queryAuthDownloadTaskProgressWithRetry(hkConnParm, progressReq));
  857. } catch (Exception e) {
  858. result.put("authDownloadTaskProgressError", e.getMessage());
  859. }
  860. Map<String, Object> channelRecordReq = makeDownloadRecordChannelListReq(downloadTaskId, resourceInfoList);
  861. result.put("downloadRecordChannelReq", channelRecordReq);
  862. try {
  863. Map<String, Object> channelRecordResp = queryDownloadRecordChannelListWithRetry(
  864. hkConnParm, channelRecordReq, resourceInfoList);
  865. result.put("downloadRecordChannelResp", channelRecordResp);
  866. result.put("downloadRecordPersonDetailReqList",
  867. makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRecordResp));
  868. result.put("downloadRecordPersonDetailRespList",
  869. queryDownloadRecordPersonDetailRespListWithRetry(hkConnParm, downloadTaskId, personId, channelRecordResp));
  870. } catch (Exception e) {
  871. result.put("downloadRecordQueryError", e.getMessage());
  872. }
  873. }
  874. }
  875. finalizePlatformConfigResult(result, ctx.kssj, ctx.jssj, resourceInfoList.size(), autoDownload);
  876. logExecute(ctx, personInfo, configAddReq, configAddResp);
  877. persistLeaveAuthSyncResult(gdba, ctx, result);
  878. return result;
  879. }
  880. /**
  881. * 2026-05-28:按平台权限配置方式,给系统内人员配置门禁点权限。
  882. */
  883. private static Map<String, Object> makeAuthConfigAddReq(String personId,
  884. List<Map<String, Object>> resourceInfoList,
  885. Timestamp kssj,
  886. Timestamp jssj) {
  887. Map<String, Object> req = new LinkedHashMap<>();
  888. Map<String, Object> personData = new LinkedHashMap<>();
  889. personData.put("indexCodes", List.of(personId));
  890. personData.put("personDataType", "person");
  891. req.put("personDatas", List.of(personData));
  892. req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
  893. req.put("startTime", makeHkTime(kssj));
  894. req.put("endTime", makeHkTime(jssj));
  895. return req;
  896. }
  897. /**
  898. * 2026-06-02:平台配置完成后,按人员和设备通道做一次定向重下发,更贴近“请假单即时生效”场景。
  899. */
  900. private static Map<String, Object> makeAuthConfigPersonResetReq(String personId,
  901. List<Map<String, Object>> resourceInfoList,
  902. String callbackUrl) {
  903. Map<String, Object> req = new LinkedHashMap<>();
  904. req.put("personIds", List.of(personId));
  905. req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
  906. req.put("isReset", false);
  907. if (StringUtils.isNotBlank(callbackUrl))
  908. req.put("callbackUrl", callbackUrl);
  909. return req;
  910. }
  911. /**
  912. * 2026-06-02:下载任务摘要查询需要按 taskId 精确查询。
  913. */
  914. private static Map<String, Object> makeAuthDownloadTaskSearchReq(String downloadTaskId) {
  915. Map<String, Object> req = new LinkedHashMap<>();
  916. req.put("authTaskIds", List.of(downloadTaskId));
  917. req.put("pageNo", 1);
  918. req.put("pageSize", 10);
  919. return req;
  920. }
  921. /**
  922. * 2026-06-02:按任务号回查设备通道下载记录。
  923. */
  924. private static Map<String, Object> makeDownloadRecordChannelListReq(String downloadTaskId,
  925. List<Map<String, Object>> resourceInfoList) {
  926. Map<String, Object> req = new LinkedHashMap<>();
  927. req.put("taskId", downloadTaskId);
  928. req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
  929. req.put("pageNo", 1);
  930. int pageSize = resourceInfoList == null ? 100 : Math.max(100, Math.min(1000, resourceInfoList.size() * 2));
  931. req.put("pageSize", pageSize);
  932. return req;
  933. }
  934. /**
  935. * 2026-05-28:平台权限配置查询请求体。
  936. */
  937. private static Map<String, Object> makeAuthConfigSearchReq(String personId,
  938. List<Map<String, Object>> resourceInfoList) {
  939. Map<String, Object> req = new LinkedHashMap<>();
  940. req.put("personDataIds", List.of(personId));
  941. req.put("personDataType", "person");
  942. req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
  943. req.put("resourceDataType", "resource");
  944. req.put("pageNo", 1);
  945. int pageSize = resourceInfoList == null ? 20 : Math.max(20, Math.min(200, resourceInfoList.size()));
  946. req.put("pageSize", pageSize);
  947. return req;
  948. }
  949. /**
  950. * 2026-05-28:平台权限配置和快捷下载复用同一批资源,但不强制带 channelIndexCodes。
  951. */
  952. private static List<Map<String, Object>> makeAuthConfigResourceInfoList(List<Map<String, Object>> resourceInfoList) {
  953. if (resourceInfoList == null || resourceInfoList.isEmpty())
  954. return List.of();
  955. List<Map<String, Object>> respList = new ArrayList<>();
  956. for (Map<String, Object> item : resourceInfoList) {
  957. Map<String, Object> row = new LinkedHashMap<>();
  958. row.put("resourceIndexCode", rdStr(item.get("resourceIndexCode")));
  959. row.put("resourceType", rdStr(item.get("resourceType")));
  960. row.put("channelNos", item.get("channelNos"));
  961. respList.add(row);
  962. }
  963. return respList;
  964. }
  965. /**
  966. * 2026-05-28:海康平台类接口统一从 data.taskId 中取任务号。
  967. */
  968. private static String rdTaskId(Map<String, Object> resp) {
  969. if (resp == null)
  970. return null;
  971. Object dataObj = resp.get("data");
  972. if (!(dataObj instanceof Map<?, ?> dataMap))
  973. return null;
  974. return rdStr(dataMap.get("taskId"));
  975. }
  976. /**
  977. * 2026-05-26:查询下发结果时,沿用“人 + 资源”这组关键条件。
  978. */
  979. private static Map<String, Object> makeAuthDownloadResultQueryReq(String personId,
  980. List<Map<String, Object>> resourceInfoList) {
  981. Map<String, Object> row = new LinkedHashMap<>();
  982. row.put("pageNo", 1);
  983. row.put("pageSize", 20);
  984. row.put("personIds", List.of(personId));
  985. row.put("resourceInfos", resourceInfoList);
  986. return row;
  987. }
  988. /**
  989. * 2026-06-02:special/person/diy/result 也是异步落库,短轮询几次再看是否已有明细。
  990. */
  991. private static Map<String, Object> querySpecialPersonAuthDownloadResultWithRetry(Map<String, Object> hkConnParm,
  992. Map<String, Object> queryReq) throws Exception {
  993. Map<String, Object> lastResp = null;
  994. int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.resultPollCount",
  995. "HK_LEAVE_AUTH_RESULT_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
  996. int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.resultPollSleepMs",
  997. "HK_LEAVE_AUTH_RESULT_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
  998. for (int i = 0; i < pollCount; i++) {
  999. if (i > 0 && sleepMs > 0) {
  1000. try {
  1001. Thread.sleep(sleepMs);
  1002. } catch (InterruptedException e) {
  1003. Thread.currentThread().interrupt();
  1004. break;
  1005. }
  1006. }
  1007. lastResp = HK_API_CLIENT.viewSpecialPersonAuthDownloadResult(hkConnParm, queryReq);
  1008. if (hasSpecialPersonAuthDownloadResult(lastResp))
  1009. break;
  1010. }
  1011. return lastResp;
  1012. }
  1013. /**
  1014. * 2026-05-26:把当前缺少的配置转换成可执行的下一步,减少联调时反复口头确认。
  1015. */
  1016. private static List<String> makeNextStepList(List<String> missingCfgList) {
  1017. List<String> nextStepList = new ArrayList<>();
  1018. if (missingCfgList == null || missingCfgList.isEmpty()) {
  1019. nextStepList.add("已具备海康下发参数,可直接调用 hkkq_leave_auth_execute 做人工联调。");
  1020. nextStepList.add("下发后可调用 hkkq_leave_auth_result 查看海康侧结果。");
  1021. return nextStepList;
  1022. }
  1023. if (missingCfgList.contains("tagId"))
  1024. nextStepList.add("联系海康侧提供当前合作方账号可用的 tagId。");
  1025. nextStepList.add("配置补齐前可继续使用 hkkq_leave_auth_preview / hkkq_leave_auth_diag 做联调。");
  1026. nextStepList.add("配置补齐后先调用 hkkq_leave_auth_execute,再调用 hkkq_leave_auth_result 回查。");
  1027. return nextStepList;
  1028. }
  1029. /**
  1030. * 2026-05-26:single/search 需要“人员 + 单个门禁资源”的精确查询体。
  1031. * 2026-05-26:这里按海康文档只传最小查询字段,不再把 channelIndexCodes 混进 single/search。
  1032. */
  1033. private static Map<String, Object> makeSingleAuthItemSearchReq(String personId,
  1034. Map<String, Object> resourceInfo) {
  1035. Map<String, Object> row = new LinkedHashMap<>();
  1036. row.put("personId", personId);
  1037. row.put("resourceInfo", makeSingleAuthItemSearchResourceInfo(resourceInfo));
  1038. return row;
  1039. }
  1040. /**
  1041. * 2026-05-26:single/search 使用最小 resourceInfo,避免把 special/person/diy 的字段误传过去。
  1042. */
  1043. private static Map<String, Object> makeSingleAuthItemSearchResourceInfo(Map<String, Object> resourceInfo) {
  1044. Map<String, Object> row = new LinkedHashMap<>();
  1045. if (resourceInfo == null)
  1046. return row;
  1047. putIfNotBlank(row, "resourceIndexCode", rdStr(resourceInfo.get("resourceIndexCode")));
  1048. putIfNotBlank(row, "resourceType", rdStr(resourceInfo.get("resourceType")));
  1049. Object channelNos = resourceInfo.get("channelNos");
  1050. if (channelNos instanceof List<?> list && !list.isEmpty())
  1051. row.put("channelNos", list);
  1052. return row;
  1053. }
  1054. /**
  1055. * 2026-05-26:从 single/search 的返回里提取模板编号,作为模板配置的兜底来源。
  1056. */
  1057. private static String extTemplateId(Object obj) {
  1058. if (obj == null)
  1059. return null;
  1060. if (obj instanceof Map<?, ?> map) {
  1061. Object templateConfigInfos = map.get("templateConfigInfos");
  1062. String templateId = extTemplateIdFromList(templateConfigInfos);
  1063. if (StringUtils.isNotBlank(templateId))
  1064. return templateId;
  1065. for (Object value : map.values()) {
  1066. templateId = extTemplateId(value);
  1067. if (StringUtils.isNotBlank(templateId))
  1068. return templateId;
  1069. }
  1070. return null;
  1071. }
  1072. if (obj instanceof List<?> list) {
  1073. for (Object item : list) {
  1074. String templateId = extTemplateId(item);
  1075. if (StringUtils.isNotBlank(templateId))
  1076. return templateId;
  1077. }
  1078. }
  1079. return null;
  1080. }
  1081. /**
  1082. * 2026-05-26:优先取模板列表第一条,避免一张表里多个模板时取值不稳定。
  1083. */
  1084. private static String extTemplateIdFromList(Object templateConfigInfos) {
  1085. if (!(templateConfigInfos instanceof List<?> list) || list.isEmpty())
  1086. return null;
  1087. for (Object item : list) {
  1088. if (item instanceof Map<?, ?> map) {
  1089. Object templateId = map.get("templateId");
  1090. String value = rdStr(templateId);
  1091. if (StringUtils.isNotBlank(value))
  1092. return value;
  1093. }
  1094. }
  1095. return null;
  1096. }
  1097. /**
  1098. * 2026-05-26:把响应体里的所有 templateId 候选都收集出来,供诊断页直接回显。
  1099. */
  1100. private static List<String> extTemplateIdList(Object obj) {
  1101. LinkedHashSet<String> valueSet = new LinkedHashSet<>();
  1102. extTemplateIdList0(obj, valueSet);
  1103. return new ArrayList<>(valueSet);
  1104. }
  1105. /**
  1106. * 2026-05-26:递归收集 templateId,避免只拿到第一条导致排查信息不完整。
  1107. */
  1108. private static void extTemplateIdList0(Object obj, LinkedHashSet<String> valueSet) {
  1109. if (obj == null || valueSet == null)
  1110. return;
  1111. if (obj instanceof Map<?, ?> map) {
  1112. Object templateId = map.get("templateId");
  1113. if (templateId != null) {
  1114. String value = rdStr(templateId);
  1115. if (StringUtils.isNotBlank(value))
  1116. valueSet.add(value);
  1117. }
  1118. for (Map.Entry<?, ?> entry : map.entrySet()) {
  1119. if ("templateId".equals(String.valueOf(entry.getKey())))
  1120. continue;
  1121. extTemplateIdList0(entry.getValue(), valueSet);
  1122. }
  1123. return;
  1124. }
  1125. if (obj instanceof List<?> list) {
  1126. for (Object item : list)
  1127. extTemplateIdList0(item, valueSet);
  1128. }
  1129. }
  1130. /**
  1131. * 2026-05-26:日志只保留关键定位信息,避免把整段 payload 以外再重复刷屏。
  1132. */
  1133. private static void logDryRun(LeaveAuthSyncCtx ctx,
  1134. Map<String, Object> personInfo,
  1135. Map<String, Object> payload) {
  1136. Map<String, Object> logRow = makeBaseLogRow(ctx);
  1137. logRow.put("mode", "dryRun");
  1138. logRow.put("personId", rdStr(personInfo.get("personId")));
  1139. logRow.put("resourceCount", rdListSize(payload.get("resourceInfos")));
  1140. logRow.put("templateCount", rdListSize(payload.get("templateConfigInfos")));
  1141. log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() dry-run:{}", logRow);
  1142. }
  1143. /**
  1144. * 2026-05-26:真实下发时记录海康返回和本地关键字段,便于复盘。
  1145. */
  1146. private static void logExecute(LeaveAuthSyncCtx ctx,
  1147. Map<String, Object> personInfo,
  1148. Map<String, Object> payload,
  1149. Map<String, Object> authSyncResp) {
  1150. Map<String, Object> logRow = makeBaseLogRow(ctx);
  1151. logRow.put("mode", "execute");
  1152. logRow.put("personId", rdStr(personInfo.get("personId")));
  1153. logRow.put("resourceCount", rdListSize(payload.get("resourceInfos")));
  1154. logRow.put("authSyncResp", authSyncResp);
  1155. log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 已执行:{}", logRow);
  1156. }
  1157. /**
  1158. * 2026-05-29:请假备注以用户提交的 `RC.ms` 为准,海康任务号与结果摘要改写到 `RC.wcmswj`。
  1159. */
  1160. private static void persistLeaveAuthSyncResult(Db gdba,
  1161. LeaveAuthSyncCtx ctx,
  1162. Map<String, Object> result) throws Exception {
  1163. if (gdba == null || ctx == null || result == null || ctx.rcid <= 0)
  1164. return;
  1165. String mode = rdStr(result.get("mode"));
  1166. boolean shouldPersist = Boolean.TRUE.equals(result.get("autoTrigger"))
  1167. || (StringUtils.isNotBlank(mode) && mode.startsWith("execute"));
  1168. if (!shouldPersist)
  1169. return;
  1170. String persistText = fitWcmswjText(makeLeaveAuthPersistText(ctx, result));
  1171. if (StringUtils.isBlank(persistText)) {
  1172. log4j.warn("HkLeaveAuthServ.persistLeaveAuthSyncResult() skip empty rc.wcmswj, rcid={}, mode={}, ok={}, msg={}",
  1173. ctx.rcid, rdStr(result.get("mode")), rdStr(result.get("ok")), rdStr(result.get("msg")));
  1174. return;
  1175. }
  1176. RcPo rcPo = new RcPo();
  1177. rcPo.setRcid(ctx.rcid);
  1178. rcPo.setWcmswj(persistText);
  1179. gdba.doUpdPo(rcPo, Set.of("wcmswj"));
  1180. gdba.commit();
  1181. log4j.info("HkLeaveAuthServ.persistLeaveAuthSyncResult() saved rc.wcmswj, rcid={}, mode={}, ok={}, msg={}",
  1182. ctx.rcid, rdStr(result.get("mode")), rdStr(result.get("ok")), rdStr(result.get("msg")));
  1183. }
  1184. /**
  1185. * 2026-06-01:自动同步若在主链路里抛异常,至少把异常摘要回写到 RC,避免线上完全没有痕迹。
  1186. */
  1187. private static void persistUnexpectedSyncError(long rcid, Exception e) {
  1188. if (rcid <= 0 || e == null)
  1189. return;
  1190. try (Db gdba = Db.makeConn()) {
  1191. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
  1192. if (ctx == null)
  1193. return;
  1194. Map<String, Object> result = new LinkedHashMap<>();
  1195. result.put("autoTrigger", true);
  1196. result.put("ok", false);
  1197. result.put("mode", "autoError");
  1198. result.put("skipReason", "自动同步执行异常。");
  1199. result.put("msg", makeExceptionMsg(e));
  1200. persistLeaveAuthSyncResult(gdba, ctx, result);
  1201. gdba.commit();
  1202. } catch (Exception persistEx) {
  1203. log4j.error("HkLeaveAuthServ.persistUnexpectedSyncError() 异常,rcid={}", rcid, persistEx);
  1204. }
  1205. }
  1206. /**
  1207. * 2026-05-29:把关键任务号和执行摘要压缩到 RC.wcmswj,供后续结果回查复用。
  1208. */
  1209. private static String makeLeaveAuthPersistText(LeaveAuthSyncCtx ctx, Map<String, Object> result) {
  1210. if (result == null)
  1211. return null;
  1212. LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
  1213. mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.ms);
  1214. mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.mswj);
  1215. mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.wcmswj);
  1216. putLeaveAuthPersistField(fieldMap, "syncTime", makeHkTime(new Timestamp(System.currentTimeMillis())));
  1217. putLeaveAuthPersistField(fieldMap, "mode", rdStr(result.get("mode")));
  1218. putLeaveAuthPersistField(fieldMap, "ok", rdStr(result.get("ok")));
  1219. putLeaveAuthPersistField(fieldMap, "msg", rdStr(result.get("msg")));
  1220. putLeaveAuthPersistField(fieldMap, "configTaskId", rdStr(result.get("configTaskId")));
  1221. putLeaveAuthPersistField(fieldMap, "downloadTaskId", rdStr(result.get("downloadTaskId")));
  1222. putLeaveAuthPersistField(fieldMap, "downloadTaskSource", rdStr(result.get("downloadTaskSource")));
  1223. putLeaveAuthPersistField(fieldMap, "callbackConfigured", rdStr(result.get("callbackConfigured")));
  1224. putLeaveAuthPersistField(fieldMap, "downloadResetAccepted", rdStr(result.get("downloadResetAccepted")));
  1225. putLeaveAuthPersistField(fieldMap, "downloadTaskAccepted", rdStr(result.get("downloadTaskAccepted")));
  1226. putLeaveAuthPersistField(fieldMap, "downloadPendingReason", rdStr(result.get("downloadPendingReason")));
  1227. putLeaveAuthPersistField(fieldMap, "downloadConfirmSource", rdStr(result.get("downloadConfirmSource")));
  1228. putLeaveAuthPersistField(fieldMap, "downloadResultConfirmed", rdStr(result.get("downloadResultConfirmed")));
  1229. putLeaveAuthPersistField(fieldMap, "downloadTaskFinished", rdStr(result.get("downloadTaskFinished")));
  1230. putLeaveAuthPersistField(fieldMap, "downloadProgressFinished", rdStr(result.get("downloadProgressFinished")));
  1231. putLeaveAuthPersistField(fieldMap, "downloadRecordChannelMatchedCount", rdStr(result.get("downloadRecordChannelMatchedCount")));
  1232. putLeaveAuthPersistField(fieldMap, "downloadRecordChannelSuccessCount", rdStr(result.get("downloadRecordChannelSuccessCount")));
  1233. putLeaveAuthPersistField(fieldMap, "downloadRecordChannelFailedCount", rdStr(result.get("downloadRecordChannelFailedCount")));
  1234. putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailMatchedCount", rdStr(result.get("downloadRecordPersonDetailMatchedCount")));
  1235. putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailSuccessCount", rdStr(result.get("downloadRecordPersonDetailSuccessCount")));
  1236. putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailFailedCount", rdStr(result.get("downloadRecordPersonDetailFailedCount")));
  1237. putLeaveAuthPersistField(fieldMap, "downloadCallbackReceived", rdStr(result.get("downloadCallbackReceived")));
  1238. putLeaveAuthPersistField(fieldMap, "callbackTaskId", rdStr(result.get("callbackTaskId")));
  1239. putLeaveAuthPersistField(fieldMap, "callbackRecvTime", rdStr(result.get("callbackRecvTime")));
  1240. putLeaveAuthPersistField(fieldMap, "callbackBodySize", rdStr(result.get("callbackBodySize")));
  1241. putLeaveAuthPersistField(fieldMap, "callbackMatchedRcid", rdStr(result.get("callbackMatchedRcid")));
  1242. putLeaveAuthPersistField(fieldMap, "callbackResourceKey", rdStr(result.get("callbackResourceKey")));
  1243. putLeaveAuthPersistField(fieldMap, "callbackResourceDownloadResult", rdStr(result.get("callbackResourceDownloadResult")));
  1244. putLeaveAuthPersistField(fieldMap, "callbackResourceSuccessCount", rdStr(result.get("callbackResourceSuccessCount")));
  1245. putLeaveAuthPersistField(fieldMap, "callbackResourceFailedCount", rdStr(result.get("callbackResourceFailedCount")));
  1246. putLeaveAuthPersistField(fieldMap, "callbackPersonId", rdStr(result.get("callbackPersonId")));
  1247. putLeaveAuthPersistField(fieldMap, "callbackPersonDownloadResult", rdStr(result.get("callbackPersonDownloadResult")));
  1248. putLeaveAuthPersistField(fieldMap, "authSyncResp", makeRespBrief(result.get("authSyncResp")));
  1249. putLeaveAuthPersistField(fieldMap, "authDownloadResultQueryResp", makeRespBrief(result.get("authDownloadResultQueryResp")));
  1250. putLeaveAuthPersistField(fieldMap, "authDownloadResetResp", makeRespBrief(result.get("authDownloadResetResp")));
  1251. putLeaveAuthPersistField(fieldMap, "downloadRecordChannelResp", makeRespBrief(result.get("downloadRecordChannelResp")));
  1252. putLeaveAuthPersistField(fieldMap, "authConfigRateResp", makeRespBrief(result.get("authConfigRateResp")));
  1253. putLeaveAuthPersistField(fieldMap, "authDownloadTaskSearchResp", makeRespBrief(result.get("authDownloadTaskSearchResp")));
  1254. putLeaveAuthPersistField(fieldMap, "authDownloadTaskProgressResp", makeRespBrief(result.get("authDownloadTaskProgressResp")));
  1255. List<String> partList = new ArrayList<>();
  1256. for (Map.Entry<String, String> entry : fieldMap.entrySet())
  1257. appendLeaveAuthPersistField(partList, entry.getKey(), entry.getValue());
  1258. return partList.isEmpty() ? null : String.join(";", partList);
  1259. }
  1260. /**
  1261. * 2026-06-01:RC.wcmswj 按数据库字节上限统一截断,避免再次抛 ORA-12899。
  1262. */
  1263. private static String fitWcmswjText(String text) {
  1264. String value = StringUtils.trimToNull(text);
  1265. if (value == null)
  1266. return null;
  1267. byte[] allBytes = value.getBytes(StandardCharsets.UTF_8);
  1268. if (allBytes.length <= RC_WCMSWJ_MAX_BYTES)
  1269. return value;
  1270. int suffixBytes = RC_WCMSWJ_TRUNCATE_SUFFIX.getBytes(StandardCharsets.UTF_8).length;
  1271. int maxContentBytes = Math.max(0, RC_WCMSWJ_MAX_BYTES - suffixBytes);
  1272. StringBuilder sb = new StringBuilder();
  1273. int usedBytes = 0;
  1274. for (int idx = 0; idx < value.length();) {
  1275. int codePoint = value.codePointAt(idx);
  1276. String ch = new String(Character.toChars(codePoint));
  1277. int chBytes = ch.getBytes(StandardCharsets.UTF_8).length;
  1278. if (usedBytes + chBytes > maxContentBytes)
  1279. break;
  1280. sb.append(ch);
  1281. usedBytes += chBytes;
  1282. idx += Character.charCount(codePoint);
  1283. }
  1284. return sb.append(RC_WCMSWJ_TRUNCATE_SUFFIX).toString();
  1285. }
  1286. /**
  1287. * 2026-05-29:统一拼接 RC.mswj 的键值对格式,兼容现有 field=value 读取逻辑。
  1288. */
  1289. private static void appendLeaveAuthPersistField(List<String> partList, String fieldName, String value) {
  1290. if (partList == null || StringUtils.isAnyBlank(fieldName, value))
  1291. return;
  1292. partList.add(fieldName + "=" + value.replace(';', ';'));
  1293. }
  1294. /**
  1295. * 2026-06-02:回写 RC.wcmswj 前先把旧字段合并进来,避免回调补写时把前序 taskId/配置摘要覆盖丢失。
  1296. */
  1297. private static void mergeLeaveAuthPersistFieldMap(Map<String, String> fieldMap, String text) {
  1298. if (fieldMap == null || StringUtils.isBlank(text))
  1299. return;
  1300. String[] partArr = StringUtils.split(text, ';');
  1301. if (partArr == null || partArr.length == 0)
  1302. return;
  1303. for (String part : partArr) {
  1304. String trimPart = StringUtils.trimToNull(part);
  1305. if (trimPart == null)
  1306. continue;
  1307. int idx = trimPart.indexOf('=');
  1308. if (idx <= 0 || idx >= trimPart.length() - 1)
  1309. continue;
  1310. fieldMap.put(StringUtils.trim(trimPart.substring(0, idx)),
  1311. StringUtils.trim(trimPart.substring(idx + 1)));
  1312. }
  1313. }
  1314. /**
  1315. * 2026-06-02:持久化字段统一后写覆盖,便于同一个 rc 反复补充下载任务与回调状态。
  1316. */
  1317. private static void putLeaveAuthPersistField(Map<String, String> fieldMap, String fieldName, String value) {
  1318. if (fieldMap == null || StringUtils.isAnyBlank(fieldName, value))
  1319. return;
  1320. fieldMap.put(fieldName, value);
  1321. }
  1322. /**
  1323. * 2026-06-01:把异常压成一行,既能定位错误类型,也不会把 RC 字段撑得过长。
  1324. */
  1325. private static String makeExceptionMsg(Exception e) {
  1326. if (e == null)
  1327. return null;
  1328. String className = e.getClass().getSimpleName();
  1329. String msg = StringUtils.trimToNull(e.getMessage());
  1330. if (StringUtils.isBlank(msg))
  1331. return className;
  1332. String text = className + ": " + msg;
  1333. return text.length() > 180 ? text.substring(0, 180) : text;
  1334. }
  1335. /**
  1336. * 2026-05-27:把海康返回对象压缩成简短描述,避免 RC 备注和描述文件过长。
  1337. */
  1338. private static String makeRespBrief(Object resp) {
  1339. if (!(resp instanceof Map<?, ?> map))
  1340. return rdStr(resp);
  1341. String code = rdStr(map.get("code"));
  1342. String msg = rdStr(map.get("msg"));
  1343. if (StringUtils.isAllBlank(code, msg))
  1344. return null;
  1345. if (StringUtils.isBlank(code))
  1346. return msg;
  1347. if (StringUtils.isBlank(msg))
  1348. return "code=" + code;
  1349. return "code=" + code + ", msg=" + msg;
  1350. }
  1351. /**
  1352. * 2026-06-01:海康临时权限对已结束请假没有意义,统一在服务入口层提前拦住。
  1353. */
  1354. static boolean ifLeaveEnded(Timestamp leaveEnd, Timestamp now) {
  1355. if (leaveEnd == null)
  1356. return false;
  1357. Timestamp baseTime = now == null ? new Timestamp(System.currentTimeMillis()) : now;
  1358. return !leaveEnd.after(baseTime);
  1359. }
  1360. /**
  1361. * 2026-05-28:从 RC 备注里提取上次执行时写回的字段值。
  1362. */
  1363. private static String rdLeaveAuthLogField(String text, String fieldName) {
  1364. if (StringUtils.isAnyBlank(text, fieldName))
  1365. return null;
  1366. String prefix = fieldName + "=";
  1367. String[] partArr = StringUtils.split(text, ';');
  1368. if (partArr == null || partArr.length == 0)
  1369. return null;
  1370. for (String part : partArr) {
  1371. String trimmedPart = StringUtils.trimToEmpty(part);
  1372. if (!trimmedPart.startsWith(prefix))
  1373. continue;
  1374. return StringUtils.trimToNull(trimmedPart.substring(prefix.length()));
  1375. }
  1376. return null;
  1377. }
  1378. /**
  1379. * 2026-05-29:优先从 RC.wcmswj 读海康任务号,兼容旧数据再回退旧版 RC.mswj/RC.ms。
  1380. */
  1381. private static String rdLeaveAuthLogField(LeaveAuthSyncCtx ctx, String fieldName) {
  1382. if (ctx == null)
  1383. return null;
  1384. String value = rdLeaveAuthLogField(ctx.wcmswj, fieldName);
  1385. if (StringUtils.isNotBlank(value))
  1386. return value;
  1387. value = rdLeaveAuthLogField(ctx.mswj, fieldName);
  1388. if (StringUtils.isNotBlank(value))
  1389. return value;
  1390. return rdLeaveAuthLogField(ctx.ms, fieldName);
  1391. }
  1392. /**
  1393. * 2026-06-02:把已落库的下载任务来源与最近一次回调摘要补回结果对象,便于结果页直接看见。
  1394. */
  1395. private static void applyPersistedLeaveAuthSnapshot(LeaveAuthSyncCtx ctx, Map<String, Object> result) {
  1396. if (ctx == null || result == null)
  1397. return;
  1398. putPersistedField(result, "callbackConfigured", rdLeaveAuthLogField(ctx, "callbackConfigured"));
  1399. putPersistedField(result, "downloadResetAccepted", rdLeaveAuthLogField(ctx, "downloadResetAccepted"));
  1400. putPersistedField(result, "downloadTaskAccepted", rdLeaveAuthLogField(ctx, "downloadTaskAccepted"));
  1401. putPersistedField(result, "downloadTaskId", rdLeaveAuthLogField(ctx, "downloadTaskId"));
  1402. putPersistedField(result, "downloadTaskSource", rdLeaveAuthLogField(ctx, "downloadTaskSource"));
  1403. putPersistedField(result, "downloadPendingReason", rdLeaveAuthLogField(ctx, "downloadPendingReason"));
  1404. putPersistedField(result, "downloadConfirmSource", rdLeaveAuthLogField(ctx, "downloadConfirmSource"));
  1405. putPersistedField(result, "downloadResultConfirmed", rdLeaveAuthLogField(ctx, "downloadResultConfirmed"));
  1406. putPersistedField(result, "downloadCallbackReceived", rdLeaveAuthLogField(ctx, "downloadCallbackReceived"));
  1407. putPersistedField(result, "callbackTaskId", rdLeaveAuthLogField(ctx, "callbackTaskId"));
  1408. putPersistedField(result, "callbackRecvTime", rdLeaveAuthLogField(ctx, "callbackRecvTime"));
  1409. putPersistedField(result, "callbackBodySize", rdLeaveAuthLogField(ctx, "callbackBodySize"));
  1410. putPersistedField(result, "callbackMatchedRcid", rdLeaveAuthLogField(ctx, "callbackMatchedRcid"));
  1411. putPersistedField(result, "callbackResourceKey", rdLeaveAuthLogField(ctx, "callbackResourceKey"));
  1412. putPersistedField(result, "callbackResourceDownloadResult", rdLeaveAuthLogField(ctx, "callbackResourceDownloadResult"));
  1413. putPersistedField(result, "callbackResourceSuccessCount", rdLeaveAuthLogField(ctx, "callbackResourceSuccessCount"));
  1414. putPersistedField(result, "callbackResourceFailedCount", rdLeaveAuthLogField(ctx, "callbackResourceFailedCount"));
  1415. putPersistedField(result, "callbackPersonId", rdLeaveAuthLogField(ctx, "callbackPersonId"));
  1416. putPersistedField(result, "callbackPersonDownloadResult", rdLeaveAuthLogField(ctx, "callbackPersonDownloadResult"));
  1417. }
  1418. /**
  1419. * 2026-06-02:海康下载回调在应答后落库,至少把任务号与最近一次设备结果写回到请假单。
  1420. */
  1421. private Map<String, Object> processLeaveAuthDownloadPushAfterAck(String pushBodyStr, boolean showDetail) {
  1422. Map<String, Object> result = new LinkedHashMap<>();
  1423. result.put("ok", true);
  1424. result.put("bodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
  1425. result.put("showDetail", showDetail);
  1426. try (Db gdba = Db.makeConn()) {
  1427. Map<String, Object> bodyMap = rdReqBodyMap(pushBodyStr);
  1428. Map<String, Object> payloadMap = extLeaveAuthCallbackPayload(bodyMap);
  1429. Map<String, Object> resourceResult = castMap(payloadMap.get("resourceDownloadResult"));
  1430. Map<String, Object> resourceDetail = castMap(payloadMap.get("resourceDownloadDetail"));
  1431. String taskId = rdLeaveAuthCallbackTaskId(resourceResult, resourceDetail, payloadMap, bodyMap);
  1432. String personId = rdStr(resourceDetail == null ? null : resourceDetail.get("personId"));
  1433. result.put("taskId", taskId);
  1434. result.put("personId", personId);
  1435. result.put("resourceResultFound", resourceResult != null);
  1436. result.put("resourceDetailFound", resourceDetail != null);
  1437. if (showDetail)
  1438. result.put("callbackBody", bodyMap);
  1439. if (StringUtils.isBlank(taskId) && StringUtils.isBlank(personId)) {
  1440. result.put("ok", false);
  1441. result.put("msg", "回调体内未找到 taskId/personId,暂无法匹配请假记录。");
  1442. return result;
  1443. }
  1444. LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtxByTaskId(gdba, taskId);
  1445. if (ctx == null && StringUtils.isNotBlank(personId)) {
  1446. Map<String, Object> hkConnParm = makeHkConnParm();
  1447. if (hkConnParm != null)
  1448. ctx = selRecentLeaveAuthSyncCtxByPersonId(gdba, hkConnParm, personId);
  1449. }
  1450. if (ctx == null) {
  1451. result.put("ok", false);
  1452. result.put("msg", "未找到对应 downloadTaskId 的请假记录。");
  1453. return result;
  1454. }
  1455. Map<String, Object> persistResult = new LinkedHashMap<>();
  1456. persistResult.put("autoTrigger", true);
  1457. persistResult.put("mode", StringUtils.defaultIfBlank(rdLeaveAuthLogField(ctx, "mode"), "execute_platform_config"));
  1458. persistResult.put("downloadTaskId", StringUtils.defaultIfBlank(taskId, rdLeaveAuthLogField(ctx, "downloadTaskId")));
  1459. persistResult.put("callbackTaskId", taskId);
  1460. persistResult.put("downloadCallbackReceived", true);
  1461. persistResult.put("callbackRecvTime", makeHkTime(new Timestamp(System.currentTimeMillis())));
  1462. persistResult.put("callbackBodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
  1463. persistResult.put("callbackMatchedRcid", ctx.rcid);
  1464. persistResult.put("downloadResetAccepted", true);
  1465. persistResult.put("downloadTaskAccepted", true);
  1466. Map<String, Object> resourceInfo = resourceResult == null ? null : castMap(resourceResult.get("resourceInfo"));
  1467. String resourceKey = makeResourceKey(resourceInfo);
  1468. persistResult.put("callbackResourceKey", resourceKey);
  1469. persistResult.put("callbackResourceDownloadResult", rdStr(resourceResult == null ? null : resourceResult.get("downloadResult")));
  1470. persistResult.put("callbackResourceSuccessCount", rdStr(resourceResult == null ? null : resourceResult.get("successedPersonCount")));
  1471. persistResult.put("callbackResourceFailedCount", rdStr(resourceResult == null ? null : resourceResult.get("failedPersonCount")));
  1472. persistResult.put("callbackPersonId", personId);
  1473. persistResult.put("callbackPersonDownloadResult", rdStr(resourceDetail == null ? null : resourceDetail.get("persondownloadResult")));
  1474. boolean callbackSuccess = isLeaveAuthCallbackSuccess(resourceResult, resourceDetail);
  1475. persistResult.put("downloadConfirmSource", callbackSuccess ? "callback" : null);
  1476. persistResult.put("downloadResultConfirmed", callbackSuccess);
  1477. persistResult.put("downloadPendingReason", callbackSuccess ? "callbackCompleted" : "callbackReturnedFailure");
  1478. persistResult.put("ok", callbackSuccess);
  1479. persistResult.put("msg", callbackSuccess ? "已收到海康下载成功回调。" : "已收到海康下载回调,但当前资源结果未全部成功。");
  1480. persistLeaveAuthSyncResult(gdba, ctx, persistResult);
  1481. result.put("matchedRcid", ctx.rcid);
  1482. result.put("callbackSummary", persistResult);
  1483. result.put("msg", callbackSuccess ? "回调已写回请假记录。" : "回调已写回,但结果未显示为成功。");
  1484. return result;
  1485. } catch (Exception e) {
  1486. log4j.error("HkLeaveAuthServ.processLeaveAuthDownloadPushAfterAck() 异常", e);
  1487. result.put("ok", false);
  1488. result.put("msg", e.getMessage());
  1489. return result;
  1490. }
  1491. }
  1492. /**
  1493. * 2026-06-02:回调体通常包在 data 下,缺 data 时直接兼容根对象。
  1494. */
  1495. private static Map<String, Object> extLeaveAuthCallbackPayload(Map<String, Object> bodyMap) {
  1496. Map<String, Object> dataMap = castMap(bodyMap == null ? null : bodyMap.get("data"));
  1497. return dataMap == null ? (bodyMap == null ? new LinkedHashMap<>() : bodyMap) : dataMap;
  1498. }
  1499. /**
  1500. * 2026-06-02:下载回调优先从 resourceDownloadResult/resourceDownloadDetail 里取 taskId。
  1501. */
  1502. private static String rdLeaveAuthCallbackTaskId(Map<String, Object> resourceResult,
  1503. Map<String, Object> resourceDetail,
  1504. Map<String, Object> payloadMap,
  1505. Map<String, Object> bodyMap) {
  1506. String taskId = rdStr(resourceResult == null ? null : resourceResult.get("taskId"));
  1507. if (StringUtils.isNotBlank(taskId))
  1508. return taskId;
  1509. taskId = rdStr(resourceDetail == null ? null : resourceDetail.get("taskId"));
  1510. if (StringUtils.isNotBlank(taskId))
  1511. return taskId;
  1512. taskId = rdStr(payloadMap == null ? null : payloadMap.get("taskId"));
  1513. if (StringUtils.isNotBlank(taskId))
  1514. return taskId;
  1515. return rdStr(bodyMap == null ? null : bodyMap.get("taskId"));
  1516. }
  1517. /**
  1518. * 2026-06-02:回调成功判定只看当前资源与当前人员是否都返回成功码。
  1519. */
  1520. private static boolean isLeaveAuthCallbackSuccess(Map<String, Object> resourceResult,
  1521. Map<String, Object> resourceDetail) {
  1522. Object resourceDownloadResult = resourceResult == null ? null : resourceResult.get("downloadResult");
  1523. Object personDownloadResult = resourceDetail == null ? null : resourceDetail.get("persondownloadResult");
  1524. boolean resourceOk = isLeaveAuthCallbackOkValue(resourceDownloadResult, true);
  1525. boolean personOk = isLeaveAuthCallbackOkValue(personDownloadResult, true);
  1526. return resourceOk && personOk;
  1527. }
  1528. /**
  1529. * 2026-06-04:结果回查直接读取 RC 快照里的回调摘要,判断这次回调本身是否成功。
  1530. */
  1531. private static boolean isPersistedLeaveAuthCallbackSuccess(Map<String, Object> result) {
  1532. if (!rdBoolLike(result == null ? null : result.get("downloadCallbackReceived")))
  1533. return false;
  1534. Object resourceDownloadResult = result == null ? null : result.get("callbackResourceDownloadResult");
  1535. Object personDownloadResult = result == null ? null : result.get("callbackPersonDownloadResult");
  1536. if (StringUtils.isAllBlank(rdStr(resourceDownloadResult), rdStr(personDownloadResult)))
  1537. return false;
  1538. boolean resourceOk = isLeaveAuthCallbackOkValue(resourceDownloadResult, true);
  1539. boolean personOk = isLeaveAuthCallbackOkValue(personDownloadResult, true);
  1540. return resourceOk && personOk;
  1541. }
  1542. /**
  1543. * 2026-06-04:海康回调里的结果字段常被 GSON 解析成 Double,0 会落成 "0.0"。
  1544. * 这里只要语义上是成功/空值,都按成功处理,避免把真实成功回调误判成失败。
  1545. */
  1546. private static boolean isLeaveAuthCallbackOkValue(Object value, boolean blankAsOk) {
  1547. if (value == null)
  1548. return blankAsOk;
  1549. if (value instanceof Number number)
  1550. return Double.compare(number.doubleValue(), 0D) == 0;
  1551. String text = rdStr(value);
  1552. if (StringUtils.isBlank(text))
  1553. return blankAsOk;
  1554. if ("success".equalsIgnoreCase(text))
  1555. return true;
  1556. if ("0".equals(text))
  1557. return true;
  1558. try {
  1559. return Double.compare(Double.parseDouble(text), 0D) == 0;
  1560. } catch (Exception ignored) {
  1561. return false;
  1562. }
  1563. }
  1564. /**
  1565. * 2026-06-02:按下载任务号回查对应请假记录,供回调补写使用。
  1566. */
  1567. private static LeaveAuthSyncCtx selLeaveAuthSyncCtxByTaskId(Db gdba, String taskId) throws Exception {
  1568. if (gdba == null || StringUtils.isBlank(taskId))
  1569. return null;
  1570. String sql = "select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
  1571. + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
  1572. + " from RC rc"
  1573. + " join RY ry on ry.RYID=rc.FZRYID"
  1574. + " where (rc.WCMSWJ like :taskLike or rc.MSWJ like :taskLike or rc.MS like :taskLike)"
  1575. + " order by rc.RCID desc";
  1576. SqlCmd sqlCmd = new SqlCmd(sql);
  1577. sqlCmd.wrStrParm("taskLike", "%" + taskId + "%");
  1578. List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
  1579. if (rowList == null || rowList.isEmpty())
  1580. return null;
  1581. Map<String, Object> row = rowList.get(0);
  1582. return new LeaveAuthSyncCtx(
  1583. rdLong(row.get("rcid")),
  1584. rdLong(row.get("bjid")),
  1585. rdLong(row.get("ryid")),
  1586. rdInt(row.get("rclbm")),
  1587. (Timestamp) row.get("kssj"),
  1588. (Timestamp) row.get("jssj"),
  1589. rdStr(row.get("xm")),
  1590. rdStr(row.get("ryh")),
  1591. rdStr(row.get("ms")),
  1592. rdStr(row.get("mswj")),
  1593. rdStr(row.get("wcmswj")));
  1594. }
  1595. /**
  1596. * 2026-06-02:当回调 taskId 没提前落库时,退化为按回调 personId 匹配最近的请假执行记录。
  1597. */
  1598. private static LeaveAuthSyncCtx selRecentLeaveAuthSyncCtxByPersonId(Db gdba,
  1599. Map<String, Object> hkConnParm,
  1600. String personId) throws Exception {
  1601. if (gdba == null || hkConnParm == null || StringUtils.isBlank(personId))
  1602. return null;
  1603. List<LeaveAuthSyncCtx> ctxList = selRecentLeaveAuthSyncCtxList(gdba, 60);
  1604. if (ctxList.isEmpty())
  1605. return null;
  1606. List<String> jobNoList = new ArrayList<>();
  1607. for (LeaveAuthSyncCtx ctx : ctxList) {
  1608. if (StringUtils.isNotBlank(ctx.jobNo))
  1609. jobNoList.add(ctx.jobNo);
  1610. }
  1611. if (jobNoList.isEmpty())
  1612. return null;
  1613. Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(hkConnParm, jobNoList);
  1614. for (LeaveAuthSyncCtx ctx : ctxList) {
  1615. Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
  1616. if (StringUtils.equals(personId, rdStr(personInfo == null ? null : personInfo.get("personId"))))
  1617. return ctx;
  1618. }
  1619. return null;
  1620. }
  1621. /**
  1622. * 2026-06-02:回调补写只关心最近执行过的请假单,避免全表扫 RC。
  1623. */
  1624. private static List<LeaveAuthSyncCtx> selRecentLeaveAuthSyncCtxList(Db gdba, int limit) throws Exception {
  1625. if (gdba == null)
  1626. return List.of();
  1627. String sql = "select * from ("
  1628. + " select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
  1629. + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
  1630. + " from RC rc"
  1631. + " join RY ry on ry.RYID=rc.FZRYID"
  1632. + " where rc.WCMSWJ like '%mode=execute_platform_config%'"
  1633. + " order by rc.RCID desc"
  1634. + " ) where rownum<=:limit";
  1635. SqlCmd sqlCmd = new SqlCmd(sql);
  1636. sqlCmd.wrIntParm("limit", Math.max(1, limit));
  1637. List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
  1638. if (rowList == null || rowList.isEmpty())
  1639. return List.of();
  1640. List<LeaveAuthSyncCtx> ctxList = new ArrayList<>();
  1641. for (Map<String, Object> row : rowList) {
  1642. ctxList.add(new LeaveAuthSyncCtx(
  1643. rdLong(row.get("rcid")),
  1644. rdLong(row.get("bjid")),
  1645. rdLong(row.get("ryid")),
  1646. rdInt(row.get("rclbm")),
  1647. (Timestamp) row.get("kssj"),
  1648. (Timestamp) row.get("jssj"),
  1649. rdStr(row.get("xm")),
  1650. rdStr(row.get("ryh")),
  1651. rdStr(row.get("ms")),
  1652. rdStr(row.get("mswj")),
  1653. rdStr(row.get("wcmswj"))));
  1654. }
  1655. return ctxList;
  1656. }
  1657. /**
  1658. * 2026-05-28:平台配置模式结果回查。
  1659. */
  1660. private Map<String, Object> refreshPlatformConfigLeaveAuthResult(Db gdba,
  1661. LeaveAuthSyncCtx ctx,
  1662. Map<String, Object> overrideParm,
  1663. Map<String, Object> result) throws Exception {
  1664. Map<String, Object> hkConnParm = rdHkConnParm();
  1665. if (hkConnParm == null) {
  1666. result.put("ok", false);
  1667. result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
  1668. return result;
  1669. }
  1670. String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
  1671. if (StringUtils.isNotBlank(tagId))
  1672. hkConnParm.put("tagId", tagId);
  1673. result.put("tagId", tagId);
  1674. result.put("tagIdSource", rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
  1675. applyPersistedLeaveAuthSnapshot(ctx, result);
  1676. String callbackUrl = rdCfgOrOverride(overrideParm, "callbackUrl", CFG_CALLBACK_URL, "HK_LEAVE_AUTH_CALLBACK_URL");
  1677. if (StringUtils.isNotBlank(callbackUrl))
  1678. result.put("platformCallbackUrl", callbackUrl);
  1679. if (!result.containsKey("callbackConfigured"))
  1680. result.put("callbackConfigured", StringUtils.isNotBlank(callbackUrl));
  1681. Map<String, Object> personInfo = null;
  1682. String personId = null;
  1683. if (StringUtils.isNotBlank(ctx.jobNo)) {
  1684. Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(hkConnParm, List.of(ctx.jobNo));
  1685. personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
  1686. if (personInfo != null) {
  1687. result.put("personInfo", makePersonInfoResp(personInfo));
  1688. personId = rdStr(personInfo.get("personId"));
  1689. }
  1690. }
  1691. List<Map<String, Object>> resourceInfoList = makeResourceInfoList(selAllActiveMjdList(gdba));
  1692. result.put("resourceInfos", resourceInfoList);
  1693. result.put("resourceCount", resourceInfoList.size());
  1694. String configTaskId = rdLeaveAuthLogField(ctx, "configTaskId");
  1695. if (StringUtils.isNotBlank(configTaskId)) {
  1696. Map<String, Object> configRateReq = Map.of("taskId", configTaskId);
  1697. result.put("configTaskId", configTaskId);
  1698. result.put("authConfigRateReq", configRateReq);
  1699. try {
  1700. result.put("authConfigRateResp", HK_API_CLIENT.searchAuthConfigRate(hkConnParm, configRateReq));
  1701. } catch (Exception e) {
  1702. result.put("authConfigRateError", e.getMessage());
  1703. }
  1704. }
  1705. if (StringUtils.isNotBlank(personId)) {
  1706. Map<String, Object> configSearchReq = makeAuthConfigSearchReq(personId, resourceInfoList);
  1707. result.put("authConfigSearchReq", configSearchReq);
  1708. try {
  1709. result.put("authConfigSearchResp", HK_API_CLIENT.searchAuthConfig(hkConnParm, configSearchReq));
  1710. } catch (Exception e) {
  1711. result.put("authConfigSearchError", e.getMessage());
  1712. }
  1713. } else {
  1714. result.put("authConfigSearchError", "未能获取海康 personId,无法查询平台权限配置。");
  1715. }
  1716. String downloadTaskId = StringUtils.defaultIfBlank(
  1717. rdLeaveAuthLogField(ctx, "downloadTaskId"),
  1718. rdLeaveAuthLogField(ctx, "callbackTaskId"));
  1719. if (StringUtils.isNotBlank(downloadTaskId)) {
  1720. Map<String, Object> taskSearchReq = makeAuthDownloadTaskSearchReq(downloadTaskId);
  1721. Map<String, Object> progressReq = Map.of("taskId", downloadTaskId);
  1722. Map<String, Object> channelRecordReq = makeDownloadRecordChannelListReq(downloadTaskId, resourceInfoList);
  1723. result.put("downloadTaskId", downloadTaskId);
  1724. if (StringUtils.isBlank(rdStr(result.get("downloadTaskSource"))))
  1725. result.put("downloadTaskSource", "personReset");
  1726. result.put("authDownloadTaskSearchReq", taskSearchReq);
  1727. result.put("authDownloadTaskProgressReq", progressReq);
  1728. result.put("downloadRecordChannelReq", channelRecordReq);
  1729. try {
  1730. result.put("authDownloadTaskSearchResp",
  1731. queryAuthDownloadTaskSearchWithRetry(hkConnParm, taskSearchReq));
  1732. } catch (Exception e) {
  1733. result.put("authDownloadTaskSearchError", e.getMessage());
  1734. }
  1735. try {
  1736. result.put("authDownloadTaskProgressResp",
  1737. queryAuthDownloadTaskProgressWithRetry(hkConnParm, progressReq));
  1738. } catch (Exception e) {
  1739. result.put("authDownloadTaskProgressError", e.getMessage());
  1740. }
  1741. try {
  1742. Map<String, Object> channelRecordResp = queryDownloadRecordChannelListWithRetry(
  1743. hkConnParm, channelRecordReq, resourceInfoList);
  1744. result.put("downloadRecordChannelResp", channelRecordResp);
  1745. result.put("downloadRecordPersonDetailReqList",
  1746. makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRecordResp));
  1747. result.put("downloadRecordPersonDetailRespList",
  1748. queryDownloadRecordPersonDetailRespListWithRetry(hkConnParm, downloadTaskId, personId, channelRecordResp));
  1749. } catch (Exception e) {
  1750. result.put("downloadRecordQueryError", e.getMessage());
  1751. }
  1752. }
  1753. result.put("mode", "viewPlatformConfigResult");
  1754. result.put("executeApiPath", "/artemis/api/acps/v1/auth_config/add");
  1755. result.put("resultApiPath", "/artemis/api/acps/v1/auth_config/rate/search");
  1756. result.put("downloadApiPath", "/artemis/api/acps/v1/authDownload/configuration/person/reset");
  1757. result.put("downloadTaskProgressApiPath", "/artemis/api/acps/v1/authDownload/task/progress");
  1758. result.put("downloadTaskSearchApiPath", "/artemis/api/acps/v1/authDownload/task/search");
  1759. result.put("downloadRecordChannelApiPath", "/artemis/api/acps/v1/download_record/channel/list/search");
  1760. result.put("downloadRecordPersonDetailApiPath", "/artemis/api/acps/v2/download_record/person/detail/search");
  1761. boolean autoDownload = rdBoolCfg("hk.leaveAuth.platform.autoDownload", "HK_LEAVE_AUTH_PLATFORM_AUTO_DOWNLOAD", true);
  1762. finalizePlatformConfigResult(result, ctx.kssj, ctx.jssj, resourceInfoList.size(), autoDownload);
  1763. return result;
  1764. }
  1765. /**
  1766. * 2026-05-29:下载任务是异步的,短轮询几次后再回显,避免刚建任务就固定看到未完成。
  1767. */
  1768. private static Map<String, Object> queryAuthDownloadTaskProgressWithRetry(Map<String, Object> hkConnParm,
  1769. Map<String, Object> progressReq) throws Exception {
  1770. Map<String, Object> lastResp = null;
  1771. int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.downloadPollCount",
  1772. "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
  1773. int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.downloadPollSleepMs",
  1774. "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
  1775. for (int i = 0; i < pollCount; i++) {
  1776. if (i > 0 && sleepMs > 0) {
  1777. try {
  1778. Thread.sleep(sleepMs);
  1779. } catch (InterruptedException e) {
  1780. Thread.currentThread().interrupt();
  1781. break;
  1782. }
  1783. }
  1784. lastResp = HK_API_CLIENT.searchAuthDownloadTaskProgress(hkConnParm, progressReq);
  1785. if (isAuthDownloadFinished(lastResp))
  1786. break;
  1787. }
  1788. return lastResp;
  1789. }
  1790. /**
  1791. * 2026-06-02:下载任务摘要可用于区分“任务不存在”和“任务已结束但无进度明细”。
  1792. */
  1793. private static Map<String, Object> queryAuthDownloadTaskSearchWithRetry(Map<String, Object> hkConnParm,
  1794. Map<String, Object> taskSearchReq) throws Exception {
  1795. Map<String, Object> lastResp = null;
  1796. int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.downloadPollCount",
  1797. "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
  1798. int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.downloadPollSleepMs",
  1799. "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
  1800. for (int i = 0; i < pollCount; i++) {
  1801. if (i > 0 && sleepMs > 0) {
  1802. try {
  1803. Thread.sleep(sleepMs);
  1804. } catch (InterruptedException e) {
  1805. Thread.currentThread().interrupt();
  1806. break;
  1807. }
  1808. }
  1809. lastResp = HK_API_CLIENT.searchAuthDownloadTask(hkConnParm, taskSearchReq);
  1810. if (hasAuthDownloadTask(lastResp))
  1811. break;
  1812. }
  1813. return lastResp;
  1814. }
  1815. /**
  1816. * 2026-06-02:下载记录有时比任务摘要落得慢,短轮询到至少出现设备记录为止。
  1817. */
  1818. private static Map<String, Object> queryDownloadRecordChannelListWithRetry(Map<String, Object> hkConnParm,
  1819. Map<String, Object> channelReq,
  1820. List<Map<String, Object>> resourceInfoList) throws Exception {
  1821. Map<String, Object> lastResp = null;
  1822. int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.recordPollCount",
  1823. "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
  1824. int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.recordPollSleepMs",
  1825. "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
  1826. int expectedCount = resourceInfoList == null ? 0 : resourceInfoList.size();
  1827. for (int i = 0; i < pollCount; i++) {
  1828. if (i > 0 && sleepMs > 0) {
  1829. try {
  1830. Thread.sleep(sleepMs);
  1831. } catch (InterruptedException e) {
  1832. Thread.currentThread().interrupt();
  1833. break;
  1834. }
  1835. }
  1836. lastResp = HK_API_CLIENT.searchDownloadRecordChannelList(hkConnParm, channelReq);
  1837. if (rdDownloadRecordChannelMatchedCount(lastResp, resourceInfoList) >= Math.max(1, expectedCount))
  1838. break;
  1839. }
  1840. return lastResp;
  1841. }
  1842. /**
  1843. * 2026-06-02:按设备通道下载记录逐条查询当前学生的人员下载详情。
  1844. */
  1845. private static List<Map<String, Object>> queryDownloadRecordPersonDetailRespListWithRetry(Map<String, Object> hkConnParm,
  1846. String downloadTaskId,
  1847. String personId,
  1848. Object channelRespObj) throws Exception {
  1849. List<Map<String, Object>> reqList = makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRespObj);
  1850. if (reqList.isEmpty())
  1851. return List.of();
  1852. List<Map<String, Object>> respList = new ArrayList<>();
  1853. for (Map<String, Object> reqWrap : reqList) {
  1854. Map<String, Object> req = castMap(reqWrap.get("req"));
  1855. if (req == null)
  1856. continue;
  1857. Map<String, Object> resp = queryDownloadRecordPersonDetailWithRetry(hkConnParm, req);
  1858. Map<String, Object> row = new LinkedHashMap<>();
  1859. row.put("downloadResultId", rdStr(reqWrap.get("downloadResultId")));
  1860. row.put("resourceInfo", reqWrap.get("resourceInfo"));
  1861. row.put("req", req);
  1862. row.put("resp", resp);
  1863. respList.add(row);
  1864. }
  1865. return respList;
  1866. }
  1867. /**
  1868. * 2026-06-02:单个设备通道的人员详情也允许短暂延迟,轮询到当前学生出现明细为止。
  1869. */
  1870. private static Map<String, Object> queryDownloadRecordPersonDetailWithRetry(Map<String, Object> hkConnParm,
  1871. Map<String, Object> detailReq) throws Exception {
  1872. Map<String, Object> lastResp = null;
  1873. int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.recordPollCount",
  1874. "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
  1875. int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.recordPollSleepMs",
  1876. "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
  1877. for (int i = 0; i < pollCount; i++) {
  1878. if (i > 0 && sleepMs > 0) {
  1879. try {
  1880. Thread.sleep(sleepMs);
  1881. } catch (InterruptedException e) {
  1882. Thread.currentThread().interrupt();
  1883. break;
  1884. }
  1885. }
  1886. lastResp = HK_API_CLIENT.searchDownloadRecordPersonDetail(hkConnParm, detailReq);
  1887. if (rdDownloadRecordPersonDetailCount(lastResp) > 0)
  1888. break;
  1889. }
  1890. return lastResp;
  1891. }
  1892. /**
  1893. * 2026-06-02:把设备通道下载记录拆成“每个门一条人员详情请求”。
  1894. */
  1895. private static List<Map<String, Object>> makeDownloadRecordPersonDetailReqList(String downloadTaskId,
  1896. String personId,
  1897. Object channelRespObj) {
  1898. List<Map<String, Object>> rowList = new ArrayList<>();
  1899. Map<String, Object> channelResp = castMap(channelRespObj);
  1900. Map<String, Object> dataMap = rdDataMap(channelResp);
  1901. if (dataMap == null)
  1902. return rowList;
  1903. Object listObj = dataMap.get("list");
  1904. if (!(listObj instanceof List<?> list) || list.isEmpty())
  1905. return rowList;
  1906. for (Object item : list) {
  1907. Map<String, Object> row = makeDownloadRecordPersonDetailReqWrap(downloadTaskId, personId, item);
  1908. if (row != null)
  1909. rowList.add(row);
  1910. }
  1911. return rowList;
  1912. }
  1913. /**
  1914. * 2026-06-02:优先带 downloadResultId,拿不到时再回退 taskId + resourceInfo。
  1915. */
  1916. private static Map<String, Object> makeDownloadRecordPersonDetailReqWrap(String downloadTaskId,
  1917. String personId,
  1918. Object channelItemObj) {
  1919. Map<String, Object> channelItem = castMap(channelItemObj);
  1920. if (channelItem == null)
  1921. return null;
  1922. Map<String, Object> resourceInfo = castMap(channelItem.get("resourceInfo"));
  1923. if (resourceInfo == null)
  1924. return null;
  1925. Map<String, Object> req = new LinkedHashMap<>();
  1926. putIfNotBlank(req, "downloadResultId", rdStr(channelItem.get("downloadResultId")));
  1927. putIfNotBlank(req, "taskId", downloadTaskId);
  1928. req.put("resourceInfo", makeDownloadRecordDetailResourceInfo(resourceInfo));
  1929. req.put("personIds", List.of(personId));
  1930. req.put("pageNo", 1);
  1931. req.put("pageSize", 20);
  1932. Map<String, Object> row = new LinkedHashMap<>();
  1933. row.put("downloadResultId", rdStr(channelItem.get("downloadResultId")));
  1934. row.put("resourceInfo", makeDownloadRecordDetailResourceInfo(resourceInfo));
  1935. row.put("req", req);
  1936. return row;
  1937. }
  1938. /**
  1939. * 2026-06-02:人员详情接口沿用下载记录里的最小资源对象。
  1940. */
  1941. private static Map<String, Object> makeDownloadRecordDetailResourceInfo(Map<String, Object> resourceInfo) {
  1942. Map<String, Object> row = new LinkedHashMap<>();
  1943. if (resourceInfo == null)
  1944. return row;
  1945. putIfNotBlank(row, "resourceIndexCode", rdStr(resourceInfo.get("resourceIndexCode")));
  1946. putIfNotBlank(row, "resourceType", rdStr(resourceInfo.get("resourceType")));
  1947. Object channelNos = resourceInfo.get("channelNos");
  1948. if (channelNos instanceof List<?> list && !list.isEmpty())
  1949. row.put("channelNos", list);
  1950. return row;
  1951. }
  1952. /**
  1953. * 2026-06-02:special/person/diy/result 只要返回 total>0 或 list 非空,就视为已经能回查到明细。
  1954. */
  1955. private static boolean hasSpecialPersonAuthDownloadResult(Object resultRespObj) {
  1956. Map<String, Object> resultResp = castMap(resultRespObj);
  1957. Map<String, Object> dataMap = rdDataMap(resultResp);
  1958. if (dataMap == null)
  1959. return false;
  1960. int total = rdInt(dataMap.get("total"));
  1961. if (total > 0)
  1962. return true;
  1963. Object listObj = dataMap.get("list");
  1964. return listObj instanceof List<?> list && !list.isEmpty();
  1965. }
  1966. /**
  1967. * 2026-05-29:统一判断海康下载任务是否完成,兼容布尔值和字符串返回。
  1968. */
  1969. private static boolean isAuthDownloadFinished(Map<String, Object> progressResp) {
  1970. if (progressResp == null)
  1971. return false;
  1972. Object dataObj = progressResp.get("data");
  1973. if (!(dataObj instanceof Map<?, ?> dataMap))
  1974. return false;
  1975. Object finishedObj = dataMap.get("isDownloadFinished");
  1976. if (finishedObj instanceof Boolean boolVal)
  1977. return boolVal;
  1978. String text = rdStr(finishedObj);
  1979. if (StringUtils.isBlank(text))
  1980. return false;
  1981. text = text.toLowerCase(Locale.ROOT);
  1982. return "true".equals(text) || "1".equals(text) || "yes".equals(text) || "y".equals(text);
  1983. }
  1984. /**
  1985. * 2026-06-02:任务摘要查询命中记录即可视为海康已接受并创建该下载任务。
  1986. */
  1987. private static boolean hasAuthDownloadTask(Object taskSearchRespObj) {
  1988. return rdAuthDownloadTaskFirst(taskSearchRespObj) != null;
  1989. }
  1990. /**
  1991. * 2026-06-02:任务摘要中的 taskStatus=2 表示海康任务已结束。
  1992. */
  1993. private static boolean isAuthDownloadTaskFinished(Object taskSearchRespObj) {
  1994. Map<String, Object> firstTask = rdAuthDownloadTaskFirst(taskSearchRespObj);
  1995. if (firstTask == null)
  1996. return false;
  1997. int taskStatus = rdInt(firstTask.get("taskStatus"));
  1998. return taskStatus == 2;
  1999. }
  2000. /**
  2001. * 2026-06-02:统一取下载任务摘要的第一条任务,避免到处重复拆分页结构。
  2002. */
  2003. @SuppressWarnings("unchecked")
  2004. private static Map<String, Object> rdAuthDownloadTaskFirst(Object taskSearchRespObj) {
  2005. Map<String, Object> taskSearchResp = castMap(taskSearchRespObj);
  2006. Map<String, Object> dataMap = rdDataMap(taskSearchResp);
  2007. if (dataMap == null)
  2008. return null;
  2009. Object listObj = dataMap.get("list");
  2010. if (!(listObj instanceof List<?> list) || list.isEmpty())
  2011. return null;
  2012. Object firstObj = list.get(0);
  2013. if (!(firstObj instanceof Map<?, ?>))
  2014. return null;
  2015. return (Map<String, Object>) firstObj;
  2016. }
  2017. /**
  2018. * 2026-06-02:统计设备通道下载记录总数。
  2019. */
  2020. private static int rdDownloadRecordChannelTotalCount(Object channelRespObj) {
  2021. Map<String, Object> channelResp = castMap(channelRespObj);
  2022. Map<String, Object> dataMap = rdDataMap(channelResp);
  2023. if (dataMap == null)
  2024. return 0;
  2025. int total = rdInt(dataMap.get("total"));
  2026. if (total > 0)
  2027. return total;
  2028. Object listObj = dataMap.get("list");
  2029. return listObj instanceof List<?> list ? list.size() : 0;
  2030. }
  2031. /**
  2032. * 2026-06-02:统计本次请假目标门禁里,真正查到下载记录的设备数量。
  2033. */
  2034. private static int rdDownloadRecordChannelMatchedCount(Object channelRespObj,
  2035. List<Map<String, Object>> expectedResourceInfoList) {
  2036. Map<String, Object> channelResp = castMap(channelRespObj);
  2037. Map<String, Object> dataMap = rdDataMap(channelResp);
  2038. if (dataMap == null)
  2039. return 0;
  2040. Object listObj = dataMap.get("list");
  2041. if (!(listObj instanceof List<?> list) || list.isEmpty())
  2042. return 0;
  2043. Set<String> expectedKeySet = makeResourceKeySet(expectedResourceInfoList);
  2044. Set<String> matchedKeySet = new LinkedHashSet<>();
  2045. for (Object item : list) {
  2046. Map<String, Object> row = castMap(item);
  2047. if (row == null)
  2048. continue;
  2049. Map<String, Object> resourceInfo = castMap(row.get("resourceInfo"));
  2050. String resourceKey = makeResourceKey(resourceInfo);
  2051. if (StringUtils.isBlank(resourceKey) || !expectedKeySet.contains(resourceKey))
  2052. continue;
  2053. matchedKeySet.add(resourceKey);
  2054. }
  2055. return matchedKeySet.size();
  2056. }
  2057. /**
  2058. * 2026-06-02:统计下载记录里设备通道级别的成功数。
  2059. */
  2060. private static int rdDownloadRecordChannelSuccessCount(Object channelRespObj,
  2061. List<Map<String, Object>> expectedResourceInfoList) {
  2062. return rdDownloadRecordChannelCountByResult(channelRespObj, expectedResourceInfoList, Set.of(0));
  2063. }
  2064. /**
  2065. * 2026-06-02:统计下载记录里设备通道级别的失败/部分失败数。
  2066. */
  2067. private static int rdDownloadRecordChannelFailedCount(Object channelRespObj,
  2068. List<Map<String, Object>> expectedResourceInfoList) {
  2069. return rdDownloadRecordChannelCountByResult(channelRespObj, expectedResourceInfoList, Set.of(1, 2));
  2070. }
  2071. /**
  2072. * 2026-06-02:按 downloadResult 聚合设备通道下载结果。
  2073. */
  2074. private static int rdDownloadRecordChannelCountByResult(Object channelRespObj,
  2075. List<Map<String, Object>> expectedResourceInfoList,
  2076. Set<Integer> acceptedResultSet) {
  2077. Map<String, Object> channelResp = castMap(channelRespObj);
  2078. Map<String, Object> dataMap = rdDataMap(channelResp);
  2079. if (dataMap == null)
  2080. return 0;
  2081. Object listObj = dataMap.get("list");
  2082. if (!(listObj instanceof List<?> list) || list.isEmpty())
  2083. return 0;
  2084. Set<String> expectedKeySet = makeResourceKeySet(expectedResourceInfoList);
  2085. Set<String> matchedKeySet = new LinkedHashSet<>();
  2086. for (Object item : list) {
  2087. Map<String, Object> row = castMap(item);
  2088. if (row == null)
  2089. continue;
  2090. Map<String, Object> resourceInfo = castMap(row.get("resourceInfo"));
  2091. String resourceKey = makeResourceKey(resourceInfo);
  2092. if (StringUtils.isBlank(resourceKey) || !expectedKeySet.contains(resourceKey))
  2093. continue;
  2094. if (acceptedResultSet.contains(rdInt(row.get("downloadResult"))))
  2095. matchedKeySet.add(resourceKey);
  2096. }
  2097. return matchedKeySet.size();
  2098. }
  2099. /**
  2100. * 2026-06-02:统计当前学生的人员下载详情中,命中的设备通道数。
  2101. */
  2102. private static int rdDownloadRecordPersonDetailMatchedCount(Object detailRespListObj) {
  2103. Set<String> matchedKeySet = new LinkedHashSet<>();
  2104. for (Map<String, Object> row : castMapList(detailRespListObj)) {
  2105. String resourceKey = makeResourceKey(castMap(row.get("resourceInfo")));
  2106. if (StringUtils.isBlank(resourceKey) || rdDownloadRecordPersonDetailCount(row.get("resp")) <= 0)
  2107. continue;
  2108. matchedKeySet.add(resourceKey);
  2109. }
  2110. return matchedKeySet.size();
  2111. }
  2112. /**
  2113. * 2026-06-02:统计当前学生在各门上的下载成功数。
  2114. */
  2115. private static int rdDownloadRecordPersonDetailSuccessCount(Object detailRespListObj) {
  2116. return rdDownloadRecordPersonDetailCountByResult(detailRespListObj, Set.of("0", "success", "SUCCESS"));
  2117. }
  2118. /**
  2119. * 2026-06-02:统计当前学生在各门上的下载失败数。
  2120. */
  2121. private static int rdDownloadRecordPersonDetailFailedCount(Object detailRespListObj) {
  2122. int matchedCount = rdDownloadRecordPersonDetailMatchedCount(detailRespListObj);
  2123. int successCount = rdDownloadRecordPersonDetailSuccessCount(detailRespListObj);
  2124. return Math.max(0, matchedCount - successCount);
  2125. }
  2126. /**
  2127. * 2026-06-02:人员详情按 persondownloadResult 聚合。
  2128. */
  2129. private static int rdDownloadRecordPersonDetailCountByResult(Object detailRespListObj, Set<String> acceptedResultSet) {
  2130. Set<String> matchedKeySet = new LinkedHashSet<>();
  2131. for (Map<String, Object> row : castMapList(detailRespListObj)) {
  2132. Map<String, Object> resp = castMap(row.get("resp"));
  2133. Map<String, Object> dataMap = rdDataMap(resp);
  2134. if (dataMap == null)
  2135. continue;
  2136. Object listObj = dataMap.get("list");
  2137. if (!(listObj instanceof List<?> list) || list.isEmpty())
  2138. continue;
  2139. String resourceKey = makeResourceKey(castMap(row.get("resourceInfo")));
  2140. if (StringUtils.isBlank(resourceKey))
  2141. continue;
  2142. for (Object item : list) {
  2143. Map<String, Object> itemMap = castMap(item);
  2144. String resultVal = rdStr(itemMap == null ? null : itemMap.get("persondownloadResult"));
  2145. if (acceptedResultSet.contains(resultVal))
  2146. matchedKeySet.add(resourceKey);
  2147. }
  2148. }
  2149. return matchedKeySet.size();
  2150. }
  2151. /**
  2152. * 2026-06-02:统计单个人员详情响应的明细数量。
  2153. */
  2154. private static int rdDownloadRecordPersonDetailCount(Object detailRespObj) {
  2155. Map<String, Object> detailResp = castMap(detailRespObj);
  2156. Map<String, Object> dataMap = rdDataMap(detailResp);
  2157. if (dataMap == null)
  2158. return 0;
  2159. int total = rdInt(dataMap.get("total"));
  2160. if (total > 0)
  2161. return total;
  2162. Object listObj = dataMap.get("list");
  2163. return listObj instanceof List<?> list ? list.size() : 0;
  2164. }
  2165. /**
  2166. * 2026-06-02:统一把资源对象转成 `设备#通道` 形式,便于跨接口对齐。
  2167. */
  2168. private static String makeResourceKey(Map<String, Object> resourceInfo) {
  2169. if (resourceInfo == null)
  2170. return null;
  2171. String resourceIndexCode = rdStr(resourceInfo.get("resourceIndexCode"));
  2172. if (StringUtils.isBlank(resourceIndexCode))
  2173. return null;
  2174. Object channelNosObj = resourceInfo.get("channelNos");
  2175. String channelNo = "1";
  2176. if (channelNosObj instanceof List<?> list && !list.isEmpty())
  2177. channelNo = rdStr(list.get(0));
  2178. return resourceIndexCode + "#" + channelNo;
  2179. }
  2180. /**
  2181. * 2026-06-02:构建本次预期下发资源的 key 集合。
  2182. */
  2183. private static Set<String> makeResourceKeySet(List<Map<String, Object>> resourceInfoList) {
  2184. Set<String> keySet = new LinkedHashSet<>();
  2185. if (resourceInfoList == null || resourceInfoList.isEmpty())
  2186. return keySet;
  2187. for (Map<String, Object> item : resourceInfoList) {
  2188. String resourceKey = makeResourceKey(item);
  2189. if (StringUtils.isNotBlank(resourceKey))
  2190. keySet.add(resourceKey);
  2191. }
  2192. return keySet;
  2193. }
  2194. /**
  2195. * 2026-06-02:平台配置模式必须同时确认“配置成功 + 平台可查 + 下载可确认”后,才对外返回成功。
  2196. * 否则 PMS 虽然拿到了 taskId,但现场门禁仍可能提示“当前时间无效”。
  2197. */
  2198. private static void finalizePlatformConfigResult(Map<String, Object> result,
  2199. Timestamp leaveBeg,
  2200. Timestamp leaveEnd,
  2201. int expectedResourceCount,
  2202. boolean autoDownload) {
  2203. int configTotalCount = rdAuthConfigTotalCount(result.get("authConfigSearchResp"));
  2204. int matchedConfigCount = rdAuthConfigMatchedCount(result.get("authConfigSearchResp"), leaveBeg, leaveEnd);
  2205. boolean configRateFinished = isAuthConfigFinished(result.get("authConfigRateResp"));
  2206. boolean configRateSuccess = isAuthConfigSuccess(result.get("authConfigRateResp"), expectedResourceCount);
  2207. boolean configSearchMatched = expectedResourceCount > 0 && matchedConfigCount >= expectedResourceCount;
  2208. boolean callbackConfigured = rdBoolLike(result.get("callbackConfigured"));
  2209. boolean downloadResetAccepted = rdBoolLike(result.get("downloadResetAccepted"))
  2210. || isHkRespAccepted(result.get("authDownloadResetResp"));
  2211. String downloadTaskId = rdStr(result.get("downloadTaskId"));
  2212. boolean downloadTaskIdPresent = StringUtils.isNotBlank(downloadTaskId);
  2213. boolean downloadTaskExists = hasAuthDownloadTask(result.get("authDownloadTaskSearchResp"));
  2214. boolean downloadTaskFinished = isAuthDownloadTaskFinished(result.get("authDownloadTaskSearchResp"));
  2215. boolean downloadProgressFinished = isAuthDownloadFinished(castMap(result.get("authDownloadTaskProgressResp")));
  2216. boolean downloadCallbackReceived = rdBoolLike(result.get("downloadCallbackReceived"));
  2217. boolean downloadCallbackSuccess = isPersistedLeaveAuthCallbackSuccess(result);
  2218. boolean downloadTaskAccepted = rdBoolLike(result.get("downloadTaskAccepted"))
  2219. || downloadResetAccepted
  2220. || downloadTaskIdPresent
  2221. || downloadTaskExists
  2222. || downloadCallbackReceived;
  2223. int downloadRecordChannelTotalCount = rdDownloadRecordChannelTotalCount(result.get("downloadRecordChannelResp"));
  2224. int downloadRecordChannelMatchedCount = rdDownloadRecordChannelMatchedCount(result.get("downloadRecordChannelResp"),
  2225. castMapList(result.get("resourceInfos")));
  2226. int downloadRecordChannelSuccessCount = rdDownloadRecordChannelSuccessCount(result.get("downloadRecordChannelResp"),
  2227. castMapList(result.get("resourceInfos")));
  2228. int downloadRecordChannelFailedCount = rdDownloadRecordChannelFailedCount(result.get("downloadRecordChannelResp"),
  2229. castMapList(result.get("resourceInfos")));
  2230. int downloadRecordPersonDetailMatchedCount = rdDownloadRecordPersonDetailMatchedCount(result.get("downloadRecordPersonDetailRespList"));
  2231. int downloadRecordPersonDetailSuccessCount = rdDownloadRecordPersonDetailSuccessCount(result.get("downloadRecordPersonDetailRespList"));
  2232. int downloadRecordPersonDetailFailedCount = rdDownloadRecordPersonDetailFailedCount(result.get("downloadRecordPersonDetailRespList"));
  2233. boolean downloadRecordConfirmed = expectedResourceCount > 0
  2234. && downloadRecordChannelMatchedCount >= expectedResourceCount
  2235. && downloadRecordChannelFailedCount == 0
  2236. && downloadRecordPersonDetailSuccessCount >= expectedResourceCount
  2237. && downloadRecordPersonDetailFailedCount == 0;
  2238. boolean downloadConfirmed = !autoDownload || downloadRecordConfirmed || downloadCallbackSuccess;
  2239. String downloadConfirmSource = null;
  2240. String downloadPendingReason;
  2241. if (!autoDownload) {
  2242. downloadConfirmSource = "notRequired";
  2243. downloadPendingReason = "downloadNotRequired";
  2244. } else if (downloadRecordConfirmed) {
  2245. downloadConfirmSource = "taskRecord";
  2246. downloadPendingReason = "taskRecordConfirmed";
  2247. } else if (downloadCallbackSuccess) {
  2248. downloadConfirmSource = "callback";
  2249. downloadPendingReason = "callbackCompleted";
  2250. } else if (!downloadTaskAccepted) {
  2251. downloadPendingReason = "resetNotAccepted";
  2252. } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent && callbackConfigured) {
  2253. downloadPendingReason = "resetAcceptedAwaitCallback";
  2254. } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent) {
  2255. downloadPendingReason = "resetAcceptedWithoutTaskIdOrCallback";
  2256. } else if (!downloadTaskExists && !downloadCallbackReceived) {
  2257. downloadPendingReason = "taskIdReturnedAwaitTaskSearch";
  2258. } else if (downloadCallbackReceived) {
  2259. downloadPendingReason = "callbackReturnedFailure";
  2260. } else if (!downloadTaskFinished && !downloadProgressFinished) {
  2261. downloadPendingReason = "taskRunning";
  2262. } else if (downloadRecordChannelMatchedCount <= 0) {
  2263. downloadPendingReason = "noChannelRecord";
  2264. } else if (downloadRecordPersonDetailMatchedCount <= 0) {
  2265. downloadPendingReason = "noPersonDetail";
  2266. } else if (downloadRecordChannelFailedCount > 0 || downloadRecordPersonDetailFailedCount > 0) {
  2267. downloadPendingReason = "recordContainsFailure";
  2268. } else if (downloadTaskFinished) {
  2269. downloadPendingReason = "taskFinishedButRecordIncomplete";
  2270. } else {
  2271. downloadPendingReason = "recordIncomplete";
  2272. }
  2273. result.put("expectedConfigCount", expectedResourceCount);
  2274. result.put("configTotalCount", configTotalCount);
  2275. result.put("matchedConfigCount", matchedConfigCount);
  2276. result.put("configRateFinished", configRateFinished);
  2277. result.put("configRateSuccess", configRateSuccess);
  2278. result.put("configSearchMatched", configSearchMatched);
  2279. result.put("callbackConfigured", callbackConfigured);
  2280. result.put("downloadResetAccepted", downloadResetAccepted);
  2281. result.put("downloadTaskAccepted", downloadTaskAccepted);
  2282. result.put("downloadTaskExists", downloadTaskExists);
  2283. result.put("downloadTaskFinished", downloadTaskFinished);
  2284. result.put("downloadProgressFinished", downloadProgressFinished);
  2285. result.put("downloadCallbackReceived", downloadCallbackReceived);
  2286. result.put("downloadCallbackSuccess", downloadCallbackSuccess);
  2287. result.put("downloadRecordChannelTotalCount", downloadRecordChannelTotalCount);
  2288. result.put("downloadRecordChannelMatchedCount", downloadRecordChannelMatchedCount);
  2289. result.put("downloadRecordChannelSuccessCount", downloadRecordChannelSuccessCount);
  2290. result.put("downloadRecordChannelFailedCount", downloadRecordChannelFailedCount);
  2291. result.put("downloadRecordPersonDetailMatchedCount", downloadRecordPersonDetailMatchedCount);
  2292. result.put("downloadRecordPersonDetailSuccessCount", downloadRecordPersonDetailSuccessCount);
  2293. result.put("downloadRecordPersonDetailFailedCount", downloadRecordPersonDetailFailedCount);
  2294. result.put("downloadRecordConfirmed", downloadRecordConfirmed);
  2295. result.put("downloadConfirmSource", downloadConfirmSource);
  2296. result.put("downloadPendingReason", downloadPendingReason);
  2297. result.put("downloadResultConfirmed", downloadConfirmed);
  2298. result.put("downloadConfirmed", downloadConfirmed);
  2299. if (!configRateSuccess) {
  2300. result.put("ok", false);
  2301. result.put("msg", "海康平台权限配置任务未确认全部成功。");
  2302. return;
  2303. }
  2304. if (!configSearchMatched) {
  2305. result.put("ok", false);
  2306. result.put("msg", "海康平台未查到覆盖当前请假时段的完整权限配置。");
  2307. return;
  2308. }
  2309. if (!downloadConfirmed) {
  2310. result.put("ok", false);
  2311. if (!downloadTaskAccepted) {
  2312. result.put("msg", "海康人员权限重下发未确认受理,设备生效状态未确认。");
  2313. } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent && callbackConfigured) {
  2314. result.put("msg", "海康已受理人员权限重下发,当前等待回调确认设备生效。");
  2315. } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent) {
  2316. result.put("msg", "海康已受理人员权限重下发,但未返回 taskId,且当前未配置回调地址,无法继续确认设备生效状态。");
  2317. } else if (!downloadTaskExists && !downloadCallbackReceived) {
  2318. result.put("msg", "海康已返回 downloadTaskId,但暂未查到任务摘要或完整设备记录。");
  2319. } else if (!downloadTaskFinished && !downloadProgressFinished) {
  2320. result.put("msg", "海康下载任务仍未结束,设备生效状态未确认。");
  2321. } else if (downloadCallbackReceived) {
  2322. result.put("msg", "已收到海康下载回调,但回调结果未显示全部成功。");
  2323. } else if (downloadRecordChannelMatchedCount <= 0) {
  2324. result.put("msg", "海康下载任务已结束,但未查询到设备通道下载记录。");
  2325. } else if (downloadRecordPersonDetailMatchedCount <= 0) {
  2326. result.put("msg", "海康已生成设备通道下载记录,但未查询到该学生的人员下载详情。");
  2327. } else if (downloadRecordChannelFailedCount > 0 || downloadRecordPersonDetailFailedCount > 0) {
  2328. result.put("msg", "海康下载记录显示存在失败或部分失败,设备生效状态未全部确认。");
  2329. } else if (downloadTaskFinished) {
  2330. result.put("msg", "海康下载任务摘要显示已结束,但设备侧下载记录仍未达到完整成功状态。");
  2331. } else if (downloadTaskExists) {
  2332. result.put("msg", "海康下载任务已创建,但设备侧下载记录仍未达到完整成功状态。");
  2333. } else {
  2334. result.put("msg", "海康下载链路未返回完整成功记录,门禁设备生效状态未确认。");
  2335. }
  2336. return;
  2337. }
  2338. result.put("ok", true);
  2339. if (autoDownload && "callback".equals(downloadConfirmSource)) {
  2340. result.put("msg", "海康平台权限配置已完成,设备生效已由回调确认。");
  2341. } else {
  2342. result.put("msg", autoDownload ? "海康平台权限配置与下载已确认完成。" : "海康平台权限配置已确认完成。");
  2343. }
  2344. }
  2345. /**
  2346. * 2026-06-02:配置任务必须走到 finished,且失败数为 0,成功数至少覆盖本次下发设备数。
  2347. */
  2348. private static boolean isAuthConfigSuccess(Object rateRespObj, int expectedResourceCount) {
  2349. Map<String, Object> rateResp = castMap(rateRespObj);
  2350. if (!isAuthConfigFinished(rateResp))
  2351. return false;
  2352. Map<String, Object> dataMap = rdDataMap(rateResp);
  2353. if (dataMap == null)
  2354. return false;
  2355. if (rdInt(dataMap.get("failedNum")) > 0 || rdInt(dataMap.get("calcChannelFailedNum")) > 0)
  2356. return false;
  2357. int expectedCount = Math.max(1, expectedResourceCount);
  2358. int successCount = Math.max(rdInt(dataMap.get("successedNum")), rdInt(dataMap.get("calcChannelSuccessNum")));
  2359. return successCount >= expectedCount;
  2360. }
  2361. /**
  2362. * 2026-06-02:统一判断平台配置任务是否完成,兼容海康返回的布尔值、字符串和状态码。
  2363. */
  2364. private static boolean isAuthConfigFinished(Object rateRespObj) {
  2365. Map<String, Object> rateResp = castMap(rateRespObj);
  2366. Map<String, Object> dataMap = rdDataMap(rateResp);
  2367. if (dataMap == null)
  2368. return false;
  2369. if (rdBoolLike(dataMap.get("isFinished")) || rdBoolLike(dataMap.get("isConfigFinished")))
  2370. return true;
  2371. String status = rdStr(dataMap.get("status"));
  2372. return "CONFIGEND".equalsIgnoreCase(status) || "FINISHED".equalsIgnoreCase(status) || "SUCCESS".equalsIgnoreCase(status);
  2373. }
  2374. /**
  2375. * 2026-06-02:统计海康平台当前查到的权限配置总数。
  2376. */
  2377. private static int rdAuthConfigTotalCount(Object searchRespObj) {
  2378. Map<String, Object> searchResp = castMap(searchRespObj);
  2379. Map<String, Object> dataMap = rdDataMap(searchResp);
  2380. if (dataMap == null)
  2381. return 0;
  2382. int total = rdInt(dataMap.get("total"));
  2383. if (total > 0)
  2384. return total;
  2385. Object listObj = dataMap.get("list");
  2386. return listObj instanceof List<?> list ? list.size() : 0;
  2387. }
  2388. /**
  2389. * 2026-06-02:按当前请假时段统计“真正命中”的平台权限配置数。
  2390. */
  2391. private static int rdAuthConfigMatchedCount(Object searchRespObj,
  2392. Timestamp leaveBeg,
  2393. Timestamp leaveEnd) {
  2394. Map<String, Object> searchResp = castMap(searchRespObj);
  2395. Map<String, Object> dataMap = rdDataMap(searchResp);
  2396. if (dataMap == null)
  2397. return 0;
  2398. Object listObj = dataMap.get("list");
  2399. if (!(listObj instanceof List<?> list) || list.isEmpty())
  2400. return 0;
  2401. int matchedCount = 0;
  2402. for (Object item : list) {
  2403. if (!(item instanceof Map<?, ?> rawMap))
  2404. continue;
  2405. String startTime = rdStr(rawMap.get("startTime"));
  2406. String endTime = rdStr(rawMap.get("endTime"));
  2407. if (sameAuthTime(startTime, leaveBeg) && sameAuthTime(endTime, leaveEnd))
  2408. matchedCount++;
  2409. }
  2410. return matchedCount;
  2411. }
  2412. /**
  2413. * 2026-06-02:把海康返回时间与当前请假时间窗按“同一时刻”比较,避免毫秒位差异误判。
  2414. */
  2415. private static boolean sameAuthTime(String hkTimeText, Timestamp expectedTime) {
  2416. if (StringUtils.isBlank(hkTimeText) || expectedTime == null)
  2417. return false;
  2418. try {
  2419. return OffsetDateTime.parse(hkTimeText).toInstant()
  2420. .equals(expectedTime.toLocalDateTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant());
  2421. } catch (Exception ignored) {
  2422. return false;
  2423. }
  2424. }
  2425. /**
  2426. * 2026-06-02:统一把海康 `{code,msg,data}` 响应里的 `data` 取成 Map。
  2427. */
  2428. @SuppressWarnings("unchecked")
  2429. private static Map<String, Object> rdDataMap(Map<String, Object> resp) {
  2430. if (resp == null)
  2431. return null;
  2432. Object dataObj = resp.get("data");
  2433. if (!(dataObj instanceof Map<?, ?>))
  2434. return null;
  2435. return (Map<String, Object>) dataObj;
  2436. }
  2437. /**
  2438. * 2026-06-04:海康标准响应 code=0 视为接口已受理,taskId 是否即时返回不再作为唯一判据。
  2439. */
  2440. private static boolean isHkRespAccepted(Object respObj) {
  2441. Map<String, Object> resp = castMap(respObj);
  2442. return "0".equals(rdStr(resp == null ? null : resp.get("code")));
  2443. }
  2444. /**
  2445. * 2026-06-02:把弱类型响应对象安全转成 Map,避免到处重复 `instanceof`。
  2446. */
  2447. @SuppressWarnings("unchecked")
  2448. private static Map<String, Object> castMap(Object value) {
  2449. if (!(value instanceof Map<?, ?>))
  2450. return null;
  2451. return (Map<String, Object>) value;
  2452. }
  2453. /**
  2454. * 2026-06-02:把弱类型列表安全转成 Map 列表,避免重复写泛型转换。
  2455. */
  2456. @SuppressWarnings("unchecked")
  2457. private static List<Map<String, Object>> castMapList(Object value) {
  2458. if (!(value instanceof List<?> list) || list.isEmpty())
  2459. return List.of();
  2460. List<Map<String, Object>> rowList = new ArrayList<>();
  2461. for (Object item : list) {
  2462. if (item instanceof Map<?, ?> map)
  2463. rowList.add((Map<String, Object>) map);
  2464. }
  2465. return rowList;
  2466. }
  2467. /**
  2468. * 2026-06-02:兼容海康返回的布尔/字符串/数字型开关字段。
  2469. */
  2470. private static boolean rdBoolLike(Object value) {
  2471. if (value instanceof Boolean boolVal)
  2472. return boolVal;
  2473. String text = rdStr(value);
  2474. if (StringUtils.isBlank(text))
  2475. return false;
  2476. text = text.toLowerCase(Locale.ROOT);
  2477. return "true".equals(text) || "1".equals(text) || "yes".equals(text) || "y".equals(text);
  2478. }
  2479. /**
  2480. * 2026-05-28:回显当前请假链路模式,便于诊断页面和日志快速识别。
  2481. */
  2482. private static String normalizeLeaveAuthMode(String mode) {
  2483. String value = StringUtils.trimToEmpty(mode).toLowerCase(Locale.ROOT);
  2484. if (StringUtils.isBlank(value))
  2485. return HK_DEF_MODE;
  2486. if ("platform".equals(value) || "platform_config".equals(value) || "config".equals(value))
  2487. return "platform_config";
  2488. if ("legacy".equals(value) || "special".equals(value) || "diy".equals(value))
  2489. return "legacy";
  2490. return value;
  2491. }
  2492. /**
  2493. * 2026-05-26:把请假信息统一写成日志和响应都能直接读的结构。
  2494. */
  2495. private static Map<String, Object> makeBaseLogRow(LeaveAuthSyncCtx ctx) {
  2496. Map<String, Object> logRow = new LinkedHashMap<>();
  2497. logRow.put("rcid", ctx.rcid);
  2498. logRow.put("bjid", ctx.bjid);
  2499. logRow.put("ryid", ctx.ryid);
  2500. logRow.put("xm", ctx.xm);
  2501. logRow.put("jobNo", ctx.jobNo);
  2502. logRow.put("leaveType", ctx.rclbm == biz.rc.RcC.RCLB_bj ? "病假" : "事假");
  2503. logRow.put("leaveBeg", makeHkTime(ctx.kssj));
  2504. logRow.put("leaveEnd", makeHkTime(ctx.jssj));
  2505. return logRow;
  2506. }
  2507. /**
  2508. * 2026-05-26:返回给前端的请假上下文,只保留业务上能直观看懂的字段。
  2509. */
  2510. private static Map<String, Object> makeLeaveCtxResp(LeaveAuthSyncCtx ctx) {
  2511. Map<String, Object> row = new LinkedHashMap<>();
  2512. row.put("rcid", ctx.rcid);
  2513. row.put("bjid", ctx.bjid);
  2514. row.put("ryid", ctx.ryid);
  2515. row.put("rclbm", ctx.rclbm);
  2516. row.put("xm", ctx.xm);
  2517. row.put("jobNo", ctx.jobNo);
  2518. row.put("leaveBeg", makeHkTime(ctx.kssj));
  2519. row.put("leaveEnd", makeHkTime(ctx.jssj));
  2520. return row;
  2521. }
  2522. /**
  2523. * 2026-05-26:海康连接参数只回显脱敏后的 appKey。
  2524. */
  2525. private static Map<String, Object> makeSafeHkConnResp(Map<String, Object> hkConnParm) {
  2526. Map<String, Object> row = new LinkedHashMap<>();
  2527. row.put("host", rdStr(hkConnParm.get("host")));
  2528. row.put("port", hkConnParm.get("port"));
  2529. row.put("appKeyMask", makeMaskStr(rdStr(hkConnParm.get("appKey"))));
  2530. return row;
  2531. }
  2532. /**
  2533. * 2026-05-26:返回海康人员详情的关键字段,便于定位 jobNo/personId 映射。
  2534. */
  2535. private static Map<String, Object> makePersonInfoResp(Map<String, Object> personInfo) {
  2536. Map<String, Object> row = new LinkedHashMap<>();
  2537. row.put("personId", rdStr(personInfo.get("personId")));
  2538. row.put("jobNo", rdStr(personInfo.get("jobNo")));
  2539. row.put("personName", rdStr(personInfo.get("personName")));
  2540. row.put("studentId", rdStr(personInfo.get("studentId")));
  2541. row.put("orgIndexCode", rdStr(personInfo.get("orgIndexCode")));
  2542. row.put("orgPathName", rdStr(personInfo.get("orgPathName")));
  2543. return row;
  2544. }
  2545. /**
  2546. * 2026-05-26:当前请假权限范围直接取全部有效门禁点,和用户新要求保持一致。
  2547. */
  2548. private static List<Map<String, Object>> selAllActiveMjdList(Db gdba) throws Exception {
  2549. String sql = "select MJDID mjdid,MC mc,SBBS sbbs,CDID cdid,MJDLBM mjdlbm,JCFXM jcfxm,JLZTM jlztm"
  2550. + " from MJD where JLZTM in (21,22,25,51,81)"
  2551. + " order by MJDID";
  2552. SqlCmd sqlCmd = new SqlCmd(sql);
  2553. return gdba.doSelMapListByC(sqlCmd);
  2554. }
  2555. /**
  2556. * 2026-05-26:请假权限同步的默认海康连接参数,避免依赖入口类。
  2557. */
  2558. private static Map<String, Object> makeDefaultHkConnParm() {
  2559. Map<String, Object> queryParm = new LinkedHashMap<>();
  2560. queryParm.put("host", HK_DEF_HOST);
  2561. queryParm.put("port", HK_DEF_PORT);
  2562. queryParm.put("appKey", HK_DEF_APP_KEY);
  2563. queryParm.put("appSecret", HK_DEF_APP_SECRET);
  2564. return queryParm;
  2565. }
  2566. /**
  2567. * 2026-05-26:把海康时间统一格式化成带时区偏移的文本。
  2568. */
  2569. private static String makeHkTime(Timestamp time) {
  2570. if (time == null)
  2571. return null;
  2572. return time.toLocalDateTime().atZone(ZoneId.of("Asia/Shanghai")).format(HK_AUTH_TIME_FMT);
  2573. }
  2574. /**
  2575. * 2026-05-26:执行后的跳过日志。
  2576. */
  2577. private static void logSkip(String reason, long rcid, Long ryid, Long bjid) {
  2578. Map<String, Object> logRow = new LinkedHashMap<>();
  2579. logRow.put("mode", "skip");
  2580. logRow.put("reason", reason);
  2581. logRow.put("rcid", rcid);
  2582. if (ryid != null && ryid > 0)
  2583. logRow.put("ryid", ryid);
  2584. if (bjid != null && bjid > 0)
  2585. logRow.put("bjid", bjid);
  2586. log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 跳过:{}", logRow);
  2587. }
  2588. /**
  2589. * 2026-05-26:读取门禁时间 / 配置 / 响应时统一做小工具,避免上层逻辑到处判空。
  2590. */
  2591. private static boolean rdBoolCfg(String propName, String envName, boolean defVal) {
  2592. String cfgVal = rdCfg(propName, envName);
  2593. if (StringUtils.isBlank(cfgVal))
  2594. return defVal;
  2595. String normVal = StringUtils.trimToEmpty(cfgVal).toLowerCase(Locale.ROOT);
  2596. return "1".equals(normVal) || "true".equals(normVal) || "yes".equals(normVal) || "y".equals(normVal);
  2597. }
  2598. /**
  2599. * 2026-05-26:整型配置读取,非法值统一回退默认值。
  2600. */
  2601. private static int rdIntCfg(String propName, String envName, int defVal) {
  2602. String cfgVal = rdCfg(propName, envName);
  2603. if (StringUtils.isBlank(cfgVal))
  2604. return defVal;
  2605. try {
  2606. return Integer.parseInt(StringUtils.trim(cfgVal));
  2607. } catch (Exception ignored) {
  2608. return defVal;
  2609. }
  2610. }
  2611. /**
  2612. * 2026-05-26:字符串配置优先读系统参数,再读环境变量。
  2613. */
  2614. private static String rdCfg(String propName, String envName) {
  2615. String value = System.getProperty(propName);
  2616. if (StringUtils.isNotBlank(value))
  2617. return StringUtils.trim(value);
  2618. if (StringUtils.isNotBlank(envName)) {
  2619. value = System.getenv(envName);
  2620. if (StringUtils.isNotBlank(value))
  2621. return StringUtils.trim(value);
  2622. }
  2623. return null;
  2624. }
  2625. /**
  2626. * 2026-05-26:诊断页支持临时覆盖配置,但自动触发仍按系统配置执行。
  2627. */
  2628. private static String rdCfgOrOverride(Map<String, Object> overrideParm,
  2629. String overrideKey,
  2630. String propName,
  2631. String envName) {
  2632. String value = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
  2633. if (StringUtils.isNotBlank(value))
  2634. return value;
  2635. return rdCfg(propName, envName);
  2636. }
  2637. /**
  2638. * 2026-05-27:组件标识缺配置时回退到默认值,先保证当前请假下发链路可按既定 tagId 联调。
  2639. */
  2640. private static String rdCfgOrOverride(Map<String, Object> overrideParm,
  2641. String overrideKey,
  2642. String propName,
  2643. String envName,
  2644. String defVal) {
  2645. String value = rdCfgOrOverride(overrideParm, overrideKey, propName, envName);
  2646. if (StringUtils.isNotBlank(value))
  2647. return value;
  2648. return StringUtils.trimToNull(defVal);
  2649. }
  2650. /**
  2651. * 2026-05-27:把组件标识来源回显出来,避免联调时分不清到底用了覆盖值、配置值还是默认值。
  2652. */
  2653. private static String rdCfgSource(Map<String, Object> overrideParm,
  2654. String overrideKey,
  2655. String propName,
  2656. String envName,
  2657. String defVal) {
  2658. String overrideVal = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
  2659. if (StringUtils.isNotBlank(overrideVal))
  2660. return "override";
  2661. String cfgVal = rdCfg(propName, envName);
  2662. if (StringUtils.isNotBlank(cfgVal))
  2663. return "cfg";
  2664. return StringUtils.isNotBlank(defVal) ? "default" : "missing";
  2665. }
  2666. /**
  2667. * 2026-05-26:整型配置支持诊断页临时覆盖,非法值继续回退默认值。
  2668. */
  2669. private static int rdIntCfgOrOverride(Map<String, Object> overrideParm,
  2670. String overrideKey,
  2671. String propName,
  2672. String envName,
  2673. int defVal) {
  2674. String value = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
  2675. if (StringUtils.isBlank(value))
  2676. return rdIntCfg(propName, envName, defVal);
  2677. try {
  2678. return Integer.parseInt(StringUtils.trim(value));
  2679. } catch (Exception ignored) {
  2680. return rdIntCfg(propName, envName, defVal);
  2681. }
  2682. }
  2683. /**
  2684. * 2026-05-26:把请求里的临时覆盖项集中收口,避免 build 逻辑依赖 servlet 上下文。
  2685. */
  2686. private Map<String, Object> makeReqOverrideParm() {
  2687. Map<String, Object> row = new LinkedHashMap<>();
  2688. putIfNotBlank(row, "tagId", rdReqStrParm("tagId", "hkLeaveAuthTagId"));
  2689. putIfNotBlank(row, "callbackUrl", rdReqStrParm("callbackUrl", "hkLeaveAuthCallbackUrl"));
  2690. putIfNotBlank(row, "templateId", rdReqStrParm("templateId", "hkLeaveAuthTemplateId"));
  2691. putIfNotBlank(row, "templateDimension", rdReqStrParm("templateDimension", "dimension", "hkLeaveAuthTemplateDimension"));
  2692. return row;
  2693. }
  2694. /**
  2695. * 2026-06-02:海康下载回调采用 application/json body,不能只靠 query 参数取值。
  2696. */
  2697. private String rdReqBody() throws IOException {
  2698. if (super.req == null)
  2699. return null;
  2700. StringBuilder sb = new StringBuilder();
  2701. BufferedReader reader = super.req.getReader();
  2702. String line;
  2703. while ((line = reader.readLine()) != null)
  2704. sb.append(line);
  2705. return sb.toString();
  2706. }
  2707. /**
  2708. * 2026-05-27:把请求里的 JSON 字符串解析成 Map,供海康原始探测接口透传。
  2709. */
  2710. private static Map<String, Object> rdReqBodyMap(String reqBodyStr) {
  2711. if (StringUtils.isBlank(reqBodyStr))
  2712. return new LinkedHashMap<>();
  2713. JsonElement jsonElement = JsonParser.parseString(reqBodyStr);
  2714. if (!jsonElement.isJsonObject())
  2715. throw new IllegalArgumentException("仅支持 JSON Object。");
  2716. JsonObject jsonObject = jsonElement.getAsJsonObject();
  2717. @SuppressWarnings("unchecked")
  2718. Map<String, Object> row = GSON.fromJson(jsonObject, Map.class);
  2719. return row == null ? new LinkedHashMap<>() : row;
  2720. }
  2721. /**
  2722. * 2026-05-26:把列表字段转成长度统计,日志只看数量不看全文。
  2723. */
  2724. private static int rdListSize(Object value) {
  2725. if (value instanceof List<?> list)
  2726. return list.size();
  2727. return 0;
  2728. }
  2729. /**
  2730. * 2026-05-26:读取请求整数参数,兼容多个别名。
  2731. */
  2732. private int rdReqIntParm(String... fieldNameArr) {
  2733. if (super.req == null || fieldNameArr == null)
  2734. return 0;
  2735. for (String fieldName : fieldNameArr) {
  2736. String value = super.req.getParameter(fieldName);
  2737. if (StringUtils.isBlank(value))
  2738. continue;
  2739. try {
  2740. return Integer.parseInt(StringUtils.trim(value));
  2741. } catch (Exception ignored) {
  2742. }
  2743. }
  2744. return 0;
  2745. }
  2746. /**
  2747. * 2026-05-26:对外部对象做字符串安全读取。
  2748. */
  2749. private static String rdStr(Object value) {
  2750. return value == null ? null : StringUtils.trimToNull(String.valueOf(value));
  2751. }
  2752. /**
  2753. * 2026-05-26:把数据库列或接口字段转成长整型。
  2754. */
  2755. private static long rdLong(Object value) {
  2756. if (value == null)
  2757. return 0L;
  2758. if (value instanceof Number number)
  2759. return number.longValue();
  2760. try {
  2761. return Long.parseLong(StringUtils.trim(String.valueOf(value)));
  2762. } catch (Exception ignored) {
  2763. return 0L;
  2764. }
  2765. }
  2766. /**
  2767. * 2026-05-26:把外部对象转成可空 Long。
  2768. */
  2769. private static int rdInt(Object value) {
  2770. if (value == null)
  2771. return 0;
  2772. if (value instanceof Number number)
  2773. return number.intValue();
  2774. try {
  2775. return Integer.parseInt(StringUtils.trim(String.valueOf(value)));
  2776. } catch (Exception ignored) {
  2777. return 0;
  2778. }
  2779. }
  2780. /**
  2781. * 2026-05-26:把文本统一转成海康人员匹配时可比较的规范键。
  2782. */
  2783. private static String makeNormKey(String value) {
  2784. return StringUtils.upperCase(StringUtils.trimToEmpty(value));
  2785. }
  2786. /**
  2787. * 2026-05-26:海康人员号脱敏回显。
  2788. */
  2789. private static String makeMaskStr(String value) {
  2790. if (StringUtils.isBlank(value))
  2791. return "";
  2792. String trimVal = StringUtils.trim(value);
  2793. if (trimVal.length() <= 4)
  2794. return "****";
  2795. return trimVal.substring(0, 2) + "****" + trimVal.substring(trimVal.length() - 2);
  2796. }
  2797. /**
  2798. * 2026-05-26:读取请求参数,兼容多个别名。
  2799. */
  2800. private long rdReqLongParm(String... fieldNameArr) {
  2801. if (super.req == null || fieldNameArr == null)
  2802. return 0L;
  2803. for (String fieldName : fieldNameArr) {
  2804. String value = super.req.getParameter(fieldName);
  2805. if (StringUtils.isBlank(value))
  2806. continue;
  2807. try {
  2808. return Long.parseLong(StringUtils.trim(value));
  2809. } catch (Exception ignored) {
  2810. }
  2811. }
  2812. return 0L;
  2813. }
  2814. /**
  2815. * 2026-05-26:读取请求字符串参数,兼容多个别名。
  2816. */
  2817. private String rdReqStrParm(String... fieldNameArr) {
  2818. if (super.req == null || fieldNameArr == null)
  2819. return null;
  2820. for (String fieldName : fieldNameArr) {
  2821. String value = super.req.getParameter(fieldName);
  2822. if (StringUtils.isNotBlank(value))
  2823. return StringUtils.trim(value);
  2824. }
  2825. return null;
  2826. }
  2827. /**
  2828. * 2026-05-26:仅在非空时写入覆盖配置。
  2829. */
  2830. private static void putIfNotBlank(Map<String, Object> row, String key, String value) {
  2831. if (StringUtils.isNotBlank(value))
  2832. row.put(key, value);
  2833. }
  2834. /**
  2835. * 2026-06-02:仅当结果里还没有该字段时,才把持久化快照补回显示对象。
  2836. */
  2837. private static void putPersistedField(Map<String, Object> row, String key, String value) {
  2838. if (row == null || StringUtils.isAnyBlank(key, value) || row.containsKey(key))
  2839. return;
  2840. row.put(key, value);
  2841. }
  2842. /**
  2843. * 2026-05-26:请假上下文只保留同步临时权限所需字段。
  2844. */
  2845. private static final class LeaveAuthSyncCtx {
  2846. private final long rcid;
  2847. private final long bjid;
  2848. private final long ryid;
  2849. private final int rclbm;
  2850. private final Timestamp kssj;
  2851. private final Timestamp jssj;
  2852. private final String xm;
  2853. private final String jobNo;
  2854. private final String ms;
  2855. private final String mswj;
  2856. private final String wcmswj;
  2857. private LeaveAuthSyncCtx(long rcid,
  2858. long bjid,
  2859. long ryid,
  2860. int rclbm,
  2861. Timestamp kssj,
  2862. Timestamp jssj,
  2863. String xm,
  2864. String jobNo,
  2865. String ms,
  2866. String mswj,
  2867. String wcmswj) {
  2868. this.rcid = rcid;
  2869. this.bjid = bjid;
  2870. this.ryid = ryid;
  2871. this.rclbm = rclbm;
  2872. this.kssj = kssj;
  2873. this.jssj = jssj;
  2874. this.xm = xm;
  2875. this.jobNo = jobNo;
  2876. this.ms = ms;
  2877. this.mswj = mswj;
  2878. this.wcmswj = wcmswj;
  2879. }
  2880. }
  2881. }