feat: 系统化待办按今日同步并优化 Excel 导入

操作记录默认从今日显示,并增强 Excel 同步的类型保护和同名分组匹配。
This commit is contained in:
yueyang 2026-10-28 09:37:21 +08:00
parent 7dd2d66935
commit 48b433be4d
5 changed files with 193 additions and 6 deletions

View File

@ -166,7 +166,11 @@ class SystemizationTodoAuditLogger
/**
* @return array<int, array<string, mixed>>
*/
public function history(int $companyId, int $limit = self::HISTORY_LIMIT): array
public function history(
int $companyId,
int $limit = self::HISTORY_LIMIT,
?string $from = null,
): array
{
if (! $this->tableReady()) {
return [];
@ -174,6 +178,7 @@ class SystemizationTodoAuditLogger
return DB::table(self::TABLE)
->where('company_id', $companyId)
->when($from !== null && $from !== '', fn ($query) => $query->where('at', '>=', $from))
->orderByDesc('id')
->limit(max(1, min($limit, self::HISTORY_LIMIT)))
->get()

View File

@ -157,13 +157,16 @@ class SystemizationTodoWorkbookImporter
$headerInfo['row'],
$companyId,
);
$existing = SystemizationTodo::withoutGlobalScopes()
$activeTodos = SystemizationTodo::withoutGlobalScopes()
->where('company_id', $companyId)
->whereNull('deleted_at')
->whereNotNull('imported_at')
->orderBy('sort_order')
->orderBy('id')
->get();
$rows = $this->alignIncomingCategories($rows, $activeTodos);
$existing = $activeTodos
->filter(static fn (SystemizationTodo $todo): bool => $todo->imported_at !== null)
->values();
[$matches, $newIndexes] = $this->matchRows($rows, $existing);
$matchedIds = array_values($matches);
$retained = $existing
@ -508,6 +511,30 @@ class SystemizationTodoWorkbookImporter
$usedIds[] = $available[0]->id;
}
// 同名待办可能分布在多个内容组,优先匹配同一「类型 + 内容」。
foreach ($rows as $rowIndex => $row) {
if (isset($matches[$rowIndex])) {
continue;
}
$key = $this->matchTitleKey($row['title']);
$available = array_values(array_filter(
$candidates[$key] ?? [],
fn (SystemizationTodo $todo): bool =>
! in_array($todo->id, $usedIds, true)
&& $this->matchGroupKey($todo->category) === $this->matchGroupKey($row['category'])
&& $this->matchGroupKey($todo->section) === $this->matchGroupKey($row['section']),
));
if ($available === []) {
continue;
}
usort($available, static fn (SystemizationTodo $a, SystemizationTodo $b): int =>
abs($a->sort_order - $row['data']['sort_order'])
<=> abs($b->sort_order - $row['data']['sort_order'])
);
$matches[$rowIndex] = $available[0]->id;
$usedIds[] = $available[0]->id;
}
foreach ($rows as $rowIndex => $row) {
if (isset($matches[$rowIndex])) {
continue;
@ -574,6 +601,39 @@ class SystemizationTodoWorkbookImporter
];
}
/**
* 内容组已唯一归属某个类型时,忽略 Excel 中误填的类型占位值。
*
* @param array<int,array<string,mixed>> $rows
* @param \Illuminate\Support\Collection<int,SystemizationTodo> $activeTodos
* @return array<int,array<string,mixed>>
*/
private function alignIncomingCategories(
array $rows,
\Illuminate\Support\Collection $activeTodos,
): array {
$categoriesBySection = [];
foreach ($activeTodos as $todo) {
$sectionKey = $this->matchGroupKey($todo->section);
$category = trim((string) $todo->category);
if ($sectionKey === '' || $category === '') {
continue;
}
$categoriesBySection[$sectionKey][$this->matchText($category)] = $category;
}
foreach ($rows as &$row) {
$categories = $categoriesBySection[$this->matchGroupKey($row['section'])] ?? [];
if (count($categories) === 1) {
$category = reset($categories);
$row['data']['category'] = $category;
$row['category'] = $category;
}
}
return $rows;
}
private function matchTitleKey(?string $value): string
{
$value = preg_replace(

View File

@ -732,12 +732,18 @@ class SystemizationTodos extends Controller
public function history(): JsonResponse
{
$events = $this->audit->history((int) company_id());
$from = $this->historyStartAt();
$events = $this->audit->history(
(int) company_id(),
SystemizationTodoAuditLogger::HISTORY_LIMIT,
$from,
);
return response()->json([
'events' => $events,
'total' => count($events),
'limit' => SystemizationTodoAuditLogger::HISTORY_LIMIT,
'from' => $from,
]);
}
@ -745,8 +751,13 @@ class SystemizationTodos extends Controller
{
$action = trim((string) $request->query('action', ''));
$keyword = trim((string) $request->query('keyword', ''));
$from = $this->historyStartAt();
$rows = array_values(array_filter(
$this->audit->history((int) company_id()),
$this->audit->history(
(int) company_id(),
SystemizationTodoAuditLogger::HISTORY_LIMIT,
$from,
),
fn (array $row): bool => $this->historyMatches($row, $action, $keyword),
));
@ -772,6 +783,11 @@ class SystemizationTodos extends Controller
]);
}
private function historyStartAt(): string
{
return $this->audit->platformNow()->startOfDay()->toDateTimeString();
}
private function historyMatches(array $row, string $action, string $keyword): bool
{
if ($action !== '' && (string) ($row['action'] ?? '') !== $action) {

View File

@ -904,7 +904,7 @@
<input type="search" data-sys-todo-history-keyword placeholder="搜类型、内容、待办事项、变更内容或操作人" aria-label="搜索操作记录">
<button type="button" data-sys-todo-history-export>导出记录 CSV</button>
<span class="sys-todo-history-meta" data-sys-todo-history-meta></span>
<span class="sys-todo-history-meta">时间为北京时间,保留最近 500 条</span>
<span class="sys-todo-history-meta">从今天开始显示,时间为北京时间,最多显示最近 500 条</span>
</div>
<div class="sys-todo-history-scroll">
<table class="sys-todo-history-table">

View File

@ -1311,6 +1311,49 @@ class SystemizationTodosTest extends FeatureTestCase
$this->assertStringNotContainsString('新增:', $csv);
}
public function test_operation_history_starts_from_today(): void
{
$this->loginAs();
try {
$this->travelTo(Carbon::parse('2026-10-27 23:59:00', 'Asia/Shanghai'));
$this->post(route('business.systemization-todos.store'), [
'category' => '收入',
'section' => '操作记录日期',
'title' => '昨天记录',
'owner' => '晨曦',
'assignee' => '栎阳',
'status' => SystemizationTodo::STATUS_INCOMPLETE,
])->assertRedirect();
$this->travelTo(Carbon::parse('2026-10-28 09:00:00', 'Asia/Shanghai'));
$this->post(route('business.systemization-todos.store'), [
'category' => '收入',
'section' => '操作记录日期',
'title' => '今天记录',
'owner' => '晨曦',
'assignee' => '栎阳',
'status' => SystemizationTodo::STATUS_INCOMPLETE,
])->assertRedirect();
$history = $this->getJson(route('business.systemization-todos.history'))
->assertOk()
->assertJsonPath('from', '2026-10-28 00:00:00')
->json();
$titles = array_column($history['events'], 'title');
$this->assertContains('今天记录', $titles);
$this->assertNotContains('昨天记录', $titles);
$csv = $this->get(route('business.systemization-todos.history.export'))
->streamedContent();
$this->assertStringContainsString('今天记录', $csv);
$this->assertStringNotContainsString('昨天记录', $csv);
} finally {
$this->travelBack();
}
}
public function test_excel_sync_audits_changes_and_matches_numbered_group_labels_without_duplicates(): void
{
$this->loginAs();
@ -1375,6 +1418,69 @@ class SystemizationTodosTest extends FeatureTestCase
}
}
public function test_excel_sync_ignores_placeholder_category_when_section_has_one_category(): void
{
$this->loginAs();
$todo = $this->createTodo('收入', '平台收入核对', '平台收入核对', '2026-11-01', 10);
$todo->update(['imported_at' => now()]);
$path = sys_get_temp_dir() . '/systemization-category-guard-' . uniqid() . '.xlsx';
try {
$this->writeWorkbook($path, [[
';lkj',
'平台收入核对',
'平台收入核对',
'晨曦',
'秋香',
'2026-10-28',
'2026-10-29',
'已完成',
null,
]]);
$result = app(SystemizationTodoWorkbookImporter::class)
->sync($path, (int) company_id(), user_id());
$this->assertSame(0, $result['created']);
$this->assertSame(1, $result['updated']);
$this->assertSame('收入', $todo->fresh()->category);
$this->assertSame('秋香', $todo->fresh()->assignee);
} finally {
@unlink($path);
}
}
public function test_excel_sync_matches_repeated_titles_to_their_own_section_first(): void
{
$this->loginAs();
$warehouse = $this->createTodo('聚水潭', '京仓费用', '配置订单利润自动分摊规则', '2026-10-30', 900);
$warehouse->update(['imported_at' => now()]);
$invoice = $this->createTodo('聚水潭', '发票费用', '配置订单利润自动分摊规则', '2026-10-30', 100);
$invoice->update(['imported_at' => now()]);
$path = sys_get_temp_dir() . '/systemization-repeated-title-' . uniqid() . '.xlsx';
try {
$this->writeWorkbook($path, [
['2', '京仓费用', '配置订单利润自动分摊规则', '人参', '人参', '2026-10-30', '2026-10-30', null, null],
['2', '发票费用', '配置订单利润自动分摊规则', '人参', '秋香', '2026-10-30', '2026-10-30', null, null],
]);
$result = app(SystemizationTodoWorkbookImporter::class)
->sync($path, (int) company_id(), user_id());
$this->assertSame(0, $result['created']);
$this->assertSame(2, $result['updated']);
$this->assertSame('京仓费用', $warehouse->fresh()->section);
$this->assertSame('发票费用', $invoice->fresh()->section);
$this->assertSame('人参', $warehouse->fresh()->assignee);
$this->assertSame('秋香', $invoice->fresh()->assignee);
} finally {
@unlink($path);
}
}
public function test_excel_sync_splits_numbered_titles_and_keeps_attachment_on_first_item(): void
{
Storage::fake('uploads');