From 964d88455e33ae3cc4e4fd0d351be70016dc2de5 Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Fri, 27 Nov 2026 15:18:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(=E5=8F=91=E7=A5=A8=E6=95=B0=E6=8D=AE):=20?= =?UTF-8?q?=E5=90=88=E5=B9=B6OA=E5=90=8C=E6=AD=A5=E5=B9=B6=E7=B2=BE?= =?UTF-8?q?=E7=AE=80=E5=8F=91=E7=A5=A8=E6=98=8E=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Commands/SyncDingProcessDetailMirror.php | 36 +++- config/ding_invoice_data.php | 10 +- ...an_backoff_to_ding_invoice_flow_mirror.php | 60 +++++++ deploy/activate-incremental-release.sh | 5 +- deploy/activate-release.sh | 5 +- .../Services/DingInvoiceSyncService.php | 156 ++++++++++++------ .../invoice-data.blade.php | 94 ++++++----- .../Feature/Business/InvoiceDataPageTest.php | 32 ++++ .../SyncDingProcessDetailMirrorTest.php | 66 ++++++++ .../Deployment/BusinessMirrorScheduleTest.php | 7 + 10 files changed, 368 insertions(+), 103 deletions(-) create mode 100644 database/migrations/2026_11_27_160000_add_scan_backoff_to_ding_invoice_flow_mirror.php diff --git a/app/Console/Commands/SyncDingProcessDetailMirror.php b/app/Console/Commands/SyncDingProcessDetailMirror.php index abc98052..bd444536 100644 --- a/app/Console/Commands/SyncDingProcessDetailMirror.php +++ b/app/Console/Commands/SyncDingProcessDetailMirror.php @@ -3,6 +3,7 @@ namespace App\Console\Commands; use Illuminate\Console\Command; +use Modules\EcommerceFinance\Services\DingInvoiceSyncService; use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer; use Throwable; @@ -12,12 +13,15 @@ class SyncDingProcessDetailMirror extends Command {--full : 从配置起始日期完整重建明细和付款事实} {--business-id= : 只同步指定审批编号,多个用逗号分隔(最多 50 个)} {--skip-approval-api : 定向同步时不调用钉钉官方审批接口} + {--skip-invoices : 不执行同轮发票增量识别} {--dry-run : 只读取上游并校验,不写入镜像}'; - protected $description = '从结构化审批镜像同步流程明细,并用钉钉官方接口补取缺失付款'; + protected $description = '同步 OA 流程结构化明细,并在同一批处理中增量识别发票'; - public function handle(DingProcessDetailMirrorSynchronizer $synchronizer): int - { + public function handle( + DingProcessDetailMirrorSynchronizer $synchronizer, + DingInvoiceSyncService $invoiceSync, + ): int { $businessIds = array_values(array_filter(array_map( 'trim', explode(',', (string) $this->option('business-id')), @@ -61,6 +65,32 @@ class SyncDingProcessDetailMirror extends Command $result['bank_amount_total'], )); + if ($businessIds === [] + && ! (bool) $this->option('dry-run') + && ! (bool) $this->option('skip-invoices') + && $result['workflows'] > 0 + && (bool) config('ding_invoice_data.sync_with_oa_process', true)) { + try { + $month = $invoiceSync->latestPendingMonth(); + if ($month !== null) { + $invoiceResult = $invoiceSync->syncMonth( + $month, + (int) config('ding_invoice_data.auto_scan_limit', 5), + ); + $this->info(sprintf( + '发票增量识别完成:%d 个流程,新识别 %d 张,保留 %d 张,剩余 %d 个流程。', + $invoiceResult['processed_flows'], + $invoiceResult['recognized_invoices'], + $invoiceResult['preserved_invoices'], + $invoiceResult['remaining_flows'], + )); + } + } catch (Throwable $exception) { + report($exception); + $this->warn('发票增量识别失败,OA 流程镜像已正常更新:' . $exception->getMessage()); + } + } + return self::SUCCESS; } } diff --git a/config/ding_invoice_data.php b/config/ding_invoice_data.php index 1eae625e..27317fa3 100644 --- a/config/ding_invoice_data.php +++ b/config/ding_invoice_data.php @@ -6,7 +6,15 @@ return [ 'max_files_per_flow' => (int) env('DING_INVOICE_MAX_FILES_PER_FLOW', 30), 'max_file_bytes' => (int) env('DING_INVOICE_MAX_FILE_BYTES', 60 * 1024 * 1024), 'max_pdf_pages' => (int) env('DING_INVOICE_MAX_PDF_PAGES', 5), - 'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 20), + 'comment_fallback_limit' => (int) env('DING_INVOICE_COMMENT_FALLBACK_LIMIT', 5), + 'auto_scan_limit' => (int) env('DING_INVOICE_AUTO_SCAN_LIMIT', 5), + 'failed_retry_minutes' => (int) env('DING_INVOICE_FAILED_RETRY_MINUTES', 60), + 'partial_retry_minutes' => (int) env('DING_INVOICE_PARTIAL_RETRY_MINUTES', 360), + 'max_scan_attempts' => (int) env('DING_INVOICE_MAX_SCAN_ATTEMPTS', 3), + 'sync_with_oa_process' => filter_var( + env('DING_INVOICE_SYNC_WITH_OA_PROCESS', true), + FILTER_VALIDATE_BOOL, + ), 'pdftotext_binary' => env('DING_INVOICE_PDFTOTEXT_BINARY', '/usr/bin/pdftotext'), 'pdftoppm_binary' => env('DING_INVOICE_PDFTOPPM_BINARY', '/usr/bin/pdftoppm'), 'tesseract_binary' => env('DING_INVOICE_TESSERACT_BINARY', '/usr/bin/tesseract'), diff --git a/database/migrations/2026_11_27_160000_add_scan_backoff_to_ding_invoice_flow_mirror.php b/database/migrations/2026_11_27_160000_add_scan_backoff_to_ding_invoice_flow_mirror.php new file mode 100644 index 00000000..40fd0607 --- /dev/null +++ b/database/migrations/2026_11_27_160000_add_scan_backoff_to_ding_invoice_flow_mirror.php @@ -0,0 +1,60 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('ding_invoice_flow_mirror')) { + return; + } + + $schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($schema): void { + if (! $schema->hasColumn('ding_invoice_flow_mirror', 'scan_attempts')) { + $table->unsignedInteger('scan_attempts')->default(0); + } + if (! $schema->hasColumn('ding_invoice_flow_mirror', 'next_scan_at')) { + $table->dateTime('next_scan_at', 6)->nullable(); + } + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('ding_invoice_flow_mirror')) { + return; + } + + $columns = []; + foreach (['scan_attempts', 'next_scan_at'] as $column) { + if ($schema->hasColumn('ding_invoice_flow_mirror', $column)) { + $columns[] = $column; + } + } + if ($columns !== []) { + $schema->table('ding_invoice_flow_mirror', function (Blueprint $table) use ($columns): void { + $table->dropColumn($columns); + }); + } + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 06c0b8e2..939d8519 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -266,8 +266,8 @@ CRON_TZ=Asia/Shanghai EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots -# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转, -# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。 +# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票; +# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。 # 每周全量校准仍保留在上面的主计划中。 cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' CRON_TZ=Asia/Shanghai @@ -275,7 +275,6 @@ CRON_TZ=Asia/Shanghai # OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1 -7,22,37,52 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:sync --auto --limit=20 --quiet >/dev/null 2>&1 EOF chmod 644 /etc/cron.d/caiwu-ding-process-details diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index ff7aab6e..cdff19d0 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -270,8 +270,8 @@ CRON_TZ=Asia/Shanghai EOF chmod 644 /etc/cron.d/caiwu-jiansun-snapshots -# OA 流程明细每 15 分钟同步结构化数据;审批快照再按 60 分钟新鲜度限频轮转, -# 避免对数百条长期不变的审批中流程每 5 分钟重复调用官方接口。 +# OA 流程明细每 15 分钟同步结构化数据,并在同一批处理中增量补发票; +# 审批快照再按 60 分钟新鲜度限频轮转,避免对长期不变的流程重复调用官方接口。 # 每周全量校准仍保留在上面的主计划中。 cat > /etc/cron.d/caiwu-ding-process-details <<'EOF' CRON_TZ=Asia/Shanghai @@ -279,7 +279,6 @@ CRON_TZ=Asia/Shanghai # OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1 * * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1 -7,22,37,52 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:sync --auto --limit=20 --quiet >/dev/null 2>&1 EOF chmod 644 /etc/cron.d/caiwu-ding-process-details diff --git a/modules/EcommerceFinance/Services/DingInvoiceSyncService.php b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php index cbd5470d..309961a5 100644 --- a/modules/EcommerceFinance/Services/DingInvoiceSyncService.php +++ b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php @@ -4,6 +4,7 @@ namespace Modules\EcommerceFinance\Services; use Illuminate\Database\ConnectionInterface; use Illuminate\Database\DatabaseManager; +use Illuminate\Database\Query\Builder; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Schema; use RuntimeException; @@ -47,6 +48,8 @@ class DingInvoiceSyncService ->update([ 'scan_status' => 'pending', 'scanned_at' => null, + 'scan_attempts' => 0, + 'next_scan_at' => null, 'updated_at' => now(), ]); } @@ -55,13 +58,8 @@ class DingInvoiceSyncService ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') - ->where('process_instance_id', '!=', '') - ->where(function ($query): void { - $query->whereIn('scan_status', ['pending', 'failed', 'partial']) - ->orWhereNull('scanned_at') - ->orWhereNull('source_name') - ->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME); - }); + ->where('process_instance_id', '!=', ''); + $this->applyScanCandidates($query); $flows = $query ->orderByDesc('paid_at') ->orderByDesc('business_id') @@ -70,18 +68,13 @@ class DingInvoiceSyncService ->all(); if ($flows === []) { - $remaining = (int) $this->connection->table('ding_invoice_flow_mirror') + $remainingQuery = $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') - ->where('process_instance_id', '!=', '') - ->where(function ($query): void { - $query->whereIn('scan_status', ['pending', 'failed', 'partial']) - ->orWhereNull('scanned_at') - ->orWhereNull('source_name') - ->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME); - }) - ->count(); + ->where('process_instance_id', '!=', ''); + $this->applyScanCandidates($remainingQuery); + $remaining = (int) $remainingQuery->count(); return [ 'status' => 'succeeded', @@ -96,7 +89,7 @@ class DingInvoiceSyncService } $businessIds = array_values(array_filter(array_column($flows, 'business_id'))); - [$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds); + [$workflows, $attachmentRows] = $this->loadWorkflowAttachments($flows); $attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows); $attachmentsByBusiness = $this->addCommentAttachmentFallback( $businessIds, @@ -139,18 +132,13 @@ class DingInvoiceSyncService $this->removeDirectory($tempRoot); } - $metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror') + $remainingQuery = $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('paid_month', $month) ->whereNotNull('process_instance_id') - ->where('process_instance_id', '!=', '') - ->where(function ($query): void { - $query->whereIn('scan_status', ['pending', 'failed', 'partial']) - ->orWhereNull('scanned_at') - ->orWhereNull('source_name') - ->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME); - }) - ->count(); + ->where('process_instance_id', '!=', ''); + $this->applyScanCandidates($remainingQuery); + $metrics['remaining_flows'] = (int) $remainingQuery->count(); $this->updateState($metrics); return [ @@ -162,21 +150,50 @@ class DingInvoiceSyncService public function latestPendingMonth(): ?string { - $month = $this->connection->table('ding_invoice_flow_mirror') + $monthQuery = $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $this->scope()) ->whereNotNull('process_instance_id') - ->where('process_instance_id', '!=', '') - ->where(function ($query): void { - $query->whereIn('scan_status', ['pending', 'failed', 'partial']) - ->orWhereNull('scanned_at') - ->orWhereNull('source_name') - ->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME); - }) - ->max('paid_month'); + ->where('process_instance_id', '!=', ''); + $this->applyScanCandidates($monthQuery); + $month = $monthQuery->max('paid_month'); return trim((string) $month) ?: null; } + private function applyScanCandidates(Builder $query): void + { + $now = now(); + $maxAttempts = max( + 1, + (int) config('ding_invoice_data.max_scan_attempts', 3), + ); + + $query->where(function (Builder $candidate) use ($now, $maxAttempts): void { + $candidate + ->whereNull('scanned_at') + ->orWhere('scan_status', 'pending') + ->orWhere(function (Builder $imported) use ($now): void { + $imported->whereIn('scan_status', ['recognized', 'no_invoice']) + ->where(function (Builder $source): void { + $source->whereNull('source_name') + ->orWhere('source_name', '!=', self::DIRECT_SOURCE_NAME); + }) + ->where(function (Builder $due) use ($now): void { + $due->whereNull('next_scan_at') + ->orWhere('next_scan_at', '<=', $now); + }); + }) + ->orWhere(function (Builder $retry) use ($now, $maxAttempts): void { + $retry->whereIn('scan_status', ['failed', 'partial']) + ->where('scan_attempts', '<', $maxAttempts) + ->where(function (Builder $due) use ($now): void { + $due->whereNull('next_scan_at') + ->orWhere('next_scan_at', '<=', $now); + }); + }); + }); + } + private function assertReady(): void { if (! Schema::connection($this->connection->getName())->hasTable('ding_invoice_flow_mirror') @@ -264,37 +281,58 @@ class DingInvoiceSyncService } /** - * @param list $businessIds + * @param list $flows * @return array{0:array>,1:list>} */ - private function loadUpstreamWorkflowsAndAttachments(array $businessIds): array + private function loadWorkflowAttachments(array $flows): array { - if ($businessIds === []) { + if ($flows === []) { return [[], []]; } - $query = $this->queries->forSourceWithTimeout('operations_replica', 120); - $placeholders = implode(',', array_fill(0, count($businessIds), '?')); - $workflowRows = $query->select( - 'SELECT businessId, processInstanceId, title, status, result ' - . 'FROM rpt.ding_Workflow ' - . "WHERE businessId IN ({$placeholders}) ORDER BY businessId", - $businessIds, - ); $workflows = []; - foreach ($workflowRows as $row) { - $businessId = trim((string) ($row['businessId'] ?? '')); - if ($businessId !== '') { - $workflows[$businessId] = $row; + $missingProcessIds = []; + foreach ($flows as $flow) { + $businessId = trim((string) ($flow->business_id ?? '')); + if ($businessId === '') { + continue; + } + $workflows[$businessId] = [ + 'businessId' => $businessId, + 'processInstanceId' => trim((string) ($flow->process_instance_id ?? '')), + 'title' => $flow->title ?? null, + 'status' => null, + 'result' => null, + ]; + if ($workflows[$businessId]['processInstanceId'] === '') { + $missingProcessIds[] = $businessId; + } + } + + if ($missingProcessIds !== []) { + $localRows = $this->connection->table('ding_process_detail_mirror') + ->where('source_scope', $this->scope()) + ->whereIn('business_id', $missingProcessIds) + ->whereNotNull('process_instance_id') + ->where('process_instance_id', '!=', '') + ->get(['business_id', 'process_instance_id']); + foreach ($localRows as $row) { + $businessId = trim((string) ($row->business_id ?? '')); + if (isset($workflows[$businessId])) { + $workflows[$businessId]['processInstanceId'] = trim( + (string) ($row->process_instance_id ?? ''), + ); + } } } $processIds = array_values(array_unique(array_filter(array_map( static fn (array $row): string => trim((string) ($row['processInstanceId'] ?? '')), - $workflowRows, + array_values($workflows), )))); if ($processIds === []) { return [$workflows, []]; } + $query = $this->queries->forSourceWithTimeout('operations_replica', 120); $processPlaceholders = implode(',', array_fill(0, count($processIds), '?')); $attachmentRows = $query->select( 'SELECT processInstanceId, name, value ' @@ -673,6 +711,20 @@ class DingInvoiceSyncService $invoiceCount > 0 => 'recognized', default => 'no_invoice', }; + $scanAttempts = (int) ($flow->scan_attempts ?? 0) + 1; + $maxAttempts = max( + 1, + (int) config('ding_invoice_data.max_scan_attempts', 3), + ); + $nextScanAt = match (true) { + $scanStatus === 'failed' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes( + max(1, (int) config('ding_invoice_data.failed_retry_minutes', 60)), + ), + $scanStatus === 'partial' && $scanAttempts < $maxAttempts => $now->copy()->addMinutes( + max(1, (int) config('ding_invoice_data.partial_retry_minutes', 360)), + ), + default => null, + }; $this->connection->table('ding_invoice_flow_mirror') ->where('source_scope', $scope) ->where('business_id', $businessId) @@ -686,6 +738,8 @@ class DingInvoiceSyncService 'scanned_file_count' => $scannedFiles, 'last_error' => $error, 'source_name' => self::DIRECT_SOURCE_NAME, + 'scan_attempts' => $scanAttempts, + 'next_scan_at' => $nextScanAt, 'scanned_at' => $now, 'updated_at' => $now, ]); diff --git a/resources/views/business/pages/financial-operations/invoice-data.blade.php b/resources/views/business/pages/financial-operations/invoice-data.blade.php index 8586e334..62801055 100644 --- a/resources/views/business/pages/financial-operations/invoice-data.blade.php +++ b/resources/views/business/pages/financial-operations/invoice-data.blade.php @@ -278,7 +278,7 @@ .invoice-data-table { width: 100%; - min-width: 178rem; + min-width: 148rem; border-collapse: collapse; color: var(--invoice-ink); font-size: 0.75rem; @@ -375,6 +375,24 @@ font-weight: 600; } + .invoice-data-process-link { + display: inline-flex; + align-items: center; + gap: 0.25rem; + color: var(--invoice-accent-dark); + font-weight: 600; + text-decoration: none; + } + + .invoice-data-process-link:hover, + .invoice-data-process-link:focus-visible { + text-decoration: underline; + } + + .invoice-data-process-link .material-icons-outlined { + font-size: 0.875rem; + } + .invoice-data-tag { display: inline-flex; min-height: 1.4rem; @@ -460,16 +478,6 @@ line-height: 1.65; } - .invoice-data-attachment { - color: var(--invoice-accent-dark); - font-weight: 600; - text-decoration: none; - } - - .invoice-data-attachment:hover { - text-decoration: underline; - } - .invoice-data-refresh-status { display: flex; align-items: center; @@ -709,11 +717,6 @@ 流程号 - 流程标题 - 提交人 - 报销类型 - 费用类型 - 收款人 发票类型 发票号码 开票日期 @@ -731,7 +734,6 @@ 发票张数 金额校对 差异金额 - 附件 打款时间 @@ -744,12 +746,20 @@ ); @endphp - {{ $row->business_id }} - {{ $row->title ?: '未命名审批' }} - {{ $row->originator_name ?: '-' }} - {{ $row->document_type ?: '-' }} - {{ $row->expense_type ?: '-' }} - {{ $row->payee_name ?: '-' }} + + + {{ $row->business_id }} + + + {{ $row->invoice_type ?: '未分类' }} @@ -777,26 +787,13 @@ ¥{{ $money($flowDifference) }} - - @if ($row->source_file_id) - 查看附件 - @else - 待关联原件 - @endif - {{ $row->paid_at ? \Illuminate\Support\Carbon::parse($row->paid_at)->format('Y-m-d') : '-' }} @empty - 当前筛选条件下没有发票明细。 + 当前筛选条件下没有发票明细。 @endforelse @@ -836,7 +833,20 @@ $difference = round((float) $row->payment_amount - (float) $row->invoice_total, 2); @endphp - {{ $row->business_id }} + + + {{ $row->business_id }} + + + {{ $row->title ?: '未命名审批' }} {{ $row->originator_name ?: '-' }} {{ $row->document_type ?: '-' }} @@ -876,10 +886,10 @@

- 口径:统计从 {{ $startMonth }} 开始。发票通过 OA 审批流程附件自动识别,按打款时间归入月份; - 一张发票一行,同一流程多张发票分别列示,并保留对应流程号。无票流程在“按流程汇总”中保留。 - 尚未关联原件的历史记录会标记为“待关联原件”。开票金额覆盖率可能超过 100%, - 表示开票金额高于本月付款,需要按具体流程复核。 + 口径:统计从 {{ $startMonth }} 开始。发票附件只由服务端临时下载并识别,页面直接展示识别结果, + 不提供附件下载。发票按打款时间归入月份,一张发票一行,同一流程多张发票分别列示。 + 无票流程在“按流程汇总”中保留。开票金额覆盖率可能超过 100%,表示开票金额高于本月付款, + 需要按具体流程复核。

diff --git a/tests/Feature/Business/InvoiceDataPageTest.php b/tests/Feature/Business/InvoiceDataPageTest.php index 9394b5fa..bcf2653d 100644 --- a/tests/Feature/Business/InvoiceDataPageTest.php +++ b/tests/Feature/Business/InvoiceDataPageTest.php @@ -168,10 +168,21 @@ class InvoiceDataPageTest extends FeatureTestCase ); $this->assertNotEmpty($detailHeader); $this->assertStringContainsString('>项目名称', $detailHeader[0]); + foreach (['流程标题', '提交人', '报销类型', '费用类型', '收款人', '附件'] as $removedHeader) { + $this->assertStringNotContainsString(">{$removedHeader}", $detailHeader[0]); + } $this->assertMatchesRegularExpression( '/>项目名称<\/th>.*>打款时间<\/th>\s*<\/tr>$/su', $detailHeader[0], ); + $response->assertSee( + route('business.pages.show', [ + 'section' => 'process-data', + 'page' => 'oa-process', + 'business_id' => 'FLOW-INVOICE-1', + ]), + false, + ); $flowHeader = null; preg_match( @@ -426,6 +437,25 @@ class InvoiceDataPageTest extends FeatureTestCase 'created_at' => $now, 'updated_at' => $now, ]); + DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([ + 'source_scope' => 'personal_permission', + 'business_id' => 'FLOW-FAILED-BACKOFF', + 'process_instance_id' => 'PROCESS-FAILED-BACKOFF', + 'paid_month' => '2026-12', + 'payment_amount' => 10, + 'payment_total' => 10, + 'invoice_count' => 0, + 'invoice_total' => 0, + 'scan_status' => 'failed', + 'attachment_count' => 1, + 'scanned_file_count' => 1, + 'source_name' => 'OA attachment scan', + 'scan_attempts' => 1, + 'next_scan_at' => $now->copy()->addHour(), + 'scanned_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]); $this->assertSame( '2026-11', @@ -471,6 +501,8 @@ class InvoiceDataPageTest extends FeatureTestCase $table->unsignedInteger('scanned_file_count')->default(0); $table->text('last_error')->nullable(); $table->string('source_name')->nullable(); + $table->unsignedInteger('scan_attempts')->default(0); + $table->dateTime('next_scan_at')->nullable(); $table->dateTime('scanned_at')->nullable(); $table->timestamps(); }); diff --git a/tests/Feature/Console/SyncDingProcessDetailMirrorTest.php b/tests/Feature/Console/SyncDingProcessDetailMirrorTest.php index 48ad3366..9442d62d 100644 --- a/tests/Feature/Console/SyncDingProcessDetailMirrorTest.php +++ b/tests/Feature/Console/SyncDingProcessDetailMirrorTest.php @@ -3,6 +3,7 @@ namespace Tests\Feature\Console; use Mockery; +use Modules\EcommerceFinance\Services\DingInvoiceSyncService; use Modules\EcommerceFinance\Services\DingProcessDetailMirrorSynchronizer; use Tests\Feature\FeatureTestCase; @@ -72,4 +73,69 @@ class SyncDingProcessDetailMirrorTest extends FeatureTestCase '--business-id' => '202610151743000310225', ])->assertFailed(); } + + public function test_incremental_oa_sync_runs_bounded_invoice_scan(): void + { + config([ + 'ding_invoice_data.sync_with_oa_process' => true, + 'ding_invoice_data.auto_scan_limit' => 5, + ]); + + $synchronizer = Mockery::mock(DingProcessDetailMirrorSynchronizer::class); + $synchronizer->shouldReceive('sync') + ->once() + ->with(false, false) + ->andReturn([ + 'status' => 'succeeded', + 'run_mode' => 'incremental', + 'workflows' => 2, + 'details' => 3, + 'payments' => 2, + 'amount_total' => 100.0, + 'bank_amount_total' => 100.0, + ]); + $this->app->instance(DingProcessDetailMirrorSynchronizer::class, $synchronizer); + + $invoices = Mockery::mock(DingInvoiceSyncService::class); + $invoices->shouldReceive('latestPendingMonth')->once()->andReturn('2026-10'); + $invoices->shouldReceive('syncMonth') + ->once() + ->with('2026-10', 5) + ->andReturn([ + 'processed_flows' => 5, + 'recognized_invoices' => 2, + 'preserved_invoices' => 3, + 'remaining_flows' => 9, + ]); + $this->app->instance(DingInvoiceSyncService::class, $invoices); + + $this->artisan('business-mirror:sync-ding-process-details') + ->expectsOutputToContain('发票增量识别完成') + ->assertSuccessful(); + } + + public function test_oa_sync_skips_invoices_when_no_workflow_changed(): void + { + $synchronizer = Mockery::mock(DingProcessDetailMirrorSynchronizer::class); + $synchronizer->shouldReceive('sync') + ->once() + ->with(false, false) + ->andReturn([ + 'status' => 'succeeded', + 'run_mode' => 'incremental', + 'workflows' => 0, + 'details' => 0, + 'payments' => 0, + 'amount_total' => 0.0, + 'bank_amount_total' => 0.0, + ]); + $this->app->instance(DingProcessDetailMirrorSynchronizer::class, $synchronizer); + + $invoices = Mockery::mock(DingInvoiceSyncService::class); + $invoices->shouldNotReceive('latestPendingMonth'); + $invoices->shouldNotReceive('syncMonth'); + $this->app->instance(DingInvoiceSyncService::class, $invoices); + + $this->artisan('business-mirror:sync-ding-process-details')->assertSuccessful(); + } } diff --git a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php index 618cb289..0a8f3095 100644 --- a/tests/Unit/Deployment/BusinessMirrorScheduleTest.php +++ b/tests/Unit/Deployment/BusinessMirrorScheduleTest.php @@ -159,6 +159,11 @@ class BusinessMirrorScheduleTest extends TestCase $contents, $script, ); + $this->assertStringNotContainsString( + 'ding-invoices:sync --auto', + $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" @@ -168,6 +173,8 @@ class BusinessMirrorScheduleTest extends TestCase . "# OA 页面每小时最多提交一次当前页审批中的流程;有请求时才启动定向刷新批处理。\n" . '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-refresh.lock ' . "/bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:process-ding-refresh-requests --quiet >/dev/null 2>&1\n" + . '* * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-invoice-scan.lock ' + . "/bin/sh /opt/caiwuxitong/run-finance-batch.sh ding-invoices:process-refresh-requests --quiet >/dev/null 2>&1\n" . 'EOF', $contents, $script, -- 2.47.2