From dd822e59ba2da31e8fbc763194b1308c19576e3e Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Thu, 3 Dec 2026 17:23:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E7=A7=91=E7=9B=AE=E6=98=A0=E5=B0=84):=20?= =?UTF-8?q?=E8=A1=A5=E6=98=A0=E5=B0=84=E8=87=AA=E5=8A=A8=E5=B8=A6=E5=85=A5?= =?UTF-8?q?=E5=90=8C=E5=90=8D=E8=A7=84=E5=88=99=20(#1704)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补映射时按同名账单项目带入一致的科目模板;冲突时不猜测。 --- .../Business/AccountMappingActions.php | 16 ++ .../Services/AccountMappingSuggestion.php | 167 ++++++++++++++++++ .../financial-rules/account-mapping.blade.php | 69 +++++++- routes/admin.php | 1 + .../Business/AccountMappingPageTest.php | 25 +++ .../AccountMappingSuggestionTest.php | 79 +++++++++ 6 files changed, 356 insertions(+), 1 deletion(-) create mode 100644 modules/EcommerceFinance/Services/AccountMappingSuggestion.php create mode 100644 tests/Unit/EcommerceFinance/AccountMappingSuggestionTest.php diff --git a/app/Http/Controllers/Business/AccountMappingActions.php b/app/Http/Controllers/Business/AccountMappingActions.php index 0d5047a6d..e0f13ceb8 100644 --- a/app/Http/Controllers/Business/AccountMappingActions.php +++ b/app/Http/Controllers/Business/AccountMappingActions.php @@ -12,6 +12,7 @@ use Modules\EcommerceFinance\Services\AccountMappingCoa; use Modules\EcommerceFinance\Services\AccountMappingCoverage; use Modules\EcommerceFinance\Services\AccountMappingResyncDispatcher; use Modules\EcommerceFinance\Services\AccountMappingStore; +use Modules\EcommerceFinance\Services\AccountMappingSuggestion; use Modules\EcommerceFinance\Services\AccountMappingValidator; use Modules\EcommerceFinance\Services\AccountMappingWorkbookImporter; use RuntimeException; @@ -74,6 +75,7 @@ class AccountMappingActions extends Controller private readonly AccountMappingCoa $coa, private readonly AccountMappingWorkbookImporter $importer, private readonly AccountMappingCoverage $coverage, + private readonly AccountMappingSuggestion $suggestion, ) { $this->middleware('auth'); $this->middleware('company.identify'); @@ -114,6 +116,20 @@ class AccountMappingActions extends Controller } } + /** 补映射时按同名账单项目查找可带入的既有规则。 */ + public function suggest(Request $request): JsonResponse + { + $data = $request->validate([ + 'platform' => ['required', 'string', 'max:120'], + 'item' => ['required', 'string', 'max:500'], + ]); + + return response()->json($this->suggestion->suggest( + (string) $data['platform'], + (string) $data['item'], + )); + } + public function store(Request $request): JsonResponse { $values = $this->payloadValues($request); diff --git a/modules/EcommerceFinance/Services/AccountMappingSuggestion.php b/modules/EcommerceFinance/Services/AccountMappingSuggestion.php new file mode 100644 index 000000000..d63941cd1 --- /dev/null +++ b/modules/EcommerceFinance/Services/AccountMappingSuggestion.php @@ -0,0 +1,167 @@ + */ + private const COPY_FIELDS = [ + 'memo', + 'invoice', + 'category', + 'feeMemo', + 'dAcct', + 'dSub', + 'cAcct', + 'cSub', + 'basis', + ]; + + /** @var list */ + private const REQUIRED_FIELDS = ['category', 'dAcct', 'cAcct', 'basis']; + + public function __construct( + private readonly AccountMappingStore $store, + ) { + } + + /** + * @return array{ + * auto_fill:bool, + * reason:string, + * matched_count:int, + * sources:list>, + * values:array + * } + */ + public function suggest(string $platform, string $item): array + { + return $this->suggestFromRules($this->store->all(), $platform, $item); + } + + /** + * @param array> $rules + * @return array{ + * auto_fill:bool, + * reason:string, + * matched_count:int, + * sources:list>, + * values:array + * } + */ + public function suggestFromRules(array $rules, string $platform, string $item): array + { + $platform = trim($platform); + $item = trim($item); + $itemKey = $this->normalizeItem($item); + + if ($itemKey === '') { + return $this->emptyResult('invalid_item'); + } + + $matches = []; + foreach ($rules as $rule) { + if (! is_array($rule) + || $this->normalizeItem((string) ($rule['item'] ?? '')) !== $itemKey) { + continue; + } + $matches[] = $rule; + } + + if ($matches === []) { + return $this->emptyResult('no_same_item'); + } + + usort($matches, static fn (array $left, array $right): int => ( + ((string) ($left['platform'] ?? '') === $platform ? 0 : 1) + <=> ((string) ($right['platform'] ?? '') === $platform ? 0 : 1) + ) ?: (((int) ($left['id'] ?? 0)) <=> ((int) ($right['id'] ?? 0)))); + + $templates = []; + foreach ($matches as $rule) { + $templates[$this->templateSignature($rule)] = true; + } + + $sources = array_map( + static fn (array $rule): array => [ + 'id' => (int) ($rule['id'] ?? 0), + 'platform' => trim((string) ($rule['platform'] ?? '')), + 'item' => trim((string) ($rule['item'] ?? '')), + 'memo' => trim((string) ($rule['memo'] ?? '')), + ], + array_slice($matches, 0, 8), + ); + $base = [ + 'matched_count' => count($matches), + 'sources' => $sources, + 'values' => [], + ]; + + if (count($templates) > 1) { + return ['auto_fill' => false, 'reason' => 'ambiguous_templates'] + $base; + } + + $template = $matches[0]; + foreach (self::REQUIRED_FIELDS as $field) { + if (trim((string) ($template[$field] ?? '')) === '') { + return ['auto_fill' => false, 'reason' => 'incomplete_template'] + $base; + } + } + + $values = []; + foreach (self::COPY_FIELDS as $field) { + $values[$field] = trim((string) ($template[$field] ?? '')); + } + + return [ + 'auto_fill' => true, + 'reason' => 'same_item', + ] + array_replace($base, ['values' => $values]); + } + + public function normalizeItem(string $item): string + { + $item = mb_strtolower(trim($item)); + $item = preg_replace('/^wx/u', '', $item) ?? $item; + + return preg_replace('/[\s\x{3000}\p{P}\p{S}]+/u', '', $item) ?? $item; + } + + /** @param array $rule */ + private function templateSignature(array $rule): string + { + $values = []; + foreach (self::COPY_FIELDS as $field) { + $values[$field] = trim((string) ($rule[$field] ?? '')); + } + + return json_encode($values, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); + } + + /** + * @return array{ + * auto_fill:bool, + * reason:string, + * matched_count:int, + * sources:list>, + * values:array + * } + */ + private function emptyResult(string $reason): array + { + return [ + 'auto_fill' => false, + 'reason' => $reason, + 'matched_count' => 0, + 'sources' => [], + 'values' => [], + ]; + } +} diff --git a/resources/views/business/pages/financial-rules/account-mapping.blade.php b/resources/views/business/pages/financial-rules/account-mapping.blade.php index ec84fa86b..9b10f54d2 100644 --- a/resources/views/business/pages/financial-rules/account-mapping.blade.php +++ b/resources/views/business/pages/financial-rules/account-mapping.blade.php @@ -277,6 +277,22 @@ white-space: nowrap; } .am-coverage-store-hint { color: var(--vip-content-muted, #595959); font-size: 0.6875rem; } + .am-mapping-suggestion { + margin: 0 0 0.75rem; + padding: 0.65rem 0.8rem; + border: 1px solid #d8c69b; + border-radius: 8px; + background: #fffaf0; + color: #5f4a1f; + font-size: 0.75rem; + line-height: 1.6; + } + .am-mapping-suggestion--warning { + border-color: #e4c8a2; + background: #fff7ed; + color: #8a541b; + } + .am-mapping-suggestion[hidden] { display: none; } /* 表格必须锁列宽(table-layout:fixed)。默认的自动列宽会按内容互相挤压, 「借方/贷方科目」两列会被挤到文字被截断;锁死后按上面 th 的宽度分配, @@ -930,6 +946,7 @@
+
@@ -1219,6 +1236,7 @@ var coverageNoticeEl = document.getElementById('amCoverageNotice'); var coverageMappingModal = document.getElementById('amCoverageMappingModal'); var coverageMappingFormEl = document.getElementById('amCoverageMappingForm'); + var coverageMappingSuggestionEl = document.getElementById('amCoverageMappingSuggestion'); var coverageMappingErrorEl = document.getElementById('amCoverageMappingError'); var coverageNoticeTimer = null; @@ -1483,6 +1501,34 @@ + mappingField('贷方科目', acctEditor('cAcct', 'cSub')); } + function renderCoverageSuggestion(suggestion) { + if (!coverageMappingSuggestionEl) { return; } + coverageMappingSuggestionEl.className = 'am-mapping-suggestion'; + coverageMappingSuggestionEl.hidden = true; + coverageMappingSuggestionEl.textContent = ''; + if (!suggestion || !suggestion.auto_fill) { + if (suggestion && suggestion.reason === 'ambiguous_templates') { + coverageMappingSuggestionEl.className = 'am-mapping-suggestion am-mapping-suggestion--warning'; + coverageMappingSuggestionEl.textContent = '已找到同名账单项目,但历史规则使用了不同科目,未自动带入,请手动核对。'; + coverageMappingSuggestionEl.hidden = false; + } else if (suggestion && suggestion.reason === 'incomplete_template') { + coverageMappingSuggestionEl.className = 'am-mapping-suggestion am-mapping-suggestion--warning'; + coverageMappingSuggestionEl.textContent = '已找到同名账单项目,但原规则字段不完整,未自动带入,请手动补齐。'; + coverageMappingSuggestionEl.hidden = false; + } + return; + } + + var source = Array.isArray(suggestion.sources) && suggestion.sources.length ? suggestion.sources[0] : null; + var sourceLabel = source + ? String(source.platform || '') + ' · ' + String(source.item || '') + : '已有同名账单项目'; + coverageMappingSuggestionEl.textContent = '已根据「' + sourceLabel + '」自动带入' + + (Number(suggestion.matched_count || 0) > 1 ? '(共 ' + Number(suggestion.matched_count) + ' 条一致规则)' : '') + + ',请核对后保存。'; + coverageMappingSuggestionEl.hidden = false; + } + function showCoverageMappingError(message) { if (!coverageMappingErrorEl) { return; } coverageMappingErrorEl.textContent = message; @@ -1492,6 +1538,10 @@ function closeCoverageMapping() { if (coverageMappingModal) { coverageMappingModal.hidden = true; } if (coverageMappingErrorEl) { coverageMappingErrorEl.hidden = true; } + if (coverageMappingSuggestionEl) { + coverageMappingSuggestionEl.hidden = true; + coverageMappingSuggestionEl.textContent = ''; + } closeMemoPicker(); editingId = null; draft = null; @@ -1503,7 +1553,13 @@ return; } hideCoverageNotice(); - loadCoa().then(function () { + var suggestionRequest = api( + 'GET', + '/suggest?platform=' + encodeURIComponent(platform || '') + + '&item=' + encodeURIComponent(item || '') + ).catch(function () { return null; }); + Promise.all([loadCoa(), suggestionRequest]).then(function (results) { + var suggestion = results[1]; draft = { platform: platform || '', item: item || '', @@ -1518,7 +1574,18 @@ cSub: '', basis: '支出基准' }; + if (suggestion && suggestion.auto_fill && suggestion.values) { + [ + 'memo', 'invoice', 'category', 'feeMemo', + 'dAcct', 'dSub', 'cAcct', 'cSub', 'basis' + ].forEach(function (field) { + if (Object.prototype.hasOwnProperty.call(suggestion.values, field)) { + draft[field] = suggestion.values[field]; + } + }); + } editingId = 'coverage-modal'; + renderCoverageSuggestion(suggestion); renderCoverageMappingForm(); var saveButton = document.getElementById('amCoverageMappingSave'); if (saveButton) { diff --git a/routes/admin.php b/routes/admin.php index 8a46f6e79..69d0264e0 100644 --- a/routes/admin.php +++ b/routes/admin.php @@ -522,6 +522,7 @@ Route::prefix('workspace/financial-rules/account-mapping/actions') Route::delete('rules/{id}', [AccountMappingActions::class, 'destroy'])->whereNumber('id')->name('rules.destroy'); Route::get('accounts', [AccountMappingActions::class, 'accounts'])->name('accounts'); Route::get('coverage', [AccountMappingActions::class, 'coverage'])->name('coverage'); + Route::get('suggest', [AccountMappingActions::class, 'suggest'])->name('suggest'); // 操作记录:新增 / 修改 / 删除 / 导入 / 重置 的历史,供页面「操作记录」查看 Route::get('history', [AccountMappingActions::class, 'history'])->name('history'); Route::get('history/export', [AccountMappingActions::class, 'historyExport'])->name('history.export'); diff --git a/tests/Feature/Business/AccountMappingPageTest.php b/tests/Feature/Business/AccountMappingPageTest.php index 3d719c2de..868ebaa2f 100644 --- a/tests/Feature/Business/AccountMappingPageTest.php +++ b/tests/Feature/Business/AccountMappingPageTest.php @@ -112,6 +112,8 @@ class AccountMappingPageTest extends FeatureTestCase ->assertDontSee('coveragePollTimer', false) ->assertSee('data-am-memo-picker', false) ->assertSee('id="amCoverageMappingModal"', false) + ->assertSee('id="amCoverageMappingSuggestion"', false) + ->assertSee('/suggest?platform=', false) ->assertSee('id="amCoverageNotice"', false) ->assertSee('保存映射') ->assertDontSee('商品名称关键词', false) @@ -197,6 +199,29 @@ class AccountMappingPageTest extends FeatureTestCase ->assertJsonPath('scope', 'all'); } + public function test_suggestion_endpoint_returns_a_same_item_mapping_template(): void + { + $this->grantAdminPermission(); + app(AccountMappingStore::class)->create([ + 'platform' => '京喜', + 'item' => 'POP商家激励金', + 'memo' => '优惠收入', + 'invoice' => '-', + 'category' => '收入', + 'dAcct' => '其他货币资金', + 'cAcct' => '主营业务收入', + 'basis' => '收入基准', + ]); + + $this->loginAs()->getJson( + $this->actionUrl('suggest') . '?platform=' . urlencode('京东') . '&item=' . urlencode('POP商家激励金') + )->assertOk() + ->assertJsonPath('auto_fill', true) + ->assertJsonPath('reason', 'same_item') + ->assertJsonPath('values.memo', '优惠收入') + ->assertJsonPath('sources.0.platform', '京喜'); + } + public function test_coverage_endpoint_rejects_invalid_month(): void { $this->grantAdminPermission(); diff --git a/tests/Unit/EcommerceFinance/AccountMappingSuggestionTest.php b/tests/Unit/EcommerceFinance/AccountMappingSuggestionTest.php new file mode 100644 index 000000000..5d3472db4 --- /dev/null +++ b/tests/Unit/EcommerceFinance/AccountMappingSuggestionTest.php @@ -0,0 +1,79 @@ +suggestFromRules([ + $this->rule('京喜', 'POP商家激励金', '优惠收入', '收入'), + ], '京东', 'POP商家激励金'); + + $this->assertTrue($result['auto_fill']); + $this->assertSame('same_item', $result['reason']); + $this->assertSame('优惠收入', $result['values']['memo']); + $this->assertSame('收入', $result['values']['category']); + $this->assertSame('京喜', $result['sources'][0]['platform']); + } + + public function test_item_normalization_ignores_wx_prefix_spaces_and_punctuation(): void + { + $result = app(AccountMappingSuggestion::class)->suggestFromRules([ + $this->rule('淘宝', '淘宝新品礼金技术服务费', '冲减收入', '收入'), + ], '天猫', 'wx 淘宝新品礼金技术服务费'); + + $this->assertTrue($result['auto_fill']); + $this->assertSame('冲减收入', $result['values']['memo']); + } + + public function test_conflicting_templates_are_not_applied_automatically(): void + { + $result = app(AccountMappingSuggestion::class)->suggestFromRules([ + $this->rule('淘宝', '服务费', '优惠收入', '收入'), + $this->rule('天猫', '服务费', '平台服务费', '平台服务费', '销售费用'), + ], '京东', '服务费'); + + $this->assertFalse($result['auto_fill']); + $this->assertSame('ambiguous_templates', $result['reason']); + $this->assertSame([], $result['values']); + } + + public function test_no_same_name_rule_returns_an_empty_suggestion(): void + { + $result = app(AccountMappingSuggestion::class)->suggestFromRules([ + $this->rule('淘宝', '服务费', '平台服务费', '平台服务费'), + ], '京东', '返利框架费'); + + $this->assertFalse($result['auto_fill']); + $this->assertSame('no_same_item', $result['reason']); + } + + /** @return array */ + private function rule( + string $platform, + string $item, + string $memo, + string $category, + string $dAcct = '其他货币资金', + ): array { + return [ + 'id' => 1, + 'platform' => $platform, + 'item' => $item, + 'memo' => $memo, + 'goods' => '', + 'invoice' => '-', + 'category' => $category, + 'feeMemo' => '', + 'dAcct' => $dAcct, + 'dSub' => '', + 'cAcct' => '主营业务收入', + 'cSub' => '', + 'basis' => in_array($category, ['收入', '往来', '转账'], true) ? '收入基准' : '支出基准', + ]; + } +}