fix: 限制OA审批同步API调用频率 (#1355)

This commit is contained in:
yueyang 2026-11-23 09:57:37 +08:00
parent f0f5b35071
commit 34dfd46e22
14 changed files with 391 additions and 99 deletions

View File

@ -3,6 +3,7 @@
namespace App\Services\Auth; namespace App\Services\Auth;
use Illuminate\Http\Client\RequestException; use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use RuntimeException; use RuntimeException;
@ -118,55 +119,90 @@ class DingTalkOAuthClient
throw new RuntimeException('DingTalk enterprise lookup requires a union id.'); 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 { try {
$userIdResponse = Http::asJson() $userIdResponse = Http::asJson()
->acceptJson() ->acceptJson()
->timeout($this->timeout()) ->timeout($this->timeout())
->withQueryParameters(['access_token' => $appToken]) ->withQueryParameters(['access_token' => $appToken])
->post($this->configuredString('dingtalk.user_by_union_id_url'), ['unionid' => $unionId]) ->post(
->throw(); $this->configuredString('dingtalk.user_by_union_id_url'),
} catch (RequestException $exception) { ['unionid' => $unionId],
throw new RuntimeException('DingTalk enterprise user lookup failed.', 0, $exception); )
} ->throw();
} catch (RequestException $exception) {
throw new RuntimeException(
'DingTalk enterprise user lookup failed.',
0,
$exception,
);
}
$userId = trim((string) $userIdResponse->json('result.userid')); $userId = trim((string) $userIdResponse->json('result.userid'));
if ((int) $userIdResponse->json('errcode', -1) !== 0 || $userId === '') { if ((int) $userIdResponse->json('errcode', -1) !== 0 || $userId === '') {
throw new RuntimeException('DingTalk identity is not an enterprise user.'); throw new RuntimeException('DingTalk identity is not an enterprise user.');
} }
try { try {
$detailResponse = Http::asJson() $detailResponse = Http::asJson()
->acceptJson() ->acceptJson()
->timeout($this->timeout()) ->timeout($this->timeout())
->withQueryParameters(['access_token' => $appToken]) ->withQueryParameters(['access_token' => $appToken])
->post($this->configuredString('dingtalk.user_detail_url'), ['userid' => $userId]) ->post(
->throw(); $this->configuredString('dingtalk.user_detail_url'),
} catch (RequestException $exception) { ['userid' => $userId],
throw new RuntimeException('DingTalk enterprise user detail lookup failed.', 0, $exception); )
} ->throw();
} catch (RequestException $exception) {
throw new RuntimeException(
'DingTalk enterprise user detail lookup failed.',
0,
$exception,
);
}
$detail = $detailResponse->json('result'); $detail = $detailResponse->json('result');
if ((int) $detailResponse->json('errcode', -1) !== 0 || ! is_array($detail)) { if ((int) $detailResponse->json('errcode', -1) !== 0 || ! is_array($detail)) {
throw new RuntimeException('DingTalk enterprise user detail was unavailable.'); throw new RuntimeException('DingTalk enterprise user detail was unavailable.');
} }
$detailUserId = trim((string) ($detail['userid'] ?? '')); $detailUserId = trim((string) ($detail['userid'] ?? ''));
if ($detailUserId !== '' && ! hash_equals($userId, $detailUserId)) { if ($detailUserId !== '' && ! hash_equals($userId, $detailUserId)) {
throw new RuntimeException('DingTalk enterprise user identity was inconsistent.'); 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 [ return [
'union_id' => $unionId, 'union_id' => $unionId,
'open_id' => $oauthProfile['open_id'] ?? null, 'open_id' => $oauthProfile['open_id'] ?? null,
'dingtalk_user_id' => $userId, ...$enterpriseProfile,
'nickname' => $this->nullableString($detail['name'] ?? ($oauthProfile['nickname'] ?? null)),
'email' => $this->nullableString($detail['email'] ?? null),
'mobile' => $this->nullableString($detail['mobile'] ?? null),
'active' => $active === true,
]; ];
} }

View File

@ -41,7 +41,12 @@ return [
'user_detail_url' => env('DINGTALK_USER_DETAIL_URL', 'https://oapi.dingtalk.com/topapi/v2/user/get'), 'user_detail_url' => env('DINGTALK_USER_DETAIL_URL', 'https://oapi.dingtalk.com/topapi/v2/user/get'),
'timeout' => (int) env('DINGTALK_HTTP_TIMEOUT', 10), '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), 'state_ttl_minutes' => (int) env('DINGTALK_STATE_TTL_MINUTES', 5),
'card' => [ 'card' => [

View File

@ -36,8 +36,12 @@ return [
'scope' => env('DING_PROCESS_DETAILS_SCOPE', 'personal_permission'), 'scope' => env('DING_PROCESS_DETAILS_SCOPE', 'personal_permission'),
'start_date' => env('DING_PROCESS_DETAILS_START_DATE', '2026-01-01'), 'start_date' => env('DING_PROCESS_DETAILS_START_DATE', '2026-01-01'),
'batch_size' => (int) env('DING_PROCESS_DETAILS_BATCH_SIZE', 150), '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), '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' => [ 'processes' => [
'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F' => [ 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F' => [
'kind' => 'daily', 'kind' => 'daily',

View File

@ -266,11 +266,12 @@ CRON_TZ=Asia/Shanghai
EOF EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细单独使用 5 分钟增量任务,避免被共用上游锁中的分钟级任务长期饿死; # OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。 # 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai 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 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 # 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 * * * * * 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 EOF

View File

@ -270,11 +270,12 @@ CRON_TZ=Asia/Shanghai
EOF EOF
chmod 644 /etc/cron.d/caiwu-jiansun-snapshots chmod 644 /etc/cron.d/caiwu-jiansun-snapshots
# OA 流程明细单独使用 5 分钟增量任务,避免被共用上游锁中的分钟级任务长期饿死; # OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转,
# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。
# 每周全量校准仍保留在上面的主计划中。 # 每周全量校准仍保留在上面的主计划中。
cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'
CRON_TZ=Asia/Shanghai 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 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 # 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 * * * * * 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 EOF

View File

@ -176,7 +176,7 @@ class DingProcessDetailMirrorRepository
$state = $this->state(); $state = $this->state();
$staleAfterMinutes = max( $staleAfterMinutes = max(
15, 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 [ return [
@ -306,7 +306,7 @@ class DingProcessDetailMirrorRepository
$state = $this->state(); $state = $this->state();
$staleAfterMinutes = max( $staleAfterMinutes = max(
15, 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 [ return [
@ -434,7 +434,7 @@ class DingProcessDetailMirrorRepository
$state = $this->state(); $state = $this->state();
$staleAfterMinutes = max( $staleAfterMinutes = max(
15, 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 [ return [

View File

@ -25,10 +25,6 @@ class DingProcessDetailMirrorSynchronizer
private const SOURCE = 'operations_replica'; 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 const BUSINESS_ID_SYNC_LIMIT = 50;
private readonly ConnectionInterface $connection; private readonly ConnectionInterface $connection;
@ -40,6 +36,9 @@ class DingProcessDetailMirrorSynchronizer
/** @var array<string,array<string,mixed>> */ /** @var array<string,array<string,mixed>> */
private array $approvalSnapshots = []; private array $approvalSnapshots = [];
/** @var array<string,true> */
private array $approvalAttemptedProcessInstanceIds = [];
private bool $forceApprovalApiSnapshots = false; private bool $forceApprovalApiSnapshots = false;
public function __construct( public function __construct(
@ -69,6 +68,7 @@ class DingProcessDetailMirrorSynchronizer
$this->approvalApiAttempts = 0; $this->approvalApiAttempts = 0;
$this->approvalApiAvailable = true; $this->approvalApiAvailable = true;
$this->approvalSnapshots = []; $this->approvalSnapshots = [];
$this->approvalAttemptedProcessInstanceIds = [];
$this->forceApprovalApiSnapshots = false; $this->forceApprovalApiSnapshots = false;
$scope = $this->scope(); $scope = $this->scope();
$state = $this->state(); $state = $this->state();
@ -183,6 +183,7 @@ class DingProcessDetailMirrorSynchronizer
$this->approvalApiAttempts = 0; $this->approvalApiAttempts = 0;
$this->approvalApiAvailable = $allowApprovalApi; $this->approvalApiAvailable = $allowApprovalApi;
$this->approvalSnapshots = []; $this->approvalSnapshots = [];
$this->approvalAttemptedProcessInstanceIds = [];
$this->forceApprovalApiSnapshots = true; $this->forceApprovalApiSnapshots = true;
$scope = $this->scope(); $scope = $this->scope();
$state = $this->state(); $state = $this->state();
@ -383,29 +384,13 @@ class DingProcessDetailMirrorSynchronizer
$cursor = $this->stateCursor($state); $cursor = $this->stateCursor($state);
$lastSchemeId = max(0, (int) ($cursor['scheme_high_watermark'] ?? 0)); $lastSchemeId = max(0, (int) ($cursor['scheme_high_watermark'] ?? 0));
$apiCursor = (string) ($cursor['approval_api_cursor'] ?? ''); $apiCursor = (string) ($cursor['approval_api_cursor'] ?? '');
// 先消化历史待核实流程,避免本轮变更流程耗尽接口额度后补查游标永远不前进。 $result = $this->extractWorkflows(
$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(
$where, $where,
$bindings, $bindings,
$cursorExpression, $cursorExpression,
'sync_cursor', 'sync_cursor',
$now, $now,
); );
$result = $result === null
? $incremental
: $this->mergeExtracted($result, $incremental);
if ($lastSchemeId > 0) { if ($lastSchemeId > 0) {
$changedProcessIds = $this->schemeChangedProcessIds( $changedProcessIds = $this->schemeChangedProcessIds(
@ -427,16 +412,18 @@ class DingProcessDetailMirrorSynchronizer
} }
} }
$fallbackIds = $this->approvalApiFallbackCandidates( // 上游刚变更的审批优先使用本轮的有限额度;剩余额度再轮转历史积压,
// 这样不会因为几百条旧流程排队而延迟当前审批人/出纳节点更新。
$backlogIds = $this->approvalApiFallbackCandidates(
$apiCursor, $apiCursor,
$result['process_instance_ids'], $result['process_instance_ids'],
); );
if ($fallbackIds !== []) { if ($backlogIds !== []) {
$result = $this->mergeExtracted( $result = $this->mergeExtracted(
$result, $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; $result['metrics']['scheme_high_watermark'] = $schemeHighWatermark;
@ -521,7 +508,7 @@ class DingProcessDetailMirrorSynchronizer
'ding_process_detail_mirror', 'ding_process_detail_mirror',
'paid_at', 'paid_at',
); );
$remainingAttempts = self::APPROVAL_API_DRAIN_LIMIT - $this->approvalApiAttempts; $remainingAttempts = $this->approvalApiCallsPerRun() - $this->approvalApiAttempts;
if (! $this->approvalApiAvailable || $remainingAttempts <= 0) { if (! $this->approvalApiAvailable || $remainingAttempts <= 0) {
return []; return [];
} }
@ -532,10 +519,14 @@ class DingProcessDetailMirrorSynchronizer
return []; return [];
} }
$cashierStaleBefore = now()->subMinutes(15); $cashierStaleBefore = now()->subMinutes($this->approvalApiRefreshMinutes());
$base = $this->connection->table('ding_process_detail_mirror') $base = $this->connection->table('ding_process_detail_mirror')
->where('source_scope', $this->scope()) ->where('source_scope', $this->scope())
->whereIn('status', ['审批中', '已完成']) ->whereIn('status', ['审批中', '已完成'])
->where(function ($freshness) use ($cashierStaleBefore): void {
$freshness->whereNull('cashier_checked_at')
->orWhere('cashier_checked_at', '<', $cashierStaleBefore);
})
->where(function ($query) use ( ->where(function ($query) use (
$cashierRefreshEnabled, $cashierRefreshEnabled,
$approverRefreshEnabled, $approverRefreshEnabled,
@ -1017,7 +1008,13 @@ class DingProcessDetailMirrorSynchronizer
$processInstanceIds = []; $processInstanceIds = [];
$processes = (array) config('upstream_mirrors.ding_process_details.processes', []); $processes = (array) config('upstream_mirrors.ding_process_details.processes', []);
$scope = $this->scope(); $scope = $this->scope();
$this->prefetchApprovalSnapshots($workflows, $scheme, $processes); $approvalFreshness = $this->approvalSnapshotFreshness($workflows);
$this->prefetchApprovalSnapshots(
$workflows,
$scheme,
$processes,
$approvalFreshness,
);
foreach ($workflows as $workflow) { foreach ($workflows as $workflow) {
$processCode = trim((string) ($workflow['processCode'] ?? '')); $processCode = trim((string) ($workflow['processCode'] ?? ''));
@ -1045,12 +1042,14 @@ class DingProcessDetailMirrorSynchronizer
); );
$needsCashierApi = $this->needsCashierApi($process, $workflow); $needsCashierApi = $this->needsCashierApi($process, $workflow);
$needsDetailAccountApi = $this->needsDetailAccountFallback($process, $fields); $needsDetailAccountApi = $this->needsDetailAccountFallback($process, $fields);
$approvalSnapshotDue = $this->approvalSnapshotDue(
$workflow,
$approvalFreshness[$processInstanceId] ?? null,
);
$approvalSnapshot = null; $approvalSnapshot = null;
if ($needsPaymentApi if ($this->forceApprovalApiSnapshots
|| $needsCashierApi || (($needsPaymentApi || $needsCashierApi || $needsDetailAccountApi)
|| $needsDetailAccountApi && $approvalSnapshotDue)) {
|| $status === '审批中'
|| $this->forceApprovalApiSnapshots) {
$approvalSnapshot = $this->approvalApiSnapshot($workflow); $approvalSnapshot = $this->approvalApiSnapshot($workflow);
} }
if ($needsPaymentApi && $approvalSnapshot !== null) { if ($needsPaymentApi && $approvalSnapshot !== null) {
@ -1070,7 +1069,11 @@ class DingProcessDetailMirrorSynchronizer
$workflow = $this->reconcileOfficialWorkflowState($workflow, $approvalSnapshot); $workflow = $this->reconcileOfficialWorkflowState($workflow, $approvalSnapshot);
$status = $this->status($workflow); $status = $this->status($workflow);
$cashierStatus = $this->cashierStatus($process, $workflow, $approvalSnapshot); $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); $taskState = $this->taskState($approvalSnapshot, $employees);
[$workflowDetails, $workflowAmountCents, $detailTableName] = $this->detailRows( [$workflowDetails, $workflowAmountCents, $detailTableName] = $this->detailRows(
@ -1178,6 +1181,73 @@ class DingProcessDetailMirrorSynchronizer
]; ];
} }
/**
* @param list<array<string,mixed>> $workflows
* @return array<string,Carbon>
*/
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<string,mixed> $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 * Warm the current-run snapshot cache in bounded parallel batches. The
* later normalization pass reuses these snapshots without extra API calls. * later normalization pass reuses these snapshots without extra API calls.
@ -1185,17 +1255,19 @@ class DingProcessDetailMirrorSynchronizer
* @param list<array<string,mixed>> $workflows * @param list<array<string,mixed>> $workflows
* @param array<string,array<string,mixed>> $scheme * @param array<string,array<string,mixed>> $scheme
* @param array<string,array<string,mixed>> $processes * @param array<string,array<string,mixed>> $processes
* @param array<string,Carbon> $approvalFreshness
*/ */
private function prefetchApprovalSnapshots( private function prefetchApprovalSnapshots(
array $workflows, array $workflows,
array $scheme, array $scheme,
array $processes, array $processes,
array $approvalFreshness,
): void { ): void {
if (! $this->approvalClient->isConfigured() || ! $this->approvalApiAvailable) { if (! $this->approvalClient->isConfigured() || ! $this->approvalApiAvailable) {
return; return;
} }
$remainingAttempts = self::APPROVAL_API_DRAIN_LIMIT - $this->approvalApiAttempts; $remainingAttempts = $this->approvalApiCallsPerRun() - $this->approvalApiAttempts;
if ($remainingAttempts <= 0) { if ($remainingAttempts <= 0) {
return; return;
} }
@ -1212,11 +1284,17 @@ class DingProcessDetailMirrorSynchronizer
$fields = (array) ($scheme[$processInstanceId] ?? []); $fields = (array) ($scheme[$processInstanceId] ?? []);
$paymentSourceState = $this->paymentSourceState($process, $fields); $paymentSourceState = $this->paymentSourceState($process, $fields);
if ($this->needsApprovalApiFallback($process, $fields, $paymentSourceState) $needsSnapshot = $this->needsApprovalApiFallback(
|| $this->needsCashierApi($process, $workflow) $process,
|| $this->needsDetailAccountFallback($process, $fields) $fields,
|| $this->status($workflow) === '审批中' $paymentSourceState,
|| $this->forceApprovalApiSnapshots) { ) || $this->needsCashierApi($process, $workflow)
|| $this->needsDetailAccountFallback($process, $fields);
if ($this->forceApprovalApiSnapshots
|| ($needsSnapshot && $this->approvalSnapshotDue(
$workflow,
$approvalFreshness[$processInstanceId] ?? null,
))) {
$processInstanceIds[] = $processInstanceId; $processInstanceIds[] = $processInstanceId;
} }
} }
@ -1243,6 +1321,9 @@ class DingProcessDetailMirrorSynchronizer
} }
$this->approvalApiAttempts += (int) ($result['attempted'] ?? 0); $this->approvalApiAttempts += (int) ($result['attempted'] ?? 0);
foreach ($processInstanceIds as $processInstanceId) {
$this->approvalAttemptedProcessInstanceIds[$processInstanceId] = true;
}
foreach ((array) ($result['snapshots'] ?? []) as $processInstanceId => $snapshot) { foreach ((array) ($result['snapshots'] ?? []) as $processInstanceId => $snapshot) {
if (is_array($snapshot)) { if (is_array($snapshot)) {
$this->approvalSnapshots[(string) $processInstanceId] = $snapshot; $this->approvalSnapshots[(string) $processInstanceId] = $snapshot;
@ -1738,11 +1819,12 @@ class DingProcessDetailMirrorSynchronizer
} }
if (! $this->approvalClient->isConfigured() if (! $this->approvalClient->isConfigured()
|| ! $this->approvalApiAvailable || ! $this->approvalApiAvailable
|| $this->approvalApiAttempts >= self::APPROVAL_API_DRAIN_LIMIT) { || $this->approvalApiAttempts >= $this->approvalApiCallsPerRun()) {
return null; return null;
} }
$this->approvalApiAttempts++; $this->approvalApiAttempts++;
$this->approvalAttemptedProcessInstanceIds[$processInstanceId] = true;
try { try {
return $this->approvalSnapshots[$processInstanceId] = return $this->approvalSnapshots[$processInstanceId] =
$this->approvalClient->processSnapshot($processInstanceId); $this->approvalClient->processSnapshot($processInstanceId);
@ -2709,6 +2791,8 @@ class DingProcessDetailMirrorSynchronizer
'scheme_high_watermark' => (int) ($metrics['scheme_high_watermark'] ?? 0), 'scheme_high_watermark' => (int) ($metrics['scheme_high_watermark'] ?? 0),
'approval_api_cursor' => (string) ($metrics['approval_api_cursor'] ?? ''), 'approval_api_cursor' => (string) ($metrics['approval_api_cursor'] ?? ''),
'approval_api_attempts' => $this->approvalApiAttempts, 'approval_api_attempts' => $this->approvalApiAttempts,
'approval_api_limit' => $this->approvalApiCallsPerRun(),
'approval_api_refresh_minutes' => $this->approvalApiRefreshMinutes(),
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'high_watermark' => null, 'high_watermark' => null,
'window_started_at' => null, 'window_started_at' => null,
@ -2785,7 +2869,7 @@ class DingProcessDetailMirrorSynchronizer
} }
$minutes = max( $minutes = max(
1, 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']); $lastSucceededAt = OaProcessTime::parse($state['last_succeeded_at']);
@ -2796,6 +2880,35 @@ class DingProcessDetailMirrorSynchronizer
->lessThanOrEqualTo(OaProcessTime::now()); ->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<string,mixed>|null */ /** @return array<string,mixed>|null */
private function state(): ?array private function state(): ?array
{ {

View File

@ -136,7 +136,8 @@ class DingTalkProcessInstanceClient
$errors = []; $errors = [];
$fatal = false; $fatal = false;
$attempted = 0; $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) { foreach (array_chunk($pending, $concurrency) as $chunk) {
$attempted += count($chunk); $attempted += count($chunk);

View File

@ -433,7 +433,7 @@ class FinanceLedgerRptSynchronizer
} }
/** /**
* 钉钉流程镜像每 5 分钟补齐付款行;财务台账优先使用这份最新付款事实。 * 钉钉流程镜像每 15 分钟补齐结构化付款行;审批快照按 60 分钟限频刷新。
* *
* @param array<int,array<string,mixed>> $workflows * @param array<int,array<string,mixed>> $workflows
* @return array<string,array<int,array<string,mixed>>> * @return array<string,array<int,array<string,mixed>>>

View File

@ -16,7 +16,7 @@ if ($RemotePath -notmatch '^/[A-Za-z0-9._/-]+$') {
$cron = @( $cron = @(
'CRON_TZ=Asia/Shanghai' 'CRON_TZ=Asia/Shanghai'
'# Process details use a dedicated schedule and OA-only mirror lock.' '# 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.' '# 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" "* * * * * 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" ) -join "`n"

View File

@ -9,11 +9,13 @@ use App\Models\Auth\SupplierPortalIdentity;
use App\Models\Auth\SupplierPortalSupplier; use App\Models\Auth\SupplierPortalSupplier;
use App\Models\Auth\User; use App\Models\Auth\User;
use App\Models\Common\Contact; use App\Models\Common\Contact;
use App\Services\Auth\DingTalkOAuthClient;
use App\Services\Auth\FinanceRoster; use App\Services\Auth\FinanceRoster;
use App\Services\Auth\SupplierPortalAccess; use App\Services\Auth\SupplierPortalAccess;
use App\Utilities\SidebarPermissions; use App\Utilities\SidebarPermissions;
use Illuminate\Http\Client\Request as ClientRequest; use Illuminate\Http\Client\Request as ClientRequest;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@ -121,6 +123,31 @@ class DingTalkLoginTest extends FeatureTestCase
$this->assertDatabaseMissing('dingtalk_oauth_states', ['state_hash' => $query['state']]); $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 public function test_bound_active_enterprise_identity_logs_in_without_storing_access_tokens(): void
{ {
Http::preventStrayRequests(); Http::preventStrayRequests();

View File

@ -178,7 +178,7 @@ class BusinessMirrorScheduleTest extends TestCase
$this->assertStringContainsString( $this->assertStringContainsString(
"cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'\n" "cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'\n"
. "CRON_TZ=Asia/Shanghai\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" . "/bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1\n"
. "# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。\n" . "# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。\n"
. '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock ' . '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock '

View File

@ -26,6 +26,7 @@ class DingProcessDetailMirrorRepositoryTest extends TestCase
], ],
'upstream_mirrors.connection' => 'business_mirror', 'upstream_mirrors.connection' => 'business_mirror',
'upstream_mirrors.ding_process_details.scope' => 'personal_permission', 'upstream_mirrors.ding_process_details.scope' => 'personal_permission',
'upstream_mirrors.ding_process_details.sync_interval_minutes' => 5,
]); ]);
DB::purge('business_mirror'); DB::purge('business_mirror');
$this->createMirrorTables(); $this->createMirrorTables();

View File

@ -1100,6 +1100,10 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
->table('business_mirror_table_states') ->table('business_mirror_table_states')
->where('dataset_key', 'ding.process_details.personal_permission') ->where('dataset_key', 'ding.process_details.personal_permission')
->update(['last_succeeded_at' => now()->subMinutes(10)]); ->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->workflows = [];
$this->query->schemeChangedWorkflows = [$workflow]; $this->query->schemeChangedWorkflows = [$workflow];
$this->approvalClient->valuesByInstance['process-api-queue'] = [ $this->approvalClient->valuesByInstance['process-api-queue'] = [
@ -1114,6 +1118,25 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), ]], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'付款金额合计' => 100, '付款金额合计' => 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); $result = $this->synchronizer->sync(false);
@ -1182,7 +1205,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
'approval_finished_at' => '2026-11-02 13:03:00', 'approval_finished_at' => '2026-11-02 13:03:00',
'payment_source_state' => 'present', 'payment_source_state' => 'present',
'cashier_status' => 'completed', 'cashier_status' => 'completed',
'cashier_checked_at' => $now, 'cashier_checked_at' => $now->copy()->subHours(2),
'current_approver_name' => null, 'current_approver_name' => null,
'document_type' => '线上代发业务报销', 'document_type' => '线上代发业务报销',
'purpose' => '10.29种菜报销', 'purpose' => '10.29种菜报销',
@ -1246,7 +1269,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
'approval_finished_at' => '2026-11-02 13:03:00', 'approval_finished_at' => '2026-11-02 13:03:00',
'payment_source_state' => 'present', 'payment_source_state' => 'present',
'cashier_status' => 'completed', 'cashier_status' => 'completed',
'cashier_checked_at' => $now, 'cashier_checked_at' => $now->copy()->subHours(2),
'current_approver_name' => '已审批', 'current_approver_name' => '已审批',
'document_type' => '线上代发业务报销', 'document_type' => '线上代发业务报销',
'purpose' => '10.29种菜报销', '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'); $connection = DB::connection('business_mirror');
$now = now(); $now = now();
@ -1293,7 +1316,7 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
'status' => '审批中', 'status' => '审批中',
'payment_source_state' => 'present', 'payment_source_state' => 'present',
'cashier_status' => 'pending_sync', 'cashier_status' => 'pending_sync',
'cashier_checked_at' => $now, 'cashier_checked_at' => $now->copy()->subHours(2),
'document_type' => '公摊借支-销账', 'document_type' => '公摊借支-销账',
'purpose' => 'AI TOKEN费用', 'purpose' => 'AI TOKEN费用',
'account_code' => '1221.04', 'account_code' => '1221.04',
@ -1372,7 +1395,15 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
'backlog-000', 'backlog-000',
array_merge(...$this->approvalClient->bulkCalls), 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( $this->assertSame(
'backlog-029', 'backlog-029',
json_decode((string) $connection->table('business_mirror_table_states') json_decode((string) $connection->table('business_mirror_table_states')
@ -1432,6 +1463,78 @@ class DingProcessDetailMirrorSynchronizerTest extends TestCase
->table('ding_process_payment_mirror')->count()); ->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 public function test_business_id_sync_fetches_titles_for_completed_detail_rows(): void
{ {
$workflow = [ $workflow = [