From 34dfd46e2218d94fd822a71fd7cb546ffbfa187a Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Mon, 23 Nov 2026 09:57:37 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E9=99=90=E5=88=B6OA=E5=AE=A1=E6=89=B9?= =?UTF-8?q?=E5=90=8C=E6=AD=A5API=E8=B0=83=E7=94=A8=E9=A2=91=E7=8E=87=20(#1?= =?UTF-8?q?355)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Services/Auth/DingTalkOAuthClient.php | 114 ++++++---- config/dingtalk.php | 7 +- config/upstream_mirrors.php | 6 +- deploy/activate-incremental-release.sh | 5 +- deploy/activate-release.sh | 5 +- .../DingProcessDetailMirrorRepository.php | 6 +- .../DingProcessDetailMirrorSynchronizer.php | 197 ++++++++++++++---- .../DingTalkProcessInstanceClient.php | 3 +- .../Services/FinanceLedgerRptSynchronizer.php | 2 +- scripts/install-ding-process-sync-cron.ps1 | 2 +- tests/Feature/Auth/DingTalkLoginTest.php | 27 +++ .../Deployment/BusinessMirrorScheduleTest.php | 2 +- .../DingProcessDetailMirrorRepositoryTest.php | 1 + ...ingProcessDetailMirrorSynchronizerTest.php | 113 +++++++++- 14 files changed, 391 insertions(+), 99 deletions(-) diff --git a/app/Services/Auth/DingTalkOAuthClient.php b/app/Services/Auth/DingTalkOAuthClient.php index acc9ada6..faa17a6e 100644 --- a/app/Services/Auth/DingTalkOAuthClient.php +++ b/app/Services/Auth/DingTalkOAuthClient.php @@ -3,6 +3,7 @@ namespace App\Services\Auth; use Illuminate\Http\Client\RequestException; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Http; use RuntimeException; @@ -118,55 +119,90 @@ class DingTalkOAuthClient throw new RuntimeException('DingTalk enterprise lookup requires a union id.'); } - $appToken = $this->appAccessToken(); + $enterpriseProfile = Cache::remember( + 'dingtalk:enterprise-user:' . hash('sha256', $unionId), + now()->addMinutes(max( + 1, + (int) config('dingtalk.enterprise_user_cache_minutes', 10), + )), + function () use ($unionId, $oauthProfile): array { + $appToken = $this->appAccessToken(); - try { - $userIdResponse = Http::asJson() - ->acceptJson() - ->timeout($this->timeout()) - ->withQueryParameters(['access_token' => $appToken]) - ->post($this->configuredString('dingtalk.user_by_union_id_url'), ['unionid' => $unionId]) - ->throw(); - } catch (RequestException $exception) { - throw new RuntimeException('DingTalk enterprise user lookup failed.', 0, $exception); - } + try { + $userIdResponse = Http::asJson() + ->acceptJson() + ->timeout($this->timeout()) + ->withQueryParameters(['access_token' => $appToken]) + ->post( + $this->configuredString('dingtalk.user_by_union_id_url'), + ['unionid' => $unionId], + ) + ->throw(); + } catch (RequestException $exception) { + throw new RuntimeException( + 'DingTalk enterprise user lookup failed.', + 0, + $exception, + ); + } - $userId = trim((string) $userIdResponse->json('result.userid')); - if ((int) $userIdResponse->json('errcode', -1) !== 0 || $userId === '') { - throw new RuntimeException('DingTalk identity is not an enterprise user.'); - } + $userId = trim((string) $userIdResponse->json('result.userid')); + if ((int) $userIdResponse->json('errcode', -1) !== 0 || $userId === '') { + throw new RuntimeException('DingTalk identity is not an enterprise user.'); + } - try { - $detailResponse = Http::asJson() - ->acceptJson() - ->timeout($this->timeout()) - ->withQueryParameters(['access_token' => $appToken]) - ->post($this->configuredString('dingtalk.user_detail_url'), ['userid' => $userId]) - ->throw(); - } catch (RequestException $exception) { - throw new RuntimeException('DingTalk enterprise user detail lookup failed.', 0, $exception); - } + try { + $detailResponse = Http::asJson() + ->acceptJson() + ->timeout($this->timeout()) + ->withQueryParameters(['access_token' => $appToken]) + ->post( + $this->configuredString('dingtalk.user_detail_url'), + ['userid' => $userId], + ) + ->throw(); + } catch (RequestException $exception) { + throw new RuntimeException( + 'DingTalk enterprise user detail lookup failed.', + 0, + $exception, + ); + } - $detail = $detailResponse->json('result'); - if ((int) $detailResponse->json('errcode', -1) !== 0 || ! is_array($detail)) { - throw new RuntimeException('DingTalk enterprise user detail was unavailable.'); - } + $detail = $detailResponse->json('result'); + if ((int) $detailResponse->json('errcode', -1) !== 0 || ! is_array($detail)) { + throw new RuntimeException('DingTalk enterprise user detail was unavailable.'); + } - $detailUserId = trim((string) ($detail['userid'] ?? '')); - if ($detailUserId !== '' && ! hash_equals($userId, $detailUserId)) { - throw new RuntimeException('DingTalk enterprise user identity was inconsistent.'); - } + $detailUserId = trim((string) ($detail['userid'] ?? '')); + if ($detailUserId !== '' && ! hash_equals($userId, $detailUserId)) { + throw new RuntimeException( + 'DingTalk enterprise user identity was inconsistent.', + ); + } - $active = filter_var($detail['active'] ?? null, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE); + $active = filter_var( + $detail['active'] ?? null, + FILTER_VALIDATE_BOOL, + FILTER_NULL_ON_FAILURE, + ); + + return [ + 'dingtalk_user_id' => $userId, + 'nickname' => $this->nullableString( + $detail['name'] ?? ($oauthProfile['nickname'] ?? null), + ), + 'email' => $this->nullableString($detail['email'] ?? null), + 'mobile' => $this->nullableString($detail['mobile'] ?? null), + 'active' => $active === true, + ]; + }, + ); return [ 'union_id' => $unionId, 'open_id' => $oauthProfile['open_id'] ?? null, - 'dingtalk_user_id' => $userId, - 'nickname' => $this->nullableString($detail['name'] ?? ($oauthProfile['nickname'] ?? null)), - 'email' => $this->nullableString($detail['email'] ?? null), - 'mobile' => $this->nullableString($detail['mobile'] ?? null), - 'active' => $active === true, + ...$enterpriseProfile, ]; } diff --git a/config/dingtalk.php b/config/dingtalk.php index 3cd80627..7df410f3 100644 --- a/config/dingtalk.php +++ b/config/dingtalk.php @@ -41,7 +41,12 @@ return [ 'user_detail_url' => env('DINGTALK_USER_DETAIL_URL', 'https://oapi.dingtalk.com/topapi/v2/user/get'), 'timeout' => (int) env('DINGTALK_HTTP_TIMEOUT', 10), - 'process_concurrency' => (int) env('DINGTALK_PROCESS_CONCURRENCY', 5), + 'process_concurrency' => (int) env('DINGTALK_PROCESS_CONCURRENCY', 2), + // 同一企业用户短时间重复登录时复用详情,避免 /v2/user/get 被重复回调放大。 + 'enterprise_user_cache_minutes' => max( + (int) env('DINGTALK_ENTERPRISE_USER_CACHE_MINUTES', 10), + 1 + ), 'state_ttl_minutes' => (int) env('DINGTALK_STATE_TTL_MINUTES', 5), 'card' => [ diff --git a/config/upstream_mirrors.php b/config/upstream_mirrors.php index d07b760b..900d9951 100644 --- a/config/upstream_mirrors.php +++ b/config/upstream_mirrors.php @@ -36,8 +36,12 @@ return [ 'scope' => env('DING_PROCESS_DETAILS_SCOPE', 'personal_permission'), 'start_date' => env('DING_PROCESS_DETAILS_START_DATE', '2026-01-01'), 'batch_size' => (int) env('DING_PROCESS_DETAILS_BATCH_SIZE', 150), - 'sync_interval_minutes' => (int) env('DING_PROCESS_DETAILS_SYNC_MINUTES', 5), + 'sync_interval_minutes' => (int) env('DING_PROCESS_DETAILS_SYNC_MINUTES', 15), 'incremental_overlap_hours' => (int) env('DING_PROCESS_DETAILS_OVERLAP_HOURS', 48), + // 审批中的流程只在快照过期或上游确实发生变更时才再调用官方接口。 + 'approval_api_refresh_minutes' => (int) env('DING_PROCESS_DETAILS_API_REFRESH_MINUTES', 60), + // 单轮最多调用多少个审批实例,避免积压时一次性打满钉钉额度。 + 'approval_api_calls_per_run' => (int) env('DING_PROCESS_DETAILS_API_CALLS_PER_RUN', 160), 'processes' => [ 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F' => [ 'kind' => 'daily', diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index ac54f987..1f15c500 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -266,11 +266,12 @@ CRON_TZ=Asia/Shanghai EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots -# OA 流程明细单独使用 5 分钟增量任务,避免被共用上游锁中的分钟级任务长期饿死; +# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转, +# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。 # 每周全量校准仍保留在上面的主计划中。 cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' CRON_TZ=Asia/Shanghai -2-59/5 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 +2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 # OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1 EOF diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index f4a0bfda..65b34add 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -270,11 +270,12 @@ CRON_TZ=Asia/Shanghai EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots -# OA 流程明细单独使用 5 分钟增量任务,避免被共用上游锁中的分钟级任务长期饿死; +# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转, +# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。 # 每周全量校准仍保留在上面的主计划中。 cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' CRON_TZ=Asia/Shanghai -2-59/5 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 +2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 # OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1 EOF diff --git a/modules/EcommerceFinance/Repositories/DingProcessDetailMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingProcessDetailMirrorRepository.php index 62208350..7f10f43b 100644 --- a/modules/EcommerceFinance/Repositories/DingProcessDetailMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/DingProcessDetailMirrorRepository.php @@ -176,7 +176,7 @@ class DingProcessDetailMirrorRepository $state = $this->state(); $staleAfterMinutes = max( 15, - (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 5) * 3, + (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 15) * 3, ); return [ @@ -306,7 +306,7 @@ class DingProcessDetailMirrorRepository $state = $this->state(); $staleAfterMinutes = max( 15, - (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 5) * 3, + (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 15) * 3, ); return [ @@ -434,7 +434,7 @@ class DingProcessDetailMirrorRepository $state = $this->state(); $staleAfterMinutes = max( 15, - (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 5) * 3, + (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 15) * 3, ); return [ diff --git a/modules/EcommerceFinance/Services/DingProcessDetailMirrorSynchronizer.php b/modules/EcommerceFinance/Services/DingProcessDetailMirrorSynchronizer.php index a774bf79..4f4ba2b8 100644 --- a/modules/EcommerceFinance/Services/DingProcessDetailMirrorSynchronizer.php +++ b/modules/EcommerceFinance/Services/DingProcessDetailMirrorSynchronizer.php @@ -25,10 +25,6 @@ class DingProcessDetailMirrorSynchronizer private const SOURCE = 'operations_replica'; - private const APPROVAL_API_DRAIN_LIMIT = 750; - - private const APPROVAL_API_BACKLOG_BATCH_LIMIT = 750; - private const BUSINESS_ID_SYNC_LIMIT = 50; private readonly ConnectionInterface $connection; @@ -40,6 +36,9 @@ class DingProcessDetailMirrorSynchronizer /** @var array> */ private array $approvalSnapshots = []; + /** @var array */ + private array $approvalAttemptedProcessInstanceIds = []; + private bool $forceApprovalApiSnapshots = false; public function __construct( @@ -69,6 +68,7 @@ class DingProcessDetailMirrorSynchronizer $this->approvalApiAttempts = 0; $this->approvalApiAvailable = true; $this->approvalSnapshots = []; + $this->approvalAttemptedProcessInstanceIds = []; $this->forceApprovalApiSnapshots = false; $scope = $this->scope(); $state = $this->state(); @@ -183,6 +183,7 @@ class DingProcessDetailMirrorSynchronizer $this->approvalApiAttempts = 0; $this->approvalApiAvailable = $allowApprovalApi; $this->approvalSnapshots = []; + $this->approvalAttemptedProcessInstanceIds = []; $this->forceApprovalApiSnapshots = true; $scope = $this->scope(); $state = $this->state(); @@ -383,29 +384,13 @@ class DingProcessDetailMirrorSynchronizer $cursor = $this->stateCursor($state); $lastSchemeId = max(0, (int) ($cursor['scheme_high_watermark'] ?? 0)); $apiCursor = (string) ($cursor['approval_api_cursor'] ?? ''); - // 先消化历史待核实流程,避免本轮变更流程耗尽接口额度后补查游标永远不前进。 - $backlogIds = $this->approvalApiFallbackCandidates( - $apiCursor, - [], - self::APPROVAL_API_BACKLOG_BATCH_LIMIT, - ); - $result = $backlogIds === [] - ? null - : $this->extractApprovalApiWorkflows($backlogIds, $now); - if ($backlogIds !== []) { - $apiCursor = (string) $backlogIds[array_key_last($backlogIds)]; - } - - $incremental = $this->extractWorkflows( + $result = $this->extractWorkflows( $where, $bindings, $cursorExpression, 'sync_cursor', $now, ); - $result = $result === null - ? $incremental - : $this->mergeExtracted($result, $incremental); if ($lastSchemeId > 0) { $changedProcessIds = $this->schemeChangedProcessIds( @@ -427,16 +412,18 @@ class DingProcessDetailMirrorSynchronizer } } - $fallbackIds = $this->approvalApiFallbackCandidates( + // 上游刚变更的审批优先使用本轮的有限额度;剩余额度再轮转历史积压, + // 这样不会因为几百条旧流程排队而延迟当前审批人/出纳节点更新。 + $backlogIds = $this->approvalApiFallbackCandidates( $apiCursor, $result['process_instance_ids'], ); - if ($fallbackIds !== []) { + if ($backlogIds !== []) { $result = $this->mergeExtracted( $result, - $this->extractApprovalApiWorkflows($fallbackIds, $now), + $this->extractApprovalApiWorkflows($backlogIds, $now), ); - $apiCursor = (string) $fallbackIds[array_key_last($fallbackIds)]; + $apiCursor = (string) $backlogIds[array_key_last($backlogIds)]; } $result['metrics']['scheme_high_watermark'] = $schemeHighWatermark; @@ -521,7 +508,7 @@ class DingProcessDetailMirrorSynchronizer 'ding_process_detail_mirror', 'paid_at', ); - $remainingAttempts = self::APPROVAL_API_DRAIN_LIMIT - $this->approvalApiAttempts; + $remainingAttempts = $this->approvalApiCallsPerRun() - $this->approvalApiAttempts; if (! $this->approvalApiAvailable || $remainingAttempts <= 0) { return []; } @@ -532,10 +519,14 @@ class DingProcessDetailMirrorSynchronizer return []; } - $cashierStaleBefore = now()->subMinutes(15); + $cashierStaleBefore = now()->subMinutes($this->approvalApiRefreshMinutes()); $base = $this->connection->table('ding_process_detail_mirror') ->where('source_scope', $this->scope()) ->whereIn('status', ['审批中', '已完成']) + ->where(function ($freshness) use ($cashierStaleBefore): void { + $freshness->whereNull('cashier_checked_at') + ->orWhere('cashier_checked_at', '<', $cashierStaleBefore); + }) ->where(function ($query) use ( $cashierRefreshEnabled, $approverRefreshEnabled, @@ -1017,7 +1008,13 @@ class DingProcessDetailMirrorSynchronizer $processInstanceIds = []; $processes = (array) config('upstream_mirrors.ding_process_details.processes', []); $scope = $this->scope(); - $this->prefetchApprovalSnapshots($workflows, $scheme, $processes); + $approvalFreshness = $this->approvalSnapshotFreshness($workflows); + $this->prefetchApprovalSnapshots( + $workflows, + $scheme, + $processes, + $approvalFreshness, + ); foreach ($workflows as $workflow) { $processCode = trim((string) ($workflow['processCode'] ?? '')); @@ -1045,12 +1042,14 @@ class DingProcessDetailMirrorSynchronizer ); $needsCashierApi = $this->needsCashierApi($process, $workflow); $needsDetailAccountApi = $this->needsDetailAccountFallback($process, $fields); + $approvalSnapshotDue = $this->approvalSnapshotDue( + $workflow, + $approvalFreshness[$processInstanceId] ?? null, + ); $approvalSnapshot = null; - if ($needsPaymentApi - || $needsCashierApi - || $needsDetailAccountApi - || $status === '审批中' - || $this->forceApprovalApiSnapshots) { + if ($this->forceApprovalApiSnapshots + || (($needsPaymentApi || $needsCashierApi || $needsDetailAccountApi) + && $approvalSnapshotDue)) { $approvalSnapshot = $this->approvalApiSnapshot($workflow); } if ($needsPaymentApi && $approvalSnapshot !== null) { @@ -1070,7 +1069,11 @@ class DingProcessDetailMirrorSynchronizer $workflow = $this->reconcileOfficialWorkflowState($workflow, $approvalSnapshot); $status = $this->status($workflow); $cashierStatus = $this->cashierStatus($process, $workflow, $approvalSnapshot); - $cashierCheckedAt = $cashierStatus === 'pending_sync' ? null : $now; + $cashierCheckedAt = isset( + $this->approvalAttemptedProcessInstanceIds[$processInstanceId], + ) || $approvalSnapshot !== null + ? $now + : ($approvalFreshness[$processInstanceId] ?? null); $taskState = $this->taskState($approvalSnapshot, $employees); [$workflowDetails, $workflowAmountCents, $detailTableName] = $this->detailRows( @@ -1178,6 +1181,73 @@ class DingProcessDetailMirrorSynchronizer ]; } + /** + * @param list> $workflows + * @return array + */ + private function approvalSnapshotFreshness(array $workflows): array + { + if (! Schema::connection($this->connection->getName())->hasColumn( + 'ding_process_detail_mirror', + 'cashier_checked_at', + )) { + return []; + } + + $processInstanceIds = array_values(array_unique(array_filter(array_map( + static fn (array $workflow): string => trim((string) ( + $workflow['processInstanceId'] ?? '' + )), + $workflows, + )))); + if ($processInstanceIds === []) { + return []; + } + + $rows = $this->connection->table('ding_process_detail_mirror') + ->where('source_scope', $this->scope()) + ->whereIn('process_instance_id', $processInstanceIds) + ->whereNotNull('cashier_checked_at') + ->groupBy('process_instance_id') + ->select('process_instance_id') + ->selectRaw('MAX(cashier_checked_at) AS checked_at') + ->get(); + + $freshness = []; + foreach ($rows as $row) { + $processInstanceId = trim((string) ($row->process_instance_id ?? '')); + $checkedAt = OaProcessTime::parse($row->checked_at ?? null); + if ($processInstanceId !== '' && $checkedAt !== null) { + $freshness[$processInstanceId] = Carbon::instance($checkedAt); + } + } + + return $freshness; + } + + /** @param array $workflow */ + private function approvalSnapshotDue(array $workflow, mixed $checkedAt): bool + { + if (! $checkedAt instanceof Carbon) { + return true; + } + + if ($checkedAt->lessThanOrEqualTo( + now()->subMinutes($this->approvalApiRefreshMinutes()), + )) { + return true; + } + + foreach (['updateAt', 'finishTime'] as $field) { + $changedAt = OaProcessTime::parse($workflow[$field] ?? null); + if ($changedAt !== null && $changedAt->gt($checkedAt)) { + return true; + } + } + + return false; + } + /** * Warm the current-run snapshot cache in bounded parallel batches. The * later normalization pass reuses these snapshots without extra API calls. @@ -1185,17 +1255,19 @@ class DingProcessDetailMirrorSynchronizer * @param list> $workflows * @param array> $scheme * @param array> $processes + * @param array $approvalFreshness */ private function prefetchApprovalSnapshots( array $workflows, array $scheme, array $processes, + array $approvalFreshness, ): void { if (! $this->approvalClient->isConfigured() || ! $this->approvalApiAvailable) { return; } - $remainingAttempts = self::APPROVAL_API_DRAIN_LIMIT - $this->approvalApiAttempts; + $remainingAttempts = $this->approvalApiCallsPerRun() - $this->approvalApiAttempts; if ($remainingAttempts <= 0) { return; } @@ -1212,11 +1284,17 @@ class DingProcessDetailMirrorSynchronizer $fields = (array) ($scheme[$processInstanceId] ?? []); $paymentSourceState = $this->paymentSourceState($process, $fields); - if ($this->needsApprovalApiFallback($process, $fields, $paymentSourceState) - || $this->needsCashierApi($process, $workflow) - || $this->needsDetailAccountFallback($process, $fields) - || $this->status($workflow) === '审批中' - || $this->forceApprovalApiSnapshots) { + $needsSnapshot = $this->needsApprovalApiFallback( + $process, + $fields, + $paymentSourceState, + ) || $this->needsCashierApi($process, $workflow) + || $this->needsDetailAccountFallback($process, $fields); + if ($this->forceApprovalApiSnapshots + || ($needsSnapshot && $this->approvalSnapshotDue( + $workflow, + $approvalFreshness[$processInstanceId] ?? null, + ))) { $processInstanceIds[] = $processInstanceId; } } @@ -1243,6 +1321,9 @@ class DingProcessDetailMirrorSynchronizer } $this->approvalApiAttempts += (int) ($result['attempted'] ?? 0); + foreach ($processInstanceIds as $processInstanceId) { + $this->approvalAttemptedProcessInstanceIds[$processInstanceId] = true; + } foreach ((array) ($result['snapshots'] ?? []) as $processInstanceId => $snapshot) { if (is_array($snapshot)) { $this->approvalSnapshots[(string) $processInstanceId] = $snapshot; @@ -1738,11 +1819,12 @@ class DingProcessDetailMirrorSynchronizer } if (! $this->approvalClient->isConfigured() || ! $this->approvalApiAvailable - || $this->approvalApiAttempts >= self::APPROVAL_API_DRAIN_LIMIT) { + || $this->approvalApiAttempts >= $this->approvalApiCallsPerRun()) { return null; } $this->approvalApiAttempts++; + $this->approvalAttemptedProcessInstanceIds[$processInstanceId] = true; try { return $this->approvalSnapshots[$processInstanceId] = $this->approvalClient->processSnapshot($processInstanceId); @@ -2709,6 +2791,8 @@ class DingProcessDetailMirrorSynchronizer 'scheme_high_watermark' => (int) ($metrics['scheme_high_watermark'] ?? 0), 'approval_api_cursor' => (string) ($metrics['approval_api_cursor'] ?? ''), 'approval_api_attempts' => $this->approvalApiAttempts, + 'approval_api_limit' => $this->approvalApiCallsPerRun(), + 'approval_api_refresh_minutes' => $this->approvalApiRefreshMinutes(), ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), 'high_watermark' => null, 'window_started_at' => null, @@ -2785,7 +2869,7 @@ class DingProcessDetailMirrorSynchronizer } $minutes = max( 1, - (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 5), + (int) config('upstream_mirrors.ding_process_details.sync_interval_minutes', 15), ); $lastSucceededAt = OaProcessTime::parse($state['last_succeeded_at']); @@ -2796,6 +2880,35 @@ class DingProcessDetailMirrorSynchronizer ->lessThanOrEqualTo(OaProcessTime::now()); } + private function approvalApiRefreshMinutes(): int + { + return max( + 1, + (int) config( + 'upstream_mirrors.ding_process_details.approval_api_refresh_minutes', + 60, + ), + ); + } + + private function approvalApiCallsPerRun(): int + { + $configured = max( + 1, + min( + (int) config( + 'upstream_mirrors.ding_process_details.approval_api_calls_per_run', + 160, + ), + 750, + ), + ); + + return $this->forceApprovalApiSnapshots + ? max(self::BUSINESS_ID_SYNC_LIMIT, $configured) + : $configured; + } + /** @return array|null */ private function state(): ?array { diff --git a/modules/EcommerceFinance/Services/DingTalkProcessInstanceClient.php b/modules/EcommerceFinance/Services/DingTalkProcessInstanceClient.php index 2c45a49c..951e5954 100644 --- a/modules/EcommerceFinance/Services/DingTalkProcessInstanceClient.php +++ b/modules/EcommerceFinance/Services/DingTalkProcessInstanceClient.php @@ -136,7 +136,8 @@ class DingTalkProcessInstanceClient $errors = []; $fatal = false; $attempted = 0; - $concurrency = max(1, min(10, (int) config('dingtalk.process_concurrency', 5))); + // 当前钉钉应用已接近付费额度上限,单批并发硬限制为 2。 + $concurrency = max(1, min(2, (int) config('dingtalk.process_concurrency', 2))); foreach (array_chunk($pending, $concurrency) as $chunk) { $attempted += count($chunk); diff --git a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php index cad17009..f4f78dd2 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php @@ -433,7 +433,7 @@ class FinanceLedgerRptSynchronizer } /** - * 钉钉流程镜像每 5 分钟补齐付款行;财务台账优先使用这份最新付款事实。 + * 钉钉流程镜像每 15 分钟补齐结构化付款行;审批快照按 60 分钟限频刷新。 * * @param array> $workflows * @return array>> diff --git a/scripts/install-ding-process-sync-cron.ps1 b/scripts/install-ding-process-sync-cron.ps1 index e112c3a3..f4437524 100644 --- a/scripts/install-ding-process-sync-cron.ps1 +++ b/scripts/install-ding-process-sync-cron.ps1 @@ -16,7 +16,7 @@ if ($RemotePath -notmatch '^/[A-Za-z0-9._/-]+$') { $cron = @( 'CRON_TZ=Asia/Shanghai' '# Process details use a dedicated schedule and OA-only mirror lock.' - "2-59/5 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh $RemotePath/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1" + "2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh $RemotePath/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1" '# Consume one queued current-page refresh per minute; idle runs do not start a batch container.' "* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh $RemotePath/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1" ) -join "`n" diff --git a/tests/Feature/Auth/DingTalkLoginTest.php b/tests/Feature/Auth/DingTalkLoginTest.php index 81775ed5..c475f991 100644 --- a/tests/Feature/Auth/DingTalkLoginTest.php +++ b/tests/Feature/Auth/DingTalkLoginTest.php @@ -9,11 +9,13 @@ use App\Models\Auth\SupplierPortalIdentity; use App\Models\Auth\SupplierPortalSupplier; use App\Models\Auth\User; use App\Models\Common\Contact; +use App\Services\Auth\DingTalkOAuthClient; use App\Services\Auth\FinanceRoster; use App\Services\Auth\SupplierPortalAccess; use App\Utilities\SidebarPermissions; use Illuminate\Http\Client\Request as ClientRequest; use Illuminate\Database\Eloquent\Collection; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Http; use Illuminate\Support\Str; @@ -121,6 +123,31 @@ class DingTalkLoginTest extends FeatureTestCase $this->assertDatabaseMissing('dingtalk_oauth_states', ['state_hash' => $query['state']]); } + public function test_enterprise_user_detail_is_cached_across_repeated_login_callbacks(): void + { + Cache::flush(); + Http::fake($this->dingtalkResponses('union-cached-login', 'open-cached-login')); + + $client = app(DingTalkOAuthClient::class); + $profile = [ + 'union_id' => 'union-cached-login', + 'open_id' => 'open-cached-login', + 'nickname' => '企业员工', + ]; + + $first = $client->enterpriseUser($profile); + $second = $client->enterpriseUser($profile); + + $this->assertSame($first, $second); + Http::assertSent(fn (ClientRequest $request): bool => + str_starts_with( + $request->url(), + 'https://oapi.dingtalk.test/topapi/user/getbyunionid?', + ) + ); + Http::assertSentCount(3); + } + public function test_bound_active_enterprise_identity_logs_in_without_storing_access_tokens(): void { Http::preventStrayRequests(); diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index e1d4e36c..9ab1c214 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -178,7 +178,7 @@ class BusinessMirrorScheduleTest extends TestCase $this->assertStringContainsString( "cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'\n" . "CRON_TZ=Asia/Shanghai\n" - . '2-59/5 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock ' + . '2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock ' . "/bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1\n" . "# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。\n" . '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock ' diff --git a/tests/Unit/EcommerceFinance/DingProcessDetailMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/DingProcessDetailMirrorRepositoryTest.php index 016849d6..e5cc88a0 100644 --- a/tests/Unit/EcommerceFinance/DingProcessDetailMirrorRepositoryTest.php +++ b/tests/Unit/EcommerceFinance/DingProcessDetailMirrorRepositoryTest.php @@ -26,6 +26,7 @@ class DingProcessDetailMirrorRepositoryTest extends TestCase ], 'upstream_mirrors.connection' => 'business_mirror', 'upstream_mirrors.ding_process_details.scope' => 'personal_permission', + 'upstream_mirrors.ding_process_details.sync_interval_minutes' => 5, ]); DB::purge('business_mirror'); $this->createMirrorTables(); diff --git a/tests/Unit/EcommerceFinance/DingProcessDetailMirrorSynchronizerTest.php b/tests/Unit/EcommerceFinance/DingProcessDetailMirrorSynchronizerTest.php index d35065f6..e7ca1bb6 100644 --- a/tests/Unit/EcommerceFinance/DingProcessDetailMirrorSynchronizerTest.php +++ b/tests/Unit/EcommerceFinance/DingProcessDetailMirrorSynchronizerTest.php @@ -1100,6 +1100,10 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase ->table('business_mirror_table_states') ->where('dataset_key', 'ding.process_details.personal_permission') ->update(['last_succeeded_at' => now()->subMinutes(10)]); + DB::connection('business_mirror') + ->table('ding_process_detail_mirror') + ->where('process_instance_id', 'process-api-queue') + ->update(['cashier_checked_at' => now()->subHours(2)]); $this->query->workflows = []; $this->query->schemeChangedWorkflows = [$workflow]; $this->approvalClient->valuesByInstance['process-api-queue'] = [ @@ -1114,6 +1118,25 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), '付款金额合计' => 100, ]; + $candidateMethod = new \ReflectionMethod( + DingProcessDetailMirrorSynchronizer::class, + 'approvalApiFallbackCandidates', + ); + $candidateMethod->setAccessible(true); + $candidateRow = DB::connection('business_mirror') + ->table('ding_process_detail_mirror') + ->where('process_instance_id', 'process-api-queue') + ->first(); + $this->assertSame('审批中', $candidateRow->status); + $this->assertSame('missing', $candidateRow->payment_source_state); + $this->assertTrue( + \Illuminate\Support\Carbon::parse($candidateRow->cashier_checked_at) + ->lessThan(now()->subMinutes(60)), + ); + $this->assertSame( + ['process-api-queue'], + $candidateMethod->invoke($this->synchronizer, '', [], 10), + ); $result = $this->synchronizer->sync(false); @@ -1182,7 +1205,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase 'approval_finished_at' => '2026-11-02 13:03:00', 'payment_source_state' => 'present', 'cashier_status' => 'completed', - 'cashier_checked_at' => $now, + 'cashier_checked_at' => $now->copy()->subHours(2), 'current_approver_name' => null, 'document_type' => '线上代发业务报销', 'purpose' => '10.29种菜报销', @@ -1246,7 +1269,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase 'approval_finished_at' => '2026-11-02 13:03:00', 'payment_source_state' => 'present', 'cashier_status' => 'completed', - 'cashier_checked_at' => $now, + 'cashier_checked_at' => $now->copy()->subHours(2), 'current_approver_name' => '已审批', 'document_type' => '线上代发业务报销', 'purpose' => '10.29种菜报销', @@ -1272,7 +1295,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase ); } - public function test_incremental_sync_drains_cashier_backlog_before_changed_workflows(): void + public function test_incremental_sync_refreshes_changed_workflows_before_stale_cashier_backlog(): void { $connection = DB::connection('business_mirror'); $now = now(); @@ -1293,7 +1316,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase 'status' => '审批中', 'payment_source_state' => 'present', 'cashier_status' => 'pending_sync', - 'cashier_checked_at' => $now, + 'cashier_checked_at' => $now->copy()->subHours(2), 'document_type' => '公摊借支-销账', 'purpose' => 'AI TOKEN费用', 'account_code' => '1221.04', @@ -1372,7 +1395,15 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase 'backlog-000', array_merge(...$this->approvalClient->bulkCalls), ); - $this->assertSame($expectedBacklog, array_slice($this->approvalClient->calls, 0, 30)); + $expectedBulk = array_map( + static fn (array $workflow): string => (string) $workflow['processInstanceId'], + $bulk, + ); + $this->assertSame($expectedBulk, array_slice($this->approvalClient->calls, 0, 60)); + $this->assertSame( + $expectedBacklog, + array_slice($this->approvalClient->calls, 60, 30), + ); $this->assertSame( 'backlog-029', json_decode((string) $connection->table('business_mirror_table_states') @@ -1432,6 +1463,78 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase ->table('ding_process_payment_mirror')->count()); } + public function test_fresh_running_workflow_does_not_repeat_the_official_snapshot(): void + { + $workflow = $this->runningWorkflow('process-fresh-running', '202611230001'); + $this->query->workflows = [$workflow]; + $this->query->scheme = [ + '收款费用明细' => json_encode([[ + 'rowValue' => [ + ['label' => '代发订单金额', 'value' => '100.00'], + ['label' => '科目编码', 'value' => '1405.06'], + ['label' => '科目名称', 'value' => '库存商品_线上代发'], + ], + ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + '收款合计' => 100, + '付款明细' => json_encode([[ + 'rowValue' => [ + ['label' => '对应序号', 'value' => '1'], + ['label' => '付款金额', 'value' => '100.00'], + ['label' => '打款时间', 'value' => '2026-11-23'], + ], + ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + ]; + + $this->synchronizer->sync(true); + $this->assertSame(['process-fresh-running'], $this->approvalClient->calls); + + $this->approvalClient->calls = []; + $this->approvalClient->bulkCalls = []; + $this->synchronizer->sync(true); + + $this->assertSame([], $this->approvalClient->calls); + $this->assertSame([], $this->approvalClient->bulkCalls); + } + + public function test_approval_api_calls_are_capped_for_each_background_run(): void + { + config([ + 'upstream_mirrors.ding_process_details.approval_api_calls_per_run' => 3, + ]); + $this->query->workflows = []; + for ($index = 0; $index < 5; $index++) { + $this->query->workflows[] = $this->runningWorkflow( + sprintf('process-capped-%d', $index), + sprintf('20261123001%d', $index), + ); + } + $this->query->scheme = [ + '收款费用明细' => json_encode([[ + 'rowValue' => [ + ['label' => '代发订单金额', 'value' => '100.00'], + ['label' => '科目编码', 'value' => '1405.06'], + ['label' => '科目名称', 'value' => '库存商品_线上代发'], + ], + ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + '收款合计' => 100, + '付款明细' => json_encode([[ + 'rowValue' => [ + ['label' => '对应序号', 'value' => '1'], + ['label' => '付款金额', 'value' => '100.00'], + ['label' => '打款时间', 'value' => '2026-11-23'], + ], + ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + ]; + + $this->synchronizer->sync(true); + + $this->assertCount(3, $this->approvalClient->calls); + $this->assertSame(5, DB::connection('business_mirror') + ->table('ding_process_detail_mirror') + ->distinct() + ->count('process_instance_id')); + } + public function test_business_id_sync_fetches_titles_for_completed_detail_rows(): void { $workflow = [