feat: 增加日志漏写翻倍扣分规则 #885

Merged
renshen merged 1 commits from feature/renshen-worklog-penalty-rule into main 2026-11-05 11:45:17 +08:00
11 changed files with 420 additions and 35 deletions

View File

@ -4,7 +4,6 @@ namespace App\Console\Commands;
use App\Services\Auth\FinanceRoster;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Exceptions\DingTalkWorklogException;
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
use Modules\EcommerceFinance\Services\DingTalkWorklogClient;
@ -66,15 +65,20 @@ class SyncDingWorklogs extends Command
'trim',
(array) config('dingtalk.worklog.finance_only_templates', ['空白日志']),
)));
$financeMembers = [];
$financeMembers = null;
$rows = [];
foreach ($reports as $reportId => $entry) {
$report = $entry['report'];
$templateName = trim((string) ($report['template_name'] ?? $entry['requested_template']));
$creatorUserId = mb_substr(trim((string) ($report['creator_userid'] ?? $report['creator_id'] ?? '')), 0, 128);
if (in_array($templateName, $financeOnlyTemplates, true)
&& ! $this->isFinanceMember($creatorUserId, $financeRoster, $financeMembers)) {
continue;
if (in_array($templateName, $financeOnlyTemplates, true)) {
$financeMembers ??= array_fill_keys(
array_column($financeRoster->cachedFinanceMembers(), 'userid'),
true,
);
if (! isset($financeMembers[$creatorUserId])) {
continue;
}
}
$submittedRaw = $report['create_time']
?? $report['created_at']
@ -147,28 +151,4 @@ class SyncDingWorklogs extends Command
return $templates !== [] ? $templates : ['财务日报'];
}
/**
* “空白日志”是全公司共用模板,只统计财务中心成员的记录。
*
* @param array<string,bool> $members
*/
private function isFinanceMember(string $userId, FinanceRoster $roster, array &$members): bool
{
if ($userId === '') {
return false;
}
if (array_key_exists($userId, $members)) {
return $members[$userId];
}
return $members[$userId] = (bool) Cache::remember(
'dingtalk:worklog:finance-member:' . hash('sha256', $userId),
now()->addMinutes(max((int) config('dingtalk.worklog.finance_cache_minutes', 720), 1)),
static function () use ($roster, $userId): bool {
$member = $roster->findEligible($userId);
return $member !== null && empty($member['restricted']);
},
);
}
}

View File

@ -2,11 +2,14 @@
namespace App\Services\Auth;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Services\UpstreamReadOnlyQueryFactory;
/** Single-person, current HR authorization lookup; no HR rows or stale grants are cached. */
class FinanceRoster
{
private const FINANCE_MEMBERS_CACHE_KEY = 'dingtalk:finance-members:v1';
public static function isDesignatedSuperAdmin(string $userId): bool
{
return $userId !== '' && in_array($userId, config('dingtalk.super_admin_user_ids', []), true);
@ -101,6 +104,75 @@ class FinanceRoster
];
}
/**
* 当前财务中心在职人员,只用于日志应提交名单和统计口径。
*
* @return list<array{userid:string,name:string}>
*/
public function financeMembers(): array
{
$roots = array_values(array_filter(
array_map('strval', (array) config('dingtalk.finance_department_ids', [])),
static fn (string $id): bool => ctype_digit($id) && (int) $id > 0,
));
if ($roots === []) {
return [];
}
$placeholders = implode(',', array_fill(0, count($roots), '?'));
$sql = <<<SQL
WITH finance_groups AS (
SELECT Id, parent_id, 0 AS depth FROM rpt.hr_groups WHERE Id IN ({$placeholders})
UNION ALL
SELECT child.Id, child.parent_id, parent.depth + 1
FROM rpt.hr_groups child
JOIN finance_groups parent ON child.parent_id = parent.Id
WHERE parent.depth < 20
), employee_departments AS (
SELECT e.userid, TRY_CAST(REPLACE(value, '"', '') AS bigint) AS dept_id
FROM rpt.hr_employee e
CROSS APPLY STRING_SPLIT(REPLACE(REPLACE(e.dept_id_list, '[', ''), ']', ''), ',')
WHERE e.active = 1
), flower_departments AS (
SELECT f.flowerNameId AS userid, TRY_CAST(REPLACE(value, '"', '') AS bigint) AS dept_id
FROM rpt.hr_flowerName_book f
CROSS APPLY STRING_SPLIT(REPLACE(REPLACE(f.deptId, '[', ''), ']', ''), ',')
WHERE f.leaveDate IS NULL AND f.flowerNameId IS NOT NULL
), finance_users AS (
SELECT DISTINCT userid FROM employee_departments WHERE dept_id IN (SELECT Id FROM finance_groups)
UNION
SELECT DISTINCT userid FROM flower_departments WHERE dept_id IN (SELECT Id FROM finance_groups)
)
SELECT DISTINCT f.flowerNameId AS userid, f.name, f.flowerName
FROM finance_users u
JOIN rpt.hr_flowerName_book f ON f.flowerNameId = u.userid
WHERE f.leaveDate IS NULL
ORDER BY f.flowerName, f.name
SQL;
$rows = $this->queries->forSourceWithTimeout('operations_replica', 60)->select($sql, $roots);
return array_values(array_filter(array_map(static function (array $row): ?array {
$userId = trim((string) ($row['userid'] ?? ''));
$flowerName = trim((string) ($row['flowerName'] ?? ''));
$name = trim((string) ($row['name'] ?? ''));
if ($userId === '' || ($flowerName === '' && $name === '')) {
return null;
}
return ['userid' => $userId, 'name' => $flowerName !== '' ? $flowerName : $name];
}, $rows)));
}
/** @return list<array{userid:string,name:string}> */
public function cachedFinanceMembers(): array
{
return (array) Cache::remember(
self::FINANCE_MEMBERS_CACHE_KEY,
now()->addMinutes(max((int) config('dingtalk.finance_roster_cache_minutes', 720), 1)),
fn (): array => $this->financeMembers(),
);
}
/** Minimal, bounded directory search for workflow selection; no HR dataset is cached. */
public function search(string $term): array
{

View File

@ -12,6 +12,7 @@ return [
// Verified HR roots: 简尚财务中心 and 龙晨品牌中心/财务中心.
'finance_department_ids' => array_values(array_filter(array_map('trim', explode(',', env('DINGTALK_FINANCE_DEPARTMENT_IDS', '22848291,994080505'))))),
'finance_roster_cache_minutes' => max((int) env('DINGTALK_FINANCE_ROSTER_CACHE_MINUTES', 720), 1),
// Individually approved, current enterprise members; never names or whole departments.
// This grants ordinary login only, with the exact courier page scope below.
'limited_login_user_ids' => array_values(array_filter(array_map('trim', explode(',', env('DINGTALK_LIMITED_LOGIN_USER_IDS', ''))))),
@ -59,7 +60,6 @@ return [
'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),
'finance_cache_minutes' => max((int) env('DINGTALK_WORKLOG_FINANCE_CACHE_MINUTES', 720), 1),
'permission_scope' => 'qyapi_report_query',
],
];

View File

@ -189,6 +189,31 @@ class DingWorklogMirrorRepository
->all();
}
public function earliestStatisticsDate(): ?string
{
$date = $this->connection->table(self::TABLE)->min('statistics_date');
return $date ? (string) $date : null;
}
/**
* @return list<array{creator_userid:string,creator_name:string,statistics_date:string}>
*/
public function submittedDatesByUser(string $from, string $to): array
{
return $this->connection->table(self::TABLE)
->whereBetween('statistics_date', [$from, $to])
->orderBy('statistics_date')
->get(['creator_userid', 'creator_name', 'statistics_date'])
->map(static fn (object $row): array => [
'creator_userid' => (string) ($row->creator_userid ?? ''),
'creator_name' => (string) ($row->creator_name ?? ''),
'statistics_date' => (string) $row->statistics_date,
])
->values()
->all();
}
public static function statisticsDate(CarbonInterface|int|string $submittedAt): Carbon
{
$submitted = self::submittedAt($submittedAt)->timezone(

View File

@ -0,0 +1,117 @@
<?php
namespace Modules\EcommerceFinance\Services;
use App\Services\Auth\FinanceRoster;
use Carbon\CarbonInterface;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
class DingWorklogPenaltyCalculator
{
private const BASE_POINTS = '10';
public function __construct(
private readonly DingWorklogMirrorRepository $repository,
private readonly FinanceRoster $roster,
) {}
/**
* @return array{
* start_date:?string,
* end_date:?string,
* members:list<array{
* userid:string,
* name:string,
* missed_dates:list<string>,
* missed_count:int,
* penalty_points:string,
* penalty_points_formatted:string,
* penalty_formula:string
* }>
* }
*/
public function summary(string $from, string $to, CarbonInterface $at): array
{
$timezone = (string) config('app.timezone', 'Asia/Shanghai');
$now = Carbon::instance($at)->timezone($timezone);
$requestedStart = Carbon::parse($from, $timezone)->startOfDay();
$requestedEnd = Carbon::parse($to, $timezone)->startOfDay();
$latestClosed = $now->hour < 12
? $now->subDays(2)->startOfDay()
: $now->subDay()->startOfDay();
$end = $requestedEnd->lessThan($latestClosed) ? $requestedEnd->copy() : $latestClosed;
$earliest = $this->repository->earliestStatisticsDate();
if ($earliest === null) {
return ['start_date' => null, 'end_date' => null, 'members' => []];
}
$earliestDate = Carbon::parse($earliest, $timezone)->startOfDay();
$start = $requestedStart->greaterThan($earliestDate) ? $requestedStart->copy() : $earliestDate;
if ($start->greaterThan($end)) {
return ['start_date' => null, 'end_date' => null, 'members' => []];
}
$submitted = [];
foreach ($this->repository->submittedDatesByUser($start->toDateString(), $end->toDateString()) as $row) {
if ($row['creator_userid'] !== '') {
$submitted[$row['creator_userid']][$row['statistics_date']] = true;
}
}
$members = [];
foreach ($this->roster->cachedFinanceMembers() as $member) {
$userId = trim((string) ($member['userid'] ?? ''));
if ($userId === '') {
continue;
}
$members[$userId] = [
'userid' => $userId,
'name' => trim((string) ($member['name'] ?? '')) ?: $userId,
'missed_dates' => [],
'missed_count' => 0,
'penalty_points' => '0',
'penalty_formula' => [],
];
}
foreach ($members as $userId => &$member) {
$sequence = 0;
for ($date = $start->copy(); $date->lessThanOrEqualTo($end); $date->addDay()) {
$dateKey = $date->toDateString();
if (isset($submitted[$userId][$dateKey])) {
continue;
}
$sequence++;
$increment = bcmul(self::BASE_POINTS, bcpow('2', (string) ($sequence - 1), 0), 0);
$member['penalty_points'] = bcadd($member['penalty_points'], $increment, 0);
$member['penalty_formula'][] = $increment;
$member['missed_dates'][] = $dateKey;
$member['missed_count']++;
}
}
unset($member);
$rows = array_values(array_filter($members, static fn (array $member): bool => $member['missed_count'] > 0));
usort($rows, static fn (array $left, array $right): int =>
(bccomp($right['penalty_points'], $left['penalty_points']) ?: strcmp($left['name'], $right['name']))
);
return [
'start_date' => $start->toDateString(),
'end_date' => $end->toDateString(),
'members' => array_map(function (array $member): array {
$member['penalty_points_formatted'] = $this->formatPoints($member['penalty_points']);
$member['penalty_formula'] = implode(' + ', $member['penalty_formula']);
return $member;
}, $rows),
];
}
private function formatPoints(string $points): string
{
return preg_replace('/\B(?=(\d{3})+(?!\d))/', ',', $points) ?: $points;
}
}

View File

@ -5,12 +5,14 @@ namespace Modules\EcommerceFinance\View;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
use Modules\EcommerceFinance\Services\DingWorklogPenaltyCalculator;
use Throwable;
class DingWorklogStatisticsPageData
{
public function __construct(
private readonly DingWorklogMirrorRepository $repository,
private readonly DingWorklogPenaltyCalculator $penaltyCalculator,
) {}
public function page(Request $request): array
@ -43,6 +45,8 @@ class DingWorklogStatisticsPageData
$daily = [];
$selectedDate = $this->date($request->query('date'))?->toDateString();
$submissions = [];
$penalty = ['start_date' => null, 'end_date' => null, 'members' => []];
$penaltyError = null;
if ($this->repository->available()) {
try {
$daily = $this->repository->dailySummary($from->toDateString(), $to->toDateString());
@ -60,6 +64,17 @@ class DingWorklogStatisticsPageData
$syncState = 'failed';
$errorCode = 'dingtalk_worklog_read_failed';
}
try {
$penalty = $this->penaltyCalculator->summary(
$from->toDateString(),
$to->toDateString(),
now(),
);
} catch (Throwable $exception) {
report($exception);
$penaltyError = '日志漏写扣分暂时无法计算。';
}
}
$currentDate = $latestStatisticsDate->toDateString();
@ -91,6 +106,8 @@ class DingWorklogStatisticsPageData
'worklogCurrent' => $current,
'worklogDaily' => $daily,
'worklogSubmissions' => $submissions,
'worklogPenalty' => $penalty,
'worklogPenaltyError' => $penaltyError,
'worklogDays' => (int) $from->diffInDays($to) + 1,
'worklogTotalSubmissions' => array_sum(array_column($daily, 'submission_count')),
'worklogTemplateName' => (string) config('dingtalk.worklog.display_name', '财务日报 / 日志'),

View File

@ -203,6 +203,25 @@
background: var(--vip-content-accent-soft, #F7F0DE);
}
.log-statistics-table .is-wrapped {
min-width: 18rem;
white-space: normal;
line-height: 1.6;
}
.log-statistics-rule {
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--vip-border, #D8D2C7);
background: #fffdf8;
color: var(--vip-content-muted, #595959);
font-size: 0.75rem;
line-height: 1.7;
}
.log-statistics-rule strong {
color: var(--vip-content-ink, #171717);
}
.log-statistics-empty {
padding: 2rem 1rem;
color: var(--vip-content-muted, #595959);
@ -380,4 +399,50 @@
</div>
@endif
</section>
<section class="log-statistics-panel" aria-label="日志漏写扣分统计" data-worklog-penalty>
<div class="log-statistics-panel__head">
<strong>日志漏写扣分统计</strong>
<span>
@if ($worklogPenalty['start_date'])
{{ $worklogPenalty['start_date'] }} 至 {{ $worklogPenalty['end_date'] }}
@else
暂无已截止统计日
@endif
</span>
</div>
<div class="log-statistics-rule">
<strong>扣分规则:</strong>第 1 次漏写扣 10 分,第 2 次扣 20 分,第 3 次扣 40 分,之后每次在上一次基础上翻倍并累计。只统计已经超过“次日 12:00”截止时间的日期。
</div>
@if ($worklogPenaltyError)
<div class="log-statistics-empty">{{ $worklogPenaltyError }}</div>
@elseif ($worklogPenalty['members'] === [])
<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>
</tr>
</thead>
<tbody>
@foreach ($worklogPenalty['members'] as $penalty)
<tr>
<td>{{ $penalty['name'] }}</td>
<td class="is-number">{{ number_format((int) $penalty['missed_count']) }}</td>
<td class="is-wrapped">{{ implode('、', $penalty['missed_dates']) }}</td>
<td class="is-wrapped">{{ $penalty['penalty_formula'] }}</td>
<td class="is-number"><strong>{{ $penalty['penalty_points_formatted'] }}</strong></td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endif
</section>
</div>

View File

@ -21,6 +21,7 @@ use Modules\EcommerceFinance\Repositories\NonJingxiRefundMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingAlipayBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository;
use Modules\EcommerceFinance\Repositories\ThirdPartyWarehouseStorageMirrorRepository;
use Modules\EcommerceFinance\Services\DingWorklogPenaltyCalculator;
use Modules\EcommerceFinance\Services\RefundPendingSyncStatus;
use Modules\EcommerceFinance\View\OrderDataPageData;
use Tests\Feature\FeatureTestCase;
@ -130,6 +131,21 @@ class PagesTest extends FeatureTestCase
->once()
->andReturn('https://open-dev.dingtalk.com/appscope/apply?content=test');
$this->app->instance(DingWorklogMirrorRepository::class, $repository);
$penalty = Mockery::mock(DingWorklogPenaltyCalculator::class);
$penalty->shouldReceive('summary')->once()->andReturn([
'start_date' => '2026-10-21',
'end_date' => '2026-11-03',
'members' => [[
'userid' => 'jiangling',
'name' => '江陵',
'missed_dates' => ['2026-10-22', '2026-10-24', '2026-10-30'],
'missed_count' => 3,
'penalty_points' => '70',
'penalty_points_formatted' => '70',
'penalty_formula' => '10 + 20 + 40',
]],
]);
$this->app->instance(DingWorklogPenaltyCalculator::class, $penalty);
try {
$this->loginAs()
@ -149,7 +165,12 @@ class PagesTest extends FeatureTestCase
->assertSeeText('2026-11-04 10:26:00')
->assertSee('id="worklog-detail"', false)
->assertSee('title="查看 2026-11-03 提交人姓名"', false)
->assertSee('title="查看 2026-11-03 日志明细"', false);
->assertSee('title="查看 2026-11-03 日志明细"', false)
->assertSee('data-worklog-penalty', false)
->assertSeeText('第 1 次漏写扣 10 分')
->assertSeeText('江陵')
->assertSeeText('10 + 20 + 40')
->assertSeeText('70');
} finally {
Carbon::setTestNow();
}

View File

@ -171,10 +171,9 @@ class SyncDingWorklogsTest extends TestCase
$this->app->instance(DingTalkWorklogClient::class, $client);
$roster = Mockery::mock(FinanceRoster::class);
$roster->shouldReceive('findEligible')->once()->with('user-renshen')
->andReturn(['restricted' => false]);
$roster->shouldReceive('findEligible')->once()->with('user-other')
->andReturn(['restricted' => true]);
$roster->shouldReceive('cachedFinanceMembers')->once()->andReturn([
['userid' => 'user-renshen', 'name' => '人参'],
]);
$this->app->instance(FinanceRoster::class, $roster);
$this->artisan('business-mirror:sync-ding-worklogs')

View File

@ -25,6 +25,34 @@ class FinanceRosterTest extends TestCase
$this->assertSame([], $roster->search("张'_%["));
}
public function test_finance_members_are_loaded_from_descendant_departments(): void
{
config(['dingtalk.finance_department_ids' => ['22848291', '994080505']]);
$query = Mockery::mock(UpstreamReadOnlyQuery::class);
$query->shouldReceive('select')->once()->with(
Mockery::on(static function (string $sql): bool {
UpstreamReadOnlyQuery::assertReadOnlySql($sql);
return str_contains($sql, 'WITH finance_groups')
&& str_contains($sql, "Id IN (?,?)")
&& str_contains($sql, 'STRING_SPLIT')
&& str_contains($sql, "REPLACE(value, '\"', '')");
}),
['22848291', '994080505'],
)->andReturn([
['userid' => '1001', 'name' => '张宏', 'flowerName' => '人参'],
['userid' => '1002', 'name' => '吕庭', 'flowerName' => '江陵'],
]);
$factory = Mockery::mock(UpstreamReadOnlyQueryFactory::class);
$factory->shouldReceive('forSourceWithTimeout')
->once()->with('operations_replica', 60)->andReturn($query);
$this->assertSame([
['userid' => '1001', 'name' => '人参'],
['userid' => '1002', 'name' => '江陵'],
], (new FinanceRoster($factory))->financeMembers());
}
#[DataProvider('rosterCases')]
public function test_roster_authorization(array $overrides, bool $expected): void
{

View File

@ -0,0 +1,61 @@
<?php
namespace Tests\Unit\EcommerceFinance;
use App\Services\Auth\FinanceRoster;
use Illuminate\Support\Carbon;
use Mockery;
use Modules\EcommerceFinance\Repositories\DingWorklogMirrorRepository;
use Modules\EcommerceFinance\Services\DingWorklogPenaltyCalculator;
use Tests\TestCase;
class DingWorklogPenaltyCalculatorTest extends TestCase
{
public function test_penalties_double_for_each_person_and_accumulate(): void
{
$submitted = [];
$misses = [
'jiangling' => ['2026-10-10', '2026-10-12', '2026-10-18'],
'qiuxiang' => ['2026-10-12', '2026-10-18'],
];
foreach (['jiangling' => '江陵', 'qiuxiang' => '秋香'] as $userId => $name) {
for ($day = 10; $day <= 18; $day++) {
$date = sprintf('2026-10-%02d', $day);
if (! in_array($date, $misses[$userId], true)) {
$submitted[] = [
'creator_userid' => $userId,
'creator_name' => $name,
'statistics_date' => $date,
];
}
}
}
$repository = Mockery::mock(DingWorklogMirrorRepository::class);
$repository->shouldReceive('earliestStatisticsDate')->once()->andReturn('2026-10-01');
$repository->shouldReceive('submittedDatesByUser')
->once()->with('2026-10-10', '2026-10-18')->andReturn($submitted);
$roster = Mockery::mock(FinanceRoster::class);
$roster->shouldReceive('cachedFinanceMembers')->once()->andReturn([
['userid' => 'jiangling', 'name' => '江陵'],
['userid' => 'qiuxiang', 'name' => '秋香'],
]);
$result = (new DingWorklogPenaltyCalculator($repository, $roster))->summary(
'2026-10-10',
'2026-10-18',
Carbon::parse('2026-10-20 10:00:00', 'Asia/Shanghai'),
);
$this->assertSame('2026-10-10', $result['start_date']);
$this->assertSame('2026-10-18', $result['end_date']);
$this->assertSame('江陵', $result['members'][0]['name']);
$this->assertSame(['2026-10-10', '2026-10-12', '2026-10-18'], $result['members'][0]['missed_dates']);
$this->assertSame(3, $result['members'][0]['missed_count']);
$this->assertSame('10 + 20 + 40', $result['members'][0]['penalty_formula']);
$this->assertSame('70', $result['members'][0]['penalty_points']);
$this->assertSame('秋香', $result['members'][1]['name']);
$this->assertSame('10 + 20', $result['members'][1]['penalty_formula']);
$this->assertSame('30', $result['members'][1]['penalty_points']);
}
}