From b3bfd33b97f7b9896b4d6b9c3e87c7263e7f94bd Mon Sep 17 00:00:00 2001 From: renshen <1005457301@qq.com> Date: Wed, 4 Nov 2026 22:16:47 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8E=A5=E5=85=A5=E9=92=89=E9=92=89?= =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E6=97=A5=E6=8A=A5=E6=97=A5=E5=BF=97=E7=BB=9F?= =?UTF-8?q?=E8=AE=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Console/Commands/SyncDingWorklogs.php | 104 +++++ app/Console/Kernel.php | 8 + app/Http/Controllers/Business/Pages.php | 1 + config/dingtalk.php | 10 + ..._04_230000_create_ding_worklog_reports.php | 43 ++ deploy/activate-incremental-release.sh | 2 + deploy/activate-release.sh | 2 + .../Exceptions/DingTalkWorklogException.php | 18 + .../DingWorklogMirrorRepository.php | 245 +++++++++++ .../Services/DingTalkWorklogClient.php | 166 +++++++ .../View/DingWorklogStatisticsPageData.php | 114 +++++ .../pages/other/log-statistics.blade.php | 404 +++++++++++++++--- tests/Feature/Business/PagesTest.php | 78 +++- .../Feature/Console/SyncDingWorklogsTest.php | 122 ++++++ .../Deployment/BusinessMirrorScheduleTest.php | 20 + .../DingTalkWorklogClientTest.php | 126 ++++++ .../DingWorklogMirrorRepositoryTest.php | 171 ++++++++ 17 files changed, 1574 insertions(+), 60 deletions(-) create mode 100644 app/Console/Commands/SyncDingWorklogs.php create mode 100644 database/migrations/2026_11_04_230000_create_ding_worklog_reports.php create mode 100644 modules/EcommerceFinance/Exceptions/DingTalkWorklogException.php create mode 100644 modules/EcommerceFinance/Repositories/DingWorklogMirrorRepository.php create mode 100644 modules/EcommerceFinance/Services/DingTalkWorklogClient.php create mode 100644 modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php create mode 100644 tests/Feature/Console/SyncDingWorklogsTest.php create mode 100644 tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php create mode 100644 tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php diff --git a/app/Console/Commands/SyncDingWorklogs.php b/app/Console/Commands/SyncDingWorklogs.php new file mode 100644 index 00000000..268e0043 --- /dev/null +++ b/app/Console/Commands/SyncDingWorklogs.php @@ -0,0 +1,104 @@ +available()) { + $this->error('日志统计镜像表尚未建立,请先执行数据库迁移。'); + + return self::FAILURE; + } + if (! $client->isConfigured()) { + $repository->recordFailure('dingtalk_credentials_missing'); + $this->error('钉钉应用凭据未配置。'); + + return self::FAILURE; + } + + $days = max((int) ($this->option('days') ?: config('dingtalk.worklog.lookback_days', 35)), 1); + $template = trim((string) ($this->option('template') ?: config('dingtalk.worklog.template_name', '财务日报'))); + $to = now(); + $from = $to->copy()->subDays($days)->startOfDay(); + + try { + $result = $client->listReports($from, $to, $template); + $now = now(); + $rows = []; + foreach ($result['reports'] as $report) { + if (! is_array($report)) { + continue; + } + $submittedRaw = $report['create_time'] + ?? $report['created_at'] + ?? $report['submit_time'] + ?? null; + if ($submittedRaw === null || $submittedRaw === '') { + continue; + } + + try { + $submittedAt = DingWorklogMirrorRepository::submittedAt($submittedRaw); + } catch (Throwable) { + continue; + } + $statisticsDate = DingWorklogMirrorRepository::statisticsDate($submittedAt); + $rows[] = [ + 'report_id' => DingWorklogMirrorRepository::reportId($report), + 'template_name' => mb_substr(trim((string) ($report['template_name'] ?? $template)), 0, 191), + 'creator_userid' => mb_substr(trim((string) ($report['creator_userid'] ?? $report['creator_id'] ?? '')), 0, 128), + 'creator_name' => mb_substr(trim((string) ($report['creator_name'] ?? $report['creator_nick'] ?? '')), 0, 191), + 'submitted_at' => $submittedAt->toDateTimeString(), + 'statistics_date' => $statisticsDate->toDateString(), + 'remark' => trim((string) ($report['remark'] ?? '')), + 'raw_payload' => json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + + $upserted = $repository->upsertReports($rows); + $repository->recordSuccess($upserted, $template, $from, $to); + + $this->info(sprintf( + '钉钉日志同步完成:读取 %d 页,写入/更新 %d 条。', + $result['pages'], + $upserted, + )); + + return self::SUCCESS; + } catch (DingTalkWorklogException $exception) { + $repository->recordFailure($exception->errorCode); + report($exception); + $this->error($exception->getMessage()); + + return self::FAILURE; + } catch (Throwable $exception) { + $repository->recordFailure('dingtalk_worklog_sync_failed'); + report($exception); + $this->error('钉钉日志同步失败,详细原因已记录到受保护日志。'); + + return self::FAILURE; + } + } +} diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 6255fe3f..04496d3d 100644 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -118,6 +118,14 @@ class Kernel extends ConsoleKernel ->withoutOverlapping(180) ->runInBackground(); + // 钉钉财务日报:高频增量同步,次日 12:00 截止的补交日志也能及时进入统计。 + $schedule->command('business-mirror:sync-ding-worklogs --quiet') + ->cron('*/15 * * * *') + ->timezone('Asia/Shanghai') + ->withoutOverlapping(15) + ->appendOutputTo(storage_path('logs/ding-worklog-sync.log')) + ->runInBackground(); + if ((bool) config('services.esign.polling_enabled', false)) { $schedule->command('esign:poll-signatures --quiet') ->cron('*/2 * * * *') diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index b3d85c7d..2fc2267a 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -4748,6 +4748,7 @@ class Pages extends Controller 'return-pickup-management' => $this->contentForReturnPickupManagement(), 'withdrawal-management' => $this->contentForWithdrawalManagement(), 'systemization-todos' => app(\App\Http\Controllers\Business\SystemizationTodos::class)->page(), + 'log-statistics' => app(\Modules\EcommerceFinance\View\DingWorklogStatisticsPageData::class)->page(request()), 'order-profit-list' => app(\Modules\EcommerceFinance\View\OrderProfitPageData::class)->page(), 'todos' => $this->contentForTodos(), 'after-sales-return-refund' => $this->contentForAfterSalesReturnRefund(), diff --git a/config/dingtalk.php b/config/dingtalk.php index 457b4a92..19b3b814 100644 --- a/config/dingtalk.php +++ b/config/dingtalk.php @@ -42,4 +42,14 @@ return [ 'timeout' => (int) env('DINGTALK_HTTP_TIMEOUT', 10), 'process_concurrency' => (int) env('DINGTALK_PROCESS_CONCURRENCY', 5), 'state_ttl_minutes' => (int) env('DINGTALK_STATE_TTL_MINUTES', 5), + + 'worklog' => [ + 'enabled' => filter_var(env('DINGTALK_WORKLOG_ENABLED', true), FILTER_VALIDATE_BOOL), + 'template_name' => env('DINGTALK_WORKLOG_TEMPLATE_NAME', '财务日报'), + 'userid' => env('DINGTALK_WORKLOG_USERID'), + 'lookback_days' => (int) env('DINGTALK_WORKLOG_LOOKBACK_DAYS', 35), + 'page_size' => min(max((int) env('DINGTALK_WORKLOG_PAGE_SIZE', 20), 1), 20), + 'max_pages' => max((int) env('DINGTALK_WORKLOG_MAX_PAGES', 100), 1), + 'permission_scope' => 'qyapi_report_query', + ], ]; diff --git a/database/migrations/2026_11_04_230000_create_ding_worklog_reports.php b/database/migrations/2026_11_04_230000_create_ding_worklog_reports.php new file mode 100644 index 00000000..eb85f43c --- /dev/null +++ b/database/migrations/2026_11_04_230000_create_ding_worklog_reports.php @@ -0,0 +1,43 @@ +connection()); + + if ($schema->hasTable('ding_worklog_reports')) { + return; + } + + $schema->create('ding_worklog_reports', function (Blueprint $table): void { + $table->string('report_id', 64)->primary(); + $table->string('template_name', 191)->nullable(); + $table->string('creator_userid', 128)->nullable(); + $table->string('creator_name', 191)->nullable(); + $table->dateTime('submitted_at')->index(); + $table->date('statistics_date')->index(); + $table->text('remark')->nullable(); + $table->longText('raw_payload')->nullable(); + $table->timestamp('synced_at')->nullable(); + $table->timestamps(); + + $table->index(['statistics_date', 'creator_userid'], 'ding_worklog_date_creator'); + $table->index(['template_name', 'submitted_at'], 'ding_worklog_template_submitted'); + }); + } + + public function down(): void + { + Schema::connection($this->connection())->dropIfExists('ding_worklog_reports'); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 7c814b3d..54d4c195 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -234,6 +234,8 @@ CRON_TZ=Asia/Shanghai 30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 # 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。 20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1 +# 钉钉财务日报每 15 分钟增量同步;次日 12:00 前补交的日志会及时归入前一统计日。 +*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-worklog-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-worklogs --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index b832d285..ebdcd1e9 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -238,6 +238,8 @@ CRON_TZ=Asia/Shanghai 30 10 * * * root /usr/bin/flock -w 1800 /run/caiwu-upstream-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan finance-ledger:sync-shop-data --balance-only --quiet >/dev/null 2>&1 # 财务流程明细每周完整校准一次,修正超过 48 小时重叠窗口才出现的上游改单或晚到付款。 20 2 * * 0 root /usr/bin/flock -w 3600 /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --full --quiet >/dev/null 2>&1 +# 钉钉财务日报每 15 分钟增量同步;次日 12:00 前补交的日志会及时归入前一统计日。 +*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-worklog-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-worklogs --quiet >/dev/null 2>&1 # 科目映射保存后保留自动重跑队列,每分钟在受限容器内串行消费。 * * * * * root /usr/bin/flock -n /run/caiwu-account-mapping-resync.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh store-receipt:auto-resync --quiet >/dev/null 2>&1 * * * * * root /usr/bin/flock -n /run/caiwu-account-bills-export.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh account-bills:exports:run --quiet >/dev/null 2>&1 diff --git a/modules/EcommerceFinance/Exceptions/DingTalkWorklogException.php b/modules/EcommerceFinance/Exceptions/DingTalkWorklogException.php new file mode 100644 index 00000000..3dd4c9e2 --- /dev/null +++ b/modules/EcommerceFinance/Exceptions/DingTalkWorklogException.php @@ -0,0 +1,18 @@ +connection = $database->connection( + (string) config('upstream_mirrors.connection', 'business_mirror') + ); + } + + public function available(): bool + { + $schema = Schema::connection($this->connection->getName()); + + return $schema->hasTable(self::TABLE) + && $schema->hasTable('business_mirror_table_states'); + } + + /** @return array|null */ + public function state(): ?array + { + if (! $this->available()) { + return null; + } + + $row = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::STATE_KEY) + ->first(); + + return $row === null ? null : (array) $row; + } + + /** @param list> $rows */ + public function upsertReports(array $rows): int + { + if ($rows === []) { + return 0; + } + + $this->connection->table(self::TABLE)->upsert( + $rows, + ['report_id'], + [ + 'template_name', + 'creator_userid', + 'creator_name', + 'submitted_at', + 'statistics_date', + 'remark', + 'raw_payload', + 'synced_at', + 'updated_at', + ], + ); + + return count($rows); + } + + public function recordSuccess(int $upserted, string $templateName, ?CarbonInterface $from, CarbonInterface $to): void + { + $now = now(); + $state = $this->state(); + $values = [ + 'source_key' => 'dingtalk_worklog', + 'source_object' => $templateName !== '' ? $templateName : '钉钉日志', + 'target_table' => self::TABLE, + 'status' => 'succeeded', + 'run_mode' => 'incremental', + 'cursor' => json_encode([ + 'from' => $from?->toDateTimeString(), + 'to' => Carbon::instance($to)->toDateTimeString(), + ], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'high_watermark' => json_encode( + ['submitted_at' => Carbon::instance($to)->toDateTimeString()], + JSON_THROW_ON_ERROR, + ), + 'window_started_at' => $from ? Carbon::instance($from) : null, + 'window_ends_at' => Carbon::instance($to), + 'initial_completed_at' => $state['initial_completed_at'] ?? $now, + 'last_attempted_at' => $now, + 'last_succeeded_at' => $now, + 'last_upserted_rows' => $upserted, + 'mirror_row_count' => $this->connection->table(self::TABLE)->count(), + 'last_error_code' => null, + 'updated_at' => $now, + ]; + + $this->connection->table('business_mirror_table_states')->updateOrInsert( + ['dataset_key' => self::STATE_KEY], + $values + ['created_at' => $state['created_at'] ?? $now], + ); + } + + public function recordFailure(string $errorCode): void + { + if (! $this->available()) { + return; + } + + $now = now(); + $state = $this->state(); + $values = [ + 'source_key' => 'dingtalk_worklog', + 'source_object' => (string) config('dingtalk.worklog.template_name', '财务日报'), + 'target_table' => self::TABLE, + 'status' => 'failed', + 'run_mode' => 'incremental', + 'last_attempted_at' => $now, + 'last_error_code' => mb_substr($errorCode, 0, 120), + 'updated_at' => $now, + ]; + + $this->connection->table('business_mirror_table_states')->updateOrInsert( + ['dataset_key' => self::STATE_KEY], + $values + [ + 'initial_completed_at' => $state['initial_completed_at'] ?? null, + 'mirror_row_count' => $this->connection->table(self::TABLE)->count(), + 'created_at' => $state['created_at'] ?? $now, + ], + ); + } + + /** + * @return list + */ + public function dailySummary(string $from, string $to): array + { + return $this->connection->table(self::TABLE) + ->whereBetween('statistics_date', [$from, $to]) + ->groupBy('statistics_date') + ->orderByDesc('statistics_date') + ->selectRaw( + 'statistics_date, COUNT(*) AS submission_count, ' + . 'COUNT(DISTINCT creator_userid) AS submitter_count, ' + . 'MIN(submitted_at) AS first_submitted_at, MAX(submitted_at) AS last_submitted_at' + ) + ->get() + ->map(static fn (object $row): array => [ + 'statistics_date' => (string) $row->statistics_date, + 'submission_count' => (int) $row->submission_count, + 'submitter_count' => (int) $row->submitter_count, + 'first_submitted_at' => $row->first_submitted_at ? (string) $row->first_submitted_at : null, + 'last_submitted_at' => $row->last_submitted_at ? (string) $row->last_submitted_at : null, + ]) + ->values() + ->all(); + } + + /** @return list */ + public function submissionsForDate(string $date, int $limit = 200): array + { + return $this->connection->table(self::TABLE) + ->where('statistics_date', $date) + ->orderByDesc('submitted_at') + ->limit(min(max($limit, 1), 500)) + ->get([ + 'report_id', + 'template_name', + 'creator_userid', + 'creator_name', + 'submitted_at', + 'statistics_date', + ]) + ->all(); + } + + public static function statisticsDate(CarbonInterface|int|string $submittedAt): Carbon + { + $submitted = self::submittedAt($submittedAt)->timezone( + (string) config('app.timezone', 'Asia/Shanghai') + ); + + return $submitted->hour < 12 + ? $submitted->copy()->subDay()->startOfDay() + : $submitted->copy()->startOfDay(); + } + + public static function submittedAt(CarbonInterface|int|string $value): Carbon + { + $timezone = (string) config('app.timezone', 'Asia/Shanghai'); + + if ($value instanceof CarbonInterface) { + return Carbon::instance($value)->timezone($timezone); + } + + if (is_int($value) || (is_string($value) && ctype_digit($value))) { + $timestamp = (int) $value; + + return Carbon::createFromTimestampMs( + $timestamp >= 1000000000000 ? $timestamp : $timestamp * 1000, + $timezone, + ); + } + + return Carbon::parse((string) $value, $timezone)->timezone($timezone); + } + + public static function reportId(array $row): string + { + $reportId = trim((string) ($row['report_id'] ?? $row['id'] ?? '')); + if ($reportId !== '') { + return mb_substr($reportId, 0, 64); + } + + return hash('sha256', json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + } + + public static function isPermissionError(?string $errorCode): bool + { + return $errorCode === 'dingtalk_worklog_permission_required'; + } + + public function permissionApplyUrl(): string + { + $clientId = trim((string) config('dingtalk.client_id', '')); + if ($clientId === '') { + return 'https://open-dev.dingtalk.com/appscope/apply'; + } + + return 'https://open-dev.dingtalk.com/appscope/apply?content=' + . rawurlencode($clientId . '#' . (string) config('dingtalk.worklog.permission_scope', 'qyapi_report_query')); + } +} diff --git a/modules/EcommerceFinance/Services/DingTalkWorklogClient.php b/modules/EcommerceFinance/Services/DingTalkWorklogClient.php new file mode 100644 index 00000000..744f8b05 --- /dev/null +++ b/modules/EcommerceFinance/Services/DingTalkWorklogClient.php @@ -0,0 +1,166 @@ +>,pages:int} + */ + public function listReports( + CarbonInterface $from, + CarbonInterface $to, + ?string $templateName = null, + ): array { + if (! $this->isConfigured()) { + throw new DingTalkWorklogException( + '钉钉应用凭据未配置', + 'dingtalk_credentials_missing', + ); + } + + $templateName = trim((string) $templateName); + $userId = trim((string) config('dingtalk.worklog.userid', '')); + $size = (int) config('dingtalk.worklog.page_size', 20); + $maxPages = (int) config('dingtalk.worklog.max_pages', 100); + $cursor = 0; + $pages = 0; + $reports = []; + + do { + $payload = [ + 'start_time' => (int) $from->getTimestampMs(), + 'end_time' => (int) $to->getTimestampMs(), + 'cursor' => $cursor, + 'size' => $size, + ]; + if ($templateName !== '') { + $payload['template_name'] = $templateName; + } + if ($userId !== '') { + $payload['userid'] = $userId; + } + + try { + $response = Http::asJson() + ->acceptJson() + ->timeout($this->timeout()) + ->post( + self::LIST_URL . '?access_token=' . rawurlencode($this->accessToken()), + $payload, + ); + } catch (ConnectionException|RequestException $exception) { + throw new DingTalkWorklogException( + '钉钉日志列表请求失败', + 'dingtalk_worklog_connection_failed', + true, + $exception, + ); + } + + $json = (array) $response->json(); + $errorCode = (int) ($json['errcode'] ?? -1); + $errorMessage = trim((string) ($json['errmsg'] ?? '')); + if (! $response->successful() || $errorCode !== 0) { + if ($errorCode === 88 + || str_contains($errorMessage, 'qyapi_report_query') + || str_contains($errorMessage, '60011')) { + throw new DingTalkWorklogException( + '钉钉日志接口缺少 qyapi_report_query 权限', + 'dingtalk_worklog_permission_required', + ); + } + + throw new DingTalkWorklogException( + '钉钉日志列表查询失败:' . ($errorMessage !== '' ? $errorMessage : 'HTTP ' . $response->status()), + in_array($response->status(), [401, 403, 429], true) || $response->status() >= 500 + ? 'dingtalk_worklog_request_retryable' + : 'dingtalk_worklog_request_failed', + in_array($response->status(), [401, 403, 429], true) || $response->status() >= 500, + ); + } + + $result = (array) ($json['result'] ?? []); + $pageRows = (array) ($result['data_list'] ?? $result['list'] ?? $result['data'] ?? []); + foreach ($pageRows as $row) { + if (is_array($row)) { + $reports[(string) ($row['report_id'] ?? $row['id'] ?? count($reports))] = $row; + } + } + $pages++; + + $hasMore = filter_var($result['has_more'] ?? false, FILTER_VALIDATE_BOOL); + $nextCursor = $result['next_cursor'] ?? null; + if (! $hasMore || ! is_numeric($nextCursor) || $pages >= $maxPages) { + break; + } + $cursor = (int) $nextCursor; + } while (true); + + return ['reports' => array_values($reports), 'pages' => $pages]; + } + + private function accessToken(): string + { + $token = Cache::remember( + self::TOKEN_CACHE_KEY, + now()->addMinutes(100), + function (): ?string { + try { + $response = Http::acceptJson() + ->timeout($this->timeout()) + ->get((string) config('dingtalk.app_token_url'), [ + 'appkey' => (string) config('dingtalk.client_id'), + 'appsecret' => (string) config('dingtalk.client_secret'), + ]) + ->throw(); + } catch (ConnectionException|RequestException $exception) { + throw new DingTalkWorklogException( + '钉钉应用令牌获取失败', + 'dingtalk_token_request_failed', + true, + $exception, + ); + } + + $token = trim((string) $response->json('access_token')); + + return (int) $response->json('errcode', -1) === 0 && $token !== '' + ? $token + : null; + }, + ); + + if (! is_string($token) || $token === '') { + throw new DingTalkWorklogException( + '钉钉应用令牌不可用', + 'dingtalk_token_unavailable', + true, + ); + } + + return $token; + } + + private function timeout(): int + { + return max(3, min(30, (int) config('dingtalk.timeout', 10))); + } +} diff --git a/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php b/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php new file mode 100644 index 00000000..2e481d4a --- /dev/null +++ b/modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php @@ -0,0 +1,114 @@ +hour < 12 + ? now()->subDay()->startOfDay() + : now()->startOfDay(); + $from = $this->date($request->query('from')) + ?? $latestStatisticsDate->copy()->subDays(13); + $to = $this->date($request->query('to')) ?? $latestStatisticsDate->copy(); + if ($from->greaterThan($to)) { + [$from, $to] = [$to, $from]; + } + if ($from->diffInDays($to) > 90) { + $from = $to->copy()->subDays(90); + } + + $state = $this->repository->available() ? $this->repository->state() : null; + $errorCode = trim((string) ($state['last_error_code'] ?? '')); + $syncState = match (true) { + ! $this->repository->available() => 'unavailable', + $errorCode !== '' => 'failed', + $state === null => 'pending', + ($state['status'] ?? '') === 'running' => 'syncing', + ($state['status'] ?? '') === 'succeeded' => 'succeeded', + default => 'pending', + }; + $permissionRequired = DingWorklogMirrorRepository::isPermissionError($errorCode); + + $daily = []; + $selectedDate = $this->date($request->query('date'))?->toDateString(); + $submissions = []; + if ($this->repository->available()) { + try { + $daily = $this->repository->dailySummary($from->toDateString(), $to->toDateString()); + $selectedDate ??= $daily[0]['statistics_date'] ?? $latestStatisticsDate->toDateString(); + $submissions = array_map(static fn (object $row): array => [ + 'report_id' => (string) $row->report_id, + 'template_name' => (string) ($row->template_name ?? ''), + 'creator_userid' => (string) ($row->creator_userid ?? ''), + 'creator_name' => (string) ($row->creator_name ?? ''), + 'submitted_at' => (string) $row->submitted_at, + 'statistics_date' => (string) $row->statistics_date, + ], $this->repository->submissionsForDate($selectedDate)); + } catch (Throwable $exception) { + report($exception); + $syncState = 'failed'; + $errorCode = 'dingtalk_worklog_read_failed'; + } + } + + $currentDate = $latestStatisticsDate->toDateString(); + $current = collect($daily)->firstWhere('statistics_date', $currentDate) ?? [ + 'statistics_date' => $currentDate, + 'submission_count' => 0, + 'submitter_count' => 0, + 'first_submitted_at' => null, + 'last_submitted_at' => null, + ]; + + return [ + 'view' => 'business.pages.other.log-statistics', + 'worklogFilters' => [ + 'from' => $from->toDateString(), + 'to' => $to->toDateString(), + 'date' => $selectedDate, + ], + 'worklogState' => [ + 'state' => $syncState, + 'error_code' => $errorCode ?: null, + 'permission_required' => $permissionRequired, + 'permission_apply_url' => $permissionRequired ? $this->repository->permissionApplyUrl() : null, + 'status' => $state['status'] ?? null, + 'last_attempted_at' => $state['last_attempted_at'] ?? null, + 'last_succeeded_at' => $state['last_succeeded_at'] ?? null, + 'mirror_row_count' => (int) ($state['mirror_row_count'] ?? 0), + ], + 'worklogCurrent' => $current, + 'worklogDaily' => $daily, + 'worklogSubmissions' => $submissions, + 'worklogDays' => (int) $from->diffInDays($to) + 1, + 'worklogTotalSubmissions' => array_sum(array_column($daily, 'submission_count')), + 'worklogTemplateName' => (string) config('dingtalk.worklog.template_name', '财务日报'), + 'worklogCutoffAt' => $latestStatisticsDate->copy()->addDay()->setTime(12, 0)->toDateTimeString(), + ]; + } + + private function date(mixed $value): ?Carbon + { + $value = trim((string) $value); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + try { + return Carbon::createFromFormat('!Y-m-d', $value)->startOfDay(); + } catch (Throwable) { + return null; + } + } +} diff --git a/resources/views/business/pages/other/log-statistics.blade.php b/resources/views/business/pages/other/log-statistics.blade.php index 6fdaafbb..172220cc 100644 --- a/resources/views/business/pages/other/log-statistics.blade.php +++ b/resources/views/business/pages/other/log-statistics.blade.php @@ -2,73 +2,377 @@ -
- -

日志统计页面已创建

-

页面入口和权限已就绪。数据来源、统计时间范围及汇总字段待确认后接入。

-
- 数据来源:待接入 - 统计口径:待配置 - 更新时间:待接入 +
+ +
+ 钉钉 {{ $worklogTemplateName }} · 次日 12:00 截止 + 统计日当天提交的日志,以及次日 12:00 前补交的日志,统一计入统计日;每日中午 12:00 后提交归入下一统计日。
+
+ + @if ($worklogState['permission_required']) + + @elseif ($worklogState['state'] === 'failed') + + @endif + +
+ + + + 重置 + + + @switch($worklogState['state']) + @case('succeeded') 已同步 @break + @case('syncing') 同步中 @break + @case('failed') 同步异常 @break + @case('unavailable') 镜像未建立 @break + @default 等待首次同步 + @endswitch + @if ($worklogState['last_succeeded_at']) + · 最近成功 {{ $worklogState['last_succeeded_at'] }} + @endif + +
+ +
+
+ {{ $worklogCurrent['statistics_date'] }} 提交人数 + {{ number_format((int) $worklogCurrent['submitter_count']) }} +
+
+ {{ $worklogCurrent['statistics_date'] }} 日志条数 + {{ number_format((int) $worklogCurrent['submission_count']) }} +
+
+ 当前统计日截止时间 + {{ $worklogCutoffAt }} +
+
+ 查询范围日志总数 + {{ number_format((int) $worklogTotalSubmissions) }} +
+
+ +
+
+ 每日日志提交统计 + {{ $worklogFilters['from'] }} 至 {{ $worklogFilters['to'] }} +
+ @if ($worklogDaily === []) +
当前时间范围暂无日志提交数据。
+ @else +
+ + + + + + + + + + + + + @foreach ($worklogDaily as $day) + @php + $isSelected = $worklogFilters['date'] === $day['statistics_date']; + $deadline = \Illuminate\Support\Carbon::parse($day['statistics_date'])->addDay()->setTime(12, 0); + @endphp + $isSelected])> + + + + + + + + @endforeach + +
统计日期截止时间提交人数日志条数首次提交最后提交
+ {{ $day['statistics_date'] }} + {{ $deadline->format('Y-m-d H:i:s') }}{{ number_format((int) $day['submitter_count']) }}{{ number_format((int) $day['submission_count']) }}{{ $day['first_submitted_at'] ?: '-' }}{{ $day['last_submitted_at'] ?: '-' }}
+
+ @endif +
+ +
+
+ 日志提交明细 + {{ $worklogFilters['date'] }} +
+ @if ($worklogSubmissions === []) +
所选统计日暂无提交记录。
+ @else +
+ + + + + + + + + + + @foreach ($worklogSubmissions as $submission) + + + + + + + @endforeach + +
提交人提交时间日志模板日志ID
{{ $submission['creator_name'] ?: ($submission['creator_userid'] ?: '未知提交人') }}{{ $submission['submitted_at'] }}{{ $submission['template_name'] ?: $worklogTemplateName }}{{ $submission['report_id'] }}
+
+ @endif
diff --git a/tests/Feature/Business/PagesTest.php b/tests/Feature/Business/PagesTest.php index 8ff47ce8..9da3a360 100644 --- a/tests/Feature/Business/PagesTest.php +++ b/tests/Feature/Business/PagesTest.php @@ -8,6 +8,7 @@ use App\Business\InventoryWarehouseMappingAlerts; use App\Business\InventoryWarehouseShortNames; use App\Jobs\Common\InventoryReportExport; use Illuminate\Http\UploadedFile; +use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Queue; use Mockery; @@ -15,6 +16,7 @@ use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Modules\EcommerceFinance\Repositories\CourierFreightReconciliationMirrorRepository; +use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository; use Modules\EcommerceFinance\Repositories\NonJingxiRefundMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; @@ -82,16 +84,72 @@ class PagesTest extends FeatureTestCase public function testLogStatisticsPageIsAvailableUnderOther(): void { - $this->loginAs() - ->get(route('business.pages.show', [ - 'section' => 'other', - 'page' => 'log-statistics', - ])) - ->assertOk() - ->assertSee('data-log-statistics', false) - ->assertSeeText('日志统计页面已创建') - ->assertSeeText('数据来源:待接入') - ->assertSeeText('统计口径:待配置'); + Carbon::setTestNow(Carbon::parse('2026-11-04 10:26:00', 'Asia/Shanghai')); + + $repository = Mockery::mock(DingWorklogMirrorRepository::class); + $repository->shouldReceive('available')->andReturnTrue(); + $repository->shouldReceive('state')->once()->andReturn([ + 'status' => 'failed', + 'last_error_code' => 'dingtalk_worklog_permission_required', + 'last_attempted_at' => '2026-11-04 10:20:00', + 'last_succeeded_at' => null, + 'mirror_row_count' => 0, + ]); + $repository->shouldReceive('dailySummary') + ->once() + ->with('2026-10-21', '2026-11-03') + ->andReturn([[ + 'statistics_date' => '2026-11-03', + 'submission_count' => 2, + 'submitter_count' => 2, + 'first_submitted_at' => '2026-11-04 10:26:00', + 'last_submitted_at' => '2026-11-04 11:20:00', + ]]); + $repository->shouldReceive('submissionsForDate') + ->once() + ->with('2026-11-03') + ->andReturn([ + (object) [ + 'report_id' => 'report-a', + 'template_name' => '财务日报', + 'creator_userid' => 'user-a', + 'creator_name' => '秋香', + 'submitted_at' => '2026-11-04 10:26:00', + 'statistics_date' => '2026-11-03', + ], + (object) [ + 'report_id' => 'report-b', + 'template_name' => '财务日报', + 'creator_userid' => 'user-b', + 'creator_name' => '李斯', + 'submitted_at' => '2026-11-04 11:20:00', + 'statistics_date' => '2026-11-03', + ], + ]); + $repository->shouldReceive('permissionApplyUrl') + ->once() + ->andReturn('https://open-dev.dingtalk.com/appscope/apply?content=test'); + $this->app->instance(DingWorklogMirrorRepository::class, $repository); + + try { + $this->loginAs() + ->get(route('business.pages.show', [ + 'section' => 'other', + 'page' => 'log-statistics', + ])) + ->assertOk() + ->assertSee('data-log-statistics', false) + ->assertSeeText('钉钉 财务日报 · 次日 12:00 截止') + ->assertSeeText('次日 12:00 前补交的日志,统一计入统计日') + ->assertSeeText('qyapi_report_query') + ->assertSeeText('前往钉钉开通') + ->assertSeeText('2026-11-03') + ->assertSeeText('秋香') + ->assertSeeText('李斯') + ->assertSeeText('2026-11-04 10:26:00'); + } finally { + Carbon::setTestNow(); + } } public function testInventoryReportProvidesAFilteredExportButton(): void diff --git a/tests/Feature/Console/SyncDingWorklogsTest.php b/tests/Feature/Console/SyncDingWorklogsTest.php new file mode 100644 index 00000000..60bc8de1 --- /dev/null +++ b/tests/Feature/Console/SyncDingWorklogsTest.php @@ -0,0 +1,122 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'app.timezone' => 'Asia/Shanghai', + 'dingtalk.worklog.enabled' => true, + 'dingtalk.worklog.template_name' => '财务日报', + 'dingtalk.worklog.lookback_days' => 35, + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key', 191)->primary(); + $table->string('source_key', 64); + $table->string('source_object', 191); + $table->string('target_table', 64); + $table->string('status', 24)->default('pending'); + $table->string('run_mode', 24)->nullable(); + $table->json('cursor')->nullable(); + $table->json('high_watermark')->nullable(); + $table->dateTime('window_started_at')->nullable(); + $table->dateTime('window_ends_at')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('last_upserted_rows')->default(0); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + (require base_path('database/migrations/2026_11_04_230000_create_ding_worklog_reports.php'))->up(); + } + + public function test_command_stores_reports_under_the_correct_statistics_date(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-05 13:00:00', 'Asia/Shanghai')); + + try { + $client = Mockery::mock(DingTalkWorklogClient::class); + $client->shouldReceive('isConfigured')->once()->andReturnTrue(); + $client->shouldReceive('listReports')->once()->andReturn([ + 'pages' => 1, + 'reports' => [ + [ + 'report_id' => 'before-noon', + 'creator_id' => 'user-a', + 'creator_name' => '秋香', + 'template_name' => '财务日报', + 'create_time' => '2026-11-04 10:26:00', + ], + [ + 'report_id' => 'last-minute', + 'creator_id' => 'user-b', + 'creator_name' => '李斯', + 'template_name' => '财务日报', + 'create_time' => '2026-11-05 11:59:59', + ], + [ + 'report_id' => 'noon', + 'creator_id' => 'user-c', + 'creator_name' => '晨曦', + 'template_name' => '财务日报', + 'create_time' => '2026-11-05 12:00:00', + ], + ], + ]); + $this->app->instance(DingTalkWorklogClient::class, $client); + + $this->artisan('business-mirror:sync-ding-worklogs') + ->expectsOutputToContain('写入/更新 3 条') + ->assertSuccessful(); + + $rows = DB::connection('business_mirror') + ->table('ding_worklog_reports') + ->orderBy('report_id') + ->get(['report_id', 'creator_userid', 'statistics_date']) + ->map(static fn (object $row): array => (array) $row) + ->all(); + + $this->assertSame([ + [ + 'report_id' => 'before-noon', + 'creator_userid' => 'user-a', + 'statistics_date' => '2026-11-03', + ], + [ + 'report_id' => 'last-minute', + 'creator_userid' => 'user-b', + 'statistics_date' => '2026-11-04', + ], + [ + 'report_id' => 'noon', + 'creator_userid' => 'user-c', + 'statistics_date' => '2026-11-05', + ], + ], $rows); + } finally { + Carbon::setTestNow(); + } + } +} diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index eb7d11ed..975af505 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -157,6 +157,12 @@ class BusinessMirrorScheduleTest extends TestCase $contents, $script, ); + $this->assertStringContainsString( + '*/15 * * * * root /usr/bin/flock -n /run/caiwu-ding-worklog-sync.lock /usr/bin/docker exec -u www-data caiwu_app php artisan business-mirror:sync-ding-worklogs --quiet', + $contents, + $script, + ); + $this->assertSame(1, substr_count($contents, 'business-mirror:sync-ding-worklogs --quiet'), $script); $this->assertStringContainsString( "cat > /etc/cron.d/caiwu-ding-process-details <<'EOF'\n" . "CRON_TZ=Asia/Shanghai\n" @@ -196,6 +202,20 @@ class BusinessMirrorScheduleTest extends TestCase ); } + public function test_laravel_scheduler_runs_worklog_sync_every_fifteen_minutes(): void + { + $contents = file_get_contents(dirname(__DIR__, 3) . '/app/Console/Kernel.php'); + + $this->assertIsString($contents); + $this->assertStringContainsString( + "\$schedule->command('business-mirror:sync-ding-worklogs --quiet')\n" + . " ->cron('*/15 * * * *')\n" + . " ->timezone('Asia/Shanghai')\n" + . ' ->withoutOverlapping(15)', + $contents, + ); + } + public function test_configured_lookup_indexes_avoid_known_long_text_columns(): void { $contents = file_get_contents(dirname(__DIR__, 3) . '/config/upstream_mirrors.php'); diff --git a/tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php b/tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php new file mode 100644 index 00000000..b65d204f --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php @@ -0,0 +1,126 @@ + 'test-client', + 'dingtalk.client_secret' => 'test-secret', + 'dingtalk.app_token_url' => 'https://example.test/token', + 'dingtalk.timeout' => 3, + 'dingtalk.worklog.template_name' => '财务日报', + 'dingtalk.worklog.page_size' => 2, + 'dingtalk.worklog.max_pages' => 10, + ]); + } + + public function test_reports_are_read_across_pages_and_deduplicated(): void + { + Http::fake(function (Request $request) { + if (str_starts_with($request->url(), 'https://example.test/token')) { + return Http::response([ + 'errcode' => 0, + 'access_token' => 'test-token', + 'expires_in' => 7200, + ]); + } + + $cursor = (int) ($request->data()['cursor'] ?? 0); + if ($cursor === 0) { + return Http::response([ + 'errcode' => 0, + 'result' => [ + 'data_list' => [ + [ + 'report_id' => 'report-a', + 'creator_name' => '秋香', + 'creator_userid' => 'user-a', + 'template_name' => '财务日报', + 'create_time' => 1793768760000, + ], + [ + 'report_id' => 'report-b', + 'creator_name' => '李斯', + 'creator_id' => 'user-b', + 'template_name' => '财务日报', + 'create_time' => 1793772000000, + ], + ], + 'has_more' => true, + 'next_cursor' => 2, + ], + ]); + } + + return Http::response([ + 'errcode' => 0, + 'result' => [ + 'data_list' => [[ + 'report_id' => 'report-b', + 'creator_name' => '李斯', + 'creator_id' => 'user-b', + 'template_name' => '财务日报', + 'create_time' => 1793772000000, + ]], + 'has_more' => false, + 'next_cursor' => 0, + ], + ]); + }); + + $result = app(DingTalkWorklogClient::class)->listReports( + Carbon::parse('2026-10-01 00:00:00', 'Asia/Shanghai'), + Carbon::parse('2026-11-05 23:59:59', 'Asia/Shanghai'), + '财务日报', + ); + + $this->assertSame(2, $result['pages']); + $this->assertSame(['report-a', 'report-b'], array_column($result['reports'], 'report_id')); + Http::assertSentCount(3); + Http::assertSent(static fn (Request $request): bool => + str_contains($request->url(), '/topapi/report/list?access_token=test-token') + && ($request->data()['template_name'] ?? null) === '财务日报' + && ($request->data()['size'] ?? null) === 2 + ); + } + + public function test_missing_report_query_permission_has_a_stable_error_code(): void + { + Http::fake([ + 'https://example.test/token*' => Http::response([ + 'errcode' => 0, + 'access_token' => 'test-token', + ]), + 'https://oapi.dingtalk.com/topapi/report/list*' => Http::response([ + 'errcode' => 88, + 'subcode' => 60011, + 'errmsg' => 'missing permission: qyapi_report_query', + ]), + ]); + + try { + app(DingTalkWorklogClient::class)->listReports( + Carbon::parse('2026-10-01 00:00:00', 'Asia/Shanghai'), + Carbon::parse('2026-11-05 23:59:59', 'Asia/Shanghai'), + '财务日报', + ); + $this->fail('缺少日志查询权限时应抛出异常。'); + } catch (DingTalkWorklogException $exception) { + $this->assertSame('dingtalk_worklog_permission_required', $exception->errorCode); + } + } +} diff --git a/tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php b/tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php new file mode 100644 index 00000000..c2459acf --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php @@ -0,0 +1,171 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'app.timezone' => 'Asia/Shanghai', + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key', 191)->primary(); + $table->string('source_key', 64); + $table->string('source_object', 191); + $table->string('target_table', 64); + $table->string('status', 24)->default('pending'); + $table->string('run_mode', 24)->nullable(); + $table->json('cursor')->nullable(); + $table->json('high_watermark')->nullable(); + $table->dateTime('window_started_at')->nullable(); + $table->dateTime('window_ends_at')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('last_upserted_rows')->default(0); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->string('last_error_code', 120)->nullable(); + $table->timestamps(); + }); + (require base_path('database/migrations/2026_11_04_230000_create_ding_worklog_reports.php'))->up(); + + $this->repository = app(DingWorklogMirrorRepository::class); + } + + public function test_submissions_before_noon_belong_to_the_previous_statistics_day(): void + { + $this->assertSame( + '2026-11-03', + DingWorklogMirrorRepository::statisticsDate('2026-11-04 10:26:00')->toDateString(), + ); + $this->assertSame( + '2026-11-04', + DingWorklogMirrorRepository::statisticsDate('2026-11-05 11:59:59')->toDateString(), + ); + $this->assertSame( + '2026-11-03', + DingWorklogMirrorRepository::statisticsDate( + Carbon::parse('2026-11-04 10:26:00', 'Asia/Shanghai')->getTimestampMs(), + )->toDateString(), + ); + } + + public function test_noon_is_the_cutoff_for_the_next_statistics_day(): void + { + $this->assertSame( + '2026-11-05', + DingWorklogMirrorRepository::statisticsDate('2026-11-05 12:00:00')->toDateString(), + ); + } + + public function test_daily_summary_and_details_use_the_saved_statistics_date(): void + { + Carbon::setTestNow(Carbon::parse('2026-11-05 15:00:00', 'Asia/Shanghai')); + + try { + $now = now(); + $this->repository->upsertReports([ + [ + 'report_id' => 'report-a', + 'template_name' => '财务日报', + 'creator_userid' => 'user-a', + 'creator_name' => '秋香', + 'submitted_at' => '2026-11-04 10:26:00', + 'statistics_date' => '2026-11-03', + 'remark' => null, + 'raw_payload' => '{}', + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + [ + 'report_id' => 'report-b', + 'template_name' => '财务日报', + 'creator_userid' => 'user-b', + 'creator_name' => '李斯', + 'submitted_at' => '2026-11-04 11:20:00', + 'statistics_date' => '2026-11-03', + 'remark' => null, + 'raw_payload' => '{}', + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + [ + 'report_id' => 'report-c', + 'template_name' => '财务日报', + 'creator_userid' => 'user-a', + 'creator_name' => '秋香', + 'submitted_at' => '2026-11-05 12:00:00', + 'statistics_date' => '2026-11-05', + 'remark' => null, + 'raw_payload' => '{}', + 'synced_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + ]); + $this->repository->recordSuccess( + 3, + '财务日报', + Carbon::parse('2026-10-01 00:00:00', 'Asia/Shanghai'), + $now, + ); + + $summary = $this->repository->dailySummary('2026-11-03', '2026-11-05'); + $this->assertSame([ + [ + 'statistics_date' => '2026-11-05', + 'submission_count' => 1, + 'submitter_count' => 1, + 'first_submitted_at' => '2026-11-05 12:00:00', + 'last_submitted_at' => '2026-11-05 12:00:00', + ], + [ + 'statistics_date' => '2026-11-03', + 'submission_count' => 2, + 'submitter_count' => 2, + 'first_submitted_at' => '2026-11-04 10:26:00', + 'last_submitted_at' => '2026-11-04 11:20:00', + ], + ], $summary); + + $details = $this->repository->submissionsForDate('2026-11-03'); + $this->assertSame(['report-b', 'report-a'], array_column($details, 'report_id')); + $this->assertSame('succeeded', $this->repository->state()['status']); + $this->assertSame(3, (int) $this->repository->state()['mirror_row_count']); + } finally { + Carbon::setTestNow(); + } + } + + public function test_permission_failure_is_exposed_to_the_page(): void + { + $this->repository->recordFailure('dingtalk_worklog_permission_required'); + + $state = $this->repository->state(); + $this->assertSame('failed', $state['status']); + $this->assertSame('dingtalk_worklog_permission_required', $state['last_error_code']); + $this->assertTrue(DingWorklogMirrorRepository::isPermissionError($state['last_error_code'])); + } +} -- 2.47.2