| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125 |
- package biz.kq;
- import base.po.RcPo;
- import com.google.gson.Gson;
- import com.google.gson.JsonElement;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import core.co.haikang.HkApiClient;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.logging.log4j.LogManager;
- import org.apache.logging.log4j.Logger;
- import ss.db.Db;
- import ss.db.SqlCmd;
- import ss.serv.Serv;
- import ss.serv.ServC;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.sql.Timestamp;
- import java.nio.charset.StandardCharsets;
- import java.time.OffsetDateTime;
- import java.time.ZoneId;
- import java.time.format.DateTimeFormatter;
- import java.util.ArrayList;
- import java.util.LinkedHashMap;
- import java.util.LinkedHashSet;
- import java.util.List;
- import java.util.Locale;
- import java.util.Map;
- import java.util.Set;
- /**
- * 2026-05-26:班主任请假后的海康临时权限同步服务。
- * 2026-05-26:请假默认走“特殊人员权限直接下发 + 结果回查”口径,不再依赖 authItemNo。
- */
- public class HkLeaveAuthServ extends Serv {
- private static final Logger log4j = LogManager.getLogger(HkLeaveAuthServ.class);
- private static final HkApiClient HK_API_CLIENT = new HkApiClient();
- private static final Gson GSON = new Gson();
- private static final String CFG_ENABLED = "hk.leaveAuth.enabled";
- private static final String CFG_EXECUTE = "hk.leaveAuth.execute";
- private static final String CFG_HOST = "hk.host";
- private static final String CFG_PORT = "hk.port";
- private static final String CFG_APP_KEY = "hk.appKey";
- private static final String CFG_APP_SECRET = "hk.appSecret";
- private static final String CFG_TAG_ID = "hk.leaveAuth.tagId";
- private static final String CFG_CALLBACK_URL = "hk.leaveAuth.callbackUrl";
- private static final String CFG_TEMPLATE_ID = "hk.leaveAuth.templateId";
- private static final String CFG_TEMPLATE_DIMENSION = "hk.leaveAuth.templateDimension";
- private static final String CFG_MODE = "hk.leaveAuth.mode";
- private static final String HK_DEF_HOST = "192.168.68.3";
- private static final int HK_DEF_PORT = 443;
- private static final String HK_DEF_APP_KEY = "25723525";
- private static final String HK_DEF_APP_SECRET = "V8KVC0McdY5KVARbIpQv";
- private static final String HK_DEF_TAG_ID = "frs";
- private static final int HK_DEF_TEMPLATE_DIMENSION = 1;
- private static final String HK_DEF_MODE = "platform_config";
- private static final int HK_DEF_DOWNLOAD_POLL_COUNT = 4;
- private static final int HK_DEF_DOWNLOAD_POLL_SLEEP_MS = 1200;
- private static final int RC_WCMSWJ_MAX_BYTES = 4000;
- private static final String RC_WCMSWJ_TRUNCATE_SUFFIX = "...";
- private static final DateTimeFormatter HK_AUTH_TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");
- /**
- * 2026-05-26:请假保存后执行入口,保持原来的挂点不变。
- */
- static void syncLeaveAuthAfterCommit(RcPo rcPo) {
- if (rcPo == null || rcPo.getRcid() <= 0)
- return;
- if (!rdBoolCfg(CFG_ENABLED, "HK_LEAVE_AUTH_ENABLED", false))
- return;
- try {
- Map<String, Object> result = buildLeaveAuthSyncResult(rcPo.getRcid(), true, Map.of());
- if (!Boolean.TRUE.equals(result.get("ok")) || StringUtils.isNotBlank(rdStr(result.get("skipReason"))))
- logSkip(rdStr(result.get("msg")), rcPo.getRcid(), null, null);
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 异常,rcid={}", rcPo.getRcid(), e);
- persistUnexpectedSyncError(rcPo.getRcid(), e);
- }
- }
- /**
- * 2026-05-26:请假权限预览入口,只回显请求和海康组装结果,不影响现网写入。
- */
- public String previewLeaveAuthSync() {
- super.wrJsonByResp(previewLeaveAuthSyncResult());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-26:请假权限诊断入口,直接回显人员、门禁资源、模板与海康探测结果。
- */
- public String diagLeaveAuthItem() {
- super.wrJsonByResp(diagLeaveAuthItemResult());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-26:自动探测海康模板编号的诊断入口,只依赖 rcid 和学生身份,不要求先提供 templateId。
- */
- public String diagLeaveAuthTemplateId() {
- super.wrJsonByResp(diagLeaveAuthTemplateIdResult());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-27:通用海康原始接口探测入口,便于逐个试海康文档候选接口并回收原始响应分析 templateId。
- */
- public String probeHkTemplateApi() {
- super.wrJsonByResp(probeHkTemplateApiResult());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-26:手工真实下发入口,只在明确传参时执行海康写操作。
- */
- public String executeLeaveAuthSync() {
- super.wrJsonByResp(executeLeaveAuthSyncResult());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-26:手工查询特殊人员权限下发结果,便于拿到配置后快速回查海康任务状态。
- */
- public String viewLeaveAuthSyncResult() {
- super.wrJsonByResp(viewLeaveAuthSyncResultData());
- return ServC.SERV_notByA;
- }
- /**
- * 2026-06-02:海康下载结果回调入口,优先把任务号与下载摘要回写到请假记录,便于现场后补确认。
- */
- public String recvLeaveAuthDownloadPush() {
- String pushBodyStr;
- try {
- pushBodyStr = rdReqBody();
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.recvLeaveAuthDownloadPush() 读取请求体异常", e);
- Map<String, Object> errResp = new LinkedHashMap<>();
- errResp.put("ok", false);
- errResp.put("msg", e.getMessage());
- if (super.resp != null)
- super.resp.setStatus(500);
- super.wrJsonByResp(errResp);
- return ServC.SERV_notByA;
- }
- boolean showDetail = "1".equals(rdReqStrParm("showDetail", "debug"))
- || "true".equalsIgnoreCase(rdReqStrParm("showDetail", "debug"));
- if (showDetail) {
- Map<String, Object> debugResp = processLeaveAuthDownloadPushAfterAck(pushBodyStr, true);
- super.wrJsonByResp(debugResp);
- return ServC.SERV_notByA;
- }
- Map<String, Object> ackResp = new LinkedHashMap<>();
- ackResp.put("ok", true);
- ackResp.put("accepted", true);
- ackResp.put("bodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
- super.wrJsonByResp(ackResp);
- try {
- processLeaveAuthDownloadPushAfterAck(pushBodyStr, false);
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.recvLeaveAuthDownloadPush() 回调已应答,但后续处理异常", e);
- }
- return ServC.SERV_notByA;
- }
- /**
- * 2026-05-26:预览态统一走同一套组装逻辑,便于和真实下发保持一致。
- */
- private Map<String, Object> previewLeaveAuthSyncResult() {
- long rcid = rdReqLongParm("rcid");
- if (rcid <= 0) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", "缺少有效的 rcid 参数。");
- return result;
- }
- try {
- return buildLeaveAuthSyncResult(rcid, false, makeReqOverrideParm());
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.previewLeaveAuthSync() 异常,rcid={}", rcid, e);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-26:诊断态直接把权限下发所需的关键拼装链路都回显出来。
- */
- private Map<String, Object> diagLeaveAuthItemResult() {
- long rcid = rdReqLongParm("rcid");
- if (rcid <= 0) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", "缺少有效的 rcid 参数。");
- return result;
- }
- try {
- Map<String, Object> result = buildLeaveAuthSyncResult(rcid, false, makeReqOverrideParm());
- result.put("diagOnly", true);
- return result;
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.diagLeaveAuthItem() 异常,rcid={}", rcid, e);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-26:自动探测 templateId,给后续真实下发前先做一轮海康侧可用模板排查。
- */
- private Map<String, Object> diagLeaveAuthTemplateIdResult() {
- long rcid = rdReqLongParm("rcid");
- if (rcid <= 0) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", "缺少有效的 rcid 参数。");
- return result;
- }
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", true);
- result.put("rcid", rcid);
- try (Db gdba = Db.makeConn()) {
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
- if (ctx == null) {
- result.put("ok", false);
- result.put("msg", "未找到对应请假记录。");
- return result;
- }
- result.put("leaveCtx", makeLeaveCtxResp(ctx));
- if (StringUtils.isBlank(ctx.jobNo)) {
- result.put("ok", false);
- result.put("msg", "学生缺少人员号(jobNo/RYH),无法匹配海康人员。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- Map<String, Object> hkConnParm = makeHkConnParm();
- if (hkConnParm == null) {
- result.put("ok", false);
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- result.put("hkConn", makeSafeHkConnResp(hkConnParm));
- Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(
- hkConnParm, List.of(ctx.jobNo));
- Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
- result.put("personQueryJobNo", ctx.jobNo);
- result.put("personInfoFound", personInfo != null);
- if (personInfo == null) {
- result.put("ok", false);
- result.put("msg", "海康侧未找到对应人员。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- result.put("personInfo", makePersonInfoResp(personInfo));
- String personId = rdStr(personInfo.get("personId"));
- if (StringUtils.isBlank(personId)) {
- result.put("ok", false);
- result.put("msg", "海康人员缺少 personId。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- int probeLimit = rdReqIntParm("probeLimit", "doorLimit", "limit");
- if (probeLimit <= 0)
- probeLimit = 3;
- List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
- List<Map<String, Object>> resourceInfoList = makeResourceInfoList(resourceSourceList);
- if (probeLimit > resourceInfoList.size())
- probeLimit = resourceInfoList.size();
- result.put("resourceCount", resourceInfoList.size());
- result.put("probeLimit", probeLimit);
- result.put("resourceSourceList", makeMjdRespList(resourceSourceList));
- List<Map<String, Object>> probeList = new ArrayList<>();
- LinkedHashSet<String> detectedTemplateIdSet = new LinkedHashSet<>();
- for (int i = 0; i < probeLimit; i++) {
- Map<String, Object> resourceInfo = resourceInfoList.get(i);
- Map<String, Object> probeRow = new LinkedHashMap<>();
- probeRow.put("resourceInfo", resourceInfo);
- probeRow.put("request", makeSingleAuthItemSearchReq(personId, resourceInfo));
- try {
- Map<String, Object> resp = HK_API_CLIENT.searchSingleAuthItem(hkConnParm, probeRow.get("request") instanceof Map<?, ?> reqMap
- ? (Map<String, Object>) reqMap
- : makeSingleAuthItemSearchReq(personId, resourceInfo));
- probeRow.put("ok", true);
- probeRow.put("response", resp);
- List<String> templateIdList = extTemplateIdList(resp);
- probeRow.put("templateIdCandidates", templateIdList);
- if (!templateIdList.isEmpty())
- detectedTemplateIdSet.addAll(templateIdList);
- } catch (Exception e) {
- probeRow.put("ok", false);
- probeRow.put("msg", e.getMessage());
- }
- probeList.add(probeRow);
- }
- result.put("probeResults", probeList);
- result.put("detectedTemplateIds", new ArrayList<>(detectedTemplateIdSet));
- result.put("detectedTemplateId", detectedTemplateIdSet.isEmpty() ? null : detectedTemplateIdSet.iterator().next());
- result.put("msg", detectedTemplateIdSet.isEmpty()
- ? "未探测到 templateId,请海康侧确认该人/门禁是否已有权限模板。"
- : "已自动探测到 templateId。");
- return result;
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.diagLeaveAuthTemplateId() 异常,rcid={}", rcid, e);
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-27:透传海康接口路径和请求体,返回原始请求与响应,作为 templateId 联调诊断口。
- */
- private Map<String, Object> probeHkTemplateApiResult() {
- Map<String, Object> result = new LinkedHashMap<>();
- String apiPath = rdReqStrParm("apiPath", "path");
- String reqBodyStr = rdReqStrParm("reqBody", "body", "json");
- long rcid = rdReqLongParm("rcid");
- result.put("ok", false);
- result.put("apiPath", apiPath);
- result.put("rcid", rcid);
- if (StringUtils.isBlank(apiPath)) {
- result.put("msg", "缺少 apiPath 参数。");
- return result;
- }
- if (!StringUtils.startsWith(apiPath, "/artemis/api/")) {
- result.put("msg", "apiPath 必须以 /artemis/api/ 开头。");
- return result;
- }
- Map<String, Object> reqBodyMap;
- try {
- reqBodyMap = rdReqBodyMap(reqBodyStr);
- } catch (Exception e) {
- result.put("msg", "reqBody 不是有效 JSON Object:" + e.getMessage());
- return result;
- }
- result.put("requestBody", reqBodyMap);
- try {
- Map<String, Object> hkConnParm = makeHkConnParm();
- if (hkConnParm == null) {
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- return result;
- }
- result.put("hkConn", makeSafeHkConnResp(hkConnParm));
- String tagId = rdCfgOrOverride(makeReqOverrideParm(), "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
- if (StringUtils.isNotBlank(tagId))
- hkConnParm.put("tagId", tagId);
- result.put("tagId", tagId);
- result.put("tagIdSource", rdCfgSource(makeReqOverrideParm(), "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
- if (rcid > 0) {
- try (Db gdba = Db.makeConn()) {
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
- if (ctx != null)
- result.put("leaveCtx", makeLeaveCtxResp(ctx));
- }
- }
- Map<String, Object> responseMap = HK_API_CLIENT.postProbeApi(hkConnParm, apiPath, reqBodyMap);
- result.put("ok", true);
- result.put("response", responseMap);
- result.put("templateIdCandidates", extTemplateIdList(responseMap));
- result.put("msg", "海康接口探测已返回,请把 response 和 templateIdCandidates 一并发我分析。");
- return result;
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.probeHkTemplateApi() 异常,apiPath={}", apiPath, e);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-26:手工触发真实下发,便于先做一次人工联调确认海康侧能成功接收。
- */
- private Map<String, Object> executeLeaveAuthSyncResult() {
- long rcid = rdReqLongParm("rcid");
- if (rcid <= 0) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", "缺少有效的 rcid 参数。");
- return result;
- }
- try {
- return buildLeaveAuthSyncResult(rcid, true, makeReqOverrideParm());
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.executeLeaveAuthSync() 异常,rcid={}", rcid, e);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-26:单独开放结果查询口,避免每次都必须先真实下发才能查看海康侧异步结果。
- */
- private Map<String, Object> viewLeaveAuthSyncResultData() {
- long rcid = rdReqLongParm("rcid");
- if (rcid <= 0) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", "缺少有效的 rcid 参数。");
- return result;
- }
- Map<String, Object> overrideParm = makeReqOverrideParm();
- try {
- Map<String, Object> result = buildLeaveAuthSyncResult(rcid, false, overrideParm);
- String modeCfg = normalizeLeaveAuthMode(rdStr(result.get("modeCfg")));
- if ("platform_config".equals(modeCfg)) {
- try (Db gdba = Db.makeConn()) {
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
- if (ctx == null) {
- result.put("ok", false);
- result.put("msg", "未找到对应请假记录。");
- return result;
- }
- return refreshPlatformConfigLeaveAuthResult(gdba, ctx, overrideParm, result);
- }
- }
- @SuppressWarnings("unchecked")
- Map<String, Object> queryReq = (Map<String, Object>) result.get("authDownloadResultQueryReq");
- if (queryReq == null) {
- result.put("ok", false);
- result.put("msg", "未能组装下发结果查询条件。");
- return result;
- }
- Map<String, Object> hkConnParm = rdHkConnParm();
- if (hkConnParm == null) {
- result.put("ok", false);
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- return result;
- }
- String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
- if (StringUtils.isNotBlank(tagId))
- hkConnParm.put("tagId", tagId);
- result.put("tagId", tagId);
- result.put("tagIdSource", rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
- result.put("mode", "viewResult");
- result.put("authDownloadResultQueryResp",
- querySpecialPersonAuthDownloadResultWithRetry(hkConnParm, queryReq));
- result.put("downloadResultConfirmed", hasSpecialPersonAuthDownloadResult(result.get("authDownloadResultQueryResp")));
- return result;
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.viewLeaveAuthSyncResultData() 异常,rcid={}", rcid, e);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-05-26:统一组装请假权限同步结果,预览和真实执行共用这条链路。
- */
- private static Map<String, Object> buildLeaveAuthSyncResult(long rcid,
- boolean autoTrigger,
- Map<String, Object> overrideParm) throws Exception {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", true);
- result.put("autoTrigger", autoTrigger);
- result.put("enabled", rdBoolCfg(CFG_ENABLED, "HK_LEAVE_AUTH_ENABLED", false));
- result.put("execute", rdBoolCfg(CFG_EXECUTE, "HK_LEAVE_AUTH_EXECUTE", false));
- result.put("modeCfg", rdCfg(CFG_MODE, "HK_LEAVE_AUTH_MODE"));
- result.put("rcid", rcid);
- try (Db gdba = Db.makeConn()) {
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
- if (ctx == null) {
- result.put("ok", false);
- result.put("msg", "未找到对应请假记录。");
- return result;
- }
- result.put("leaveCtx", makeLeaveCtxResp(ctx));
- applyPersistedLeaveAuthSnapshot(ctx, result);
- Timestamp now = new Timestamp(System.currentTimeMillis());
- result.put("syncTime", makeHkTime(now));
- result.put("leaveExpired", ifLeaveEnded(ctx.jssj, now));
- if (ifLeaveEnded(ctx.jssj, now)) {
- result.put("ok", false);
- result.put("mode", "skipExpired");
- result.put("skipReason", "请假时间段已结束,跳过海康自动开门。");
- result.put("msg", "请假结束时间早于当前时间,不能再下发海康临时权限。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- if (StringUtils.isBlank(ctx.jobNo)) {
- result.put("ok", false);
- result.put("msg", "学生缺少人员号(jobNo/RYH),无法匹配海康人员。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- Map<String, Object> hkConnParm = makeHkConnParm();
- if (hkConnParm == null) {
- result.put("ok", false);
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- result.put("hkConn", makeSafeHkConnResp(hkConnParm));
- Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(
- hkConnParm, List.of(ctx.jobNo));
- Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
- result.put("personQueryJobNo", ctx.jobNo);
- result.put("personInfoFound", personInfo != null);
- if (personInfo == null) {
- result.put("ok", false);
- result.put("msg", "海康侧未找到对应人员。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- result.put("personInfo", makePersonInfoResp(personInfo));
- String personId = rdStr(personInfo.get("personId"));
- if (StringUtils.isBlank(personId)) {
- result.put("ok", false);
- result.put("msg", "海康人员缺少 personId。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
- List<Map<String, Object>> resourceInfoList = makeResourceInfoList(resourceSourceList);
- result.put("resourceSourceList", makeMjdRespList(resourceSourceList));
- result.put("resourceInfos", resourceInfoList);
- result.put("resourceCount", resourceInfoList.size());
- if (resourceInfoList.isEmpty()) {
- result.put("ok", false);
- result.put("msg", "未找到可下发的有效门禁点。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
- String callbackUrl = rdCfgOrOverride(overrideParm, "callbackUrl", CFG_CALLBACK_URL, "HK_LEAVE_AUTH_CALLBACK_URL");
- Integer templateDimension = rdIntCfgOrOverride(
- overrideParm, "templateDimension", CFG_TEMPLATE_DIMENSION, "HK_LEAVE_AUTH_TEMPLATE_DIMENSION", HK_DEF_TEMPLATE_DIMENSION);
- String templateId = rdCfgOrOverride(overrideParm, "templateId", CFG_TEMPLATE_ID, "HK_LEAVE_AUTH_TEMPLATE_ID");
- String mode = normalizeLeaveAuthMode(rdCfgOrOverride(overrideParm, "mode", CFG_MODE, "HK_LEAVE_AUTH_MODE"));
- String tagIdSource = rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
- if (StringUtils.isNotBlank(tagId))
- hkConnParm.put("tagId", tagId);
- // 2026-05-27:当前请假自动开门按“添加权限配置”口径执行,templateId 只在海康侧明确要求时才附带。
- Map<String, Object> singleSearchReq = null;
- Map<String, Object> singleSearchResp = null;
- String probedTemplateId = null;
- String templateIdSource = "missing";
- if (StringUtils.isBlank(templateId)) {
- singleSearchReq = makeSingleAuthItemSearchReq(personId, resourceInfoList.get(0));
- result.put("singleSearchReq", singleSearchReq);
- try {
- singleSearchResp = HK_API_CLIENT.searchSingleAuthItem(hkConnParm, singleSearchReq);
- result.put("singleSearchResp", singleSearchResp);
- } catch (Exception e) {
- result.put("singleSearchError", e.getMessage());
- result.put("templateProbeStatus", "failed");
- result.put("templateProbeHint", "海康侧 single/search 当前不能稳定用于自动探测 templateId,请改为显式配置。");
- }
- probedTemplateId = extTemplateId(singleSearchResp);
- templateIdSource = StringUtils.isNotBlank(probedTemplateId) ? "singleSearchResp" : "missing";
- }
- if (StringUtils.isNotBlank(templateId))
- templateIdSource = "cfg";
- String effectiveTemplateId = StringUtils.defaultIfBlank(templateId, probedTemplateId);
- result.put("templateIdSource", templateIdSource);
- result.put("templateId", effectiveTemplateId);
- result.put("downloadMode", StringUtils.isBlank(effectiveTemplateId) ? "addPermissionConfig" : "addPermissionConfigWithTemplate");
- result.put("templateDimension", templateDimension);
- result.put("mode", mode);
- result.put("tagId", tagId);
- result.put("tagIdSource", tagIdSource);
- result.put("callbackUrl", callbackUrl);
- result.put("configReady", StringUtils.isNotBlank(tagId));
- List<String> missingCfgList = new ArrayList<>();
- if (StringUtils.isBlank(tagId))
- missingCfgList.add("tagId");
- result.put("missingConfig", missingCfgList);
- result.put("nextSteps", makeNextStepList(missingCfgList));
- result.put("tagIdAdvice", "当前项目只做接口下发时,tagId 只要海康侧提供可用值即可;若还要求平台门禁管理可见,再评估是否改成 acs。");
- result.put("templateIdAdvice", "templateId 仅在海康侧明确要求模板时再补;当前请假自动开门默认可不传。");
- result.put("executeApiPath", "/artemis/api/acps/v1/authDownload/special/person/diy");
- result.put("resultApiPath", "/artemis/api/acps/v1/authDownload/special/person/diy/result");
- // 2026-05-27:templateId 为空时,不再把 templateConfigInfos 强塞进请求体,避免把新增权限配置卡死。
- Map<String, Object> payload = makeSpecialAuthPayload(
- ctx, personInfo, personId, resourceInfoList, tagId, callbackUrl, effectiveTemplateId, templateDimension);
- result.put("payload", payload);
- result.put("authDownloadResultQueryReq", makeAuthDownloadResultQueryReq(personId, resourceInfoList));
- if (StringUtils.isBlank(tagId)) {
- result.put("skipReason", "缺少海康下发配置 tagId,暂不执行下发。");
- result.put("mode", "preview");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- boolean execute = rdBoolCfg(CFG_EXECUTE, "HK_LEAVE_AUTH_EXECUTE", false);
- boolean platformConfigMode = "platform_config".equalsIgnoreCase(mode);
- boolean legacyMode = !platformConfigMode;
- if (!autoTrigger || !execute) {
- result.put("mode", "dryRun");
- if (autoTrigger)
- logDryRun(ctx, personInfo, payload);
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- if (platformConfigMode) {
- return runPlatformConfigMode(gdba, ctx, personInfo, personId, resourceInfoList, tagId, callbackUrl, templateId,
- templateDimension, payload, result);
- }
- if (legacyMode) {
- Map<String, Object> authSyncResp = HK_API_CLIENT.downloadSpecialPersonAuth(hkConnParm, payload);
- result.put("mode", "execute");
- result.put("authSyncResp", authSyncResp);
- try {
- Map<String, Object> queryReq = makeAuthDownloadResultQueryReq(personId, resourceInfoList);
- result.put("authDownloadResultQueryReq", queryReq);
- result.put("authDownloadResultQueryResp",
- querySpecialPersonAuthDownloadResultWithRetry(hkConnParm, queryReq));
- result.put("downloadResultConfirmed", hasSpecialPersonAuthDownloadResult(result.get("authDownloadResultQueryResp")));
- } catch (Exception e) {
- result.put("authDownloadResultQueryError", e.getMessage());
- }
- logExecute(ctx, personInfo, payload, authSyncResp);
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- result.put("ok", false);
- result.put("msg", "未知的海康请假模式:" + mode);
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- }
- /**
- * 2026-05-26:把请假记录和人员信息一次性查出来,避免业务层自己拼 SQL。
- */
- private static LeaveAuthSyncCtx selLeaveAuthSyncCtx(Db gdba, long rcid) throws Exception {
- String sql = "select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
- + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
- + " from RC rc"
- + " left join RY on ry.RYID=rc.FZRYID"
- + " where rc.RCID=:rcid";
- SqlCmd sqlCmd = new SqlCmd(sql);
- sqlCmd.wrLongParm("rcid", rcid);
- List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
- if (rowList == null || rowList.isEmpty())
- return null;
- Map<String, Object> row = rowList.get(0);
- return new LeaveAuthSyncCtx(
- rdLong(row.get("rcid")),
- rdLong(row.get("bjid")),
- rdLong(row.get("ryid")),
- rdInt(row.get("rclbm")),
- (Timestamp) row.get("kssj"),
- (Timestamp) row.get("jssj"),
- rdStr(row.get("xm")),
- rdStr(row.get("ryh")),
- rdStr(row.get("ms")),
- rdStr(row.get("mswj")),
- rdStr(row.get("wcmswj")));
- }
- /**
- * 2026-05-26:海康连接参数优先读配置,缺失时直接回退到现有默认网关参数。
- */
- private static Map<String, Object> makeHkConnParm() {
- String host = rdCfg(CFG_HOST, "HK_HOST");
- String appKey = rdCfg(CFG_APP_KEY, "HK_APP_KEY");
- String appSecret = rdCfg(CFG_APP_SECRET, "HK_APP_SECRET");
- if (StringUtils.isAnyBlank(host, appKey, appSecret))
- return makeDefaultHkConnParm();
- Map<String, Object> queryParm = new LinkedHashMap<>();
- queryParm.put("host", host);
- queryParm.put("port", rdIntCfg(CFG_PORT, "HK_PORT", HK_DEF_PORT));
- queryParm.put("appKey", appKey);
- queryParm.put("appSecret", appSecret);
- return queryParm;
- }
- /**
- * 2026-05-26:回读当前海康连接参数,给手工执行口复用。
- */
- private static Map<String, Object> rdHkConnParm() {
- return makeHkConnParm();
- }
- /**
- * 2026-05-26:请假权限直接按当前所有有效门禁点下发,避免再做班级或住宿点的额外过滤。
- */
- private static List<Map<String, Object>> makeResourceInfoList(List<Map<String, Object>> mjdList) {
- if (mjdList == null || mjdList.isEmpty())
- return List.of();
- LinkedHashSet<String> resourceIndexCodeSet = new LinkedHashSet<>();
- List<Map<String, Object>> resourceInfoList = new ArrayList<>();
- for (Map<String, Object> mjd : mjdList) {
- String resourceIndexCode = rdStr(mjd.get("sbbs"));
- if (StringUtils.isBlank(resourceIndexCode))
- continue;
- if (!resourceIndexCodeSet.add(resourceIndexCode))
- continue;
- resourceInfoList.add(makeResourceInfo(resourceIndexCode));
- }
- return resourceInfoList;
- }
- /**
- * 2026-05-26:把 MJD 记录回显成前端能直接看懂的资源来源列表。
- */
- private static List<Map<String, Object>> makeMjdRespList(List<Map<String, Object>> mjdList) {
- if (mjdList == null || mjdList.isEmpty())
- return List.of();
- List<Map<String, Object>> respList = new ArrayList<>();
- for (Map<String, Object> mjd : mjdList) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("mjdid", rdLong(mjd.get("mjdid")));
- row.put("mc", rdStr(mjd.get("mc")));
- row.put("sbbs", rdStr(mjd.get("sbbs")));
- row.put("cdid", rdLong(mjd.get("cdid")));
- row.put("mjdlbm", rdLong(mjd.get("mjdlbm")));
- row.put("jcfxm", rdStr(mjd.get("jcfxm")));
- row.put("jlztm", rdLong(mjd.get("jlztm")));
- respList.add(row);
- }
- return respList;
- }
- /**
- * 2026-05-26:给海康 special/person/diy 拼单条门禁资源信息。
- */
- private static Map<String, Object> makeResourceInfo(String resourceIndexCode) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("resourceIndexCode", resourceIndexCode);
- row.put("resourceType", "acsDevice");
- row.put("channelNos", List.of(1));
- row.put("channelIndexCodes", List.of(resourceIndexCode));
- return row;
- }
- /**
- * 2026-05-26:按海康文档组装请假特殊权限的真正下发体。
- */
- private static Map<String, Object> makeSpecialAuthPayload(LeaveAuthSyncCtx ctx,
- Map<String, Object> personInfo,
- String personId,
- List<Map<String, Object>> resourceInfoList,
- String tagId,
- String callbackUrl,
- String templateId,
- Integer templateDimension) {
- Map<String, Object> payload = new LinkedHashMap<>();
- payload.put("priority", 1);
- if (StringUtils.isNotBlank(callbackUrl))
- payload.put("callbackUrl", callbackUrl);
- payload.put("resourceInfos", resourceInfoList);
- payload.put("personInfos", List.of(makePersonInfoPayload(ctx, personInfo, personId)));
- if (StringUtils.isNotBlank(templateId))
- payload.put("templateConfigInfos", makeTemplateConfigInfos(templateId, templateDimension));
- return payload;
- }
- /**
- * 2026-05-26:把请假学生信息转成海康 special/person/diy 需要的 personInfos。
- */
- private static Map<String, Object> makePersonInfoPayload(LeaveAuthSyncCtx ctx,
- Map<String, Object> personInfo,
- String personId) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("personStatus", "ADD");
- row.put("personId", personId);
- row.put("beginTime", makeHkTime(ctx.kssj));
- row.put("endTime", makeHkTime(ctx.jssj));
- row.put("name", rdStr(personInfo.get("personName")));
- row.put("personType", "COMMON");
- return row;
- }
- /**
- * 2026-05-26:海康权限模板配置只保留最小必要字段。
- */
- private static List<Map<String, Object>> makeTemplateConfigInfos(String templateId, Integer templateDimension) {
- if (StringUtils.isBlank(templateId))
- return List.of();
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("dimension", templateDimension == null || templateDimension <= 0 ? HK_DEF_TEMPLATE_DIMENSION : templateDimension);
- row.put("templateId", templateId);
- return List.of(row);
- }
- /**
- * 2026-05-28:按平台权限配置模式执行。
- * 流程:添加权限配置 -> 查询配置进度 -> 按配置快捷下载 -> 查询下载进度。
- */
- private static Map<String, Object> runPlatformConfigMode(Db gdba,
- LeaveAuthSyncCtx ctx,
- Map<String, Object> personInfo,
- String personId,
- List<Map<String, Object>> resourceInfoList,
- String tagId,
- String callbackUrl,
- String templateId,
- Integer templateDimension,
- Map<String, Object> legacyPayload,
- Map<String, Object> result) throws Exception {
- Map<String, Object> hkConnParm = makeHkConnParm();
- if (hkConnParm == null) {
- result.put("ok", false);
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- if (StringUtils.isNotBlank(tagId))
- hkConnParm.put("tagId", tagId);
- Map<String, Object> configAddReq = makeAuthConfigAddReq(personId, resourceInfoList, ctx.kssj, ctx.jssj);
- result.put("platformConfigAddReq", configAddReq);
- result.put("executeApiPath", "/artemis/api/acps/v1/auth_config/add");
- result.put("resultApiPath", "/artemis/api/acps/v1/auth_config/rate/search");
- result.put("downloadApiPath", "/artemis/api/acps/v1/authDownload/configuration/person/reset");
- result.put("downloadTaskProgressApiPath", "/artemis/api/acps/v1/authDownload/task/progress");
- result.put("downloadTaskSearchApiPath", "/artemis/api/acps/v1/authDownload/task/search");
- result.put("downloadRecordChannelApiPath", "/artemis/api/acps/v1/download_record/channel/list/search");
- result.put("downloadRecordPersonDetailApiPath", "/artemis/api/acps/v2/download_record/person/detail/search");
- boolean callbackConfigured = StringUtils.isNotBlank(callbackUrl);
- result.put("callbackConfigured", callbackConfigured);
- if (callbackConfigured)
- result.put("platformCallbackUrl", callbackUrl);
- if (StringUtils.isNotBlank(templateId))
- result.put("platformTemplateId", templateId);
- result.put("platformTemplateDimension", templateDimension);
- result.put("payload", legacyPayload);
- Map<String, Object> configAddResp = HK_API_CLIENT.addAuthConfig(hkConnParm, configAddReq);
- result.put("authSyncResp", configAddResp);
- result.put("mode", "execute_platform_config");
- String configTaskId = rdTaskId(configAddResp);
- result.put("configTaskId", configTaskId);
- if (StringUtils.isBlank(configTaskId)) {
- result.put("ok", false);
- result.put("msg", "平台权限配置返回成功,但未拿到 taskId。");
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- Map<String, Object> configRateReq = Map.of("taskId", configTaskId);
- result.put("authConfigRateReq", configRateReq);
- try {
- result.put("authConfigRateResp", HK_API_CLIENT.searchAuthConfigRate(hkConnParm, configRateReq));
- } catch (Exception e) {
- result.put("authConfigRateError", e.getMessage());
- }
- Map<String, Object> configSearchReq = makeAuthConfigSearchReq(personId, resourceInfoList);
- result.put("authConfigSearchReq", configSearchReq);
- try {
- result.put("authConfigSearchResp", HK_API_CLIENT.searchAuthConfig(hkConnParm, configSearchReq));
- } catch (Exception e) {
- result.put("authConfigSearchError", e.getMessage());
- }
- boolean autoDownload = rdBoolCfg("hk.leaveAuth.platform.autoDownload", "HK_LEAVE_AUTH_PLATFORM_AUTO_DOWNLOAD", true);
- result.put("downloadMode", autoDownload ? "platformConfigAndDownload" : "platformConfigOnly");
- if (autoDownload) {
- Map<String, Object> resetReq = makeAuthConfigPersonResetReq(personId, resourceInfoList, callbackUrl);
- result.put("authDownloadResetReq", resetReq);
- Map<String, Object> resetResp = HK_API_CLIENT.resetAuthDownloadByPerson(hkConnParm, resetReq);
- result.put("authDownloadResetResp", resetResp);
- boolean downloadResetAccepted = isHkRespAccepted(resetResp);
- result.put("downloadResetAccepted", downloadResetAccepted);
- String downloadTaskId = rdTaskId(resetResp);
- String downloadTaskSource = downloadResetAccepted || StringUtils.isNotBlank(downloadTaskId) ? "personReset" : null;
- result.put("downloadTaskAccepted", downloadResetAccepted || StringUtils.isNotBlank(downloadTaskId));
- result.put("downloadTaskId", downloadTaskId);
- result.put("downloadTaskSource", downloadTaskSource);
- if (downloadResetAccepted && StringUtils.isBlank(downloadTaskId)) {
- result.put("downloadPendingReason",
- callbackConfigured ? "resetAcceptedAwaitCallback" : "resetAcceptedWithoutTaskIdOrCallback");
- } else if (!downloadResetAccepted) {
- result.put("downloadPendingReason", "resetNotAccepted");
- }
- if (StringUtils.isNotBlank(downloadTaskId)) {
- Map<String, Object> taskSearchReq = makeAuthDownloadTaskSearchReq(downloadTaskId);
- result.put("authDownloadTaskSearchReq", taskSearchReq);
- try {
- result.put("authDownloadTaskSearchResp",
- queryAuthDownloadTaskSearchWithRetry(hkConnParm, taskSearchReq));
- } catch (Exception e) {
- result.put("authDownloadTaskSearchError", e.getMessage());
- }
- Map<String, Object> progressReq = Map.of("taskId", downloadTaskId);
- result.put("authDownloadTaskProgressReq", progressReq);
- try {
- result.put("authDownloadTaskProgressResp",
- queryAuthDownloadTaskProgressWithRetry(hkConnParm, progressReq));
- } catch (Exception e) {
- result.put("authDownloadTaskProgressError", e.getMessage());
- }
- Map<String, Object> channelRecordReq = makeDownloadRecordChannelListReq(downloadTaskId, resourceInfoList);
- result.put("downloadRecordChannelReq", channelRecordReq);
- try {
- Map<String, Object> channelRecordResp = queryDownloadRecordChannelListWithRetry(
- hkConnParm, channelRecordReq, resourceInfoList);
- result.put("downloadRecordChannelResp", channelRecordResp);
- result.put("downloadRecordPersonDetailReqList",
- makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRecordResp));
- result.put("downloadRecordPersonDetailRespList",
- queryDownloadRecordPersonDetailRespListWithRetry(hkConnParm, downloadTaskId, personId, channelRecordResp));
- } catch (Exception e) {
- result.put("downloadRecordQueryError", e.getMessage());
- }
- }
- }
- finalizePlatformConfigResult(result, ctx.kssj, ctx.jssj, resourceInfoList.size(), autoDownload);
- logExecute(ctx, personInfo, configAddReq, configAddResp);
- persistLeaveAuthSyncResult(gdba, ctx, result);
- return result;
- }
- /**
- * 2026-05-28:按平台权限配置方式,给系统内人员配置门禁点权限。
- */
- private static Map<String, Object> makeAuthConfigAddReq(String personId,
- List<Map<String, Object>> resourceInfoList,
- Timestamp kssj,
- Timestamp jssj) {
- Map<String, Object> req = new LinkedHashMap<>();
- Map<String, Object> personData = new LinkedHashMap<>();
- personData.put("indexCodes", List.of(personId));
- personData.put("personDataType", "person");
- req.put("personDatas", List.of(personData));
- req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
- req.put("startTime", makeHkTime(kssj));
- req.put("endTime", makeHkTime(jssj));
- return req;
- }
- /**
- * 2026-06-02:平台配置完成后,按人员和设备通道做一次定向重下发,更贴近“请假单即时生效”场景。
- */
- private static Map<String, Object> makeAuthConfigPersonResetReq(String personId,
- List<Map<String, Object>> resourceInfoList,
- String callbackUrl) {
- Map<String, Object> req = new LinkedHashMap<>();
- req.put("personIds", List.of(personId));
- req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
- req.put("isReset", false);
- if (StringUtils.isNotBlank(callbackUrl))
- req.put("callbackUrl", callbackUrl);
- return req;
- }
- /**
- * 2026-06-02:下载任务摘要查询需要按 taskId 精确查询。
- */
- private static Map<String, Object> makeAuthDownloadTaskSearchReq(String downloadTaskId) {
- Map<String, Object> req = new LinkedHashMap<>();
- req.put("authTaskIds", List.of(downloadTaskId));
- req.put("pageNo", 1);
- req.put("pageSize", 10);
- return req;
- }
- /**
- * 2026-06-02:按任务号回查设备通道下载记录。
- */
- private static Map<String, Object> makeDownloadRecordChannelListReq(String downloadTaskId,
- List<Map<String, Object>> resourceInfoList) {
- Map<String, Object> req = new LinkedHashMap<>();
- req.put("taskId", downloadTaskId);
- req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
- req.put("pageNo", 1);
- int pageSize = resourceInfoList == null ? 100 : Math.max(100, Math.min(1000, resourceInfoList.size() * 2));
- req.put("pageSize", pageSize);
- return req;
- }
- /**
- * 2026-05-28:平台权限配置查询请求体。
- */
- private static Map<String, Object> makeAuthConfigSearchReq(String personId,
- List<Map<String, Object>> resourceInfoList) {
- Map<String, Object> req = new LinkedHashMap<>();
- req.put("personDataIds", List.of(personId));
- req.put("personDataType", "person");
- req.put("resourceInfos", makeAuthConfigResourceInfoList(resourceInfoList));
- req.put("resourceDataType", "resource");
- req.put("pageNo", 1);
- int pageSize = resourceInfoList == null ? 20 : Math.max(20, Math.min(200, resourceInfoList.size()));
- req.put("pageSize", pageSize);
- return req;
- }
- /**
- * 2026-05-28:平台权限配置和快捷下载复用同一批资源,但不强制带 channelIndexCodes。
- */
- private static List<Map<String, Object>> makeAuthConfigResourceInfoList(List<Map<String, Object>> resourceInfoList) {
- if (resourceInfoList == null || resourceInfoList.isEmpty())
- return List.of();
- List<Map<String, Object>> respList = new ArrayList<>();
- for (Map<String, Object> item : resourceInfoList) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("resourceIndexCode", rdStr(item.get("resourceIndexCode")));
- row.put("resourceType", rdStr(item.get("resourceType")));
- row.put("channelNos", item.get("channelNos"));
- respList.add(row);
- }
- return respList;
- }
- /**
- * 2026-05-28:海康平台类接口统一从 data.taskId 中取任务号。
- */
- private static String rdTaskId(Map<String, Object> resp) {
- if (resp == null)
- return null;
- Object dataObj = resp.get("data");
- if (!(dataObj instanceof Map<?, ?> dataMap))
- return null;
- return rdStr(dataMap.get("taskId"));
- }
- /**
- * 2026-05-26:查询下发结果时,沿用“人 + 资源”这组关键条件。
- */
- private static Map<String, Object> makeAuthDownloadResultQueryReq(String personId,
- List<Map<String, Object>> resourceInfoList) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("pageNo", 1);
- row.put("pageSize", 20);
- row.put("personIds", List.of(personId));
- row.put("resourceInfos", resourceInfoList);
- return row;
- }
- /**
- * 2026-06-02:special/person/diy/result 也是异步落库,短轮询几次再看是否已有明细。
- */
- private static Map<String, Object> querySpecialPersonAuthDownloadResultWithRetry(Map<String, Object> hkConnParm,
- Map<String, Object> queryReq) throws Exception {
- Map<String, Object> lastResp = null;
- int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.resultPollCount",
- "HK_LEAVE_AUTH_RESULT_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
- int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.resultPollSleepMs",
- "HK_LEAVE_AUTH_RESULT_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
- for (int i = 0; i < pollCount; i++) {
- if (i > 0 && sleepMs > 0) {
- try {
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- lastResp = HK_API_CLIENT.viewSpecialPersonAuthDownloadResult(hkConnParm, queryReq);
- if (hasSpecialPersonAuthDownloadResult(lastResp))
- break;
- }
- return lastResp;
- }
- /**
- * 2026-05-26:把当前缺少的配置转换成可执行的下一步,减少联调时反复口头确认。
- */
- private static List<String> makeNextStepList(List<String> missingCfgList) {
- List<String> nextStepList = new ArrayList<>();
- if (missingCfgList == null || missingCfgList.isEmpty()) {
- nextStepList.add("已具备海康下发参数,可直接调用 hkkq_leave_auth_execute 做人工联调。");
- nextStepList.add("下发后可调用 hkkq_leave_auth_result 查看海康侧结果。");
- return nextStepList;
- }
- if (missingCfgList.contains("tagId"))
- nextStepList.add("联系海康侧提供当前合作方账号可用的 tagId。");
- nextStepList.add("配置补齐前可继续使用 hkkq_leave_auth_preview / hkkq_leave_auth_diag 做联调。");
- nextStepList.add("配置补齐后先调用 hkkq_leave_auth_execute,再调用 hkkq_leave_auth_result 回查。");
- return nextStepList;
- }
- /**
- * 2026-05-26:single/search 需要“人员 + 单个门禁资源”的精确查询体。
- * 2026-05-26:这里按海康文档只传最小查询字段,不再把 channelIndexCodes 混进 single/search。
- */
- private static Map<String, Object> makeSingleAuthItemSearchReq(String personId,
- Map<String, Object> resourceInfo) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("personId", personId);
- row.put("resourceInfo", makeSingleAuthItemSearchResourceInfo(resourceInfo));
- return row;
- }
- /**
- * 2026-05-26:single/search 使用最小 resourceInfo,避免把 special/person/diy 的字段误传过去。
- */
- private static Map<String, Object> makeSingleAuthItemSearchResourceInfo(Map<String, Object> resourceInfo) {
- Map<String, Object> row = new LinkedHashMap<>();
- if (resourceInfo == null)
- return row;
- putIfNotBlank(row, "resourceIndexCode", rdStr(resourceInfo.get("resourceIndexCode")));
- putIfNotBlank(row, "resourceType", rdStr(resourceInfo.get("resourceType")));
- Object channelNos = resourceInfo.get("channelNos");
- if (channelNos instanceof List<?> list && !list.isEmpty())
- row.put("channelNos", list);
- return row;
- }
- /**
- * 2026-05-26:从 single/search 的返回里提取模板编号,作为模板配置的兜底来源。
- */
- private static String extTemplateId(Object obj) {
- if (obj == null)
- return null;
- if (obj instanceof Map<?, ?> map) {
- Object templateConfigInfos = map.get("templateConfigInfos");
- String templateId = extTemplateIdFromList(templateConfigInfos);
- if (StringUtils.isNotBlank(templateId))
- return templateId;
- for (Object value : map.values()) {
- templateId = extTemplateId(value);
- if (StringUtils.isNotBlank(templateId))
- return templateId;
- }
- return null;
- }
- if (obj instanceof List<?> list) {
- for (Object item : list) {
- String templateId = extTemplateId(item);
- if (StringUtils.isNotBlank(templateId))
- return templateId;
- }
- }
- return null;
- }
- /**
- * 2026-05-26:优先取模板列表第一条,避免一张表里多个模板时取值不稳定。
- */
- private static String extTemplateIdFromList(Object templateConfigInfos) {
- if (!(templateConfigInfos instanceof List<?> list) || list.isEmpty())
- return null;
- for (Object item : list) {
- if (item instanceof Map<?, ?> map) {
- Object templateId = map.get("templateId");
- String value = rdStr(templateId);
- if (StringUtils.isNotBlank(value))
- return value;
- }
- }
- return null;
- }
- /**
- * 2026-05-26:把响应体里的所有 templateId 候选都收集出来,供诊断页直接回显。
- */
- private static List<String> extTemplateIdList(Object obj) {
- LinkedHashSet<String> valueSet = new LinkedHashSet<>();
- extTemplateIdList0(obj, valueSet);
- return new ArrayList<>(valueSet);
- }
- /**
- * 2026-05-26:递归收集 templateId,避免只拿到第一条导致排查信息不完整。
- */
- private static void extTemplateIdList0(Object obj, LinkedHashSet<String> valueSet) {
- if (obj == null || valueSet == null)
- return;
- if (obj instanceof Map<?, ?> map) {
- Object templateId = map.get("templateId");
- if (templateId != null) {
- String value = rdStr(templateId);
- if (StringUtils.isNotBlank(value))
- valueSet.add(value);
- }
- for (Map.Entry<?, ?> entry : map.entrySet()) {
- if ("templateId".equals(String.valueOf(entry.getKey())))
- continue;
- extTemplateIdList0(entry.getValue(), valueSet);
- }
- return;
- }
- if (obj instanceof List<?> list) {
- for (Object item : list)
- extTemplateIdList0(item, valueSet);
- }
- }
- /**
- * 2026-05-26:日志只保留关键定位信息,避免把整段 payload 以外再重复刷屏。
- */
- private static void logDryRun(LeaveAuthSyncCtx ctx,
- Map<String, Object> personInfo,
- Map<String, Object> payload) {
- Map<String, Object> logRow = makeBaseLogRow(ctx);
- logRow.put("mode", "dryRun");
- logRow.put("personId", rdStr(personInfo.get("personId")));
- logRow.put("resourceCount", rdListSize(payload.get("resourceInfos")));
- logRow.put("templateCount", rdListSize(payload.get("templateConfigInfos")));
- log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() dry-run:{}", logRow);
- }
- /**
- * 2026-05-26:真实下发时记录海康返回和本地关键字段,便于复盘。
- */
- private static void logExecute(LeaveAuthSyncCtx ctx,
- Map<String, Object> personInfo,
- Map<String, Object> payload,
- Map<String, Object> authSyncResp) {
- Map<String, Object> logRow = makeBaseLogRow(ctx);
- logRow.put("mode", "execute");
- logRow.put("personId", rdStr(personInfo.get("personId")));
- logRow.put("resourceCount", rdListSize(payload.get("resourceInfos")));
- logRow.put("authSyncResp", authSyncResp);
- log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 已执行:{}", logRow);
- }
- /**
- * 2026-05-29:请假备注以用户提交的 `RC.ms` 为准,海康任务号与结果摘要改写到 `RC.wcmswj`。
- */
- private static void persistLeaveAuthSyncResult(Db gdba,
- LeaveAuthSyncCtx ctx,
- Map<String, Object> result) throws Exception {
- if (gdba == null || ctx == null || result == null || ctx.rcid <= 0)
- return;
- String mode = rdStr(result.get("mode"));
- boolean shouldPersist = Boolean.TRUE.equals(result.get("autoTrigger"))
- || (StringUtils.isNotBlank(mode) && mode.startsWith("execute"));
- if (!shouldPersist)
- return;
- String persistText = fitWcmswjText(makeLeaveAuthPersistText(ctx, result));
- if (StringUtils.isBlank(persistText)) {
- log4j.warn("HkLeaveAuthServ.persistLeaveAuthSyncResult() skip empty rc.wcmswj, rcid={}, mode={}, ok={}, msg={}",
- ctx.rcid, rdStr(result.get("mode")), rdStr(result.get("ok")), rdStr(result.get("msg")));
- return;
- }
- RcPo rcPo = new RcPo();
- rcPo.setRcid(ctx.rcid);
- rcPo.setWcmswj(persistText);
- gdba.doUpdPo(rcPo, Set.of("wcmswj"));
- gdba.commit();
- log4j.info("HkLeaveAuthServ.persistLeaveAuthSyncResult() saved rc.wcmswj, rcid={}, mode={}, ok={}, msg={}",
- ctx.rcid, rdStr(result.get("mode")), rdStr(result.get("ok")), rdStr(result.get("msg")));
- }
- /**
- * 2026-06-01:自动同步若在主链路里抛异常,至少把异常摘要回写到 RC,避免线上完全没有痕迹。
- */
- private static void persistUnexpectedSyncError(long rcid, Exception e) {
- if (rcid <= 0 || e == null)
- return;
- try (Db gdba = Db.makeConn()) {
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
- if (ctx == null)
- return;
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("autoTrigger", true);
- result.put("ok", false);
- result.put("mode", "autoError");
- result.put("skipReason", "自动同步执行异常。");
- result.put("msg", makeExceptionMsg(e));
- persistLeaveAuthSyncResult(gdba, ctx, result);
- gdba.commit();
- } catch (Exception persistEx) {
- log4j.error("HkLeaveAuthServ.persistUnexpectedSyncError() 异常,rcid={}", rcid, persistEx);
- }
- }
- /**
- * 2026-05-29:把关键任务号和执行摘要压缩到 RC.wcmswj,供后续结果回查复用。
- */
- private static String makeLeaveAuthPersistText(LeaveAuthSyncCtx ctx, Map<String, Object> result) {
- if (result == null)
- return null;
- LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
- mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.ms);
- mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.mswj);
- mergeLeaveAuthPersistFieldMap(fieldMap, ctx == null ? null : ctx.wcmswj);
- putLeaveAuthPersistField(fieldMap, "syncTime", makeHkTime(new Timestamp(System.currentTimeMillis())));
- putLeaveAuthPersistField(fieldMap, "mode", rdStr(result.get("mode")));
- putLeaveAuthPersistField(fieldMap, "ok", rdStr(result.get("ok")));
- putLeaveAuthPersistField(fieldMap, "msg", rdStr(result.get("msg")));
- putLeaveAuthPersistField(fieldMap, "configTaskId", rdStr(result.get("configTaskId")));
- putLeaveAuthPersistField(fieldMap, "downloadTaskId", rdStr(result.get("downloadTaskId")));
- putLeaveAuthPersistField(fieldMap, "downloadTaskSource", rdStr(result.get("downloadTaskSource")));
- putLeaveAuthPersistField(fieldMap, "callbackConfigured", rdStr(result.get("callbackConfigured")));
- putLeaveAuthPersistField(fieldMap, "downloadResetAccepted", rdStr(result.get("downloadResetAccepted")));
- putLeaveAuthPersistField(fieldMap, "downloadTaskAccepted", rdStr(result.get("downloadTaskAccepted")));
- putLeaveAuthPersistField(fieldMap, "downloadPendingReason", rdStr(result.get("downloadPendingReason")));
- putLeaveAuthPersistField(fieldMap, "downloadConfirmSource", rdStr(result.get("downloadConfirmSource")));
- putLeaveAuthPersistField(fieldMap, "downloadResultConfirmed", rdStr(result.get("downloadResultConfirmed")));
- putLeaveAuthPersistField(fieldMap, "downloadTaskFinished", rdStr(result.get("downloadTaskFinished")));
- putLeaveAuthPersistField(fieldMap, "downloadProgressFinished", rdStr(result.get("downloadProgressFinished")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordChannelMatchedCount", rdStr(result.get("downloadRecordChannelMatchedCount")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordChannelSuccessCount", rdStr(result.get("downloadRecordChannelSuccessCount")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordChannelFailedCount", rdStr(result.get("downloadRecordChannelFailedCount")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailMatchedCount", rdStr(result.get("downloadRecordPersonDetailMatchedCount")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailSuccessCount", rdStr(result.get("downloadRecordPersonDetailSuccessCount")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordPersonDetailFailedCount", rdStr(result.get("downloadRecordPersonDetailFailedCount")));
- putLeaveAuthPersistField(fieldMap, "downloadCallbackReceived", rdStr(result.get("downloadCallbackReceived")));
- putLeaveAuthPersistField(fieldMap, "callbackTaskId", rdStr(result.get("callbackTaskId")));
- putLeaveAuthPersistField(fieldMap, "callbackRecvTime", rdStr(result.get("callbackRecvTime")));
- putLeaveAuthPersistField(fieldMap, "callbackBodySize", rdStr(result.get("callbackBodySize")));
- putLeaveAuthPersistField(fieldMap, "callbackMatchedRcid", rdStr(result.get("callbackMatchedRcid")));
- putLeaveAuthPersistField(fieldMap, "callbackResourceKey", rdStr(result.get("callbackResourceKey")));
- putLeaveAuthPersistField(fieldMap, "callbackResourceDownloadResult", rdStr(result.get("callbackResourceDownloadResult")));
- putLeaveAuthPersistField(fieldMap, "callbackResourceSuccessCount", rdStr(result.get("callbackResourceSuccessCount")));
- putLeaveAuthPersistField(fieldMap, "callbackResourceFailedCount", rdStr(result.get("callbackResourceFailedCount")));
- putLeaveAuthPersistField(fieldMap, "callbackPersonId", rdStr(result.get("callbackPersonId")));
- putLeaveAuthPersistField(fieldMap, "callbackPersonDownloadResult", rdStr(result.get("callbackPersonDownloadResult")));
- putLeaveAuthPersistField(fieldMap, "authSyncResp", makeRespBrief(result.get("authSyncResp")));
- putLeaveAuthPersistField(fieldMap, "authDownloadResultQueryResp", makeRespBrief(result.get("authDownloadResultQueryResp")));
- putLeaveAuthPersistField(fieldMap, "authDownloadResetResp", makeRespBrief(result.get("authDownloadResetResp")));
- putLeaveAuthPersistField(fieldMap, "downloadRecordChannelResp", makeRespBrief(result.get("downloadRecordChannelResp")));
- putLeaveAuthPersistField(fieldMap, "authConfigRateResp", makeRespBrief(result.get("authConfigRateResp")));
- putLeaveAuthPersistField(fieldMap, "authDownloadTaskSearchResp", makeRespBrief(result.get("authDownloadTaskSearchResp")));
- putLeaveAuthPersistField(fieldMap, "authDownloadTaskProgressResp", makeRespBrief(result.get("authDownloadTaskProgressResp")));
- List<String> partList = new ArrayList<>();
- for (Map.Entry<String, String> entry : fieldMap.entrySet())
- appendLeaveAuthPersistField(partList, entry.getKey(), entry.getValue());
- return partList.isEmpty() ? null : String.join(";", partList);
- }
- /**
- * 2026-06-01:RC.wcmswj 按数据库字节上限统一截断,避免再次抛 ORA-12899。
- */
- private static String fitWcmswjText(String text) {
- String value = StringUtils.trimToNull(text);
- if (value == null)
- return null;
- byte[] allBytes = value.getBytes(StandardCharsets.UTF_8);
- if (allBytes.length <= RC_WCMSWJ_MAX_BYTES)
- return value;
- int suffixBytes = RC_WCMSWJ_TRUNCATE_SUFFIX.getBytes(StandardCharsets.UTF_8).length;
- int maxContentBytes = Math.max(0, RC_WCMSWJ_MAX_BYTES - suffixBytes);
- StringBuilder sb = new StringBuilder();
- int usedBytes = 0;
- for (int idx = 0; idx < value.length();) {
- int codePoint = value.codePointAt(idx);
- String ch = new String(Character.toChars(codePoint));
- int chBytes = ch.getBytes(StandardCharsets.UTF_8).length;
- if (usedBytes + chBytes > maxContentBytes)
- break;
- sb.append(ch);
- usedBytes += chBytes;
- idx += Character.charCount(codePoint);
- }
- return sb.append(RC_WCMSWJ_TRUNCATE_SUFFIX).toString();
- }
- /**
- * 2026-05-29:统一拼接 RC.mswj 的键值对格式,兼容现有 field=value 读取逻辑。
- */
- private static void appendLeaveAuthPersistField(List<String> partList, String fieldName, String value) {
- if (partList == null || StringUtils.isAnyBlank(fieldName, value))
- return;
- partList.add(fieldName + "=" + value.replace(';', ';'));
- }
- /**
- * 2026-06-02:回写 RC.wcmswj 前先把旧字段合并进来,避免回调补写时把前序 taskId/配置摘要覆盖丢失。
- */
- private static void mergeLeaveAuthPersistFieldMap(Map<String, String> fieldMap, String text) {
- if (fieldMap == null || StringUtils.isBlank(text))
- return;
- String[] partArr = StringUtils.split(text, ';');
- if (partArr == null || partArr.length == 0)
- return;
- for (String part : partArr) {
- String trimPart = StringUtils.trimToNull(part);
- if (trimPart == null)
- continue;
- int idx = trimPart.indexOf('=');
- if (idx <= 0 || idx >= trimPart.length() - 1)
- continue;
- fieldMap.put(StringUtils.trim(trimPart.substring(0, idx)),
- StringUtils.trim(trimPart.substring(idx + 1)));
- }
- }
- /**
- * 2026-06-02:持久化字段统一后写覆盖,便于同一个 rc 反复补充下载任务与回调状态。
- */
- private static void putLeaveAuthPersistField(Map<String, String> fieldMap, String fieldName, String value) {
- if (fieldMap == null || StringUtils.isAnyBlank(fieldName, value))
- return;
- fieldMap.put(fieldName, value);
- }
- /**
- * 2026-06-01:把异常压成一行,既能定位错误类型,也不会把 RC 字段撑得过长。
- */
- private static String makeExceptionMsg(Exception e) {
- if (e == null)
- return null;
- String className = e.getClass().getSimpleName();
- String msg = StringUtils.trimToNull(e.getMessage());
- if (StringUtils.isBlank(msg))
- return className;
- String text = className + ": " + msg;
- return text.length() > 180 ? text.substring(0, 180) : text;
- }
- /**
- * 2026-05-27:把海康返回对象压缩成简短描述,避免 RC 备注和描述文件过长。
- */
- private static String makeRespBrief(Object resp) {
- if (!(resp instanceof Map<?, ?> map))
- return rdStr(resp);
- String code = rdStr(map.get("code"));
- String msg = rdStr(map.get("msg"));
- if (StringUtils.isAllBlank(code, msg))
- return null;
- if (StringUtils.isBlank(code))
- return msg;
- if (StringUtils.isBlank(msg))
- return "code=" + code;
- return "code=" + code + ", msg=" + msg;
- }
- /**
- * 2026-06-01:海康临时权限对已结束请假没有意义,统一在服务入口层提前拦住。
- */
- static boolean ifLeaveEnded(Timestamp leaveEnd, Timestamp now) {
- if (leaveEnd == null)
- return false;
- Timestamp baseTime = now == null ? new Timestamp(System.currentTimeMillis()) : now;
- return !leaveEnd.after(baseTime);
- }
- /**
- * 2026-05-28:从 RC 备注里提取上次执行时写回的字段值。
- */
- private static String rdLeaveAuthLogField(String text, String fieldName) {
- if (StringUtils.isAnyBlank(text, fieldName))
- return null;
- String prefix = fieldName + "=";
- String[] partArr = StringUtils.split(text, ';');
- if (partArr == null || partArr.length == 0)
- return null;
- for (String part : partArr) {
- String trimmedPart = StringUtils.trimToEmpty(part);
- if (!trimmedPart.startsWith(prefix))
- continue;
- return StringUtils.trimToNull(trimmedPart.substring(prefix.length()));
- }
- return null;
- }
- /**
- * 2026-05-29:优先从 RC.wcmswj 读海康任务号,兼容旧数据再回退旧版 RC.mswj/RC.ms。
- */
- private static String rdLeaveAuthLogField(LeaveAuthSyncCtx ctx, String fieldName) {
- if (ctx == null)
- return null;
- String value = rdLeaveAuthLogField(ctx.wcmswj, fieldName);
- if (StringUtils.isNotBlank(value))
- return value;
- value = rdLeaveAuthLogField(ctx.mswj, fieldName);
- if (StringUtils.isNotBlank(value))
- return value;
- return rdLeaveAuthLogField(ctx.ms, fieldName);
- }
- /**
- * 2026-06-02:把已落库的下载任务来源与最近一次回调摘要补回结果对象,便于结果页直接看见。
- */
- private static void applyPersistedLeaveAuthSnapshot(LeaveAuthSyncCtx ctx, Map<String, Object> result) {
- if (ctx == null || result == null)
- return;
- putPersistedField(result, "callbackConfigured", rdLeaveAuthLogField(ctx, "callbackConfigured"));
- putPersistedField(result, "downloadResetAccepted", rdLeaveAuthLogField(ctx, "downloadResetAccepted"));
- putPersistedField(result, "downloadTaskAccepted", rdLeaveAuthLogField(ctx, "downloadTaskAccepted"));
- putPersistedField(result, "downloadTaskId", rdLeaveAuthLogField(ctx, "downloadTaskId"));
- putPersistedField(result, "downloadTaskSource", rdLeaveAuthLogField(ctx, "downloadTaskSource"));
- putPersistedField(result, "downloadPendingReason", rdLeaveAuthLogField(ctx, "downloadPendingReason"));
- putPersistedField(result, "downloadConfirmSource", rdLeaveAuthLogField(ctx, "downloadConfirmSource"));
- putPersistedField(result, "downloadResultConfirmed", rdLeaveAuthLogField(ctx, "downloadResultConfirmed"));
- putPersistedField(result, "downloadCallbackReceived", rdLeaveAuthLogField(ctx, "downloadCallbackReceived"));
- putPersistedField(result, "callbackTaskId", rdLeaveAuthLogField(ctx, "callbackTaskId"));
- putPersistedField(result, "callbackRecvTime", rdLeaveAuthLogField(ctx, "callbackRecvTime"));
- putPersistedField(result, "callbackBodySize", rdLeaveAuthLogField(ctx, "callbackBodySize"));
- putPersistedField(result, "callbackMatchedRcid", rdLeaveAuthLogField(ctx, "callbackMatchedRcid"));
- putPersistedField(result, "callbackResourceKey", rdLeaveAuthLogField(ctx, "callbackResourceKey"));
- putPersistedField(result, "callbackResourceDownloadResult", rdLeaveAuthLogField(ctx, "callbackResourceDownloadResult"));
- putPersistedField(result, "callbackResourceSuccessCount", rdLeaveAuthLogField(ctx, "callbackResourceSuccessCount"));
- putPersistedField(result, "callbackResourceFailedCount", rdLeaveAuthLogField(ctx, "callbackResourceFailedCount"));
- putPersistedField(result, "callbackPersonId", rdLeaveAuthLogField(ctx, "callbackPersonId"));
- putPersistedField(result, "callbackPersonDownloadResult", rdLeaveAuthLogField(ctx, "callbackPersonDownloadResult"));
- }
- /**
- * 2026-06-02:海康下载回调在应答后落库,至少把任务号与最近一次设备结果写回到请假单。
- */
- private Map<String, Object> processLeaveAuthDownloadPushAfterAck(String pushBodyStr, boolean showDetail) {
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("ok", true);
- result.put("bodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
- result.put("showDetail", showDetail);
- try (Db gdba = Db.makeConn()) {
- Map<String, Object> bodyMap = rdReqBodyMap(pushBodyStr);
- Map<String, Object> payloadMap = extLeaveAuthCallbackPayload(bodyMap);
- Map<String, Object> resourceResult = castMap(payloadMap.get("resourceDownloadResult"));
- Map<String, Object> resourceDetail = castMap(payloadMap.get("resourceDownloadDetail"));
- String taskId = rdLeaveAuthCallbackTaskId(resourceResult, resourceDetail, payloadMap, bodyMap);
- String personId = rdStr(resourceDetail == null ? null : resourceDetail.get("personId"));
- result.put("taskId", taskId);
- result.put("personId", personId);
- result.put("resourceResultFound", resourceResult != null);
- result.put("resourceDetailFound", resourceDetail != null);
- if (showDetail)
- result.put("callbackBody", bodyMap);
- if (StringUtils.isBlank(taskId) && StringUtils.isBlank(personId)) {
- result.put("ok", false);
- result.put("msg", "回调体内未找到 taskId/personId,暂无法匹配请假记录。");
- return result;
- }
- LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtxByTaskId(gdba, taskId);
- if (ctx == null && StringUtils.isNotBlank(personId)) {
- Map<String, Object> hkConnParm = makeHkConnParm();
- if (hkConnParm != null)
- ctx = selRecentLeaveAuthSyncCtxByPersonId(gdba, hkConnParm, personId);
- }
- if (ctx == null) {
- result.put("ok", false);
- result.put("msg", "未找到对应 downloadTaskId 的请假记录。");
- return result;
- }
- Map<String, Object> persistResult = new LinkedHashMap<>();
- persistResult.put("autoTrigger", true);
- persistResult.put("mode", StringUtils.defaultIfBlank(rdLeaveAuthLogField(ctx, "mode"), "execute_platform_config"));
- persistResult.put("downloadTaskId", StringUtils.defaultIfBlank(taskId, rdLeaveAuthLogField(ctx, "downloadTaskId")));
- persistResult.put("callbackTaskId", taskId);
- persistResult.put("downloadCallbackReceived", true);
- persistResult.put("callbackRecvTime", makeHkTime(new Timestamp(System.currentTimeMillis())));
- persistResult.put("callbackBodySize", pushBodyStr == null ? 0 : pushBodyStr.length());
- persistResult.put("callbackMatchedRcid", ctx.rcid);
- persistResult.put("downloadResetAccepted", true);
- persistResult.put("downloadTaskAccepted", true);
- Map<String, Object> resourceInfo = resourceResult == null ? null : castMap(resourceResult.get("resourceInfo"));
- String resourceKey = makeResourceKey(resourceInfo);
- persistResult.put("callbackResourceKey", resourceKey);
- persistResult.put("callbackResourceDownloadResult", rdStr(resourceResult == null ? null : resourceResult.get("downloadResult")));
- persistResult.put("callbackResourceSuccessCount", rdStr(resourceResult == null ? null : resourceResult.get("successedPersonCount")));
- persistResult.put("callbackResourceFailedCount", rdStr(resourceResult == null ? null : resourceResult.get("failedPersonCount")));
- persistResult.put("callbackPersonId", personId);
- persistResult.put("callbackPersonDownloadResult", rdStr(resourceDetail == null ? null : resourceDetail.get("persondownloadResult")));
- boolean callbackSuccess = isLeaveAuthCallbackSuccess(resourceResult, resourceDetail);
- persistResult.put("downloadConfirmSource", callbackSuccess ? "callback" : null);
- persistResult.put("downloadResultConfirmed", callbackSuccess);
- persistResult.put("downloadPendingReason", callbackSuccess ? "callbackCompleted" : "callbackReturnedFailure");
- persistResult.put("ok", callbackSuccess);
- persistResult.put("msg", callbackSuccess ? "已收到海康下载成功回调。" : "已收到海康下载回调,但当前资源结果未全部成功。");
- persistLeaveAuthSyncResult(gdba, ctx, persistResult);
- result.put("matchedRcid", ctx.rcid);
- result.put("callbackSummary", persistResult);
- result.put("msg", callbackSuccess ? "回调已写回请假记录。" : "回调已写回,但结果未显示为成功。");
- return result;
- } catch (Exception e) {
- log4j.error("HkLeaveAuthServ.processLeaveAuthDownloadPushAfterAck() 异常", e);
- result.put("ok", false);
- result.put("msg", e.getMessage());
- return result;
- }
- }
- /**
- * 2026-06-02:回调体通常包在 data 下,缺 data 时直接兼容根对象。
- */
- private static Map<String, Object> extLeaveAuthCallbackPayload(Map<String, Object> bodyMap) {
- Map<String, Object> dataMap = castMap(bodyMap == null ? null : bodyMap.get("data"));
- return dataMap == null ? (bodyMap == null ? new LinkedHashMap<>() : bodyMap) : dataMap;
- }
- /**
- * 2026-06-02:下载回调优先从 resourceDownloadResult/resourceDownloadDetail 里取 taskId。
- */
- private static String rdLeaveAuthCallbackTaskId(Map<String, Object> resourceResult,
- Map<String, Object> resourceDetail,
- Map<String, Object> payloadMap,
- Map<String, Object> bodyMap) {
- String taskId = rdStr(resourceResult == null ? null : resourceResult.get("taskId"));
- if (StringUtils.isNotBlank(taskId))
- return taskId;
- taskId = rdStr(resourceDetail == null ? null : resourceDetail.get("taskId"));
- if (StringUtils.isNotBlank(taskId))
- return taskId;
- taskId = rdStr(payloadMap == null ? null : payloadMap.get("taskId"));
- if (StringUtils.isNotBlank(taskId))
- return taskId;
- return rdStr(bodyMap == null ? null : bodyMap.get("taskId"));
- }
- /**
- * 2026-06-02:回调成功判定只看当前资源与当前人员是否都返回成功码。
- */
- private static boolean isLeaveAuthCallbackSuccess(Map<String, Object> resourceResult,
- Map<String, Object> resourceDetail) {
- Object resourceDownloadResult = resourceResult == null ? null : resourceResult.get("downloadResult");
- Object personDownloadResult = resourceDetail == null ? null : resourceDetail.get("persondownloadResult");
- boolean resourceOk = isLeaveAuthCallbackOkValue(resourceDownloadResult, true);
- boolean personOk = isLeaveAuthCallbackOkValue(personDownloadResult, true);
- return resourceOk && personOk;
- }
- /**
- * 2026-06-04:结果回查直接读取 RC 快照里的回调摘要,判断这次回调本身是否成功。
- */
- private static boolean isPersistedLeaveAuthCallbackSuccess(Map<String, Object> result) {
- if (!rdBoolLike(result == null ? null : result.get("downloadCallbackReceived")))
- return false;
- Object resourceDownloadResult = result == null ? null : result.get("callbackResourceDownloadResult");
- Object personDownloadResult = result == null ? null : result.get("callbackPersonDownloadResult");
- if (StringUtils.isAllBlank(rdStr(resourceDownloadResult), rdStr(personDownloadResult)))
- return false;
- boolean resourceOk = isLeaveAuthCallbackOkValue(resourceDownloadResult, true);
- boolean personOk = isLeaveAuthCallbackOkValue(personDownloadResult, true);
- return resourceOk && personOk;
- }
- /**
- * 2026-06-04:海康回调里的结果字段常被 GSON 解析成 Double,0 会落成 "0.0"。
- * 这里只要语义上是成功/空值,都按成功处理,避免把真实成功回调误判成失败。
- */
- private static boolean isLeaveAuthCallbackOkValue(Object value, boolean blankAsOk) {
- if (value == null)
- return blankAsOk;
- if (value instanceof Number number)
- return Double.compare(number.doubleValue(), 0D) == 0;
- String text = rdStr(value);
- if (StringUtils.isBlank(text))
- return blankAsOk;
- if ("success".equalsIgnoreCase(text))
- return true;
- if ("0".equals(text))
- return true;
- try {
- return Double.compare(Double.parseDouble(text), 0D) == 0;
- } catch (Exception ignored) {
- return false;
- }
- }
- /**
- * 2026-06-02:按下载任务号回查对应请假记录,供回调补写使用。
- */
- private static LeaveAuthSyncCtx selLeaveAuthSyncCtxByTaskId(Db gdba, String taskId) throws Exception {
- if (gdba == null || StringUtils.isBlank(taskId))
- return null;
- String sql = "select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
- + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
- + " from RC rc"
- + " join RY ry on ry.RYID=rc.FZRYID"
- + " where (rc.WCMSWJ like :taskLike or rc.MSWJ like :taskLike or rc.MS like :taskLike)"
- + " order by rc.RCID desc";
- SqlCmd sqlCmd = new SqlCmd(sql);
- sqlCmd.wrStrParm("taskLike", "%" + taskId + "%");
- List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
- if (rowList == null || rowList.isEmpty())
- return null;
- Map<String, Object> row = rowList.get(0);
- return new LeaveAuthSyncCtx(
- rdLong(row.get("rcid")),
- rdLong(row.get("bjid")),
- rdLong(row.get("ryid")),
- rdInt(row.get("rclbm")),
- (Timestamp) row.get("kssj"),
- (Timestamp) row.get("jssj"),
- rdStr(row.get("xm")),
- rdStr(row.get("ryh")),
- rdStr(row.get("ms")),
- rdStr(row.get("mswj")),
- rdStr(row.get("wcmswj")));
- }
- /**
- * 2026-06-02:当回调 taskId 没提前落库时,退化为按回调 personId 匹配最近的请假执行记录。
- */
- private static LeaveAuthSyncCtx selRecentLeaveAuthSyncCtxByPersonId(Db gdba,
- Map<String, Object> hkConnParm,
- String personId) throws Exception {
- if (gdba == null || hkConnParm == null || StringUtils.isBlank(personId))
- return null;
- List<LeaveAuthSyncCtx> ctxList = selRecentLeaveAuthSyncCtxList(gdba, 60);
- if (ctxList.isEmpty())
- return null;
- List<String> jobNoList = new ArrayList<>();
- for (LeaveAuthSyncCtx ctx : ctxList) {
- if (StringUtils.isNotBlank(ctx.jobNo))
- jobNoList.add(ctx.jobNo);
- }
- if (jobNoList.isEmpty())
- return null;
- Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(hkConnParm, jobNoList);
- for (LeaveAuthSyncCtx ctx : ctxList) {
- Map<String, Object> personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
- if (StringUtils.equals(personId, rdStr(personInfo == null ? null : personInfo.get("personId"))))
- return ctx;
- }
- return null;
- }
- /**
- * 2026-06-02:回调补写只关心最近执行过的请假单,避免全表扫 RC。
- */
- private static List<LeaveAuthSyncCtx> selRecentLeaveAuthSyncCtxList(Db gdba, int limit) throws Exception {
- if (gdba == null)
- return List.of();
- String sql = "select * from ("
- + " select rc.RCID rcid,rc.BJID bjid,rc.FZRYID ryid,rc.RCLBM rclbm,rc.KSSJ kssj,rc.JSSJ jssj,"
- + " rc.MS ms,rc.MSWJ mswj,rc.WCMSWJ wcmswj,ry.XM xm,ry.RYH ryh"
- + " from RC rc"
- + " join RY ry on ry.RYID=rc.FZRYID"
- + " where rc.WCMSWJ like '%mode=execute_platform_config%'"
- + " order by rc.RCID desc"
- + " ) where rownum<=:limit";
- SqlCmd sqlCmd = new SqlCmd(sql);
- sqlCmd.wrIntParm("limit", Math.max(1, limit));
- List<Map<String, Object>> rowList = gdba.doSelMapListByC(sqlCmd);
- if (rowList == null || rowList.isEmpty())
- return List.of();
- List<LeaveAuthSyncCtx> ctxList = new ArrayList<>();
- for (Map<String, Object> row : rowList) {
- ctxList.add(new LeaveAuthSyncCtx(
- rdLong(row.get("rcid")),
- rdLong(row.get("bjid")),
- rdLong(row.get("ryid")),
- rdInt(row.get("rclbm")),
- (Timestamp) row.get("kssj"),
- (Timestamp) row.get("jssj"),
- rdStr(row.get("xm")),
- rdStr(row.get("ryh")),
- rdStr(row.get("ms")),
- rdStr(row.get("mswj")),
- rdStr(row.get("wcmswj"))));
- }
- return ctxList;
- }
- /**
- * 2026-05-28:平台配置模式结果回查。
- */
- private Map<String, Object> refreshPlatformConfigLeaveAuthResult(Db gdba,
- LeaveAuthSyncCtx ctx,
- Map<String, Object> overrideParm,
- Map<String, Object> result) throws Exception {
- Map<String, Object> hkConnParm = rdHkConnParm();
- if (hkConnParm == null) {
- result.put("ok", false);
- result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
- return result;
- }
- String tagId = rdCfgOrOverride(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID);
- if (StringUtils.isNotBlank(tagId))
- hkConnParm.put("tagId", tagId);
- result.put("tagId", tagId);
- result.put("tagIdSource", rdCfgSource(overrideParm, "tagId", CFG_TAG_ID, "HK_LEAVE_AUTH_TAG_ID", HK_DEF_TAG_ID));
- applyPersistedLeaveAuthSnapshot(ctx, result);
- String callbackUrl = rdCfgOrOverride(overrideParm, "callbackUrl", CFG_CALLBACK_URL, "HK_LEAVE_AUTH_CALLBACK_URL");
- if (StringUtils.isNotBlank(callbackUrl))
- result.put("platformCallbackUrl", callbackUrl);
- if (!result.containsKey("callbackConfigured"))
- result.put("callbackConfigured", StringUtils.isNotBlank(callbackUrl));
- Map<String, Object> personInfo = null;
- String personId = null;
- if (StringUtils.isNotBlank(ctx.jobNo)) {
- Map<String, Map<String, Object>> personInfoMap = HK_API_CLIENT.loadPersonInfoMapByJobNo(hkConnParm, List.of(ctx.jobNo));
- personInfo = personInfoMap.get(makeNormKey(ctx.jobNo));
- if (personInfo != null) {
- result.put("personInfo", makePersonInfoResp(personInfo));
- personId = rdStr(personInfo.get("personId"));
- }
- }
- List<Map<String, Object>> resourceInfoList = makeResourceInfoList(selAllActiveMjdList(gdba));
- result.put("resourceInfos", resourceInfoList);
- result.put("resourceCount", resourceInfoList.size());
- String configTaskId = rdLeaveAuthLogField(ctx, "configTaskId");
- if (StringUtils.isNotBlank(configTaskId)) {
- Map<String, Object> configRateReq = Map.of("taskId", configTaskId);
- result.put("configTaskId", configTaskId);
- result.put("authConfigRateReq", configRateReq);
- try {
- result.put("authConfigRateResp", HK_API_CLIENT.searchAuthConfigRate(hkConnParm, configRateReq));
- } catch (Exception e) {
- result.put("authConfigRateError", e.getMessage());
- }
- }
- if (StringUtils.isNotBlank(personId)) {
- Map<String, Object> configSearchReq = makeAuthConfigSearchReq(personId, resourceInfoList);
- result.put("authConfigSearchReq", configSearchReq);
- try {
- result.put("authConfigSearchResp", HK_API_CLIENT.searchAuthConfig(hkConnParm, configSearchReq));
- } catch (Exception e) {
- result.put("authConfigSearchError", e.getMessage());
- }
- } else {
- result.put("authConfigSearchError", "未能获取海康 personId,无法查询平台权限配置。");
- }
- String downloadTaskId = StringUtils.defaultIfBlank(
- rdLeaveAuthLogField(ctx, "downloadTaskId"),
- rdLeaveAuthLogField(ctx, "callbackTaskId"));
- if (StringUtils.isNotBlank(downloadTaskId)) {
- Map<String, Object> taskSearchReq = makeAuthDownloadTaskSearchReq(downloadTaskId);
- Map<String, Object> progressReq = Map.of("taskId", downloadTaskId);
- Map<String, Object> channelRecordReq = makeDownloadRecordChannelListReq(downloadTaskId, resourceInfoList);
- result.put("downloadTaskId", downloadTaskId);
- if (StringUtils.isBlank(rdStr(result.get("downloadTaskSource"))))
- result.put("downloadTaskSource", "personReset");
- result.put("authDownloadTaskSearchReq", taskSearchReq);
- result.put("authDownloadTaskProgressReq", progressReq);
- result.put("downloadRecordChannelReq", channelRecordReq);
- try {
- result.put("authDownloadTaskSearchResp",
- queryAuthDownloadTaskSearchWithRetry(hkConnParm, taskSearchReq));
- } catch (Exception e) {
- result.put("authDownloadTaskSearchError", e.getMessage());
- }
- try {
- result.put("authDownloadTaskProgressResp",
- queryAuthDownloadTaskProgressWithRetry(hkConnParm, progressReq));
- } catch (Exception e) {
- result.put("authDownloadTaskProgressError", e.getMessage());
- }
- try {
- Map<String, Object> channelRecordResp = queryDownloadRecordChannelListWithRetry(
- hkConnParm, channelRecordReq, resourceInfoList);
- result.put("downloadRecordChannelResp", channelRecordResp);
- result.put("downloadRecordPersonDetailReqList",
- makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRecordResp));
- result.put("downloadRecordPersonDetailRespList",
- queryDownloadRecordPersonDetailRespListWithRetry(hkConnParm, downloadTaskId, personId, channelRecordResp));
- } catch (Exception e) {
- result.put("downloadRecordQueryError", e.getMessage());
- }
- }
- result.put("mode", "viewPlatformConfigResult");
- result.put("executeApiPath", "/artemis/api/acps/v1/auth_config/add");
- result.put("resultApiPath", "/artemis/api/acps/v1/auth_config/rate/search");
- result.put("downloadApiPath", "/artemis/api/acps/v1/authDownload/configuration/person/reset");
- result.put("downloadTaskProgressApiPath", "/artemis/api/acps/v1/authDownload/task/progress");
- result.put("downloadTaskSearchApiPath", "/artemis/api/acps/v1/authDownload/task/search");
- result.put("downloadRecordChannelApiPath", "/artemis/api/acps/v1/download_record/channel/list/search");
- result.put("downloadRecordPersonDetailApiPath", "/artemis/api/acps/v2/download_record/person/detail/search");
- boolean autoDownload = rdBoolCfg("hk.leaveAuth.platform.autoDownload", "HK_LEAVE_AUTH_PLATFORM_AUTO_DOWNLOAD", true);
- finalizePlatformConfigResult(result, ctx.kssj, ctx.jssj, resourceInfoList.size(), autoDownload);
- return result;
- }
- /**
- * 2026-05-29:下载任务是异步的,短轮询几次后再回显,避免刚建任务就固定看到未完成。
- */
- private static Map<String, Object> queryAuthDownloadTaskProgressWithRetry(Map<String, Object> hkConnParm,
- Map<String, Object> progressReq) throws Exception {
- Map<String, Object> lastResp = null;
- int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.downloadPollCount",
- "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
- int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.downloadPollSleepMs",
- "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
- for (int i = 0; i < pollCount; i++) {
- if (i > 0 && sleepMs > 0) {
- try {
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- lastResp = HK_API_CLIENT.searchAuthDownloadTaskProgress(hkConnParm, progressReq);
- if (isAuthDownloadFinished(lastResp))
- break;
- }
- return lastResp;
- }
- /**
- * 2026-06-02:下载任务摘要可用于区分“任务不存在”和“任务已结束但无进度明细”。
- */
- private static Map<String, Object> queryAuthDownloadTaskSearchWithRetry(Map<String, Object> hkConnParm,
- Map<String, Object> taskSearchReq) throws Exception {
- Map<String, Object> lastResp = null;
- int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.downloadPollCount",
- "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
- int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.downloadPollSleepMs",
- "HK_LEAVE_AUTH_PLATFORM_DOWNLOAD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
- for (int i = 0; i < pollCount; i++) {
- if (i > 0 && sleepMs > 0) {
- try {
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- lastResp = HK_API_CLIENT.searchAuthDownloadTask(hkConnParm, taskSearchReq);
- if (hasAuthDownloadTask(lastResp))
- break;
- }
- return lastResp;
- }
- /**
- * 2026-06-02:下载记录有时比任务摘要落得慢,短轮询到至少出现设备记录为止。
- */
- private static Map<String, Object> queryDownloadRecordChannelListWithRetry(Map<String, Object> hkConnParm,
- Map<String, Object> channelReq,
- List<Map<String, Object>> resourceInfoList) throws Exception {
- Map<String, Object> lastResp = null;
- int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.recordPollCount",
- "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
- int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.recordPollSleepMs",
- "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
- int expectedCount = resourceInfoList == null ? 0 : resourceInfoList.size();
- for (int i = 0; i < pollCount; i++) {
- if (i > 0 && sleepMs > 0) {
- try {
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- lastResp = HK_API_CLIENT.searchDownloadRecordChannelList(hkConnParm, channelReq);
- if (rdDownloadRecordChannelMatchedCount(lastResp, resourceInfoList) >= Math.max(1, expectedCount))
- break;
- }
- return lastResp;
- }
- /**
- * 2026-06-02:按设备通道下载记录逐条查询当前学生的人员下载详情。
- */
- private static List<Map<String, Object>> queryDownloadRecordPersonDetailRespListWithRetry(Map<String, Object> hkConnParm,
- String downloadTaskId,
- String personId,
- Object channelRespObj) throws Exception {
- List<Map<String, Object>> reqList = makeDownloadRecordPersonDetailReqList(downloadTaskId, personId, channelRespObj);
- if (reqList.isEmpty())
- return List.of();
- List<Map<String, Object>> respList = new ArrayList<>();
- for (Map<String, Object> reqWrap : reqList) {
- Map<String, Object> req = castMap(reqWrap.get("req"));
- if (req == null)
- continue;
- Map<String, Object> resp = queryDownloadRecordPersonDetailWithRetry(hkConnParm, req);
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("downloadResultId", rdStr(reqWrap.get("downloadResultId")));
- row.put("resourceInfo", reqWrap.get("resourceInfo"));
- row.put("req", req);
- row.put("resp", resp);
- respList.add(row);
- }
- return respList;
- }
- /**
- * 2026-06-02:单个设备通道的人员详情也允许短暂延迟,轮询到当前学生出现明细为止。
- */
- private static Map<String, Object> queryDownloadRecordPersonDetailWithRetry(Map<String, Object> hkConnParm,
- Map<String, Object> detailReq) throws Exception {
- Map<String, Object> lastResp = null;
- int pollCount = Math.max(1, rdIntCfg("hk.leaveAuth.platform.recordPollCount",
- "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_COUNT", HK_DEF_DOWNLOAD_POLL_COUNT));
- int sleepMs = Math.max(0, rdIntCfg("hk.leaveAuth.platform.recordPollSleepMs",
- "HK_LEAVE_AUTH_PLATFORM_RECORD_POLL_SLEEP_MS", HK_DEF_DOWNLOAD_POLL_SLEEP_MS));
- for (int i = 0; i < pollCount; i++) {
- if (i > 0 && sleepMs > 0) {
- try {
- Thread.sleep(sleepMs);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- break;
- }
- }
- lastResp = HK_API_CLIENT.searchDownloadRecordPersonDetail(hkConnParm, detailReq);
- if (rdDownloadRecordPersonDetailCount(lastResp) > 0)
- break;
- }
- return lastResp;
- }
- /**
- * 2026-06-02:把设备通道下载记录拆成“每个门一条人员详情请求”。
- */
- private static List<Map<String, Object>> makeDownloadRecordPersonDetailReqList(String downloadTaskId,
- String personId,
- Object channelRespObj) {
- List<Map<String, Object>> rowList = new ArrayList<>();
- Map<String, Object> channelResp = castMap(channelRespObj);
- Map<String, Object> dataMap = rdDataMap(channelResp);
- if (dataMap == null)
- return rowList;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- return rowList;
- for (Object item : list) {
- Map<String, Object> row = makeDownloadRecordPersonDetailReqWrap(downloadTaskId, personId, item);
- if (row != null)
- rowList.add(row);
- }
- return rowList;
- }
- /**
- * 2026-06-02:优先带 downloadResultId,拿不到时再回退 taskId + resourceInfo。
- */
- private static Map<String, Object> makeDownloadRecordPersonDetailReqWrap(String downloadTaskId,
- String personId,
- Object channelItemObj) {
- Map<String, Object> channelItem = castMap(channelItemObj);
- if (channelItem == null)
- return null;
- Map<String, Object> resourceInfo = castMap(channelItem.get("resourceInfo"));
- if (resourceInfo == null)
- return null;
- Map<String, Object> req = new LinkedHashMap<>();
- putIfNotBlank(req, "downloadResultId", rdStr(channelItem.get("downloadResultId")));
- putIfNotBlank(req, "taskId", downloadTaskId);
- req.put("resourceInfo", makeDownloadRecordDetailResourceInfo(resourceInfo));
- req.put("personIds", List.of(personId));
- req.put("pageNo", 1);
- req.put("pageSize", 20);
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("downloadResultId", rdStr(channelItem.get("downloadResultId")));
- row.put("resourceInfo", makeDownloadRecordDetailResourceInfo(resourceInfo));
- row.put("req", req);
- return row;
- }
- /**
- * 2026-06-02:人员详情接口沿用下载记录里的最小资源对象。
- */
- private static Map<String, Object> makeDownloadRecordDetailResourceInfo(Map<String, Object> resourceInfo) {
- Map<String, Object> row = new LinkedHashMap<>();
- if (resourceInfo == null)
- return row;
- putIfNotBlank(row, "resourceIndexCode", rdStr(resourceInfo.get("resourceIndexCode")));
- putIfNotBlank(row, "resourceType", rdStr(resourceInfo.get("resourceType")));
- Object channelNos = resourceInfo.get("channelNos");
- if (channelNos instanceof List<?> list && !list.isEmpty())
- row.put("channelNos", list);
- return row;
- }
- /**
- * 2026-06-02:special/person/diy/result 只要返回 total>0 或 list 非空,就视为已经能回查到明细。
- */
- private static boolean hasSpecialPersonAuthDownloadResult(Object resultRespObj) {
- Map<String, Object> resultResp = castMap(resultRespObj);
- Map<String, Object> dataMap = rdDataMap(resultResp);
- if (dataMap == null)
- return false;
- int total = rdInt(dataMap.get("total"));
- if (total > 0)
- return true;
- Object listObj = dataMap.get("list");
- return listObj instanceof List<?> list && !list.isEmpty();
- }
- /**
- * 2026-05-29:统一判断海康下载任务是否完成,兼容布尔值和字符串返回。
- */
- private static boolean isAuthDownloadFinished(Map<String, Object> progressResp) {
- if (progressResp == null)
- return false;
- Object dataObj = progressResp.get("data");
- if (!(dataObj instanceof Map<?, ?> dataMap))
- return false;
- Object finishedObj = dataMap.get("isDownloadFinished");
- if (finishedObj instanceof Boolean boolVal)
- return boolVal;
- String text = rdStr(finishedObj);
- if (StringUtils.isBlank(text))
- return false;
- text = text.toLowerCase(Locale.ROOT);
- return "true".equals(text) || "1".equals(text) || "yes".equals(text) || "y".equals(text);
- }
- /**
- * 2026-06-02:任务摘要查询命中记录即可视为海康已接受并创建该下载任务。
- */
- private static boolean hasAuthDownloadTask(Object taskSearchRespObj) {
- return rdAuthDownloadTaskFirst(taskSearchRespObj) != null;
- }
- /**
- * 2026-06-02:任务摘要中的 taskStatus=2 表示海康任务已结束。
- */
- private static boolean isAuthDownloadTaskFinished(Object taskSearchRespObj) {
- Map<String, Object> firstTask = rdAuthDownloadTaskFirst(taskSearchRespObj);
- if (firstTask == null)
- return false;
- int taskStatus = rdInt(firstTask.get("taskStatus"));
- return taskStatus == 2;
- }
- /**
- * 2026-06-02:统一取下载任务摘要的第一条任务,避免到处重复拆分页结构。
- */
- @SuppressWarnings("unchecked")
- private static Map<String, Object> rdAuthDownloadTaskFirst(Object taskSearchRespObj) {
- Map<String, Object> taskSearchResp = castMap(taskSearchRespObj);
- Map<String, Object> dataMap = rdDataMap(taskSearchResp);
- if (dataMap == null)
- return null;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- return null;
- Object firstObj = list.get(0);
- if (!(firstObj instanceof Map<?, ?>))
- return null;
- return (Map<String, Object>) firstObj;
- }
- /**
- * 2026-06-02:统计设备通道下载记录总数。
- */
- private static int rdDownloadRecordChannelTotalCount(Object channelRespObj) {
- Map<String, Object> channelResp = castMap(channelRespObj);
- Map<String, Object> dataMap = rdDataMap(channelResp);
- if (dataMap == null)
- return 0;
- int total = rdInt(dataMap.get("total"));
- if (total > 0)
- return total;
- Object listObj = dataMap.get("list");
- return listObj instanceof List<?> list ? list.size() : 0;
- }
- /**
- * 2026-06-02:统计本次请假目标门禁里,真正查到下载记录的设备数量。
- */
- private static int rdDownloadRecordChannelMatchedCount(Object channelRespObj,
- List<Map<String, Object>> expectedResourceInfoList) {
- Map<String, Object> channelResp = castMap(channelRespObj);
- Map<String, Object> dataMap = rdDataMap(channelResp);
- if (dataMap == null)
- return 0;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- return 0;
- Set<String> expectedKeySet = makeResourceKeySet(expectedResourceInfoList);
- Set<String> matchedKeySet = new LinkedHashSet<>();
- for (Object item : list) {
- Map<String, Object> row = castMap(item);
- if (row == null)
- continue;
- Map<String, Object> resourceInfo = castMap(row.get("resourceInfo"));
- String resourceKey = makeResourceKey(resourceInfo);
- if (StringUtils.isBlank(resourceKey) || !expectedKeySet.contains(resourceKey))
- continue;
- matchedKeySet.add(resourceKey);
- }
- return matchedKeySet.size();
- }
- /**
- * 2026-06-02:统计下载记录里设备通道级别的成功数。
- */
- private static int rdDownloadRecordChannelSuccessCount(Object channelRespObj,
- List<Map<String, Object>> expectedResourceInfoList) {
- return rdDownloadRecordChannelCountByResult(channelRespObj, expectedResourceInfoList, Set.of(0));
- }
- /**
- * 2026-06-02:统计下载记录里设备通道级别的失败/部分失败数。
- */
- private static int rdDownloadRecordChannelFailedCount(Object channelRespObj,
- List<Map<String, Object>> expectedResourceInfoList) {
- return rdDownloadRecordChannelCountByResult(channelRespObj, expectedResourceInfoList, Set.of(1, 2));
- }
- /**
- * 2026-06-02:按 downloadResult 聚合设备通道下载结果。
- */
- private static int rdDownloadRecordChannelCountByResult(Object channelRespObj,
- List<Map<String, Object>> expectedResourceInfoList,
- Set<Integer> acceptedResultSet) {
- Map<String, Object> channelResp = castMap(channelRespObj);
- Map<String, Object> dataMap = rdDataMap(channelResp);
- if (dataMap == null)
- return 0;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- return 0;
- Set<String> expectedKeySet = makeResourceKeySet(expectedResourceInfoList);
- Set<String> matchedKeySet = new LinkedHashSet<>();
- for (Object item : list) {
- Map<String, Object> row = castMap(item);
- if (row == null)
- continue;
- Map<String, Object> resourceInfo = castMap(row.get("resourceInfo"));
- String resourceKey = makeResourceKey(resourceInfo);
- if (StringUtils.isBlank(resourceKey) || !expectedKeySet.contains(resourceKey))
- continue;
- if (acceptedResultSet.contains(rdInt(row.get("downloadResult"))))
- matchedKeySet.add(resourceKey);
- }
- return matchedKeySet.size();
- }
- /**
- * 2026-06-02:统计当前学生的人员下载详情中,命中的设备通道数。
- */
- private static int rdDownloadRecordPersonDetailMatchedCount(Object detailRespListObj) {
- Set<String> matchedKeySet = new LinkedHashSet<>();
- for (Map<String, Object> row : castMapList(detailRespListObj)) {
- String resourceKey = makeResourceKey(castMap(row.get("resourceInfo")));
- if (StringUtils.isBlank(resourceKey) || rdDownloadRecordPersonDetailCount(row.get("resp")) <= 0)
- continue;
- matchedKeySet.add(resourceKey);
- }
- return matchedKeySet.size();
- }
- /**
- * 2026-06-02:统计当前学生在各门上的下载成功数。
- */
- private static int rdDownloadRecordPersonDetailSuccessCount(Object detailRespListObj) {
- return rdDownloadRecordPersonDetailCountByResult(detailRespListObj, Set.of("0", "success", "SUCCESS"));
- }
- /**
- * 2026-06-02:统计当前学生在各门上的下载失败数。
- */
- private static int rdDownloadRecordPersonDetailFailedCount(Object detailRespListObj) {
- int matchedCount = rdDownloadRecordPersonDetailMatchedCount(detailRespListObj);
- int successCount = rdDownloadRecordPersonDetailSuccessCount(detailRespListObj);
- return Math.max(0, matchedCount - successCount);
- }
- /**
- * 2026-06-02:人员详情按 persondownloadResult 聚合。
- */
- private static int rdDownloadRecordPersonDetailCountByResult(Object detailRespListObj, Set<String> acceptedResultSet) {
- Set<String> matchedKeySet = new LinkedHashSet<>();
- for (Map<String, Object> row : castMapList(detailRespListObj)) {
- Map<String, Object> resp = castMap(row.get("resp"));
- Map<String, Object> dataMap = rdDataMap(resp);
- if (dataMap == null)
- continue;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- continue;
- String resourceKey = makeResourceKey(castMap(row.get("resourceInfo")));
- if (StringUtils.isBlank(resourceKey))
- continue;
- for (Object item : list) {
- Map<String, Object> itemMap = castMap(item);
- String resultVal = rdStr(itemMap == null ? null : itemMap.get("persondownloadResult"));
- if (acceptedResultSet.contains(resultVal))
- matchedKeySet.add(resourceKey);
- }
- }
- return matchedKeySet.size();
- }
- /**
- * 2026-06-02:统计单个人员详情响应的明细数量。
- */
- private static int rdDownloadRecordPersonDetailCount(Object detailRespObj) {
- Map<String, Object> detailResp = castMap(detailRespObj);
- Map<String, Object> dataMap = rdDataMap(detailResp);
- if (dataMap == null)
- return 0;
- int total = rdInt(dataMap.get("total"));
- if (total > 0)
- return total;
- Object listObj = dataMap.get("list");
- return listObj instanceof List<?> list ? list.size() : 0;
- }
- /**
- * 2026-06-02:统一把资源对象转成 `设备#通道` 形式,便于跨接口对齐。
- */
- private static String makeResourceKey(Map<String, Object> resourceInfo) {
- if (resourceInfo == null)
- return null;
- String resourceIndexCode = rdStr(resourceInfo.get("resourceIndexCode"));
- if (StringUtils.isBlank(resourceIndexCode))
- return null;
- Object channelNosObj = resourceInfo.get("channelNos");
- String channelNo = "1";
- if (channelNosObj instanceof List<?> list && !list.isEmpty())
- channelNo = rdStr(list.get(0));
- return resourceIndexCode + "#" + channelNo;
- }
- /**
- * 2026-06-02:构建本次预期下发资源的 key 集合。
- */
- private static Set<String> makeResourceKeySet(List<Map<String, Object>> resourceInfoList) {
- Set<String> keySet = new LinkedHashSet<>();
- if (resourceInfoList == null || resourceInfoList.isEmpty())
- return keySet;
- for (Map<String, Object> item : resourceInfoList) {
- String resourceKey = makeResourceKey(item);
- if (StringUtils.isNotBlank(resourceKey))
- keySet.add(resourceKey);
- }
- return keySet;
- }
- /**
- * 2026-06-02:平台配置模式必须同时确认“配置成功 + 平台可查 + 下载可确认”后,才对外返回成功。
- * 否则 PMS 虽然拿到了 taskId,但现场门禁仍可能提示“当前时间无效”。
- */
- private static void finalizePlatformConfigResult(Map<String, Object> result,
- Timestamp leaveBeg,
- Timestamp leaveEnd,
- int expectedResourceCount,
- boolean autoDownload) {
- int configTotalCount = rdAuthConfigTotalCount(result.get("authConfigSearchResp"));
- int matchedConfigCount = rdAuthConfigMatchedCount(result.get("authConfigSearchResp"), leaveBeg, leaveEnd);
- boolean configRateFinished = isAuthConfigFinished(result.get("authConfigRateResp"));
- boolean configRateSuccess = isAuthConfigSuccess(result.get("authConfigRateResp"), expectedResourceCount);
- boolean configSearchMatched = expectedResourceCount > 0 && matchedConfigCount >= expectedResourceCount;
- boolean callbackConfigured = rdBoolLike(result.get("callbackConfigured"));
- boolean downloadResetAccepted = rdBoolLike(result.get("downloadResetAccepted"))
- || isHkRespAccepted(result.get("authDownloadResetResp"));
- String downloadTaskId = rdStr(result.get("downloadTaskId"));
- boolean downloadTaskIdPresent = StringUtils.isNotBlank(downloadTaskId);
- boolean downloadTaskExists = hasAuthDownloadTask(result.get("authDownloadTaskSearchResp"));
- boolean downloadTaskFinished = isAuthDownloadTaskFinished(result.get("authDownloadTaskSearchResp"));
- boolean downloadProgressFinished = isAuthDownloadFinished(castMap(result.get("authDownloadTaskProgressResp")));
- boolean downloadCallbackReceived = rdBoolLike(result.get("downloadCallbackReceived"));
- boolean downloadCallbackSuccess = isPersistedLeaveAuthCallbackSuccess(result);
- boolean downloadTaskAccepted = rdBoolLike(result.get("downloadTaskAccepted"))
- || downloadResetAccepted
- || downloadTaskIdPresent
- || downloadTaskExists
- || downloadCallbackReceived;
- int downloadRecordChannelTotalCount = rdDownloadRecordChannelTotalCount(result.get("downloadRecordChannelResp"));
- int downloadRecordChannelMatchedCount = rdDownloadRecordChannelMatchedCount(result.get("downloadRecordChannelResp"),
- castMapList(result.get("resourceInfos")));
- int downloadRecordChannelSuccessCount = rdDownloadRecordChannelSuccessCount(result.get("downloadRecordChannelResp"),
- castMapList(result.get("resourceInfos")));
- int downloadRecordChannelFailedCount = rdDownloadRecordChannelFailedCount(result.get("downloadRecordChannelResp"),
- castMapList(result.get("resourceInfos")));
- int downloadRecordPersonDetailMatchedCount = rdDownloadRecordPersonDetailMatchedCount(result.get("downloadRecordPersonDetailRespList"));
- int downloadRecordPersonDetailSuccessCount = rdDownloadRecordPersonDetailSuccessCount(result.get("downloadRecordPersonDetailRespList"));
- int downloadRecordPersonDetailFailedCount = rdDownloadRecordPersonDetailFailedCount(result.get("downloadRecordPersonDetailRespList"));
- boolean downloadRecordConfirmed = expectedResourceCount > 0
- && downloadRecordChannelMatchedCount >= expectedResourceCount
- && downloadRecordChannelFailedCount == 0
- && downloadRecordPersonDetailSuccessCount >= expectedResourceCount
- && downloadRecordPersonDetailFailedCount == 0;
- boolean downloadConfirmed = !autoDownload || downloadRecordConfirmed || downloadCallbackSuccess;
- String downloadConfirmSource = null;
- String downloadPendingReason;
- if (!autoDownload) {
- downloadConfirmSource = "notRequired";
- downloadPendingReason = "downloadNotRequired";
- } else if (downloadRecordConfirmed) {
- downloadConfirmSource = "taskRecord";
- downloadPendingReason = "taskRecordConfirmed";
- } else if (downloadCallbackSuccess) {
- downloadConfirmSource = "callback";
- downloadPendingReason = "callbackCompleted";
- } else if (!downloadTaskAccepted) {
- downloadPendingReason = "resetNotAccepted";
- } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent && callbackConfigured) {
- downloadPendingReason = "resetAcceptedAwaitCallback";
- } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent) {
- downloadPendingReason = "resetAcceptedWithoutTaskIdOrCallback";
- } else if (!downloadTaskExists && !downloadCallbackReceived) {
- downloadPendingReason = "taskIdReturnedAwaitTaskSearch";
- } else if (downloadCallbackReceived) {
- downloadPendingReason = "callbackReturnedFailure";
- } else if (!downloadTaskFinished && !downloadProgressFinished) {
- downloadPendingReason = "taskRunning";
- } else if (downloadRecordChannelMatchedCount <= 0) {
- downloadPendingReason = "noChannelRecord";
- } else if (downloadRecordPersonDetailMatchedCount <= 0) {
- downloadPendingReason = "noPersonDetail";
- } else if (downloadRecordChannelFailedCount > 0 || downloadRecordPersonDetailFailedCount > 0) {
- downloadPendingReason = "recordContainsFailure";
- } else if (downloadTaskFinished) {
- downloadPendingReason = "taskFinishedButRecordIncomplete";
- } else {
- downloadPendingReason = "recordIncomplete";
- }
- result.put("expectedConfigCount", expectedResourceCount);
- result.put("configTotalCount", configTotalCount);
- result.put("matchedConfigCount", matchedConfigCount);
- result.put("configRateFinished", configRateFinished);
- result.put("configRateSuccess", configRateSuccess);
- result.put("configSearchMatched", configSearchMatched);
- result.put("callbackConfigured", callbackConfigured);
- result.put("downloadResetAccepted", downloadResetAccepted);
- result.put("downloadTaskAccepted", downloadTaskAccepted);
- result.put("downloadTaskExists", downloadTaskExists);
- result.put("downloadTaskFinished", downloadTaskFinished);
- result.put("downloadProgressFinished", downloadProgressFinished);
- result.put("downloadCallbackReceived", downloadCallbackReceived);
- result.put("downloadCallbackSuccess", downloadCallbackSuccess);
- result.put("downloadRecordChannelTotalCount", downloadRecordChannelTotalCount);
- result.put("downloadRecordChannelMatchedCount", downloadRecordChannelMatchedCount);
- result.put("downloadRecordChannelSuccessCount", downloadRecordChannelSuccessCount);
- result.put("downloadRecordChannelFailedCount", downloadRecordChannelFailedCount);
- result.put("downloadRecordPersonDetailMatchedCount", downloadRecordPersonDetailMatchedCount);
- result.put("downloadRecordPersonDetailSuccessCount", downloadRecordPersonDetailSuccessCount);
- result.put("downloadRecordPersonDetailFailedCount", downloadRecordPersonDetailFailedCount);
- result.put("downloadRecordConfirmed", downloadRecordConfirmed);
- result.put("downloadConfirmSource", downloadConfirmSource);
- result.put("downloadPendingReason", downloadPendingReason);
- result.put("downloadResultConfirmed", downloadConfirmed);
- result.put("downloadConfirmed", downloadConfirmed);
- if (!configRateSuccess) {
- result.put("ok", false);
- result.put("msg", "海康平台权限配置任务未确认全部成功。");
- return;
- }
- if (!configSearchMatched) {
- result.put("ok", false);
- result.put("msg", "海康平台未查到覆盖当前请假时段的完整权限配置。");
- return;
- }
- if (!downloadConfirmed) {
- result.put("ok", false);
- if (!downloadTaskAccepted) {
- result.put("msg", "海康人员权限重下发未确认受理,设备生效状态未确认。");
- } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent && callbackConfigured) {
- result.put("msg", "海康已受理人员权限重下发,当前等待回调确认设备生效。");
- } else if (!downloadTaskExists && !downloadCallbackReceived && !downloadTaskIdPresent) {
- result.put("msg", "海康已受理人员权限重下发,但未返回 taskId,且当前未配置回调地址,无法继续确认设备生效状态。");
- } else if (!downloadTaskExists && !downloadCallbackReceived) {
- result.put("msg", "海康已返回 downloadTaskId,但暂未查到任务摘要或完整设备记录。");
- } else if (!downloadTaskFinished && !downloadProgressFinished) {
- result.put("msg", "海康下载任务仍未结束,设备生效状态未确认。");
- } else if (downloadCallbackReceived) {
- result.put("msg", "已收到海康下载回调,但回调结果未显示全部成功。");
- } else if (downloadRecordChannelMatchedCount <= 0) {
- result.put("msg", "海康下载任务已结束,但未查询到设备通道下载记录。");
- } else if (downloadRecordPersonDetailMatchedCount <= 0) {
- result.put("msg", "海康已生成设备通道下载记录,但未查询到该学生的人员下载详情。");
- } else if (downloadRecordChannelFailedCount > 0 || downloadRecordPersonDetailFailedCount > 0) {
- result.put("msg", "海康下载记录显示存在失败或部分失败,设备生效状态未全部确认。");
- } else if (downloadTaskFinished) {
- result.put("msg", "海康下载任务摘要显示已结束,但设备侧下载记录仍未达到完整成功状态。");
- } else if (downloadTaskExists) {
- result.put("msg", "海康下载任务已创建,但设备侧下载记录仍未达到完整成功状态。");
- } else {
- result.put("msg", "海康下载链路未返回完整成功记录,门禁设备生效状态未确认。");
- }
- return;
- }
- result.put("ok", true);
- if (autoDownload && "callback".equals(downloadConfirmSource)) {
- result.put("msg", "海康平台权限配置已完成,设备生效已由回调确认。");
- } else {
- result.put("msg", autoDownload ? "海康平台权限配置与下载已确认完成。" : "海康平台权限配置已确认完成。");
- }
- }
- /**
- * 2026-06-02:配置任务必须走到 finished,且失败数为 0,成功数至少覆盖本次下发设备数。
- */
- private static boolean isAuthConfigSuccess(Object rateRespObj, int expectedResourceCount) {
- Map<String, Object> rateResp = castMap(rateRespObj);
- if (!isAuthConfigFinished(rateResp))
- return false;
- Map<String, Object> dataMap = rdDataMap(rateResp);
- if (dataMap == null)
- return false;
- if (rdInt(dataMap.get("failedNum")) > 0 || rdInt(dataMap.get("calcChannelFailedNum")) > 0)
- return false;
- int expectedCount = Math.max(1, expectedResourceCount);
- int successCount = Math.max(rdInt(dataMap.get("successedNum")), rdInt(dataMap.get("calcChannelSuccessNum")));
- return successCount >= expectedCount;
- }
- /**
- * 2026-06-02:统一判断平台配置任务是否完成,兼容海康返回的布尔值、字符串和状态码。
- */
- private static boolean isAuthConfigFinished(Object rateRespObj) {
- Map<String, Object> rateResp = castMap(rateRespObj);
- Map<String, Object> dataMap = rdDataMap(rateResp);
- if (dataMap == null)
- return false;
- if (rdBoolLike(dataMap.get("isFinished")) || rdBoolLike(dataMap.get("isConfigFinished")))
- return true;
- String status = rdStr(dataMap.get("status"));
- return "CONFIGEND".equalsIgnoreCase(status) || "FINISHED".equalsIgnoreCase(status) || "SUCCESS".equalsIgnoreCase(status);
- }
- /**
- * 2026-06-02:统计海康平台当前查到的权限配置总数。
- */
- private static int rdAuthConfigTotalCount(Object searchRespObj) {
- Map<String, Object> searchResp = castMap(searchRespObj);
- Map<String, Object> dataMap = rdDataMap(searchResp);
- if (dataMap == null)
- return 0;
- int total = rdInt(dataMap.get("total"));
- if (total > 0)
- return total;
- Object listObj = dataMap.get("list");
- return listObj instanceof List<?> list ? list.size() : 0;
- }
- /**
- * 2026-06-02:按当前请假时段统计“真正命中”的平台权限配置数。
- */
- private static int rdAuthConfigMatchedCount(Object searchRespObj,
- Timestamp leaveBeg,
- Timestamp leaveEnd) {
- Map<String, Object> searchResp = castMap(searchRespObj);
- Map<String, Object> dataMap = rdDataMap(searchResp);
- if (dataMap == null)
- return 0;
- Object listObj = dataMap.get("list");
- if (!(listObj instanceof List<?> list) || list.isEmpty())
- return 0;
- int matchedCount = 0;
- for (Object item : list) {
- if (!(item instanceof Map<?, ?> rawMap))
- continue;
- String startTime = rdStr(rawMap.get("startTime"));
- String endTime = rdStr(rawMap.get("endTime"));
- if (sameAuthTime(startTime, leaveBeg) && sameAuthTime(endTime, leaveEnd))
- matchedCount++;
- }
- return matchedCount;
- }
- /**
- * 2026-06-02:把海康返回时间与当前请假时间窗按“同一时刻”比较,避免毫秒位差异误判。
- */
- private static boolean sameAuthTime(String hkTimeText, Timestamp expectedTime) {
- if (StringUtils.isBlank(hkTimeText) || expectedTime == null)
- return false;
- try {
- return OffsetDateTime.parse(hkTimeText).toInstant()
- .equals(expectedTime.toLocalDateTime().atZone(ZoneId.of("Asia/Shanghai")).toInstant());
- } catch (Exception ignored) {
- return false;
- }
- }
- /**
- * 2026-06-02:统一把海康 `{code,msg,data}` 响应里的 `data` 取成 Map。
- */
- @SuppressWarnings("unchecked")
- private static Map<String, Object> rdDataMap(Map<String, Object> resp) {
- if (resp == null)
- return null;
- Object dataObj = resp.get("data");
- if (!(dataObj instanceof Map<?, ?>))
- return null;
- return (Map<String, Object>) dataObj;
- }
- /**
- * 2026-06-04:海康标准响应 code=0 视为接口已受理,taskId 是否即时返回不再作为唯一判据。
- */
- private static boolean isHkRespAccepted(Object respObj) {
- Map<String, Object> resp = castMap(respObj);
- return "0".equals(rdStr(resp == null ? null : resp.get("code")));
- }
- /**
- * 2026-06-02:把弱类型响应对象安全转成 Map,避免到处重复 `instanceof`。
- */
- @SuppressWarnings("unchecked")
- private static Map<String, Object> castMap(Object value) {
- if (!(value instanceof Map<?, ?>))
- return null;
- return (Map<String, Object>) value;
- }
- /**
- * 2026-06-02:把弱类型列表安全转成 Map 列表,避免重复写泛型转换。
- */
- @SuppressWarnings("unchecked")
- private static List<Map<String, Object>> castMapList(Object value) {
- if (!(value instanceof List<?> list) || list.isEmpty())
- return List.of();
- List<Map<String, Object>> rowList = new ArrayList<>();
- for (Object item : list) {
- if (item instanceof Map<?, ?> map)
- rowList.add((Map<String, Object>) map);
- }
- return rowList;
- }
- /**
- * 2026-06-02:兼容海康返回的布尔/字符串/数字型开关字段。
- */
- private static boolean rdBoolLike(Object value) {
- if (value instanceof Boolean boolVal)
- return boolVal;
- String text = rdStr(value);
- if (StringUtils.isBlank(text))
- return false;
- text = text.toLowerCase(Locale.ROOT);
- return "true".equals(text) || "1".equals(text) || "yes".equals(text) || "y".equals(text);
- }
- /**
- * 2026-05-28:回显当前请假链路模式,便于诊断页面和日志快速识别。
- */
- private static String normalizeLeaveAuthMode(String mode) {
- String value = StringUtils.trimToEmpty(mode).toLowerCase(Locale.ROOT);
- if (StringUtils.isBlank(value))
- return HK_DEF_MODE;
- if ("platform".equals(value) || "platform_config".equals(value) || "config".equals(value))
- return "platform_config";
- if ("legacy".equals(value) || "special".equals(value) || "diy".equals(value))
- return "legacy";
- return value;
- }
- /**
- * 2026-05-26:把请假信息统一写成日志和响应都能直接读的结构。
- */
- private static Map<String, Object> makeBaseLogRow(LeaveAuthSyncCtx ctx) {
- Map<String, Object> logRow = new LinkedHashMap<>();
- logRow.put("rcid", ctx.rcid);
- logRow.put("bjid", ctx.bjid);
- logRow.put("ryid", ctx.ryid);
- logRow.put("xm", ctx.xm);
- logRow.put("jobNo", ctx.jobNo);
- logRow.put("leaveType", ctx.rclbm == biz.rc.RcC.RCLB_bj ? "病假" : "事假");
- logRow.put("leaveBeg", makeHkTime(ctx.kssj));
- logRow.put("leaveEnd", makeHkTime(ctx.jssj));
- return logRow;
- }
- /**
- * 2026-05-26:返回给前端的请假上下文,只保留业务上能直观看懂的字段。
- */
- private static Map<String, Object> makeLeaveCtxResp(LeaveAuthSyncCtx ctx) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("rcid", ctx.rcid);
- row.put("bjid", ctx.bjid);
- row.put("ryid", ctx.ryid);
- row.put("rclbm", ctx.rclbm);
- row.put("xm", ctx.xm);
- row.put("jobNo", ctx.jobNo);
- row.put("leaveBeg", makeHkTime(ctx.kssj));
- row.put("leaveEnd", makeHkTime(ctx.jssj));
- return row;
- }
- /**
- * 2026-05-26:海康连接参数只回显脱敏后的 appKey。
- */
- private static Map<String, Object> makeSafeHkConnResp(Map<String, Object> hkConnParm) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("host", rdStr(hkConnParm.get("host")));
- row.put("port", hkConnParm.get("port"));
- row.put("appKeyMask", makeMaskStr(rdStr(hkConnParm.get("appKey"))));
- return row;
- }
- /**
- * 2026-05-26:返回海康人员详情的关键字段,便于定位 jobNo/personId 映射。
- */
- private static Map<String, Object> makePersonInfoResp(Map<String, Object> personInfo) {
- Map<String, Object> row = new LinkedHashMap<>();
- row.put("personId", rdStr(personInfo.get("personId")));
- row.put("jobNo", rdStr(personInfo.get("jobNo")));
- row.put("personName", rdStr(personInfo.get("personName")));
- row.put("studentId", rdStr(personInfo.get("studentId")));
- row.put("orgIndexCode", rdStr(personInfo.get("orgIndexCode")));
- row.put("orgPathName", rdStr(personInfo.get("orgPathName")));
- return row;
- }
- /**
- * 2026-05-26:当前请假权限范围直接取全部有效门禁点,和用户新要求保持一致。
- */
- private static List<Map<String, Object>> selAllActiveMjdList(Db gdba) throws Exception {
- String sql = "select MJDID mjdid,MC mc,SBBS sbbs,CDID cdid,MJDLBM mjdlbm,JCFXM jcfxm,JLZTM jlztm"
- + " from MJD where JLZTM in (21,22,25,51,81)"
- + " order by MJDID";
- SqlCmd sqlCmd = new SqlCmd(sql);
- return gdba.doSelMapListByC(sqlCmd);
- }
- /**
- * 2026-05-26:请假权限同步的默认海康连接参数,避免依赖入口类。
- */
- private static Map<String, Object> makeDefaultHkConnParm() {
- Map<String, Object> queryParm = new LinkedHashMap<>();
- queryParm.put("host", HK_DEF_HOST);
- queryParm.put("port", HK_DEF_PORT);
- queryParm.put("appKey", HK_DEF_APP_KEY);
- queryParm.put("appSecret", HK_DEF_APP_SECRET);
- return queryParm;
- }
- /**
- * 2026-05-26:把海康时间统一格式化成带时区偏移的文本。
- */
- private static String makeHkTime(Timestamp time) {
- if (time == null)
- return null;
- return time.toLocalDateTime().atZone(ZoneId.of("Asia/Shanghai")).format(HK_AUTH_TIME_FMT);
- }
- /**
- * 2026-05-26:执行后的跳过日志。
- */
- private static void logSkip(String reason, long rcid, Long ryid, Long bjid) {
- Map<String, Object> logRow = new LinkedHashMap<>();
- logRow.put("mode", "skip");
- logRow.put("reason", reason);
- logRow.put("rcid", rcid);
- if (ryid != null && ryid > 0)
- logRow.put("ryid", ryid);
- if (bjid != null && bjid > 0)
- logRow.put("bjid", bjid);
- log4j.info("HkLeaveAuthServ.syncLeaveAuthAfterCommit() 跳过:{}", logRow);
- }
- /**
- * 2026-05-26:读取门禁时间 / 配置 / 响应时统一做小工具,避免上层逻辑到处判空。
- */
- private static boolean rdBoolCfg(String propName, String envName, boolean defVal) {
- String cfgVal = rdCfg(propName, envName);
- if (StringUtils.isBlank(cfgVal))
- return defVal;
- String normVal = StringUtils.trimToEmpty(cfgVal).toLowerCase(Locale.ROOT);
- return "1".equals(normVal) || "true".equals(normVal) || "yes".equals(normVal) || "y".equals(normVal);
- }
- /**
- * 2026-05-26:整型配置读取,非法值统一回退默认值。
- */
- private static int rdIntCfg(String propName, String envName, int defVal) {
- String cfgVal = rdCfg(propName, envName);
- if (StringUtils.isBlank(cfgVal))
- return defVal;
- try {
- return Integer.parseInt(StringUtils.trim(cfgVal));
- } catch (Exception ignored) {
- return defVal;
- }
- }
- /**
- * 2026-05-26:字符串配置优先读系统参数,再读环境变量。
- */
- private static String rdCfg(String propName, String envName) {
- String value = System.getProperty(propName);
- if (StringUtils.isNotBlank(value))
- return StringUtils.trim(value);
- if (StringUtils.isNotBlank(envName)) {
- value = System.getenv(envName);
- if (StringUtils.isNotBlank(value))
- return StringUtils.trim(value);
- }
- return null;
- }
- /**
- * 2026-05-26:诊断页支持临时覆盖配置,但自动触发仍按系统配置执行。
- */
- private static String rdCfgOrOverride(Map<String, Object> overrideParm,
- String overrideKey,
- String propName,
- String envName) {
- String value = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
- if (StringUtils.isNotBlank(value))
- return value;
- return rdCfg(propName, envName);
- }
- /**
- * 2026-05-27:组件标识缺配置时回退到默认值,先保证当前请假下发链路可按既定 tagId 联调。
- */
- private static String rdCfgOrOverride(Map<String, Object> overrideParm,
- String overrideKey,
- String propName,
- String envName,
- String defVal) {
- String value = rdCfgOrOverride(overrideParm, overrideKey, propName, envName);
- if (StringUtils.isNotBlank(value))
- return value;
- return StringUtils.trimToNull(defVal);
- }
- /**
- * 2026-05-27:把组件标识来源回显出来,避免联调时分不清到底用了覆盖值、配置值还是默认值。
- */
- private static String rdCfgSource(Map<String, Object> overrideParm,
- String overrideKey,
- String propName,
- String envName,
- String defVal) {
- String overrideVal = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
- if (StringUtils.isNotBlank(overrideVal))
- return "override";
- String cfgVal = rdCfg(propName, envName);
- if (StringUtils.isNotBlank(cfgVal))
- return "cfg";
- return StringUtils.isNotBlank(defVal) ? "default" : "missing";
- }
- /**
- * 2026-05-26:整型配置支持诊断页临时覆盖,非法值继续回退默认值。
- */
- private static int rdIntCfgOrOverride(Map<String, Object> overrideParm,
- String overrideKey,
- String propName,
- String envName,
- int defVal) {
- String value = rdStr(overrideParm == null ? null : overrideParm.get(overrideKey));
- if (StringUtils.isBlank(value))
- return rdIntCfg(propName, envName, defVal);
- try {
- return Integer.parseInt(StringUtils.trim(value));
- } catch (Exception ignored) {
- return rdIntCfg(propName, envName, defVal);
- }
- }
- /**
- * 2026-05-26:把请求里的临时覆盖项集中收口,避免 build 逻辑依赖 servlet 上下文。
- */
- private Map<String, Object> makeReqOverrideParm() {
- Map<String, Object> row = new LinkedHashMap<>();
- putIfNotBlank(row, "tagId", rdReqStrParm("tagId", "hkLeaveAuthTagId"));
- putIfNotBlank(row, "callbackUrl", rdReqStrParm("callbackUrl", "hkLeaveAuthCallbackUrl"));
- putIfNotBlank(row, "templateId", rdReqStrParm("templateId", "hkLeaveAuthTemplateId"));
- putIfNotBlank(row, "templateDimension", rdReqStrParm("templateDimension", "dimension", "hkLeaveAuthTemplateDimension"));
- return row;
- }
- /**
- * 2026-06-02:海康下载回调采用 application/json body,不能只靠 query 参数取值。
- */
- private String rdReqBody() throws IOException {
- if (super.req == null)
- return null;
- StringBuilder sb = new StringBuilder();
- BufferedReader reader = super.req.getReader();
- String line;
- while ((line = reader.readLine()) != null)
- sb.append(line);
- return sb.toString();
- }
- /**
- * 2026-05-27:把请求里的 JSON 字符串解析成 Map,供海康原始探测接口透传。
- */
- private static Map<String, Object> rdReqBodyMap(String reqBodyStr) {
- if (StringUtils.isBlank(reqBodyStr))
- return new LinkedHashMap<>();
- JsonElement jsonElement = JsonParser.parseString(reqBodyStr);
- if (!jsonElement.isJsonObject())
- throw new IllegalArgumentException("仅支持 JSON Object。");
- JsonObject jsonObject = jsonElement.getAsJsonObject();
- @SuppressWarnings("unchecked")
- Map<String, Object> row = GSON.fromJson(jsonObject, Map.class);
- return row == null ? new LinkedHashMap<>() : row;
- }
- /**
- * 2026-05-26:把列表字段转成长度统计,日志只看数量不看全文。
- */
- private static int rdListSize(Object value) {
- if (value instanceof List<?> list)
- return list.size();
- return 0;
- }
- /**
- * 2026-05-26:读取请求整数参数,兼容多个别名。
- */
- private int rdReqIntParm(String... fieldNameArr) {
- if (super.req == null || fieldNameArr == null)
- return 0;
- for (String fieldName : fieldNameArr) {
- String value = super.req.getParameter(fieldName);
- if (StringUtils.isBlank(value))
- continue;
- try {
- return Integer.parseInt(StringUtils.trim(value));
- } catch (Exception ignored) {
- }
- }
- return 0;
- }
- /**
- * 2026-05-26:对外部对象做字符串安全读取。
- */
- private static String rdStr(Object value) {
- return value == null ? null : StringUtils.trimToNull(String.valueOf(value));
- }
- /**
- * 2026-05-26:把数据库列或接口字段转成长整型。
- */
- private static long rdLong(Object value) {
- if (value == null)
- return 0L;
- if (value instanceof Number number)
- return number.longValue();
- try {
- return Long.parseLong(StringUtils.trim(String.valueOf(value)));
- } catch (Exception ignored) {
- return 0L;
- }
- }
- /**
- * 2026-05-26:把外部对象转成可空 Long。
- */
- private static int rdInt(Object value) {
- if (value == null)
- return 0;
- if (value instanceof Number number)
- return number.intValue();
- try {
- return Integer.parseInt(StringUtils.trim(String.valueOf(value)));
- } catch (Exception ignored) {
- return 0;
- }
- }
- /**
- * 2026-05-26:把文本统一转成海康人员匹配时可比较的规范键。
- */
- private static String makeNormKey(String value) {
- return StringUtils.upperCase(StringUtils.trimToEmpty(value));
- }
- /**
- * 2026-05-26:海康人员号脱敏回显。
- */
- private static String makeMaskStr(String value) {
- if (StringUtils.isBlank(value))
- return "";
- String trimVal = StringUtils.trim(value);
- if (trimVal.length() <= 4)
- return "****";
- return trimVal.substring(0, 2) + "****" + trimVal.substring(trimVal.length() - 2);
- }
- /**
- * 2026-05-26:读取请求参数,兼容多个别名。
- */
- private long rdReqLongParm(String... fieldNameArr) {
- if (super.req == null || fieldNameArr == null)
- return 0L;
- for (String fieldName : fieldNameArr) {
- String value = super.req.getParameter(fieldName);
- if (StringUtils.isBlank(value))
- continue;
- try {
- return Long.parseLong(StringUtils.trim(value));
- } catch (Exception ignored) {
- }
- }
- return 0L;
- }
- /**
- * 2026-05-26:读取请求字符串参数,兼容多个别名。
- */
- private String rdReqStrParm(String... fieldNameArr) {
- if (super.req == null || fieldNameArr == null)
- return null;
- for (String fieldName : fieldNameArr) {
- String value = super.req.getParameter(fieldName);
- if (StringUtils.isNotBlank(value))
- return StringUtils.trim(value);
- }
- return null;
- }
- /**
- * 2026-05-26:仅在非空时写入覆盖配置。
- */
- private static void putIfNotBlank(Map<String, Object> row, String key, String value) {
- if (StringUtils.isNotBlank(value))
- row.put(key, value);
- }
- /**
- * 2026-06-02:仅当结果里还没有该字段时,才把持久化快照补回显示对象。
- */
- private static void putPersistedField(Map<String, Object> row, String key, String value) {
- if (row == null || StringUtils.isAnyBlank(key, value) || row.containsKey(key))
- return;
- row.put(key, value);
- }
- /**
- * 2026-05-26:请假上下文只保留同步临时权限所需字段。
- */
- private static final class LeaveAuthSyncCtx {
- private final long rcid;
- private final long bjid;
- private final long ryid;
- private final int rclbm;
- private final Timestamp kssj;
- private final Timestamp jssj;
- private final String xm;
- private final String jobNo;
- private final String ms;
- private final String mswj;
- private final String wcmswj;
- private LeaveAuthSyncCtx(long rcid,
- long bjid,
- long ryid,
- int rclbm,
- Timestamp kssj,
- Timestamp jssj,
- String xm,
- String jobNo,
- String ms,
- String mswj,
- String wcmswj) {
- this.rcid = rcid;
- this.bjid = bjid;
- this.ryid = ryid;
- this.rclbm = rclbm;
- this.kssj = kssj;
- this.jssj = jssj;
- this.xm = xm;
- this.jobNo = jobNo;
- this.ms = ms;
- this.mswj = mswj;
- this.wcmswj = wcmswj;
- }
- }
- }
|