feat: 接入钉钉财务日报日志统计 #876
104
app/Console/Commands/SyncDingWorklogs.php
Normal file
104
app/Console/Commands/SyncDingWorklogs.php
Normal file
@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Modules\EcommerceFinance\Exceptions\DingTalkWorklogException;
|
||||
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
|
||||
use Modules\EcommerceFinance\Services\DingTalkWorklogClient;
|
||||
use Throwable;
|
||||
|
||||
class SyncDingWorklogs extends Command
|
||||
{
|
||||
protected $signature = 'business-mirror:sync-ding-worklogs
|
||||
{--days= : 回看天数,默认使用配置值}
|
||||
{--template= : 日志模板名称,默认使用配置值}';
|
||||
|
||||
protected $description = '同步钉钉财务日报到日志统计镜像';
|
||||
|
||||
public function handle(
|
||||
DingTalkWorklogClient $client,
|
||||
DingWorklogMirrorRepository $repository,
|
||||
): int {
|
||||
if (! (bool) config('dingtalk.worklog.enabled', true)) {
|
||||
return self::SUCCESS;
|
||||
}
|
||||
if (! $repository->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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 * * * *')
|
||||
|
||||
@ -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(),
|
||||
|
||||
@ -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',
|
||||
],
|
||||
];
|
||||
|
||||
@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
private function connection(): string
|
||||
{
|
||||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
$schema = Schema::connection($this->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');
|
||||
}
|
||||
};
|
||||
@ -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
|
||||
|
||||
@ -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
|
||||
|
||||
@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
use Throwable;
|
||||
|
||||
class DingTalkWorklogException extends RuntimeException
|
||||
{
|
||||
public function __construct(
|
||||
string $message,
|
||||
public readonly string $errorCode = 'dingtalk_worklog_error',
|
||||
public readonly bool $retryable = false,
|
||||
?Throwable $previous = null,
|
||||
) {
|
||||
parent::__construct($message, 0, $previous);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,245 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Repositories;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Database\ConnectionInterface;
|
||||
use Illuminate\Database\DatabaseManager;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Throwable;
|
||||
|
||||
class DingWorklogMirrorRepository
|
||||
{
|
||||
public const TABLE = 'ding_worklog_reports';
|
||||
|
||||
public const STATE_KEY = 'dingtalk.worklog.finance_daily_reports';
|
||||
|
||||
private readonly ConnectionInterface $connection;
|
||||
|
||||
public function __construct(DatabaseManager $database)
|
||||
{
|
||||
$this->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<string,mixed>|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<array<string,mixed>> $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<array{
|
||||
* statistics_date:string,
|
||||
* submission_count:int,
|
||||
* submitter_count:int,
|
||||
* first_submitted_at:?string,
|
||||
* last_submitted_at:?string
|
||||
* }>
|
||||
*/
|
||||
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<object> */
|
||||
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'));
|
||||
}
|
||||
}
|
||||
166
modules/EcommerceFinance/Services/DingTalkWorklogClient.php
Normal file
166
modules/EcommerceFinance/Services/DingTalkWorklogClient.php
Normal file
@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\Services;
|
||||
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Modules\EcommerceFinance\Exceptions\DingTalkWorklogException;
|
||||
|
||||
class DingTalkWorklogClient
|
||||
{
|
||||
private const LIST_URL = 'https://oapi.dingtalk.com/topapi/report/list';
|
||||
|
||||
private const TOKEN_CACHE_KEY = 'dingtalk:app_access_token';
|
||||
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return trim((string) config('dingtalk.client_id', '')) !== ''
|
||||
&& trim((string) config('dingtalk.client_secret', '')) !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{reports:list<array<string,mixed>>,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)));
|
||||
}
|
||||
}
|
||||
114
modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php
Normal file
114
modules/EcommerceFinance/View/DingWorklogStatisticsPageData.php
Normal file
@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\EcommerceFinance\View;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
|
||||
use Throwable;
|
||||
|
||||
class DingWorklogStatisticsPageData
|
||||
{
|
||||
public function __construct(
|
||||
private readonly DingWorklogMirrorRepository $repository,
|
||||
) {}
|
||||
|
||||
public function page(Request $request): array
|
||||
{
|
||||
$latestStatisticsDate = now()->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2,73 +2,377 @@
|
||||
<style>
|
||||
.log-statistics-page {
|
||||
display: grid;
|
||||
min-height: 22rem;
|
||||
place-items: center;
|
||||
padding: 2rem;
|
||||
}
|
||||
|
||||
.log-statistics-empty {
|
||||
display: grid;
|
||||
width: min(34rem, 100%);
|
||||
justify-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 2rem;
|
||||
border: 1px dashed var(--vip-border, #D8D2C7);
|
||||
border-radius: 12px;
|
||||
background: var(--vip-surface, #fff);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.log-statistics-empty__icon {
|
||||
display: grid;
|
||||
width: 2.75rem;
|
||||
height: 2.75rem;
|
||||
place-items: center;
|
||||
border-radius: 999px;
|
||||
background: var(--vip-content-accent-soft, #F7F0DE);
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
}
|
||||
|
||||
.log-statistics-empty h2 {
|
||||
margin: 0;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font-size: 0.875rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.log-statistics-note {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.65rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
|
||||
.log-statistics-note .material-icons-outlined {
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font-size: 1.15rem;
|
||||
}
|
||||
|
||||
.log-statistics-note strong {
|
||||
display: block;
|
||||
font-size: 0.8125rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-statistics-empty p {
|
||||
margin: 0;
|
||||
.log-statistics-note span {
|
||||
display: block;
|
||||
margin-top: 0.15rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.log-statistics-alert {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.65rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1px solid rgba(184, 0, 0, 0.3);
|
||||
border-radius: 8px;
|
||||
background: rgba(184, 0, 0, 0.04);
|
||||
color: var(--vip-danger, #B80000);
|
||||
font-size: 0.75rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.log-statistics-fields {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 0.4rem;
|
||||
margin-top: 0.25rem;
|
||||
.log-statistics-alert a {
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-statistics-fields span {
|
||||
padding: 0.3rem 0.55rem;
|
||||
.log-statistics-filters {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 0.65rem;
|
||||
padding: 0.85rem 1rem;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 4px;
|
||||
background: #fbfaf6;
|
||||
border-radius: 8px;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
|
||||
.log-statistics-field {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.log-statistics-field input {
|
||||
min-height: 2rem;
|
||||
padding: 0 0.6rem;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 6px;
|
||||
background: var(--vip-surface, #fff);
|
||||
color: var(--vip-content-ink, #171717);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.log-statistics-button {
|
||||
display: inline-flex;
|
||||
min-height: 2rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 0.8rem;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 6px;
|
||||
background: var(--vip-surface, #fff);
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font: inherit;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.log-statistics-button--primary {
|
||||
border-color: var(--vip-content-accent-dark, #856632);
|
||||
background: var(--vip-content-accent-dark, #856632);
|
||||
color: var(--vip-surface, #fff);
|
||||
}
|
||||
|
||||
.log-statistics-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.log-statistics-card {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
padding: 0.9rem 1rem;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
|
||||
.log-statistics-card span {
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
|
||||
.log-statistics-card strong {
|
||||
font-size: 1.15rem;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.log-statistics-panel {
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-radius: 8px;
|
||||
background: var(--vip-surface, #fff);
|
||||
}
|
||||
|
||||
.log-statistics-panel__head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
border-bottom: 1px solid var(--vip-border, #D8D2C7);
|
||||
background: var(--vip-content-accent-soft, #F7F0DE);
|
||||
}
|
||||
|
||||
.log-statistics-panel__head strong {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-statistics-panel__head span {
|
||||
color: var(--vip-content-muted, #595959);
|
||||
font-size: 0.6875rem;
|
||||
}
|
||||
|
||||
.log-statistics-table-wrap {
|
||||
overflow: auto;
|
||||
max-height: 28rem;
|
||||
}
|
||||
|
||||
.log-statistics-table {
|
||||
width: 100%;
|
||||
min-width: 54rem;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.log-statistics-table th,
|
||||
.log-statistics-table td {
|
||||
padding: 0.55rem 0.7rem;
|
||||
border-right: 1px solid var(--vip-border, #D8D2C7);
|
||||
border-bottom: 1px solid var(--vip-border, #D8D2C7);
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.log-statistics-table th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
background: #fffaf0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-statistics-table .is-number {
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.log-statistics-table a {
|
||||
color: var(--vip-content-accent-dark, #856632);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.log-statistics-table tr.is-selected td {
|
||||
background: var(--vip-content-accent-soft, #F7F0DE);
|
||||
}
|
||||
|
||||
.log-statistics-empty {
|
||||
padding: 2rem 1rem;
|
||||
color: var(--vip-content-muted, #595959);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.log-statistics-state {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-statistics-state.is-succeeded { color: var(--vip-success, #53793E); }
|
||||
.log-statistics-state.is-failed { color: var(--vip-danger, #B80000); }
|
||||
.log-statistics-state.is-pending,
|
||||
.log-statistics-state.is-syncing,
|
||||
.log-statistics-state.is-unavailable { color: var(--vip-warning, #935F07); }
|
||||
</style>
|
||||
|
||||
<section class="log-statistics-empty" aria-label="日志统计待接入">
|
||||
<span class="material-icons-outlined log-statistics-empty__icon" aria-hidden="true">query_stats</span>
|
||||
<h2>日志统计页面已创建</h2>
|
||||
<p>页面入口和权限已就绪。数据来源、统计时间范围及汇总字段待确认后接入。</p>
|
||||
<div class="log-statistics-fields" aria-label="待配置项">
|
||||
<span>数据来源:待接入</span>
|
||||
<span>统计口径:待配置</span>
|
||||
<span>更新时间:待接入</span>
|
||||
<div class="log-statistics-note">
|
||||
<span class="material-icons-outlined" aria-hidden="true">schedule</span>
|
||||
<div>
|
||||
<strong>钉钉 {{ $worklogTemplateName }} · 次日 12:00 截止</strong>
|
||||
<span>统计日当天提交的日志,以及次日 12:00 前补交的日志,统一计入统计日;每日中午 12:00 后提交归入下一统计日。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if ($worklogState['permission_required'])
|
||||
<div class="log-statistics-alert" role="alert">
|
||||
<span class="material-icons-outlined" aria-hidden="true">key_off</span>
|
||||
<div>
|
||||
钉钉日志接口尚未授权,需要应用权限 <strong>qyapi_report_query</strong>。
|
||||
@if ($worklogState['permission_apply_url'])
|
||||
<a href="{{ $worklogState['permission_apply_url'] }}" target="_blank" rel="noopener">前往钉钉开通</a>
|
||||
@endif
|
||||
开通后系统会自动重试同步。
|
||||
</div>
|
||||
</div>
|
||||
@elseif ($worklogState['state'] === 'failed')
|
||||
<div class="log-statistics-alert" role="alert">
|
||||
<span class="material-icons-outlined" aria-hidden="true">error_outline</span>
|
||||
<div>日志同步失败,当前展示最近成功数据。错误代码:{{ $worklogState['error_code'] ?: '未知错误' }}</div>
|
||||
</div>
|
||||
@endif
|
||||
|
||||
<form class="log-statistics-filters" method="GET" action="{{ route('business.pages.show', ['section' => 'other', 'page' => 'log-statistics']) }}">
|
||||
<label class="log-statistics-field">
|
||||
<span>开始日期</span>
|
||||
<input type="date" name="from" value="{{ $worklogFilters['from'] }}">
|
||||
</label>
|
||||
<label class="log-statistics-field">
|
||||
<span>结束日期</span>
|
||||
<input type="date" name="to" value="{{ $worklogFilters['to'] }}">
|
||||
</label>
|
||||
<button class="log-statistics-button log-statistics-button--primary" type="submit">查询</button>
|
||||
<a class="log-statistics-button" href="{{ route('business.pages.show', ['section' => 'other', 'page' => 'log-statistics']) }}">重置</a>
|
||||
<span class="log-statistics-state is-{{ $worklogState['state'] }}">
|
||||
<span class="material-icons-outlined" aria-hidden="true">sync</span>
|
||||
@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
|
||||
</span>
|
||||
</form>
|
||||
|
||||
<div class="log-statistics-cards">
|
||||
<div class="log-statistics-card">
|
||||
<span>{{ $worklogCurrent['statistics_date'] }} 提交人数</span>
|
||||
<strong>{{ number_format((int) $worklogCurrent['submitter_count']) }}</strong>
|
||||
</div>
|
||||
<div class="log-statistics-card">
|
||||
<span>{{ $worklogCurrent['statistics_date'] }} 日志条数</span>
|
||||
<strong>{{ number_format((int) $worklogCurrent['submission_count']) }}</strong>
|
||||
</div>
|
||||
<div class="log-statistics-card">
|
||||
<span>当前统计日截止时间</span>
|
||||
<strong>{{ $worklogCutoffAt }}</strong>
|
||||
</div>
|
||||
<div class="log-statistics-card">
|
||||
<span>查询范围日志总数</span>
|
||||
<strong>{{ number_format((int) $worklogTotalSubmissions) }}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section class="log-statistics-panel" aria-label="每日日志提交统计">
|
||||
<div class="log-statistics-panel__head">
|
||||
<strong>每日日志提交统计</strong>
|
||||
<span>{{ $worklogFilters['from'] }} 至 {{ $worklogFilters['to'] }}</span>
|
||||
</div>
|
||||
@if ($worklogDaily === [])
|
||||
<div class="log-statistics-empty">当前时间范围暂无日志提交数据。</div>
|
||||
@else
|
||||
<div class="log-statistics-table-wrap">
|
||||
<table class="log-statistics-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>统计日期</th>
|
||||
<th>截止时间</th>
|
||||
<th>提交人数</th>
|
||||
<th>日志条数</th>
|
||||
<th>首次提交</th>
|
||||
<th>最后提交</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($worklogDaily as $day)
|
||||
@php
|
||||
$isSelected = $worklogFilters['date'] === $day['statistics_date'];
|
||||
$deadline = \Illuminate\Support\Carbon::parse($day['statistics_date'])->addDay()->setTime(12, 0);
|
||||
@endphp
|
||||
<tr @class(['is-selected' => $isSelected])>
|
||||
<td>
|
||||
<a href="{{ route('business.pages.show', [
|
||||
'section' => 'other',
|
||||
'page' => 'log-statistics',
|
||||
'from' => $worklogFilters['from'],
|
||||
'to' => $worklogFilters['to'],
|
||||
'date' => $day['statistics_date'],
|
||||
]) }}">{{ $day['statistics_date'] }}</a>
|
||||
</td>
|
||||
<td>{{ $deadline->format('Y-m-d H:i:s') }}</td>
|
||||
<td class="is-number">{{ number_format((int) $day['submitter_count']) }}</td>
|
||||
<td class="is-number">{{ number_format((int) $day['submission_count']) }}</td>
|
||||
<td>{{ $day['first_submitted_at'] ?: '-' }}</td>
|
||||
<td>{{ $day['last_submitted_at'] ?: '-' }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@endif
|
||||
</section>
|
||||
|
||||
<section class="log-statistics-panel" aria-label="日志提交明细">
|
||||
<div class="log-statistics-panel__head">
|
||||
<strong>日志提交明细</strong>
|
||||
<span>{{ $worklogFilters['date'] }}</span>
|
||||
</div>
|
||||
@if ($worklogSubmissions === [])
|
||||
<div class="log-statistics-empty">所选统计日暂无提交记录。</div>
|
||||
@else
|
||||
<div class="log-statistics-table-wrap">
|
||||
<table class="log-statistics-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>提交人</th>
|
||||
<th>提交时间</th>
|
||||
<th>日志模板</th>
|
||||
<th>日志ID</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach ($worklogSubmissions as $submission)
|
||||
<tr>
|
||||
<td>{{ $submission['creator_name'] ?: ($submission['creator_userid'] ?: '未知提交人') }}</td>
|
||||
<td>{{ $submission['submitted_at'] }}</td>
|
||||
<td>{{ $submission['template_name'] ?: $worklogTemplateName }}</td>
|
||||
<td>{{ $submission['report_id'] }}</td>
|
||||
</tr>
|
||||
@endforeach
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@endif
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@ -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
|
||||
|
||||
122
tests/Feature/Console/SyncDingWorklogsTest.php
Normal file
122
tests/Feature/Console/SyncDingWorklogsTest.php
Normal file
@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature\Console;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Mockery;
|
||||
use Modules\EcommerceFinance\Services\DingTalkWorklogClient;
|
||||
use Tests\TestCase;
|
||||
|
||||
class SyncDingWorklogsTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'database.connections.business_mirror' => [
|
||||
'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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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');
|
||||
|
||||
126
tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php
Normal file
126
tests/Unit/EcommerceFinance/DingTalkWorklogClientTest.php
Normal file
@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Http\Client\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Modules\EcommerceFinance\Exceptions\DingTalkWorklogException;
|
||||
use Modules\EcommerceFinance\Services\DingTalkWorklogClient;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DingTalkWorklogClientTest extends TestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Cache::flush();
|
||||
config([
|
||||
'dingtalk.client_id' => '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);
|
||||
}
|
||||
}
|
||||
}
|
||||
171
tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php
Normal file
171
tests/Unit/EcommerceFinance/DingWorklogMirrorRepositoryTest.php
Normal file
@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\EcommerceFinance;
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
|
||||
use Tests\TestCase;
|
||||
|
||||
class DingWorklogMirrorRepositoryTest extends TestCase
|
||||
{
|
||||
private DingWorklogMirrorRepository $repository;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
config([
|
||||
'database.connections.business_mirror' => [
|
||||
'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']));
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user