From a7624108d0245a264357a3c4fd276790d2c36f43 Mon Sep 17 00:00:00 2001 From: shanshi <3316401569@qq.com> Date: Mon, 16 Nov 2026 18:50:08 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=8E=A5=E5=85=A5=E9=92=89=E9=92=89?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E4=B8=AD=E4=BB=98=E6=AC=BE=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Services/DingPaymentAccountMatcher.php | 294 ++++++++++++++++++ .../Services/FinanceLedgerRptSynchronizer.php | 27 +- .../DingPaymentAccountMatcherTest.php | 123 ++++++++ ...nanceLedgerRptSynchronizerDingTalkTest.php | 194 ++++++++++++ 4 files changed, 635 insertions(+), 3 deletions(-) create mode 100644 modules/EcommerceFinance/Services/DingPaymentAccountMatcher.php create mode 100644 tests/Unit/EcommerceFinance/DingPaymentAccountMatcherTest.php create mode 100644 tests/Unit/EcommerceFinance/FinanceLedgerRptSynchronizerDingTalkTest.php diff --git a/modules/EcommerceFinance/Services/DingPaymentAccountMatcher.php b/modules/EcommerceFinance/Services/DingPaymentAccountMatcher.php new file mode 100644 index 00000000..433a7a3d --- /dev/null +++ b/modules/EcommerceFinance/Services/DingPaymentAccountMatcher.php @@ -0,0 +1,294 @@ + '农业银行', + '中国工商银行' => '工商银行', + '中国建设银行' => '建设银行', + '江苏江南农村商业银行' => '江南农村商业银行', + '江南农村商业银行' => '江南农村商业银行', + '江南农商行' => '江南农村商业银行', + '农村商业银行' => '江南农村商业银行', + '农商银行' => '江南农村商业银行', + '农业银行' => '农业银行', + '工商银行' => '工商银行', + '中国银行' => '中国银行', + '招商银行' => '招商银行', + '建设银行' => '建设银行', + '交通银行' => '交通银行', + '华夏银行' => '华夏银行', + '兴业银行' => '兴业银行', + '中信银行' => '中信银行', + '光大银行' => '光大银行', + '浦发银行' => '浦发银行', + '平安银行' => '平安银行', + '网商银行' => '网商银行', + '邮政储蓄银行' => '邮政储蓄银行', + '农行' => '农业银行', + '工行' => '工商银行', + '中行' => '中国银行', + '招行' => '招商银行', + '建行' => '建设银行', + '交行' => '交通银行', + '华夏行' => '华夏银行', + '农商' => '江南农村商业银行', + '支付宝' => '支付宝', + '微信' => '微信', + ]; + + private const SOURCE_PREFIXES = [ + '银行存款_公司账户_', + '银行存款_个人账户_', + '银行存款_个体工商户_', + '银行存款_网商银行_', + '银行存款_支付宝_', + '银行存款_', + '库存现金_', + ]; + + /** @var array>|null */ + private ?array $accounts = null; + + /** @var array|null */ + private ?array $sourceMappings = null; + + /** @var array> */ + private array $codeHints = []; + + /** @var array|null */ + private ?array $usage = null; + + public function __construct(private readonly DatabaseManager $databases) + { + } + + public function reset(): void + { + $this->accounts = null; + $this->sourceMappings = null; + $this->codeHints = []; + $this->usage = null; + } + + public function remember(string $accountCode, string $accountShort): void + { + $accountCode = trim($accountCode); + $accountShort = trim($accountShort); + if ($accountCode === '' || $accountShort === '' || ! isset($this->accounts()[$accountShort])) { + return; + } + + $this->codeHints[$accountCode][$accountShort] = true; + } + + public function resolve( + string $sourceName, + string $accountCode = '', + string $rawAccountShort = '', + ): string { + $rawAccountShort = trim($rawAccountShort); + if ($rawAccountShort !== '' && isset($this->accounts()[$rawAccountShort])) { + return $rawAccountShort; + } + + $codeHints = array_keys($this->codeHints[trim($accountCode)] ?? []); + if (count($codeHints) === 1) { + return (string) $codeHints[0]; + } + + $mapped = trim($this->sourceMappings()[trim($sourceName)] ?? ''); + if ($mapped !== '' && isset($this->accounts()[$mapped])) { + return $mapped; + } + + $sourceName = trim($sourceName); + if ($sourceName === '') { + return ''; + } + + $sourceBank = $this->bankOf($sourceName); + $sourceKey = $this->normalizeName($sourceName); + if ($sourceKey === '') { + return ''; + } + + $candidates = []; + foreach ($this->accounts() as $short => $account) { + if ($sourceBank !== '' && $account['bank'] !== $sourceBank) { + continue; + } + + $shortKey = $this->normalizeName($short); + $companyKey = $this->normalizeName((string) ($account['company_name'] ?? '')); + if (! $this->sameKeyword($sourceKey, $shortKey) + && ! $this->sameKeyword($sourceKey, $companyKey)) { + continue; + } + + $candidates[$short] = true; + } + + $candidates = array_keys($candidates); + if (count($candidates) === 1) { + return (string) $candidates[0]; + } + if (count($candidates) < 2) { + return ''; + } + + $usage = $this->usage(); + usort($candidates, static fn (string $left, string $right): int => + ($usage[$right] ?? 0) <=> ($usage[$left] ?? 0) + ); + $top = $candidates[0]; + $topUsage = (int) ($usage[$top] ?? 0); + $secondUsage = (int) ($usage[$candidates[1]] ?? 0); + + // Normal RMB accounts normally dominate. Leave rare/currency-specific + // accounts to explicit 账户简称 or 科目编码 instead of guessing. + return $topUsage >= 3 && $topUsage >= max(3, $secondUsage * 3) ? $top : ''; + } + + /** @return array> */ + private function accounts(): array + { + if ($this->accounts !== null) { + return $this->accounts; + } + + $accounts = []; + foreach ($this->connection()->table('fin_accounts') + ->whereNotNull('account_short') + ->where('account_short', '<>', '') + ->get(['account_short', 'company_name', 'account_type', 'bank_name']) as $row) { + $short = trim((string) $row->account_short); + if ($short === '') { + continue; + } + $bank = $this->bankOf( + $short . ' ' . (string) ($row->bank_name ?? '') . ' ' . (string) ($row->company_name ?? ''), + ); + $accounts[$short] = [ + 'company_name' => (string) ($row->company_name ?? ''), + 'account_type' => (string) ($row->account_type ?? ''), + 'bank' => $bank, + ]; + } + + return $this->accounts = $accounts; + } + + /** @return array */ + private function sourceMappings(): array + { + if ($this->sourceMappings !== null) { + return $this->sourceMappings; + } + + $mappings = []; + foreach ($this->connection()->table('fin_account_map') + ->where('source', 'dingtalk') + ->whereNotNull('account_short') + ->where('account_short', '<>', '') + ->get(['source_value', 'account_short']) as $row) { + $source = trim((string) $row->source_value); + $short = trim((string) $row->account_short); + if ($source !== '' && $short !== '' && isset($this->accounts()[$short])) { + $mappings[$source] = $short; + } + } + + return $this->sourceMappings = $mappings; + } + + /** @return array */ + private function usage(): array + { + if ($this->usage !== null) { + return $this->usage; + } + + $usage = []; + foreach ($this->connection()->table('fin_transactions') + ->where('source', 'dingtalk') + ->whereNotNull('account_short') + ->where('account_short', '<>', '') + ->selectRaw('account_short, COUNT(*) AS aggregate') + ->groupBy('account_short') + ->get() as $row) { + $usage[(string) $row->account_short] = (int) $row->aggregate; + } + + return $this->usage = $usage; + } + + private function sameKeyword(string $source, string $candidate): bool + { + if ($source === '' || $candidate === '') { + return false; + } + + return $source === $candidate + || (mb_strlen($source) >= 3 && str_contains($candidate, $source)) + || (mb_strlen($candidate) >= 3 && str_contains($source, $candidate)); + } + + private function bankOf(string $value): string + { + foreach (self::BANK_ALIASES as $alias => $canonical) { + if (str_contains($value, $alias)) { + return $canonical; + } + } + + return ''; + } + + private function normalizeName(string $value): string + { + $value = mb_strtolower(trim($value), 'UTF-8'); + foreach (self::SOURCE_PREFIXES as $prefix) { + $value = str_replace(mb_strtolower($prefix, 'UTF-8'), '', $value); + } + foreach (array_keys(self::BANK_ALIASES) as $bank) { + $value = str_replace(mb_strtolower($bank, 'UTF-8'), '', $value); + } + foreach ([ + '股份有限公司', + '有限责任公司', + '有限公司', + '基本户', + '一般户', + '公司账户', + '个人账户', + '个体工商户', + '账户', + '银行', + '现金', + ] as $suffix) { + $value = str_replace($suffix, '', $value); + } + + return preg_replace('/[\s_\-—()()【】\[\].,,。::\/\\\\"]+/u', '', $value) ?? ''; + } + + private function connection() + { + return $this->databases->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } +} diff --git a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php index a10b38c1..9cbb331d 100644 --- a/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php +++ b/modules/EcommerceFinance/Services/FinanceLedgerRptSynchronizer.php @@ -44,6 +44,7 @@ class FinanceLedgerRptSynchronizer public function __construct( private readonly UpstreamReadOnlyQueryFactory $queries, private readonly FinanceLedgerTransactionWriter $writer, + private readonly DingPaymentAccountMatcher $paymentAccountMatcher, ) { } @@ -82,6 +83,7 @@ class FinanceLedgerRptSynchronizer private function dingTalkRows(string $from, string $to): array { $query = $this->query(); + $this->paymentAccountMatcher->reset(); $workflows = $query->select( 'SELECT processInstanceId, processCode, businessId, title, status, originatorUserId, ' @@ -117,12 +119,22 @@ class FinanceLedgerRptSynchronizer $byInstance[$pid][$name] = (string) $scheme['value']; } + $paymentsByInstance = []; + foreach ($byInstance as $pid => $fields) { + $payments = $this->paymentRows($fields['付款明细'] ?? ''); + $paymentsByInstance[$pid] = $payments; + foreach ($payments as $payment) { + $this->paymentAccountMatcher->remember($payment['code'], $payment['account_short']); + } + } + $rows = []; foreach ($workflows as $workflow) { $pid = (string) $workflow['processInstanceId']; $code = (string) $workflow['processCode']; $processName = (string) (config('finance_ledger.dingtalk_process_codes.' . $code) ?: '钉钉审批'); - if ((string) $workflow['status'] !== 'COMPLETED') { + $status = strtoupper(trim((string) $workflow['status'])); + if (! in_array($status, ['COMPLETED', 'RUNNING'], true)) { continue; } @@ -163,7 +175,7 @@ class FinanceLedgerRptSynchronizer continue; } - $payments = $this->paymentRows($fields['付款明细'] ?? ''); + $payments = $paymentsByInstance[$pid] ?? []; $details = $this->detailRows($fields[self::DETAIL_FIELDS[$code] ?? ''] ?? '', $code); $detailMap = []; foreach ($details as $detail) { @@ -179,6 +191,9 @@ class FinanceLedgerRptSynchronizer if ($payment['amount'] == 0.0 && $payment['code'] === '') { continue; } + if ($payment['date'] === '') { + continue; + } $tokens = $this->seqTokens($payment['seq']) ?: ['_all']; $matched = []; foreach ($tokens as $token) { @@ -237,7 +252,11 @@ class FinanceLedgerRptSynchronizer $rows[] = $this->row([ 'date' => $payment['date'], - 'account_short' => '', + 'account_short' => $this->paymentAccountMatcher->resolve( + $payment['name'], + $payment['code'], + $payment['account_short'], + ), 'source_value' => $payment['name'], 'source' => 'dingtalk', 'process_type' => $processName, @@ -509,6 +528,7 @@ class FinanceLedgerRptSynchronizer 'amount' => $this->toNumber($row['付款金额'] ?? $row['付款总金额'] ?? null), 'code' => trim((string) ($row['科目编码'] ?? '')), 'name' => trim((string) ($row['科目名称'] ?? '')), + 'account_short' => trim((string) ($row['账户简称'] ?? '')), 'date' => $this->date($row['打款时间'] ?? null), ]; } @@ -537,6 +557,7 @@ class FinanceLedgerRptSynchronizer 'amount' => $this->toNumber($values[2] ?? null), 'code' => $code, 'name' => trim((string) ($values[4] ?? '')), + 'account_short' => '', 'date' => $date, ]; } diff --git a/tests/Unit/EcommerceFinance/DingPaymentAccountMatcherTest.php b/tests/Unit/EcommerceFinance/DingPaymentAccountMatcherTest.php new file mode 100644 index 00000000..e96c26a7 --- /dev/null +++ b/tests/Unit/EcommerceFinance/DingPaymentAccountMatcherTest.php @@ -0,0 +1,123 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('fin_accounts', function (Blueprint $table): void { + $table->string('account_short'); + $table->string('company_name')->nullable(); + $table->string('account_type')->nullable(); + $table->string('bank_name')->nullable(); + }); + Schema::connection('business_mirror')->create('fin_account_map', function (Blueprint $table): void { + $table->string('source'); + $table->string('source_value'); + $table->string('account_short')->nullable(); + }); + Schema::connection('business_mirror')->create('fin_transactions', function (Blueprint $table): void { + $table->string('source'); + $table->string('account_short')->nullable(); + }); + + $this->matcher = app(DingPaymentAccountMatcher::class); + } + + public function test_exact_account_short_and_learned_code_win_before_keyword_matching(): void + { + $this->account('锋黛招行', '常州锋黛家居有限公司', '招商银行常州新北支行'); + $this->account('石洪明华夏', '石洪明', '华夏银行常州分行营业部'); + + $this->assertSame( + '锋黛招行', + $this->matcher->resolve('招商银行', '1002.01.647', '锋黛招行'), + ); + + $this->matcher->remember('1002.01.647', '锋黛招行'); + $this->assertSame( + '锋黛招行', + $this->matcher->resolve('招商银行', '1002.01.647', ''), + ); + } + + public function test_saved_alias_and_unique_bank_company_keyword_are_used(): void + { + $this->account('石洪明华夏', '石洪明', '华夏银行常州分行营业部'); + $this->account('欧栗中行', '常州欧栗家居有限公司', '中国银行常州经济开发区支行'); + DB::connection('business_mirror')->table('fin_account_map')->insert([ + 'source' => 'dingtalk', + 'source_value' => '华夏银行-石洪明', + 'account_short' => '石洪明华夏', + ]); + + $this->assertSame( + '石洪明华夏', + $this->matcher->resolve('华夏银行-石洪明', '', ''), + ); + $this->assertSame( + '欧栗中行', + $this->matcher->resolve('中国银行-欧栗', '', ''), + ); + } + + public function test_dominant_ordinary_account_resolves_same_bank_candidates(): void + { + $this->account('欧伯娜中行0884', '常州欧伯娜家居有限公司', '中国银行常州经济开发区支行'); + $this->account('欧伯娜中行3233', '常州欧伯娜家居有限公司', '中国银行常州崔桥支行'); + foreach (range(1, 6) as $index) { + DB::connection('business_mirror')->table('fin_transactions')->insert([ + 'source' => 'dingtalk', + 'account_short' => '欧伯娜中行0884', + ]); + } + DB::connection('business_mirror')->table('fin_transactions')->insert([ + 'source' => 'dingtalk', + 'account_short' => '欧伯娜中行3233', + ]); + + $this->assertSame( + '欧伯娜中行0884', + $this->matcher->resolve('中国银行-欧伯娜', '', ''), + ); + } + + public function test_ambiguous_account_without_clear_usage_stays_unmatched(): void + { + $this->account('欧伯娜中行0884', '常州欧伯娜家居有限公司', '中国银行常州经济开发区支行'); + $this->account('欧伯娜中行3233', '常州欧伯娜家居有限公司', '中国银行常州崔桥支行'); + + $this->assertSame('', $this->matcher->resolve('中国银行-欧伯娜', '', '')); + } + + private function account(string $short, string $company, string $bank): void + { + DB::connection('business_mirror')->table('fin_accounts')->insert([ + 'account_short' => $short, + 'company_name' => $company, + 'account_type' => '公户', + 'bank_name' => $bank, + ]); + } +} diff --git a/tests/Unit/EcommerceFinance/FinanceLedgerRptSynchronizerDingTalkTest.php b/tests/Unit/EcommerceFinance/FinanceLedgerRptSynchronizerDingTalkTest.php new file mode 100644 index 00000000..ec5c6031 --- /dev/null +++ b/tests/Unit/EcommerceFinance/FinanceLedgerRptSynchronizerDingTalkTest.php @@ -0,0 +1,194 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'finance_ledger.dingtalk_process_codes' => [ + 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F' => '日常费用报销流程', + ], + ]); + DB::purge('business_mirror'); + + Schema::connection('business_mirror')->create('fin_accounts', function (Blueprint $table): void { + $table->string('account_short'); + $table->string('company_name')->nullable(); + $table->string('account_type')->nullable(); + $table->string('bank_name')->nullable(); + }); + Schema::connection('business_mirror')->create('fin_account_map', function (Blueprint $table): void { + $table->string('source'); + $table->string('source_value'); + $table->string('account_short')->nullable(); + }); + Schema::connection('business_mirror')->create('fin_transactions', function (Blueprint $table): void { + $table->string('source'); + $table->string('account_short')->nullable(); + }); + DB::connection('business_mirror')->table('fin_accounts')->insert([ + 'account_short' => '锋黛招行', + 'company_name' => '常州锋黛家居有限公司', + 'account_type' => '公户', + 'bank_name' => '招商银行常州新北支行', + ]); + + $this->query = new FakeFinanceLedgerRptQuery(); + $factory = new class($this->query) extends UpstreamReadOnlyQueryFactory { + public function __construct(private readonly UpstreamReadOnlyQuery $query) {} + + public function forSource(string $source): UpstreamReadOnlyQuery + { + return $this->query; + } + + public function forSourceWithTimeout(string $source, int $timeoutSeconds): UpstreamReadOnlyQuery + { + return $this->query; + } + }; + $this->synchronizer = new FinanceLedgerRptSynchronizer( + $factory, + app(FinanceLedgerTransactionWriter::class), + app(DingPaymentAccountMatcher::class), + ); + } + + public function test_running_workflow_with_complete_payment_details_enters_ledger(): void + { + $this->query->workflows = [[ + 'processInstanceId' => 'running-paid-process', + 'processCode' => 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F', + 'businessId' => 'APPROVAL-RUNNING-1', + 'title' => '山时提交的日常报销', + 'status' => 'RUNNING', + 'originatorUserId' => 'user-shan', + 'originatorDeptName' => '财务部', + 'joinAt' => '2026-11-10 09:00:00', + 'finishTime' => null, + ]]; + $this->query->schemes = [[ + 'id' => 1, + 'processInstanceId' => 'running-paid-process', + 'name' => '付款明细', + 'value' => json_encode([[ + 'rowValue' => [ + ['label' => '对应序号', 'value' => '1'], + ['label' => '付款金额', 'value' => '100.00'], + ['label' => '科目编码', 'value' => '1002.01.647'], + ['label' => '科目名称', 'value' => '招商银行'], + ['label' => '账户简称', 'value' => '锋黛招行'], + ['label' => '打款时间', 'value' => '2026-11-10'], + ], + ]], JSON_UNESCAPED_UNICODE), + ]]; + $this->query->employees = [ + ['userid' => 'user-shan', 'name' => '山时'], + ]; + + $rows = $this->dingTalkRows(); + + $this->assertCount(1, $rows); + $this->assertSame('2026-11-10', $rows[0]['txn_date']); + $this->assertSame(100.0, $rows[0]['expense']); + $this->assertSame('锋黛招行', $rows[0]['account_short']); + $this->assertSame('APPROVAL-RUNNING-1', $rows[0]['approval_no']); + } + + public function test_running_workflow_without_payment_date_is_not_posted(): void + { + $this->query->workflows = [[ + 'processInstanceId' => 'running-unpaid-process', + 'processCode' => 'PROC-B290696F-EC2A-4F76-87BA-E0A12E10D09F', + 'businessId' => 'APPROVAL-RUNNING-2', + 'title' => '山时提交的未付款报销', + 'status' => 'RUNNING', + 'originatorUserId' => 'user-shan', + 'originatorDeptName' => '财务部', + 'joinAt' => '2026-11-11 09:00:00', + 'finishTime' => null, + ]]; + $this->query->schemes = [[ + 'id' => 2, + 'processInstanceId' => 'running-unpaid-process', + 'name' => '付款明细', + 'value' => json_encode([[ + 'rowValue' => [ + ['label' => '对应序号', 'value' => '1'], + ['label' => '付款金额', 'value' => '100.00'], + ['label' => '科目编码', 'value' => '1002.01.647'], + ['label' => '科目名称', 'value' => '招商银行'], + ['label' => '账户简称', 'value' => '锋黛招行'], + ['label' => '打款时间', 'value' => ''], + ], + ]], JSON_UNESCAPED_UNICODE), + ]]; + $this->query->employees = [ + ['userid' => 'user-shan', 'name' => '山时'], + ]; + + $this->assertSame([], $this->dingTalkRows()); + } + + private function dingTalkRows(): array + { + $method = new ReflectionMethod($this->synchronizer, 'dingTalkRows'); + $method->setAccessible(true); + + return $method->invoke($this->synchronizer, '2026-11-01', '2026-11-16'); + } +} + +class FakeFinanceLedgerRptQuery extends UpstreamReadOnlyQuery +{ + public array $workflows = []; + + public array $schemes = []; + + public array $employees = []; + + public function __construct() + { + parent::__construct('operations_replica'); + } + + public function select(string $sql, array $bindings = []): array + { + if (str_contains($sql, 'rpt.fin_ledger_dingtalk_workflow')) { + return $this->workflows; + } + if (str_contains($sql, 'rpt.fin_ledger_dingtalk_scheme')) { + return $this->schemes; + } + if (str_contains($sql, 'rpt.hr_employee')) { + return $this->employees; + } + + return []; + } +} -- 2.47.2