Browse Source

修复: 补齐海康请假临近开始补偿与状态追踪

1. 具体改动
- 在 HkLeaveAuthServ 中新增 hkkq_leave_auth_pending 补偿入口与每分钟定时扫描逻辑,对临近开始或已开始但尚未确认的平台权限先做 auth_config/search 回查,未命中时再触发 auth_config/add 重试。
- 将请假资源解析改为优先复用已落库 resourceKeys,并为 acsDevice/search 增加本地缓存,减少重复全量拉取海康门禁设备造成的链路时延。
- 为 RC.WCMSWJ 与 RCHKLA 增加 syncStage、retryCount、nextRetryTime、firstAcceptTime、platformConfirmTime、lastError、totalCostMs 等状态字段写入,且兼容扩展表尚未升级时的灰度部署。
- 更新 hkkq.serv.xml、hkkq.timer.xml,补充 docs/sql/2026-06-10_rchkla_stage_upgrade.sql 与 docs/2026-06-10_海康请假临近开始补偿与设备缓存改造.md 说明。

2. 影响范围或行为变化
- 新增 hkkqLeaveAuthPendingPlan,每 1 分钟补偿一次请假临近开始的未确认权限,降低请假开始后数分钟内刷脸提示权限过期的空窗概率。
- delete 回收成功后会把阶段切到 deleted,避免宿舍门权限已回收时又被 pending 补偿任务误下发。
- 临近开始补偿与候选扫描统一使用 Java 当前时间绑定参数,不再依赖数据库 sysdate 判断当前时间窗。

3. 验证情况
- 已执行 javac --% -sourcepath tmp_empty_src -cp out/artifacts/PMS_war_exploded/WEB-INF/classes;out/artifacts/PMS_war_exploded/WEB-INF/lib/* -d tmp_hk_leave_auth_compile src/biz/kq/HkLeaveAuthServ.java。
- 未执行正式环境联调与自动化测试,仅完成本地单文件编译校验。
“gaohp” 5 months ago
parent
commit
0f46203436

+ 117 - 0
docs/2026-06-10_海康请假临近开始补偿与设备缓存改造.md

@@ -0,0 +1,117 @@
+# 海康请假临近开始补偿与设备缓存改造
+
+## 改动目标
+
+本次改动针对“请假开始后 1-5 分钟内刷脸仍提示权限过期”的空窗问题,做了两类补强:
+
+1. 减轻海康下发主链路重量,避免每次请假都实时全量拉 `acsDevice/search`。
+2. 增加“临近开始未确认”的自动补偿,避免首次 `auth_config/add` 已受理但 `auth_config/search` 尚未及时命中时完全依赖人工重试。
+
+## 代码改动
+
+### 1. 海康设备列表改成带缓存加载
+
+文件:[src/biz/kq/HkLeaveAuthServ.java](/H:/gaohp/feifan_project/PMS_20260508/PMS/src/biz/kq/HkLeaveAuthServ.java)
+
+- `buildLeaveAuthResourceBundle` 不再每次都直接调用海康设备列表接口。
+- 新增 `loadAcsDeviceListWithCache`,默认缓存 30 分钟。
+- 当请假记录已持久化 `resourceKeys` 时,补偿链路、结果回查链路优先复用已落库资源集合,不再重新映射全部门禁点。
+
+可选配置:
+
+- `hk.leaveAuth.acsDeviceCacheMinutes`
+- `HK_LEAVE_AUTH_ACS_DEVICE_CACHE_MINUTES`
+
+### 2. 新增临近开始补偿任务
+
+文件:
+
+- [src/biz/kq/HkLeaveAuthServ.java](/H:/gaohp/feifan_project/PMS_20260508/PMS/src/biz/kq/HkLeaveAuthServ.java)
+- [web/cfg/biz/kq/hkkq.serv.xml](/H:/gaohp/feifan_project/PMS_20260508/PMS/web/cfg/biz/kq/hkkq.serv.xml)
+- [web/cfg/biz/kq/hkkq.timer.xml](/H:/gaohp/feifan_project/PMS_20260508/PMS/web/cfg/biz/kq/hkkq.timer.xml)
+
+新增服务:
+
+- `hkkq_leave_auth_pending`
+
+新增定时器:
+
+- `hkkqLeaveAuthPendingPlan`
+- Cron:`0 0/1 * * * ?`
+
+执行逻辑:
+
+1. 扫描开始时间已到或即将到达的请假记录。
+2. 先调用 `auth_config/search` 做平台确认回查。
+3. 如果仍未确认,且已到重试时间,则再次执行 `auth_config/add`。
+4. 补偿状态写回 `RC.WCMSWJ`,同时优先回写 `RCHKLA`。
+
+可选配置:
+
+- `hk.leaveAuth.pending.batchLimit`
+- `HK_LEAVE_AUTH_PENDING_BATCH_LIMIT`
+- `hk.leaveAuth.pending.advanceMinutes`
+- `HK_LEAVE_AUTH_PENDING_ADVANCE_MINUTES`
+- `hk.leaveAuth.pending.retryDelaySeconds`
+- `HK_LEAVE_AUTH_PENDING_RETRY_DELAY_SECONDS`
+
+### 3. 扩展表增加独立阶段字段
+
+文件:
+
+- [docs/sql/2026-06-10_rchkla.sql](/H:/gaohp/feifan_project/PMS_20260508/PMS/docs/sql/2026-06-10_rchkla.sql)
+- [docs/sql/2026-06-10_rchkla_stage_upgrade.sql](/H:/gaohp/feifan_project/PMS_20260508/PMS/docs/sql/2026-06-10_rchkla_stage_upgrade.sql)
+
+新增字段:
+
+- `SYNC_STAGE`
+- `RETRY_COUNT`
+- `NEXT_RETRY_TIME`
+- `FIRST_ACCEPT_TIME`
+- `PLATFORM_CONFIRM_TIME`
+- `LAST_ERROR`
+- `TOTAL_COST_MS`
+
+阶段含义:
+
+- `pending`:未完成首次有效下发
+- `accepted`:海康已受理,但平台确认未完成
+- `retrying`:补偿任务已进入重试
+- `confirmed`:`auth_config/search` 已确认
+- `expired`:请假已结束,不再补偿
+- `deleted`:请假结束后权限已回收
+
+说明:
+
+- 代码已兼容“表已存在但未执行升级 SQL”的过渡场景。
+- 若未执行升级 SQL,核心补偿链路仍可运行,但 `RCHKLA` 中不会完整落独立阶段字段。
+
+## 部署步骤
+
+1. 发布最新代码。
+2. 如果正式库已经有 `RCHKLA`,执行:
+
+```sql
+@docs/sql/2026-06-10_rchkla_stage_upgrade.sql
+```
+
+3. 如果正式库还没有 `RCHKLA`,直接执行:
+
+```sql
+@docs/sql/2026-06-10_rchkla.sql
+```
+
+4. 重启应用后,确认 `hkkqLeaveAuthPendingPlan` 已加载。
+
+## 验证
+
+本地已执行:
+
+```powershell
+javac --% -sourcepath tmp_empty_src -cp out/artifacts/PMS_war_exploded/WEB-INF/classes;out/artifacts/PMS_war_exploded/WEB-INF/lib/* -d tmp_hk_leave_auth_compile src/biz/kq/HkLeaveAuthServ.java
+```
+
+结果:
+
+- `HkLeaveAuthServ.java` 编译通过。
+- 未执行正式环境联调验证,需部署后结合真实请假单观察 `RCHKLA` 阶段流转与 `auth_config/search` 确认时间。

+ 15 - 0
docs/sql/2026-06-10_rchkla.sql

@@ -13,6 +13,13 @@ create table RCHKLA (
     EXPECTED_CONFIG_COUNT number(10),
     MATCHED_CONFIG_COUNT number(10),
     CONFIG_TASK_ID varchar2(128),
+    SYNC_STAGE varchar2(60),
+    RETRY_COUNT number(10),
+    NEXT_RETRY_TIME timestamp,
+    FIRST_ACCEPT_TIME timestamp,
+    PLATFORM_CONFIRM_TIME timestamp,
+    LAST_ERROR varchar2(1000),
+    TOTAL_COST_MS number(20),
     DELETE_TIME timestamp,
     DELETE_MODE varchar2(120),
     DELETE_CONFIRMED number(1),
@@ -36,6 +43,13 @@ comment on column RCHKLA.RCID is '对应 RC.RCID';
 comment on column RCHKLA.SYNC_MODE is '最近一次海康请假链路模式';
 comment on column RCHKLA.SYNC_TIME is '最近一次海康同步时间';
 comment on column RCHKLA.CONFIG_TASK_ID is 'auth_config/add 链路任务号';
+comment on column RCHKLA.SYNC_STAGE is 'pending/accepted/retrying/confirmed/expired/deleted';
+comment on column RCHKLA.RETRY_COUNT is '补偿重试次数';
+comment on column RCHKLA.NEXT_RETRY_TIME is '下次允许补偿时间';
+comment on column RCHKLA.FIRST_ACCEPT_TIME is '首次被海康平台受理时间';
+comment on column RCHKLA.PLATFORM_CONFIRM_TIME is 'auth_config/search 首次确认完成时间';
+comment on column RCHKLA.LAST_ERROR is '最近一次补偿或下发错误摘要';
+comment on column RCHKLA.TOTAL_COST_MS is '首次受理到平台确认的耗时毫秒数';
 comment on column RCHKLA.DELETE_TASK_ID is 'auth_config/delete 链路任务号';
 comment on column RCHKLA.DOWNLOAD_TASK_ID is '海康下载任务号';
 comment on column RCHKLA.CALLBACK_TASK_ID is '海康下载回调任务号';
@@ -46,3 +60,4 @@ create index IDX_RCHKLA_DEL_TASK on RCHKLA (DELETE_TASK_ID);
 create index IDX_RCHKLA_DW_TASK on RCHKLA (DOWNLOAD_TASK_ID);
 create index IDX_RCHKLA_CB_TASK on RCHKLA (CALLBACK_TASK_ID);
 create index IDX_RCHKLA_RECYCLE on RCHKLA (PLATFORM_CONFIG_CONFIRMED, DELETE_CONFIRMED, UPDATED_AT);
+create index IDX_RCHKLA_PENDING on RCHKLA (SYNC_STAGE, NEXT_RETRY_TIME, UPDATED_AT);

+ 19 - 0
docs/sql/2026-06-10_rchkla_stage_upgrade.sql

@@ -0,0 +1,19 @@
+alter table RCHKLA add (
+    SYNC_STAGE varchar2(60),
+    RETRY_COUNT number(10),
+    NEXT_RETRY_TIME timestamp,
+    FIRST_ACCEPT_TIME timestamp,
+    PLATFORM_CONFIRM_TIME timestamp,
+    LAST_ERROR varchar2(1000),
+    TOTAL_COST_MS number(20)
+);
+
+comment on column RCHKLA.SYNC_STAGE is 'pending/accepted/retrying/confirmed/expired/deleted';
+comment on column RCHKLA.RETRY_COUNT is '补偿重试次数';
+comment on column RCHKLA.NEXT_RETRY_TIME is '下次允许补偿时间';
+comment on column RCHKLA.FIRST_ACCEPT_TIME is '首次被海康平台受理时间';
+comment on column RCHKLA.PLATFORM_CONFIRM_TIME is 'auth_config/search 首次确认完成时间';
+comment on column RCHKLA.LAST_ERROR is '最近一次补偿或下发错误摘要';
+comment on column RCHKLA.TOTAL_COST_MS is '首次受理到平台确认的耗时毫秒数';
+
+create index IDX_RCHKLA_PENDING on RCHKLA (SYNC_STAGE, NEXT_RETRY_TIME, UPDATED_AT);

+ 558 - 16
src/biz/kq/HkLeaveAuthServ.java

@@ -63,11 +63,17 @@ public class HkLeaveAuthServ extends Serv {
     private static final int HK_DEF_DOWNLOAD_POLL_SLEEP_MS = 1200;
     private static final int HK_DEF_RECYCLE_LIMIT = 20;
     private static final int HK_DEF_BACKFILL_LIMIT = 200;
+    private static final int HK_DEF_PENDING_LIMIT = 20;
+    private static final int HK_DEF_PENDING_ADVANCE_MINUTES = 10;
+    private static final int HK_DEF_PENDING_RETRY_DELAY_SECONDS = 60;
+    private static final int HK_DEF_ACS_DEVICE_CACHE_MINUTES = 30;
     private static final String HK_LEAVE_AUTH_EXT_TAB = "RCHKLA";
     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");
     private static final Pattern MJD_CHANNEL_NAME_PATTERN = Pattern.compile("^(.*?)(?:_门_(\\d+))?$");
+    private static final Object ACS_DEVICE_CACHE_LOCK = new Object();
+    private static volatile AcsDeviceCacheSnapshot ACS_DEVICE_CACHE = null;
 
     /**
      * 2026-05-26:请假保存后执行入口,保持原来的挂点不变。
@@ -154,6 +160,16 @@ public class HkLeaveAuthServ extends Serv {
         return ServC.SERV_notByA;
     }
 
+    /**
+     * 2026-06-10:扫描临近开始但尚未确认的请假权限,优先 search 补确认,必要时再触发 add 重试。
+     */
+    public String syncPendingLeaveAuth() {
+        Map<String, Object> result = syncPendingLeaveAuthResult();
+        if (super.resp != null)
+            super.wrJsonByResp(result);
+        return ServC.SERV_notByA;
+    }
+
     /**
      * 2026-06-10:手工把现有 RC 里的海康请假摘要回填到独立扩展表,便于后续按 rcid/taskId 结构化追踪。
      */
@@ -316,8 +332,7 @@ public class HkLeaveAuthServ extends Serv {
             if (probeLimit <= 0)
                 probeLimit = 3;
 
-            List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
-            LeaveAuthResourceBundle resourceBundle = buildLeaveAuthResourceBundle(hkConnParm, resourceSourceList);
+            LeaveAuthResourceBundle resourceBundle = resolveSyncResourceBundle(gdba, hkConnParm, ctx, result);
             List<Map<String, Object>> resourceInfoList = resourceBundle.resourceInfoList;
             if (probeLimit > resourceInfoList.size())
                 probeLimit = resourceInfoList.size();
@@ -329,7 +344,7 @@ public class HkLeaveAuthServ extends Serv {
             result.put("hkAcsDeviceCount", resourceBundle.hkAcsDeviceCount);
             result.put("resourceSourceList", resourceBundle.resourceSourceList);
             result.put("resourceUnmappedList", resourceBundle.unmappedSourceList);
-            result.put("resourceMapMode", "acsDeviceSearchByNameAndChannel");
+            result.put("resourceMapMode", resourceBundle.resourceMapMode);
             if (!resourceBundle.unmappedSourceList.isEmpty()) {
                 result.put("ok", false);
                 result.put("msg", makeResourceMapErrorMsg(resourceBundle.unmappedSourceList));
@@ -555,6 +570,183 @@ public class HkLeaveAuthServ extends Serv {
         }
     }
 
+    /**
+     * 2026-06-10:每分钟补偿一次临近开始但尚未完成平台确认的请假,先 search,仍未命中才 retry add。
+     */
+    private Map<String, Object> syncPendingLeaveAuthResult() {
+        Map<String, Object> result = new LinkedHashMap<>();
+        result.put("ok", true);
+        result.put("mode", "execute_platform_config_pending_batch");
+
+        int limit = rdReqIntParm("limit", "batchSize");
+        if (limit <= 0)
+            limit = rdIntCfg("hk.leaveAuth.pending.batchLimit", "HK_LEAVE_AUTH_PENDING_BATCH_LIMIT", HK_DEF_PENDING_LIMIT);
+        int advanceMinutes = rdReqIntParm("advanceMinutes", "windowMinutes");
+        if (advanceMinutes <= 0)
+            advanceMinutes = rdIntCfg("hk.leaveAuth.pending.advanceMinutes", "HK_LEAVE_AUTH_PENDING_ADVANCE_MINUTES",
+                    HK_DEF_PENDING_ADVANCE_MINUTES);
+        int retryDelaySeconds = rdReqIntParm("retryDelaySeconds", "retryDelay");
+        if (retryDelaySeconds <= 0)
+            retryDelaySeconds = rdIntCfg("hk.leaveAuth.pending.retryDelaySeconds", "HK_LEAVE_AUTH_PENDING_RETRY_DELAY_SECONDS",
+                    HK_DEF_PENDING_RETRY_DELAY_SECONDS);
+
+        Timestamp now = new Timestamp(System.currentTimeMillis());
+        Timestamp windowEnd = new Timestamp(now.getTime() + Math.max(1, advanceMinutes) * 60_000L);
+        result.put("limit", limit);
+        result.put("advanceMinutes", advanceMinutes);
+        result.put("retryDelaySeconds", retryDelaySeconds);
+        result.put("now", makeHkTime(now));
+        result.put("windowEnd", makeHkTime(windowEnd));
+
+        try (Db gdba = Db.makeConn()) {
+            List<LeaveAuthSyncCtx> ctxList = selPendingPlatformConfigCtxList(gdba, now, windowEnd, limit);
+            result.put("candidateCount", ctxList.size());
+
+            List<Map<String, Object>> detailList = new ArrayList<>();
+            int confirmedCount = 0;
+            int retriedCount = 0;
+            int skippedCount = 0;
+            int failedCount = 0;
+            for (LeaveAuthSyncCtx ctx : ctxList) {
+                Map<String, Object> item = executePendingPlatformConfigSync(ctx.rcid, now, retryDelaySeconds);
+                detailList.add(item);
+
+                if (rdBoolLike(item.get("platformConfigConfirmed")) || rdBoolLike(item.get("configSearchMatched"))) {
+                    confirmedCount++;
+                } else if ("retryAdd".equals(rdStr(item.get("pendingAction")))) {
+                    retriedCount++;
+                    if (!rdBoolLike(item.get("ok")))
+                        failedCount++;
+                } else if (StringUtils.isNotBlank(rdStr(item.get("pendingSkipReason")))) {
+                    skippedCount++;
+                } else if (!rdBoolLike(item.get("ok"))) {
+                    failedCount++;
+                }
+            }
+
+            result.put("confirmedCount", confirmedCount);
+            result.put("retriedCount", retriedCount);
+            result.put("skippedCount", skippedCount);
+            result.put("failedCount", failedCount);
+            result.put("detailList", detailList);
+            result.put("msg", "请假临近开始补偿执行完成。");
+            log4j.info("HkLeaveAuthServ.syncPendingLeaveAuthResult() 完成:limit={}, candidateCount={}, confirmedCount={}, retriedCount={}, skippedCount={}, failedCount={}",
+                    limit, ctxList.size(), confirmedCount, retriedCount, skippedCount, failedCount);
+            return result;
+        } catch (Exception e) {
+            log4j.error("HkLeaveAuthServ.syncPendingLeaveAuthResult() 异常", e);
+            result.put("ok", false);
+            result.put("msg", e.getMessage());
+            return result;
+        }
+    }
+
+    /**
+     * 2026-06-10:补偿任务对单条请假先做平台 search 回查,仍未确认时再调用 add 重试。
+     */
+    private Map<String, Object> executePendingPlatformConfigSync(long rcid,
+                                                                 Timestamp now,
+                                                                 int retryDelaySeconds) {
+        try (Db gdba = Db.makeConn()) {
+            LeaveAuthSyncCtx ctx = selLeaveAuthSyncCtx(gdba, rcid);
+            Map<String, Object> result = new LinkedHashMap<>();
+            result.put("rcid", rcid);
+            result.put("pendingAction", "search");
+            result.put("retryDelaySeconds", retryDelaySeconds);
+
+            if (ctx == null) {
+                result.put("ok", false);
+                result.put("msg", "未找到对应请假记录。");
+                return result;
+            }
+
+            result.put("leaveCtx", makeLeaveCtxResp(ctx));
+            applyPersistedLeaveAuthSnapshot(ctx, result);
+            if (ifLeaveEnded(ctx.jssj, now)) {
+                result.put("ok", false);
+                result.put("pendingSkipReason", "leaveEnded");
+                result.put("msg", "请假已结束,跳过临近开始补偿。");
+                markLeaveAuthStageExpired(result, now);
+                persistLeaveAuthSyncResult(gdba, ctx, result);
+                gdba.commit();
+                return result;
+            }
+
+            if (rdBoolLike(result.get("platformConfigConfirmed")) || rdBoolLike(result.get("configSearchMatched"))) {
+                result.put("ok", true);
+                result.put("pendingSkipReason", "alreadyConfirmed");
+                result.put("msg", "海康平台权限已确认,无需重复补偿。");
+                markLeaveAuthStageConfirmed(result, ctx, now);
+                persistLeaveAuthSyncResult(gdba, ctx, result);
+                gdba.commit();
+                return result;
+            }
+
+            Timestamp nextRetryTime = rdLeaveAuthPersistTime(rdLeaveAuthLogField(ctx, "nextRetryTime"));
+            Map<String, Object> refreshResult = new LinkedHashMap<>();
+            refreshResult.put("autoTrigger", true);
+            refreshResult.put("pendingAction", "search");
+            refreshResult.put("pendingRetry", true);
+            refreshResult = refreshPlatformConfigLeaveAuthResult(gdba, ctx, Map.of(), refreshResult);
+            refreshResult.put("mode", StringUtils.defaultIfBlank(rdLeaveAuthLogField(ctx, "mode"), "execute_platform_config"));
+            refreshResult.put("pendingAction", "search");
+            refreshResult.put("retryDelaySeconds", retryDelaySeconds);
+
+            if (rdBoolLike(refreshResult.get("platformConfigConfirmed")) || rdBoolLike(refreshResult.get("configSearchMatched"))) {
+                markLeaveAuthStageConfirmed(refreshResult, ctx, now);
+                persistLeaveAuthSyncResult(gdba, ctx, refreshResult);
+                gdba.commit();
+                return refreshResult;
+            }
+
+            if (nextRetryTime != null && nextRetryTime.after(now)) {
+                refreshResult.put("pendingSkipReason", "retryNotDue");
+                refreshResult.put("retryDueTime", makeHkTime(nextRetryTime));
+                markLeaveAuthStagePending(refreshResult, ctx, "accepted", now, false, retryDelaySeconds);
+                persistLeaveAuthSyncResult(gdba, ctx, refreshResult);
+                gdba.commit();
+                return refreshResult;
+            }
+        } catch (Exception e) {
+            Map<String, Object> result = new LinkedHashMap<>();
+            result.put("ok", false);
+            result.put("rcid", rcid);
+            result.put("pendingAction", "search");
+            result.put("msg", makeExceptionMsg(e));
+            return result;
+        }
+
+        Map<String, Object> retryResult;
+        try {
+            retryResult = buildLeaveAuthSyncResult(rcid, true, Map.of());
+            retryResult.put("pendingAction", "retryAdd");
+        } catch (Exception e) {
+            retryResult = new LinkedHashMap<>();
+            retryResult.put("ok", false);
+            retryResult.put("rcid", rcid);
+            retryResult.put("pendingAction", "retryAdd");
+            retryResult.put("msg", makeExceptionMsg(e));
+        }
+
+        try (Db gdba = Db.makeConn()) {
+            LeaveAuthSyncCtx freshCtx = selLeaveAuthSyncCtx(gdba, rcid);
+            if (freshCtx != null) {
+                Timestamp retryNow = new Timestamp(System.currentTimeMillis());
+                if (rdBoolLike(retryResult.get("platformConfigConfirmed")) || rdBoolLike(retryResult.get("configSearchMatched"))) {
+                    markLeaveAuthStageConfirmed(retryResult, freshCtx, retryNow);
+                } else {
+                    markLeaveAuthStagePending(retryResult, freshCtx, "retrying", retryNow, true, retryDelaySeconds);
+                }
+                persistLeaveAuthSyncResult(gdba, freshCtx, retryResult);
+                gdba.commit();
+            }
+        } catch (Exception e) {
+            log4j.error("HkLeaveAuthServ.executePendingPlatformConfigSync() 回写补偿状态异常,rcid={}", rcid, e);
+            retryResult.put("pendingPersistError", e.getMessage());
+        }
+        return retryResult;
+    }
+
     /**
      * 2026-06-10:把历史 RC.wcmswj/mswj/ms 里的海康同步摘要回填到扩展表,避免后续仍靠 like 文本检索。
      */
@@ -665,6 +857,7 @@ public class HkLeaveAuthServ extends Serv {
                     rdLeaveAuthLogField(ctx, "deleteConfirmSource"), "persisted"));
             result.put("deleteSkipReason", "alreadyConfirmed");
             result.put("msg", "该请假记录的海康临时权限已回收,无需重复删除。");
+            markLeaveAuthStageDeleted(result, ctx, now);
             persistLeaveAuthSyncResult(gdba, ctx, result);
             return result;
         }
@@ -752,6 +945,7 @@ public class HkLeaveAuthServ extends Serv {
             result.put("deleteTaskAccepted", false);
             result.put("deleteSkipReason", "searchAlreadyEmpty");
             result.put("msg", "海康侧当前请假时段权限已不存在,无需再次删除。");
+            markLeaveAuthStageDeleted(result, ctx, now);
             persistLeaveAuthSyncResult(gdba, ctx, result);
             return result;
         }
@@ -820,6 +1014,7 @@ public class HkLeaveAuthServ extends Serv {
         }
 
         result.put("msg", "海康当前请假时段权限已完成回收。");
+        markLeaveAuthStageDeleted(result, ctx, now);
         persistLeaveAuthSyncResult(gdba, ctx, result);
         return result;
     }
@@ -918,6 +1113,7 @@ public class HkLeaveAuthServ extends Serv {
                 result.put("mode", "skipExpired");
                 result.put("skipReason", "请假时间段已结束,跳过海康自动开门。");
                 result.put("msg", "请假结束时间早于当前时间,不能再下发海康临时权限。");
+                markLeaveAuthStageExpired(result, now);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -925,6 +1121,7 @@ public class HkLeaveAuthServ extends Serv {
             if (StringUtils.isBlank(ctx.jobNo)) {
                 result.put("ok", false);
                 result.put("msg", "学生缺少人员号(jobNo/RYH),无法匹配海康人员。");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -933,6 +1130,7 @@ public class HkLeaveAuthServ extends Serv {
             if (hkConnParm == null) {
                 result.put("ok", false);
                 result.put("msg", "缺少海康连接配置,请补齐 hk.host / hk.appKey / hk.appSecret。");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -946,6 +1144,7 @@ public class HkLeaveAuthServ extends Serv {
             if (personInfo == null) {
                 result.put("ok", false);
                 result.put("msg", "海康侧未找到对应人员。");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -955,12 +1154,12 @@ public class HkLeaveAuthServ extends Serv {
             if (StringUtils.isBlank(personId)) {
                 result.put("ok", false);
                 result.put("msg", "海康人员缺少 personId。");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
 
-            List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
-            LeaveAuthResourceBundle resourceBundle = buildLeaveAuthResourceBundle(hkConnParm, resourceSourceList);
+            LeaveAuthResourceBundle resourceBundle = resolveSyncResourceBundle(gdba, hkConnParm, ctx, result);
             List<Map<String, Object>> resourceInfoList = resourceBundle.resourceInfoList;
             result.put("resourceSourceList", resourceBundle.resourceSourceList);
             result.put("resourceUnmappedList", resourceBundle.unmappedSourceList);
@@ -970,16 +1169,18 @@ public class HkLeaveAuthServ extends Serv {
             result.put("resourceSourceCount", resourceBundle.resourceSourceList.size());
             result.put("resourceMappedCount", resourceInfoList.size());
             result.put("hkAcsDeviceCount", resourceBundle.hkAcsDeviceCount);
-            result.put("resourceMapMode", "acsDeviceSearchByNameAndChannel");
+            result.put("resourceMapMode", resourceBundle.resourceMapMode);
             if (!resourceBundle.unmappedSourceList.isEmpty()) {
                 result.put("ok", false);
                 result.put("msg", makeResourceMapErrorMsg(resourceBundle.unmappedSourceList));
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
             if (resourceInfoList.isEmpty()) {
                 result.put("ok", false);
                 result.put("msg", "未找到可下发的有效门禁点。");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -1063,6 +1264,7 @@ public class HkLeaveAuthServ extends Serv {
             if (StringUtils.isBlank(tagId)) {
                 result.put("skipReason", "缺少海康下发配置 tagId,暂不执行下发。");
                 result.put("mode", "preview");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
                 return result;
             }
@@ -1070,6 +1272,7 @@ public class HkLeaveAuthServ extends Serv {
             boolean execute = rdBoolCfg(CFG_EXECUTE, "HK_LEAVE_AUTH_EXECUTE", false);
             if (!autoTrigger || !execute) {
                 result.put("mode", "dryRun");
+                markLeaveAuthStagePending(result, ctx, "pending", now, false, 0);
                 if (autoTrigger)
                     logDryRun(ctx, personInfo, payload);
                 persistLeaveAuthSyncResult(gdba, ctx, result);
@@ -1177,9 +1380,9 @@ public class HkLeaveAuthServ extends Serv {
     private static LeaveAuthResourceBundle buildLeaveAuthResourceBundle(Map<String, Object> hkConnParm,
                                                                         List<Map<String, Object>> mjdList) throws Exception {
         if (mjdList == null || mjdList.isEmpty())
-            return new LeaveAuthResourceBundle(List.of(), List.of(), List.of(), 0);
+            return new LeaveAuthResourceBundle(List.of(), List.of(), List.of(), 0, "acsDeviceSearchByNameAndChannel");
 
-        List<Map<String, Object>> acsDeviceList = HK_API_CLIENT.loadAcsDeviceList(hkConnParm);
+        List<Map<String, Object>> acsDeviceList = loadAcsDeviceListWithCache(hkConnParm);
         Map<String, List<Map<String, Object>>> acsDeviceMap = makeAcsDeviceNameMap(acsDeviceList);
         LinkedHashSet<String> resourceKeySet = new LinkedHashSet<>();
         List<Map<String, Object>> resourceInfoList = new ArrayList<>();
@@ -1246,7 +1449,57 @@ public class HkLeaveAuthServ extends Serv {
             resourceInfoList.add(makeResourceInfo(resourceIndexCode, channelNo));
         }
 
-        return new LeaveAuthResourceBundle(resourceInfoList, resourceSourceList, unmappedSourceList, acsDeviceList.size());
+        return new LeaveAuthResourceBundle(resourceInfoList, resourceSourceList, unmappedSourceList,
+                acsDeviceList.size(), "acsDeviceSearchByNameAndChannel");
+    }
+
+    /**
+     * 2026-06-10:已有 resourceKeys 时优先复用持久化资源集合,避免补偿/结果查询再次全量拉门禁设备。
+     */
+    private static LeaveAuthResourceBundle resolveSyncResourceBundle(Db gdba,
+                                                                     Map<String, Object> hkConnParm,
+                                                                     LeaveAuthSyncCtx ctx,
+                                                                     Map<String, Object> result) throws Exception {
+        List<Map<String, Object>> persistedResourceInfoList = rdPersistedResourceInfoList(ctx);
+        if (!persistedResourceInfoList.isEmpty()) {
+            if (result != null)
+                result.put("resourceResolveSource", "persistedResourceKeys");
+            return new LeaveAuthResourceBundle(persistedResourceInfoList, List.of(), List.of(), 0, "persistedResourceKeys");
+        }
+
+        List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
+        if (result != null)
+            result.put("resourceResolveSource", "currentActiveMjd");
+        return buildLeaveAuthResourceBundle(hkConnParm, resourceSourceList);
+    }
+
+    /**
+     * 2026-06-10:门禁设备映射改成带 TTL 的本地缓存,减少临近开始时每次请假都全量查海康设备。
+     */
+    private static List<Map<String, Object>> loadAcsDeviceListWithCache(Map<String, Object> hkConnParm) throws Exception {
+        long nowMs = System.currentTimeMillis();
+        int cacheMinutes = Math.max(1, rdIntCfg("hk.leaveAuth.acsDeviceCacheMinutes",
+                "HK_LEAVE_AUTH_ACS_DEVICE_CACHE_MINUTES", HK_DEF_ACS_DEVICE_CACHE_MINUTES));
+        AcsDeviceCacheSnapshot snapshot = ACS_DEVICE_CACHE;
+        if (snapshot != null && snapshot.isFresh(nowMs, cacheMinutes))
+            return snapshot.deviceList;
+
+        synchronized (ACS_DEVICE_CACHE_LOCK) {
+            snapshot = ACS_DEVICE_CACHE;
+            if (snapshot != null && snapshot.isFresh(nowMs, cacheMinutes))
+                return snapshot.deviceList;
+            try {
+                List<Map<String, Object>> deviceList = List.copyOf(new ArrayList<>(HK_API_CLIENT.loadAcsDeviceList(hkConnParm)));
+                ACS_DEVICE_CACHE = new AcsDeviceCacheSnapshot(deviceList, nowMs);
+                return deviceList;
+            } catch (Exception e) {
+                if (snapshot != null && !snapshot.deviceList.isEmpty()) {
+                    log4j.warn("HkLeaveAuthServ.loadAcsDeviceListWithCache() 刷新海康设备缓存失败,改用旧缓存:{}", e.getMessage());
+                    return snapshot.deviceList;
+                }
+                throw e;
+            }
+        }
     }
 
     /**
@@ -1448,12 +1701,15 @@ public class HkLeaveAuthServ extends Serv {
         if (!isHkRespAccepted(configAddResp)) {
             result.put("ok", false);
             result.put("msg", "海康平台未受理权限配置请求。");
+            markLeaveAuthStagePending(result, ctx, "pending", new Timestamp(System.currentTimeMillis()), false, 0);
             persistLeaveAuthSyncResult(gdba, ctx, result);
             return result;
         }
 
         String configTaskId = rdTaskId(configAddResp);
         result.put("configTaskId", configTaskId);
+        if (StringUtils.isBlank(rdStr(result.get("firstAcceptTime"))))
+            result.put("firstAcceptTime", makeHkTime(new Timestamp(System.currentTimeMillis())));
         if (StringUtils.isNotBlank(configTaskId)) {
             Map<String, Object> configRateReq = Map.of("taskId", configTaskId);
             result.put("authConfigRateReq", configRateReq);
@@ -1476,6 +1732,13 @@ public class HkLeaveAuthServ extends Serv {
         }
 
         finalizePlatformConfigResult(result, ctx.kssj, ctx.jssj, resourceInfoList.size());
+        if (rdBoolLike(result.get("platformConfigConfirmed")) || rdBoolLike(result.get("configSearchMatched"))) {
+            markLeaveAuthStageConfirmed(result, ctx, new Timestamp(System.currentTimeMillis()));
+        } else {
+            markLeaveAuthStagePending(result, ctx, "accepted", new Timestamp(System.currentTimeMillis()),
+                    false, rdIntCfg("hk.leaveAuth.pending.retryDelaySeconds", "HK_LEAVE_AUTH_PENDING_RETRY_DELAY_SECONDS",
+                            HK_DEF_PENDING_RETRY_DELAY_SECONDS));
+        }
         logExecute(ctx, personInfo, configAddReq, configAddResp);
         persistLeaveAuthSyncResult(gdba, ctx, result);
         return result;
@@ -1951,6 +2214,7 @@ public class HkLeaveAuthServ extends Serv {
             result.put("mode", "autoError");
             result.put("skipReason", "自动同步执行异常。");
             result.put("msg", makeExceptionMsg(e));
+            markLeaveAuthStagePending(result, ctx, "pending", new Timestamp(System.currentTimeMillis()), false, 0);
             persistLeaveAuthSyncResult(gdba, ctx, result);
             gdba.commit();
         } catch (Exception persistEx) {
@@ -1987,6 +2251,13 @@ public class HkLeaveAuthServ extends Serv {
         putLeaveAuthPersistField(fieldMap, "expectedConfigCount", rdStr(result.get("expectedConfigCount")));
         putLeaveAuthPersistField(fieldMap, "matchedConfigCount", rdStr(result.get("matchedConfigCount")));
         putLeaveAuthPersistField(fieldMap, "configTaskId", rdStr(result.get("configTaskId")));
+        replaceLeaveAuthPersistField(fieldMap, "syncStage", rdStr(result.get("syncStage")));
+        replaceLeaveAuthPersistField(fieldMap, "retryCount", rdStr(result.get("retryCount")));
+        replaceLeaveAuthPersistField(fieldMap, "nextRetryTime", rdStr(result.get("nextRetryTime")));
+        replaceLeaveAuthPersistField(fieldMap, "firstAcceptTime", rdStr(result.get("firstAcceptTime")));
+        replaceLeaveAuthPersistField(fieldMap, "platformConfirmTime", rdStr(result.get("platformConfirmTime")));
+        replaceLeaveAuthPersistField(fieldMap, "lastError", rdStr(result.get("lastError")));
+        replaceLeaveAuthPersistField(fieldMap, "totalCostMs", rdStr(result.get("totalCostMs")));
         putLeaveAuthPersistField(fieldMap, "deleteTime", rdStr(result.get("deleteTime")));
         putLeaveAuthPersistField(fieldMap, "deleteMode", rdStr(result.get("deleteMode")));
         putLeaveAuthPersistField(fieldMap, "deleteConfirmed", rdStr(result.get("deleteConfirmed")));
@@ -2133,6 +2404,19 @@ public class HkLeaveAuthServ extends Serv {
         fieldMap.put(fieldName, value);
     }
 
+    /**
+     * 2026-06-10:阶段字段允许显式清空,避免确认成功后仍残留旧的 nextRetryTime / lastError。
+     */
+    private static void replaceLeaveAuthPersistField(Map<String, String> fieldMap, String fieldName, String value) {
+        if (fieldMap == null || StringUtils.isBlank(fieldName))
+            return;
+        if (StringUtils.isBlank(value)) {
+            fieldMap.remove(fieldName);
+            return;
+        }
+        fieldMap.put(fieldName, value);
+    }
+
     /**
      * 2026-06-10:RC 摘要写完后顺手同步扩展表;若扩展表尚未建好,则只保留 RC 兼容摘要,不阻断主链路。
      */
@@ -2168,6 +2452,26 @@ public class HkLeaveAuthServ extends Serv {
         }
     }
 
+    /**
+     * 2026-06-10:扩展表阶段列允许晚于主表创建,代码侧先做存在性探测,避免未跑升级 SQL 时阻断主链路。
+     */
+    private static boolean ifLeaveAuthExtStageColsReady(Db gdba) {
+        if (gdba == null || !ifLeaveAuthExtTableReady(gdba))
+            return false;
+        try {
+            String sql = "select count(*) rowcnt from user_tab_columns where table_name=:tableName"
+                    + " and column_name in ('SYNC_STAGE','RETRY_COUNT','NEXT_RETRY_TIME','FIRST_ACCEPT_TIME',"
+                    + " 'PLATFORM_CONFIRM_TIME','LAST_ERROR','TOTAL_COST_MS')";
+            SqlCmd sqlCmd = new SqlCmd(sql);
+            sqlCmd.wrStrParm("tableName", HK_LEAVE_AUTH_EXT_TAB);
+            gdba.doSelByC(sqlCmd);
+            return gdba.rowNum > 0 && gdba.rdIntCol("rowcnt") >= 7;
+        } catch (Exception e) {
+            log4j.warn("HkLeaveAuthServ.ifLeaveAuthExtStageColsReady() 检测扩展字段异常", e);
+            return false;
+        }
+    }
+
     /**
      * 2026-06-10:把海康请假关键状态结构化 upsert 到 RCHKLA,后续查询优先走这张表而不是全文 like。
      */
@@ -2178,6 +2482,24 @@ public class HkLeaveAuthServ extends Serv {
         if (gdba == null || ctx == null || ctx.rcid <= 0 || fieldMap == null || fieldMap.isEmpty())
             return;
 
+        boolean stageColsReady = ifLeaveAuthExtStageColsReady(gdba);
+        String stageSelect = stageColsReady
+                ? ",:syncStage sync_stage,:retryCount retry_count,:nextRetryTime next_retry_time,"
+                + " :firstAcceptTime first_accept_time,:platformConfirmTime platform_confirm_time,"
+                + " :lastError last_error,:totalCostMs total_cost_ms"
+                : "";
+        String stageUpdate = stageColsReady
+                ? ",t.SYNC_STAGE=s.sync_stage,t.RETRY_COUNT=s.retry_count,t.NEXT_RETRY_TIME=s.next_retry_time,"
+                + " t.FIRST_ACCEPT_TIME=s.first_accept_time,t.PLATFORM_CONFIRM_TIME=s.platform_confirm_time,"
+                + " t.LAST_ERROR=s.last_error,t.TOTAL_COST_MS=s.total_cost_ms"
+                : "";
+        String stageInsertCols = stageColsReady
+                ? ",SYNC_STAGE,RETRY_COUNT,NEXT_RETRY_TIME,FIRST_ACCEPT_TIME,PLATFORM_CONFIRM_TIME,LAST_ERROR,TOTAL_COST_MS"
+                : "";
+        String stageInsertVals = stageColsReady
+                ? ",s.sync_stage,s.retry_count,s.next_retry_time,s.first_accept_time,s.platform_confirm_time,s.last_error,s.total_cost_ms"
+                : "";
+
         String sql = "merge into RCHKLA t using (select"
                 + " :rcid rcid,:syncMode sync_mode,:syncTime sync_time,:syncOk sync_ok,:syncMsg sync_msg,"
                 + " :personId person_id,:resourceKeys resource_keys,:resourceCount resource_count,"
@@ -2191,6 +2513,7 @@ public class HkLeaveAuthServ extends Serv {
                 + " :downloadResultConfirmed download_result_confirmed,"
                 + " :downloadCallbackReceived download_callback_received,:callbackTaskId callback_task_id,"
                 + " :callbackRecvTime callback_recv_time,:wcmswjSnapshot wcmswj_snapshot,:updatedAt updated_at"
+                + stageSelect
                 + " from dual) s on (t.RCID=s.RCID)"
                 + " when matched then update set"
                 + " t.SYNC_MODE=s.sync_mode,t.SYNC_TIME=s.sync_time,t.SYNC_OK=s.sync_ok,t.SYNC_MSG=s.sync_msg,"
@@ -2208,20 +2531,23 @@ public class HkLeaveAuthServ extends Serv {
                 + " t.DOWNLOAD_CALLBACK_RECEIVED=s.download_callback_received,"
                 + " t.CALLBACK_TASK_ID=s.callback_task_id,t.CALLBACK_RECV_TIME=s.callback_recv_time,"
                 + " t.WCMSWJ_SNAPSHOT=s.wcmswj_snapshot,t.UPDATED_AT=s.updated_at"
+                + stageUpdate
                 + " when not matched then insert"
                 + " (RCID,SYNC_MODE,SYNC_TIME,SYNC_OK,SYNC_MSG,PERSON_ID,RESOURCE_KEYS,RESOURCE_COUNT,"
                 + " PLATFORM_CONFIG_CONFIRMED,PLATFORM_CONFIRM_SOURCE,CONFIG_SEARCH_MATCHED,"
                 + " EXPECTED_CONFIG_COUNT,MATCHED_CONFIG_COUNT,CONFIG_TASK_ID,DELETE_TIME,DELETE_MODE,"
                 + " DELETE_CONFIRMED,DELETE_CONFIRM_SOURCE,DELETE_TASK_ACCEPTED,DELETE_TASK_ID,DELETE_SKIP_REASON,"
                 + " DOWNLOAD_TASK_ID,DOWNLOAD_TASK_SOURCE,DOWNLOAD_RESULT_CONFIRMED,DOWNLOAD_CALLBACK_RECEIVED,"
-                + " CALLBACK_TASK_ID,CALLBACK_RECV_TIME,WCMSWJ_SNAPSHOT,UPDATED_AT)"
+                + " CALLBACK_TASK_ID,CALLBACK_RECV_TIME,WCMSWJ_SNAPSHOT,UPDATED_AT"
+                + stageInsertCols + ")"
                 + " values"
                 + " (s.rcid,s.sync_mode,s.sync_time,s.sync_ok,s.sync_msg,s.person_id,s.resource_keys,s.resource_count,"
                 + " s.platform_config_confirmed,s.platform_confirm_source,s.config_search_matched,"
                 + " s.expected_config_count,s.matched_config_count,s.config_task_id,s.delete_time,s.delete_mode,"
                 + " s.delete_confirmed,s.delete_confirm_source,s.delete_task_accepted,s.delete_task_id,s.delete_skip_reason,"
                 + " s.download_task_id,s.download_task_source,s.download_result_confirmed,s.download_callback_received,"
-                + " s.callback_task_id,s.callback_recv_time,s.wcmswj_snapshot,s.updated_at)";
+                + " s.callback_task_id,s.callback_recv_time,s.wcmswj_snapshot,s.updated_at"
+                + stageInsertVals + ")";
         SqlCmd sqlCmd = new SqlCmd(sql);
         sqlCmd.wrLongParm("rcid", ctx.rcid);
         sqlCmd.wrStrParm("syncMode", fieldMap.get("mode"));
@@ -2252,6 +2578,15 @@ public class HkLeaveAuthServ extends Serv {
         sqlCmd.wrTimeParm("callbackRecvTime", rdLeaveAuthPersistTime(fieldMap.get("callbackRecvTime")));
         sqlCmd.wrStrParm("wcmswjSnapshot", StringUtils.defaultIfBlank(snapshotText, ctx.wcmswj));
         sqlCmd.wrTimeParm("updatedAt", new Timestamp(System.currentTimeMillis()));
+        if (stageColsReady) {
+            sqlCmd.wrStrParm("syncStage", fieldMap.get("syncStage"));
+            sqlCmd.wrIntParm("retryCount", rdLeaveAuthPersistInt(fieldMap.get("retryCount")));
+            sqlCmd.wrTimeParm("nextRetryTime", rdLeaveAuthPersistTime(fieldMap.get("nextRetryTime")));
+            sqlCmd.wrTimeParm("firstAcceptTime", rdLeaveAuthPersistTime(fieldMap.get("firstAcceptTime")));
+            sqlCmd.wrTimeParm("platformConfirmTime", rdLeaveAuthPersistTime(fieldMap.get("platformConfirmTime")));
+            sqlCmd.wrStrParm("lastError", fieldMap.get("lastError"));
+            sqlCmd.wrLongParm("totalCostMs", rdLeaveAuthPersistLong(fieldMap.get("totalCostMs")));
+        }
         gdba.doModByC(sqlCmd);
     }
 
@@ -2293,6 +2628,20 @@ public class HkLeaveAuthServ extends Serv {
         }
     }
 
+    /**
+     * 2026-06-10:阶段耗时统一落 long,兼容确认耗时超过 int 范围的场景。
+     */
+    private static Long rdLeaveAuthPersistLong(String text) {
+        String value = rdStr(text);
+        if (StringUtils.isBlank(value))
+            return null;
+        try {
+            return Long.valueOf(value);
+        } catch (Exception ignored) {
+            return null;
+        }
+    }
+
     /**
      * 2026-06-01:把异常压成一行,既能定位错误类型,也不会把 RC 字段撑得过长。
      */
@@ -2382,6 +2731,13 @@ public class HkLeaveAuthServ extends Serv {
         putPersistedField(result, "configSearchMatched", rdLeaveAuthLogField(ctx, "configSearchMatched"));
         putPersistedField(result, "expectedConfigCount", rdLeaveAuthLogField(ctx, "expectedConfigCount"));
         putPersistedField(result, "matchedConfigCount", rdLeaveAuthLogField(ctx, "matchedConfigCount"));
+        putPersistedField(result, "syncStage", rdLeaveAuthLogField(ctx, "syncStage"));
+        putPersistedField(result, "retryCount", rdLeaveAuthLogField(ctx, "retryCount"));
+        putPersistedField(result, "nextRetryTime", rdLeaveAuthLogField(ctx, "nextRetryTime"));
+        putPersistedField(result, "firstAcceptTime", rdLeaveAuthLogField(ctx, "firstAcceptTime"));
+        putPersistedField(result, "platformConfirmTime", rdLeaveAuthLogField(ctx, "platformConfirmTime"));
+        putPersistedField(result, "lastError", rdLeaveAuthLogField(ctx, "lastError"));
+        putPersistedField(result, "totalCostMs", rdLeaveAuthLogField(ctx, "totalCostMs"));
         putPersistedField(result, "deleteTime", rdLeaveAuthLogField(ctx, "deleteTime"));
         putPersistedField(result, "deleteMode", rdLeaveAuthLogField(ctx, "deleteMode"));
         putPersistedField(result, "deleteConfirmed", rdLeaveAuthLogField(ctx, "deleteConfirmed"));
@@ -2416,6 +2772,115 @@ public class HkLeaveAuthServ extends Serv {
         putPersistedField(result, "callbackPersonDownloadResult", rdLeaveAuthLogField(ctx, "callbackPersonDownloadResult"));
     }
 
+    /**
+     * 2026-06-10:未完成的平台权限按 pending/accepted/retrying 记录阶段和下次补偿时间。
+     */
+    private static void markLeaveAuthStagePending(Map<String, Object> result,
+                                                  LeaveAuthSyncCtx ctx,
+                                                  String stage,
+                                                  Timestamp now,
+                                                  boolean incrementRetry,
+                                                  int retryDelaySeconds) {
+        if (result == null)
+            return;
+        result.put("syncStage", StringUtils.defaultIfBlank(stage, "pending"));
+
+        String firstAcceptTime = rdStr(result.get("firstAcceptTime"));
+        if (StringUtils.isBlank(firstAcceptTime))
+            firstAcceptTime = rdLeaveAuthLogField(ctx, "firstAcceptTime");
+        if (StringUtils.isBlank(firstAcceptTime)
+                && (StringUtils.isNotBlank(rdStr(result.get("configTaskId")))
+                || "accepted".equals(stage)
+                || "retrying".equals(stage)))
+            firstAcceptTime = makeHkTime(now == null ? new Timestamp(System.currentTimeMillis()) : now);
+        if (StringUtils.isNotBlank(firstAcceptTime))
+            result.put("firstAcceptTime", firstAcceptTime);
+
+        int retryCount = Math.max(rdInt(result.get("retryCount")), rdInt(rdLeaveAuthLogField(ctx, "retryCount")));
+        if (incrementRetry)
+            retryCount++;
+        result.put("retryCount", retryCount);
+
+        if (retryDelaySeconds > 0 && now != null)
+            result.put("nextRetryTime", makeHkTime(new Timestamp(now.getTime() + retryDelaySeconds * 1000L)));
+
+        if (!rdBoolLike(result.get("ok")) && StringUtils.isBlank(rdStr(result.get("lastError"))))
+            result.put("lastError", rdStr(result.get("msg")));
+        updateLeaveAuthTotalCost(result, ctx);
+    }
+
+    /**
+     * 2026-06-10:平台权限确认完成后清空补偿计划,并记录最终确认时间。
+     */
+    private static void markLeaveAuthStageConfirmed(Map<String, Object> result,
+                                                    LeaveAuthSyncCtx ctx,
+                                                    Timestamp now) {
+        if (result == null)
+            return;
+        Timestamp currentNow = now == null ? new Timestamp(System.currentTimeMillis()) : now;
+        result.put("syncStage", "confirmed");
+        if (StringUtils.isBlank(rdStr(result.get("firstAcceptTime")))) {
+            String firstAcceptTime = rdLeaveAuthLogField(ctx, "firstAcceptTime");
+            if (StringUtils.isNotBlank(firstAcceptTime))
+                result.put("firstAcceptTime", firstAcceptTime);
+        }
+        result.put("platformConfirmTime", StringUtils.defaultIfBlank(rdStr(result.get("platformConfirmTime")), makeHkTime(currentNow)));
+        result.put("nextRetryTime", "");
+        result.put("lastError", "");
+        result.put("retryCount", Math.max(rdInt(result.get("retryCount")), rdInt(rdLeaveAuthLogField(ctx, "retryCount"))));
+        updateLeaveAuthTotalCost(result, ctx);
+    }
+
+    /**
+     * 2026-06-10:权限回收成功后,状态切到 deleted,避免宿舍门权限清掉后仍被 pending 定时器误补。
+     */
+    private static void markLeaveAuthStageDeleted(Map<String, Object> result,
+                                                  LeaveAuthSyncCtx ctx,
+                                                  Timestamp now) {
+        if (result == null)
+            return;
+        result.put("syncStage", "deleted");
+        result.put("deleteTime", StringUtils.defaultIfBlank(rdStr(result.get("deleteTime")),
+                makeHkTime(now == null ? new Timestamp(System.currentTimeMillis()) : now)));
+        result.put("nextRetryTime", "");
+        result.put("lastError", "");
+        result.put("retryCount", Math.max(rdInt(result.get("retryCount")), rdInt(rdLeaveAuthLogField(ctx, "retryCount"))));
+        updateLeaveAuthTotalCost(result, ctx);
+    }
+
+    /**
+     * 2026-06-10:过期记录不再参与补偿。
+     */
+    private static void markLeaveAuthStageExpired(Map<String, Object> result, Timestamp now) {
+        if (result == null)
+            return;
+        result.put("syncStage", "expired");
+        result.put("nextRetryTime", "");
+        if (StringUtils.isBlank(rdStr(result.get("platformConfirmTime"))) && StringUtils.isBlank(rdStr(result.get("firstAcceptTime"))))
+            result.put("platformConfirmTime", "");
+        if (StringUtils.isBlank(rdStr(result.get("lastError"))) && !rdBoolLike(result.get("ok")))
+            result.put("lastError", rdStr(result.get("msg")));
+        if (now != null)
+            result.put("syncTime", makeHkTime(now));
+    }
+
+    /**
+     * 2026-06-10:总耗时统一按“首次受理 -> 平台确认”计算,便于后续排查 5 分钟空窗。
+     */
+    private static void updateLeaveAuthTotalCost(Map<String, Object> result, LeaveAuthSyncCtx ctx) {
+        if (result == null)
+            return;
+        String firstAcceptTime = StringUtils.defaultIfBlank(rdStr(result.get("firstAcceptTime")),
+                rdLeaveAuthLogField(ctx, "firstAcceptTime"));
+        String platformConfirmTime = StringUtils.defaultIfBlank(rdStr(result.get("platformConfirmTime")),
+                rdLeaveAuthLogField(ctx, "platformConfirmTime"));
+        Timestamp firstTs = rdLeaveAuthPersistTime(firstAcceptTime);
+        Timestamp confirmTs = rdLeaveAuthPersistTime(platformConfirmTime);
+        if (firstTs == null || confirmTs == null || confirmTs.before(firstTs))
+            return;
+        result.put("totalCostMs", confirmTs.getTime() - firstTs.getTime());
+    }
+
     /**
      * 2026-06-10:删除链路优先复用新增时已落库的资源键,避免因为门禁映射变化误删其他资源。
      */
@@ -2443,7 +2908,7 @@ public class HkLeaveAuthServ extends Serv {
         result.put("resourceSourceCount", resourceBundle.resourceSourceList.size());
         result.put("resourceMappedCount", resourceBundle.resourceInfoList.size());
         result.put("hkAcsDeviceCount", resourceBundle.hkAcsDeviceCount);
-        result.put("resourceMapMode", "acsDeviceSearchByNameAndChannel");
+        result.put("resourceMapMode", resourceBundle.resourceMapMode);
         if (!resourceBundle.unmappedSourceList.isEmpty()) {
             result.put("ok", false);
             result.put("msg", "历史请假记录未保留 resourceKeys,且当前门禁点映射不完整,无法安全执行 delete。");
@@ -2816,6 +3281,61 @@ public class HkLeaveAuthServ extends Serv {
         return ctxList;
     }
 
+    /**
+     * 2026-06-10:挑选“临近开始或已开始、尚未确认”的请假记录,专供每分钟补偿任务使用。
+     * 这里统一使用 Java 当前时间绑定参数,避免数据库 sysdate 为 UTC 时造成时间窗偏移。
+     */
+    private static List<LeaveAuthSyncCtx> selPendingPlatformConfigCtxList(Db gdba,
+                                                                          Timestamp now,
+                                                                          Timestamp windowEnd,
+                                                                          int limit) throws Exception {
+        if (gdba == null || now == null || windowEnd == null)
+            return List.of();
+        boolean extTableReady = ifLeaveAuthExtTableReady(gdba);
+        String baseSelect = " 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";
+        String baseJoin = " from RC rc"
+                + " join RY ry on ry.RYID=rc.FZRYID";
+        if (extTableReady)
+            baseJoin += " left join RCHKLA ext on ext.RCID=rc.RCID";
+
+        String sql = "select * from (" + baseSelect + baseJoin
+                + " where rc.RCLBM in(" + biz.rc.RcC.RCLB_sj + "," + biz.rc.RcC.RCLB_bj + ")"
+                + " and rc.KSSJ is not null and rc.JSSJ is not null"
+                + " and rc.JSSJ>:nowTs"
+                + " and rc.KSSJ<=:windowEndTs";
+        if (extTableReady) {
+            sql += " and ("
+                    + " (ext.RCID is not null"
+                    + " and nvl(ext.DELETE_CONFIRMED,0)=0"
+                    + " and (nvl(ext.PLATFORM_CONFIG_CONFIRMED,0)=0 or nvl(ext.CONFIG_SEARCH_MATCHED,0)=0))"
+                    + " or (ext.RCID is null"
+                    + " and nvl(rc.WCMSWJ,' ') not like '%platformConfigConfirmed=true%'"
+                    + " and nvl(rc.WCMSWJ,' ') not like '%configSearchMatched=true%'"
+                    + " and nvl(rc.WCMSWJ,' ') not like '%deleteConfirmed=true%')"
+                    + " )";
+        } else {
+            sql += " and nvl(rc.WCMSWJ,' ') not like '%platformConfigConfirmed=true%'"
+                    + " and nvl(rc.WCMSWJ,' ') not like '%configSearchMatched=true%'"
+                    + " and nvl(rc.WCMSWJ,' ') not like '%deleteConfirmed=true%'";
+        }
+        sql += " order by rc.KSSJ asc,rc.RCID asc"
+                + " ) where rownum<=:limit";
+
+        SqlCmd sqlCmd = new SqlCmd(sql);
+        sqlCmd.wrTimeParm("nowTs", now);
+        sqlCmd.wrTimeParm("windowEndTs", windowEnd);
+        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(buildLeaveAuthSyncCtx(row));
+        return ctxList;
+    }
+
     /**
      * 2026-06-10:最近执行记录优先读扩展表,兼容 delete/recycle 后 mode 被覆盖的场景。
      */
@@ -2958,8 +3478,7 @@ public class HkLeaveAuthServ extends Serv {
             }
         }
 
-        List<Map<String, Object>> resourceSourceList = selAllActiveMjdList(gdba);
-        LeaveAuthResourceBundle resourceBundle = buildLeaveAuthResourceBundle(hkConnParm, resourceSourceList);
+        LeaveAuthResourceBundle resourceBundle = resolveSyncResourceBundle(gdba, hkConnParm, ctx, result);
         List<Map<String, Object>> resourceInfoList = resourceBundle.resourceInfoList;
         result.put("resourceSourceList", resourceBundle.resourceSourceList);
         result.put("resourceUnmappedList", resourceBundle.unmappedSourceList);
@@ -2969,7 +3488,7 @@ public class HkLeaveAuthServ extends Serv {
         result.put("resourceSourceCount", resourceBundle.resourceSourceList.size());
         result.put("resourceMappedCount", resourceInfoList.size());
         result.put("hkAcsDeviceCount", resourceBundle.hkAcsDeviceCount);
-        result.put("resourceMapMode", "acsDeviceSearchByNameAndChannel");
+        result.put("resourceMapMode", resourceBundle.resourceMapMode);
         if (!resourceBundle.unmappedSourceList.isEmpty()) {
             result.put("ok", false);
             result.put("msg", makeResourceMapErrorMsg(resourceBundle.unmappedSourceList));
@@ -4518,6 +5037,26 @@ public class HkLeaveAuthServ extends Serv {
         row.put(key, value);
     }
 
+    /**
+     * 2026-06-10:缓存最近一次海康门禁设备清单,降低临近开始补偿时的接口压力。
+     */
+    private static final class AcsDeviceCacheSnapshot {
+        private final List<Map<String, Object>> deviceList;
+        private final long fetchTimeMs;
+
+        private AcsDeviceCacheSnapshot(List<Map<String, Object>> deviceList, long fetchTimeMs) {
+            this.deviceList = deviceList == null ? List.of() : deviceList;
+            this.fetchTimeMs = fetchTimeMs;
+        }
+
+        private boolean isFresh(long nowMs, int cacheMinutes) {
+            if (deviceList == null || deviceList.isEmpty())
+                return false;
+            long ttlMs = Math.max(1, cacheMinutes) * 60_000L;
+            return nowMs - fetchTimeMs < ttlMs;
+        }
+    }
+
     /**
      * 2026-06-08:封装一次请假资源映射结果,避免调用方分别维护“原始门禁点 / 已映射资源 / 未映射资源”三套列表。
      */
@@ -4526,15 +5065,18 @@ public class HkLeaveAuthServ extends Serv {
         private final List<Map<String, Object>> resourceSourceList;
         private final List<Map<String, Object>> unmappedSourceList;
         private final int hkAcsDeviceCount;
+        private final String resourceMapMode;
 
         private LeaveAuthResourceBundle(List<Map<String, Object>> resourceInfoList,
                                         List<Map<String, Object>> resourceSourceList,
                                         List<Map<String, Object>> unmappedSourceList,
-                                        int hkAcsDeviceCount) {
+                                        int hkAcsDeviceCount,
+                                        String resourceMapMode) {
             this.resourceInfoList = resourceInfoList == null ? List.of() : resourceInfoList;
             this.resourceSourceList = resourceSourceList == null ? List.of() : resourceSourceList;
             this.unmappedSourceList = unmappedSourceList == null ? List.of() : unmappedSourceList;
             this.hkAcsDeviceCount = hkAcsDeviceCount;
+            this.resourceMapMode = StringUtils.defaultIfBlank(resourceMapMode, "acsDeviceSearchByNameAndChannel");
         }
     }
 

+ 1 - 0
web/cfg/biz/kq/hkkq.serv.xml

@@ -20,6 +20,7 @@
 	<serv name="hkkq_leave_auth_delete" desc="海康请假权限删除" clazz="biz.kq.HkLeaveAuthServ" func="executeLeaveAuthDelete" auth="true"/>
 	<serv name="hkkq_leave_auth_result" desc="海康请假权限下发结果查询" clazz="biz.kq.HkLeaveAuthServ" func="viewLeaveAuthSyncResult" auth="true"/>
 	<serv name="hkkq_leave_auth_backfill_ext" desc="海康请假权限扩展表回填" clazz="biz.kq.HkLeaveAuthServ" func="backfillLeaveAuthExt" auth="true"/>
+	<serv name="hkkq_leave_auth_pending" desc="海康请假权限临近开始补偿" clazz="biz.kq.HkLeaveAuthServ" func="syncPendingLeaveAuth" pub="true"/>
 	<serv name="hkkq_leave_auth_recycle" desc="海康请假权限到期回收" clazz="biz.kq.HkLeaveAuthServ" func="recycleExpiredLeaveAuth" pub="true"/>
 	<serv name="hkkq_leave_auth_download_push" desc="海康请假权限下载回调" clazz="biz.kq.HkLeaveAuthServ" func="recvLeaveAuthDownloadPush" pub="true"/>
 	<serv name="hkkq_event_push" desc="海康事件订阅回调" clazz="biz.kq.HkKqServ" func="recvHkEventPush" pub="true"/>

+ 1 - 0
web/cfg/biz/kq/hkkq.timer.xml

@@ -8,6 +8,7 @@
 	<timer name="hkkqEveningPlan" desc="海康晚修迟到兜底汇总" trigger="0 0 20 * * ?" serv="hkkq_timer_plan" parm='{"planCode":"wx"}'/>
 	<timer name="hkkqNightStartPlan" desc="海康归寝20点未归基线(20:40触发)" trigger="0 40 20 * * ?" serv="hkkq_timer_plan" parm='{"planCode":"gq2000"}'/>
 	<timer name="hkkqNightFirstPlan" desc="海康归寝第一次未归兜底" trigger="0 31 21 * * ?" serv="hkkq_timer_plan" parm='{"planCode":"gq2131"}'/>
+	<timer name="hkkqLeaveAuthPendingPlan" desc="海康请假权限临近开始补偿" trigger="0 0/1 * * * ?" serv="hkkq_leave_auth_pending"/>
 	<timer name="hkkqLeaveAuthRecyclePlan" desc="海康请假权限到期回收" trigger="0 0/5 * * * ?" serv="hkkq_leave_auth_recycle"/>
 	<!--<timer name="hkkqNightFinalPlan" desc="海康归寝最终未归兜底" trigger="59 59 23 * * ?" serv="hkkq_timer_plan" parm='{"planCode":"gq235959"}'/>-->
 </timers>