From c625dfea0ed08f6f6291c11234a038594db24aeb Mon Sep 17 00:00:00 2001 From: yueyang <2495544247@qq.com> Date: Thu, 26 Nov 2026 16:45:06 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=20OA=20=E5=8F=91?= =?UTF-8?q?=E7=A5=A8=E6=95=B0=E6=8D=AE=E9=A1=B5=E9=9D=A2=E4=B8=8E=E6=8A=93?= =?UTF-8?q?=E5=8F=96=E9=93=BE=E8=B7=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Http/Controllers/Business/Pages.php | 1 + .../business_navigation_page_extensions.php | 1 + config/ding_invoice_data.php | 21 + ...0000_create_ding_invoice_mirror_tables.php | 125 +++ deploy/activate-incremental-release.sh | 1 + deploy/activate-release.sh | 1 + deploy/finance-batch-imports.json | 1 + deploy/run-finance-batch.sh | 8 +- .../Console/ImportDingInvoiceWorkbook.php | 49 + .../ProcessDingInvoiceRefreshRequests.php | 51 + .../Console/SyncDingInvoices.php | 37 + .../Http/Controllers/InvoiceData.php | 207 ++++ modules/EcommerceFinance/Providers/Main.php | 6 + .../DingInvoiceDataMirrorRepository.php | 452 ++++++++ modules/EcommerceFinance/Routes/admin.php | 25 + .../Services/DingInvoiceFileRecognizer.php | 257 +++++ .../Services/DingInvoiceRefreshQueue.php | 247 +++++ .../Services/DingInvoiceSyncService.php | 725 +++++++++++++ .../Services/DingInvoiceTextParser.php | 126 +++ .../Services/DingInvoiceVisionClient.php | 169 +++ .../Services/DingInvoiceWorkbookImporter.php | 395 +++++++ .../View/InvoiceDataPageData.php | 173 ++++ .../invoice-data.blade.php | 978 ++++++++++++++++++ .../invoice-data-pagination.blade.php | 22 + .../Feature/Business/InvoiceDataPageTest.php | 296 ++++++ .../Business/InvoiceDataRefreshQueueTest.php | 44 + .../Business/ProcessDetailsNavigationTest.php | 5 +- .../Console/ImportDingInvoiceWorkbookTest.php | 185 ++++ tests/Unit/DingInvoiceTextParserTest.php | 47 + 29 files changed, 4653 insertions(+), 2 deletions(-) create mode 100644 config/ding_invoice_data.php create mode 100644 database/migrations/2026_11_26_170000_create_ding_invoice_mirror_tables.php create mode 100644 modules/EcommerceFinance/Console/ImportDingInvoiceWorkbook.php create mode 100644 modules/EcommerceFinance/Console/ProcessDingInvoiceRefreshRequests.php create mode 100644 modules/EcommerceFinance/Console/SyncDingInvoices.php create mode 100644 modules/EcommerceFinance/Http/Controllers/InvoiceData.php create mode 100644 modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceFileRecognizer.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceRefreshQueue.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceSyncService.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceTextParser.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceVisionClient.php create mode 100644 modules/EcommerceFinance/Services/DingInvoiceWorkbookImporter.php create mode 100644 modules/EcommerceFinance/View/InvoiceDataPageData.php create mode 100644 resources/views/business/pages/financial-operations/invoice-data.blade.php create mode 100644 resources/views/business/pages/financial-operations/partials/invoice-data-pagination.blade.php create mode 100644 tests/Feature/Business/InvoiceDataPageTest.php create mode 100644 tests/Feature/Business/InvoiceDataRefreshQueueTest.php create mode 100644 tests/Feature/Console/ImportDingInvoiceWorkbookTest.php create mode 100644 tests/Unit/DingInvoiceTextParserTest.php diff --git a/app/Http/Controllers/Business/Pages.php b/app/Http/Controllers/Business/Pages.php index 054de90f9..71b348748 100644 --- a/app/Http/Controllers/Business/Pages.php +++ b/app/Http/Controllers/Business/Pages.php @@ -5580,6 +5580,7 @@ class Pages extends Controller 'product-costs' => $this->contentForProductCosts(), 'financial-analysis' => $this->contentForFinancialAnalysis(), 'oa-process' => $this->contentForProcessDetails(), + 'invoice-data' => app(\Modules\EcommerceFinance\View\InvoiceDataPageData::class)->page(request()), 'management-expenses' => $this->contentForManagementExpenses(), 'labor-expenses' => $this->contentForLaborExpenses(), 'courier-surcharge' => $this->contentForCourierSurcharge($tab), diff --git a/config/business_navigation_page_extensions.php b/config/business_navigation_page_extensions.php index c61ac703a..5eb00df6f 100644 --- a/config/business_navigation_page_extensions.php +++ b/config/business_navigation_page_extensions.php @@ -19,6 +19,7 @@ return [ 'icon' => 'account_tree', 'pages' => [ ['slug' => 'oa-process', 'title' => 'OA流程'], + ['slug' => 'invoice-data', 'title' => '发票数据', 'icon' => 'receipt_long'], ], ], ], diff --git a/config/ding_invoice_data.php b/config/ding_invoice_data.php new file mode 100644 index 000000000..df4222f32 --- /dev/null +++ b/config/ding_invoice_data.php @@ -0,0 +1,21 @@ + 'operations_replica.rpt.ding_invoices', + 'flow_batch_size' => (int) env('DING_INVOICE_SCAN_BATCH_SIZE', 20), + '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), + 'pdftotext_binary' => env('DING_INVOICE_PDFTOTEXT_BINARY', '/usr/bin/pdftotext'), + 'pdftoppm_binary' => env('DING_INVOICE_PDFTOPPM_BINARY', '/usr/bin/pdftoppm'), + 'ocr' => [ + 'api_key' => env('DING_INVOICE_OCR_API_KEY', env('DEEPSEEK_API_KEY', '')), + 'base_url' => env( + 'DING_INVOICE_OCR_BASE_URL', + 'https://api.deepseek.com/chat/completions', + ), + 'model' => env('DING_INVOICE_OCR_MODEL', 'deepseek-chat'), + 'timeout_seconds' => (int) env('DING_INVOICE_OCR_TIMEOUT', 90), + ], +]; diff --git a/database/migrations/2026_11_26_170000_create_ding_invoice_mirror_tables.php b/database/migrations/2026_11_26_170000_create_ding_invoice_mirror_tables.php new file mode 100644 index 000000000..ffee85eef --- /dev/null +++ b/database/migrations/2026_11_26_170000_create_ding_invoice_mirror_tables.php @@ -0,0 +1,125 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + + if (! $schema->hasTable('ding_invoice_flow_mirror')) { + $schema->create('ding_invoice_flow_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope', 40)->default('personal_permission'); + $table->string('business_id', 32); + $table->string('process_instance_id', 100)->nullable(); + $table->string('paid_month', 7)->default(''); + $table->string('title', 255)->nullable(); + $table->string('originator_name', 100)->nullable(); + $table->string('document_type', 100)->nullable(); + $table->string('expense_type', 255)->nullable(); + $table->string('payee_name', 255)->nullable(); + $table->dateTime('paid_at')->nullable(); + $table->decimal('payment_amount', 18, 2)->default(0); + $table->decimal('payment_total', 18, 2)->default(0); + $table->unsignedInteger('invoice_count')->default(0); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('scan_status', 24)->default('imported')->index(); + $table->unsignedInteger('attachment_count')->default(0); + $table->unsignedInteger('scanned_file_count')->default(0); + $table->text('last_error')->nullable(); + $table->string('source_name', 255)->nullable(); + $table->dateTime('scanned_at', 6)->nullable(); + $table->timestamps(); + + $table->unique( + ['source_scope', 'business_id'], + 'ding_invoice_flow_scope_business_unique', + ); + $table->index( + ['source_scope', 'paid_month'], + 'ding_invoice_flow_scope_month_index', + ); + $table->index( + ['source_scope', 'paid_month', 'scan_status'], + 'ding_invoice_flow_scope_month_status_index', + ); + }); + } + + if (! $schema->hasTable('ding_invoice_record_mirror')) { + $schema->create('ding_invoice_record_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope', 40)->default('personal_permission'); + $table->string('business_id', 32); + $table->string('process_instance_id', 100)->nullable(); + $table->string('paid_month', 7)->default(''); + $table->string('invoice_key', 64); + $table->string('invoice_type', 100)->nullable(); + $table->string('seller_name', 255)->nullable(); + $table->string('seller_tax_no', 64)->nullable(); + $table->string('buyer_name', 255)->nullable(); + $table->string('buyer_tax_no', 64)->nullable(); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('invoice_number', 32)->nullable(); + $table->date('invoice_date')->nullable(); + $table->text('item_name')->nullable(); + $table->decimal('amount_without_tax', 18, 2)->nullable(); + $table->string('tax_rate', 32)->nullable(); + $table->decimal('tax_amount', 18, 2)->nullable(); + $table->string('source_file_id', 100)->nullable(); + $table->string('source_file_name', 255)->nullable(); + $table->string('source_file_type', 32)->nullable(); + $table->string('source_field', 255)->nullable(); + $table->string('source_path', 1024)->nullable(); + $table->string('source_hash', 64)->nullable(); + $table->string('ocr_provider', 32)->nullable(); + $table->json('recognition_payload')->nullable(); + $table->timestamps(); + + $table->unique( + ['source_scope', 'business_id', 'invoice_key'], + 'ding_invoice_record_scope_business_key_unique', + ); + $table->index( + ['source_scope', 'business_id'], + 'ding_invoice_record_scope_business_index', + ); + $table->index( + ['source_scope', 'invoice_type'], + 'ding_invoice_record_scope_type_index', + ); + $table->index( + ['source_scope', 'invoice_date'], + 'ding_invoice_record_scope_date_index', + ); + $table->index('invoice_number', 'ding_invoice_record_number_index'); + }); + } + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + $schema->dropIfExists('ding_invoice_record_mirror'); + $schema->dropIfExists('ding_invoice_flow_mirror'); + } +}; diff --git a/deploy/activate-incremental-release.sh b/deploy/activate-incremental-release.sh index 466053df8..dbbc1a50a 100644 --- a/deploy/activate-incremental-release.sh +++ b/deploy/activate-incremental-release.sh @@ -271,6 +271,7 @@ CRON_TZ=Asia/Shanghai 2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 # 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 EOF chmod 644 /etc/cron.d/caiwu-ding-process-details diff --git a/deploy/activate-release.sh b/deploy/activate-release.sh index b85fd0382..67c7793be 100644 --- a/deploy/activate-release.sh +++ b/deploy/activate-release.sh @@ -275,6 +275,7 @@ CRON_TZ=Asia/Shanghai 2-59/15 * * * * root CAIWU_BATCH_LOCK_WAIT=900 /usr/bin/flock -n /run/caiwu-ding-process-details.lock /bin/sh /opt/caiwuxitong/run-finance-batch.sh business-mirror:sync-ding-process-details --quiet >/dev/null 2>&1 # 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 EOF chmod 644 /etc/cron.d/caiwu-ding-process-details diff --git a/deploy/finance-batch-imports.json b/deploy/finance-batch-imports.json index 3f69a243c..e191701a6 100644 --- a/deploy/finance-batch-imports.json +++ b/deploy/finance-batch-imports.json @@ -38,6 +38,7 @@ "business-mirror:import-jd-wallet", "business-mirror:import-pdd-platform-balances", "ding:import-process-details", + "ding-invoices:import", "jst-order-labels:import-planting-rules", "jst-order-labels:import", "jst-order-labels:sync-daily", diff --git a/deploy/run-finance-batch.sh b/deploy/run-finance-batch.sh index 19b9186d5..43bba79fa 100644 --- a/deploy/run-finance-batch.sh +++ b/deploy/run-finance-batch.sh @@ -9,7 +9,7 @@ CAIWU_BATCH_CALLER_DIR="$PWD" export CAIWU_BATCH_CALLER_DIR case "${1:-}" in *:import|*:import-*|*:import:*|payables:unpriced-cycle|product:monthly-weighted-average:base|planting-details:sync-work-orders|jst-order-labels:sync-daily) is_import=1 ;; - jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; + jushuitan:sync-shipping|store-receipt:order-match:sync|store-receipt:planting-daily|store-receipt:product-cost:sync|store-receipt:auto-resync|order-data:warm-shop-candidates|business-mirror:sync-tables|business-mirror:sync-ding-process-details|business-mirror:process-ding-refresh-requests|business-mirror:index-work-order-waybills|business-mirror:refresh-paid-sales|ding-invoices:sync|ding-invoices:process-refresh-requests|account-bills:exports:run|finance-ledger:recalculate|product:monthly-weighted-average:auto|product:monthly-weighted-average:compute|product:monthly-weighted-average:report|finance:monthly-weighted-product-cost:auto) ;; *) echo 'Unsupported finance batch command' >&2; exit 64 ;; esac case "${1:-}" in @@ -46,6 +46,12 @@ if [ "$1" = 'business-mirror:process-ding-refresh-requests' ]; then pending_request="$(find "$storage_root/app/ding-process-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)" [ -n "$pending_request" ] || exit 0 fi +if [ "$1" = 'ding-invoices:process-refresh-requests' ]; then + storage_root="$(docker inspect caiwu_app --format '{{range .Mounts}}{{if eq .Destination "/var/www/html/storage"}}{{.Source}}{{end}}{{end}}')" + [ -n "$storage_root" ] && [ -d "$storage_root/app/ding-invoice-refresh" ] || exit 0 + pending_request="$(find "$storage_root/app/ding-invoice-refresh" -maxdepth 1 -type f -name '*.pending' -print -quit)" + [ -n "$pending_request" ] || exit 0 +fi if [ "$1" != 'account-bills:exports:run' ]; then exec 9>"$LOCK_FILE" if ! flock -w "${CAIWU_BATCH_LOCK_WAIT:-1800}" 9; then diff --git a/modules/EcommerceFinance/Console/ImportDingInvoiceWorkbook.php b/modules/EcommerceFinance/Console/ImportDingInvoiceWorkbook.php new file mode 100644 index 000000000..e8563ccf5 --- /dev/null +++ b/modules/EcommerceFinance/Console/ImportDingInvoiceWorkbook.php @@ -0,0 +1,49 @@ +import( + (string) $this->argument('file'), + (string) $this->option('scope'), + ! $this->option('keep-existing-months'), + ); + } catch (Throwable $exception) { + report($exception); + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(sprintf( + '发票台账导入完成:%d 个流程、%d 张发票、开票金额 %.2f 元;月份 %s。', + $result['flows'], + $result['invoices'], + $result['invoice_total'], + implode(',', $result['months']), + )); + $this->line(sprintf( + '耗时 %.2f 秒;PHP 峰值内存 %.1f MiB。', + microtime(true) - $startedAt, + memory_get_peak_usage(true) / 1024 / 1024, + )); + + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Console/ProcessDingInvoiceRefreshRequests.php b/modules/EcommerceFinance/Console/ProcessDingInvoiceRefreshRequests.php new file mode 100644 index 000000000..463e19f23 --- /dev/null +++ b/modules/EcommerceFinance/Console/ProcessDingInvoiceRefreshRequests.php @@ -0,0 +1,51 @@ +cleanup(); + $request = $queue->claimNext(); + if ($request === null) { + return self::SUCCESS; + } + + try { + $result = $sync->syncMonth( + (string) ($request['month'] ?? ''), + (int) $this->option('limit'), + (bool) ($request['force'] ?? false), + ); + if ((int) ($result['remaining_flows'] ?? 0) > 0) { + $queue->defer((string) $request['token'], $result, false); + $this->info('本批发票抓取完成,剩余流程等待下一批处理。'); + + return self::SUCCESS; + } + $queue->complete((string) $request['token'], $result); + $this->info(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } catch (Throwable $exception) { + report($exception); + $queue->fail((string) $request['token'], $exception->getMessage()); + $this->error($exception->getMessage()); + + return self::FAILURE; + } + } +} diff --git a/modules/EcommerceFinance/Console/SyncDingInvoices.php b/modules/EcommerceFinance/Console/SyncDingInvoices.php new file mode 100644 index 000000000..4a029544e --- /dev/null +++ b/modules/EcommerceFinance/Console/SyncDingInvoices.php @@ -0,0 +1,37 @@ +syncMonth( + (string) ($this->option('month') ?: now()->format('Y-m')), + (int) $this->option('limit'), + (bool) $this->option('force'), + ); + } catch (Throwable $exception) { + report($exception); + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + $this->info(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } +} diff --git a/modules/EcommerceFinance/Http/Controllers/InvoiceData.php b/modules/EcommerceFinance/Http/Controllers/InvoiceData.php new file mode 100644 index 000000000..3adacf3c5 --- /dev/null +++ b/modules/EcommerceFinance/Http/Controllers/InvoiceData.php @@ -0,0 +1,207 @@ +filters($request); + + return response()->streamDownload(function () use ($filters): void { + $stream = fopen('php://output', 'wb'); + fwrite($stream, "\xEF\xBB\xBF"); + + if ($filters['view'] === DingInvoiceDataMirrorRepository::VIEW_FLOWS) { + fputcsv($stream, [ + '流程号', + '标题', + '提交人', + '报销类型', + '费用类型', + '收款人', + '打款时间', + '本月付款金额', + '付款合计', + '发票张数', + '发票价税合计', + '付款差额', + '扫描状态', + '扫描说明', + ]); + foreach ($this->repository->exportRows($filters) as $row) { + $payment = (float) ($row['payment_amount'] ?? 0); + $invoice = (float) ($row['invoice_total'] ?? 0); + fputcsv($stream, [ + (string) ($row['business_id'] ?? ''), + (string) ($row['title'] ?? ''), + (string) ($row['originator_name'] ?? ''), + (string) ($row['document_type'] ?? ''), + (string) ($row['expense_type'] ?? ''), + (string) ($row['payee_name'] ?? ''), + (string) ($row['paid_at'] ?? ''), + number_format($payment, 2, '.', ''), + number_format((float) ($row['payment_total'] ?? 0), 2, '.', ''), + (int) ($row['invoice_count'] ?? 0), + number_format($invoice, 2, '.', ''), + number_format(round($payment - $invoice, 2), 2, '.', ''), + (string) ($row['scan_status'] ?? ''), + (string) ($row['last_error'] ?? ''), + ]); + } + } else { + fputcsv($stream, [ + '流程号', + '标题', + '提交人', + '报销类型', + '收款人', + '打款时间', + '本月付款金额', + '发票类型', + '销售方名称', + '销售方税号', + '购买方名称', + '购买方税号', + '价税合计', + '发票号码', + '开票日期', + '项目名称', + '金额', + '税率', + '税额', + '付款差额', + '附件名称', + ]); + foreach ($this->repository->exportRows($filters) as $row) { + $payment = (float) ($row['payment_amount'] ?? 0); + $invoice = (float) ($row['invoice_total'] ?? 0); + fputcsv($stream, [ + (string) ($row['business_id'] ?? ''), + (string) ($row['title'] ?? ''), + (string) ($row['originator_name'] ?? ''), + (string) ($row['document_type'] ?? ''), + (string) ($row['payee_name'] ?? ''), + (string) ($row['paid_at'] ?? ''), + number_format($payment, 2, '.', ''), + (string) ($row['invoice_type'] ?? ''), + (string) ($row['seller_name'] ?? ''), + (string) ($row['seller_tax_no'] ?? ''), + (string) ($row['buyer_name'] ?? ''), + (string) ($row['buyer_tax_no'] ?? ''), + number_format($invoice, 2, '.', ''), + (string) ($row['invoice_number'] ?? ''), + (string) ($row['invoice_date'] ?? ''), + (string) ($row['item_name'] ?? ''), + $row['amount_without_tax'] === null + ? '' + : number_format((float) $row['amount_without_tax'], 2, '.', ''), + (string) ($row['tax_rate'] ?? ''), + $row['tax_amount'] === null + ? '' + : number_format((float) $row['tax_amount'], 2, '.', ''), + number_format(round($payment - $invoice, 2), 2, '.', ''), + (string) ($row['source_file_name'] ?? ''), + ]); + } + } + fclose($stream); + }, 'OA发票数据_' . ($filters['month'] ?: 'all') . '_' . now()->format('Ymd_His') . '.csv', [ + 'Content-Type' => 'text/csv; charset=UTF-8', + 'Cache-Control' => 'private, no-store', + ]); + } + + public function attachment(int $invoice): RedirectResponse + { + // The row endpoint is intentionally not used for arbitrary IDs. Query the + // exact invoice record, then let DingTalk enforce whether the current app + // can mint a temporary download URL for that process attachment. + $invoiceRow = \Illuminate\Support\Facades\DB::connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + )->table('ding_invoice_record_mirror') + ->where('id', $invoice) + ->where('source_scope', $this->repository->scope()) + ->first(); + abort_if($invoiceRow === null, 404); + + $processInstanceId = trim((string) ($invoiceRow->process_instance_id ?? '')); + $fileId = trim((string) ($invoiceRow->source_file_id ?? '')); + abort_if($processInstanceId === '' || $fileId === '', 404, '该发票没有可下载的原始附件。'); + + $uri = app(DingTalkApprovalAttachmentDownloader::class) + ->downloadUri($processInstanceId, $fileId); + abort_if($uri === null, 404, '原始发票附件暂时无法下载。'); + + return redirect()->away($uri); + } + + public function requestRefresh(Request $request): JsonResponse + { + $validated = $request->validate([ + 'month' => ['required', 'date_format:Y-m'], + 'force' => ['nullable', 'boolean'], + ]); + $state = app(DingInvoiceRefreshQueue::class)->enqueue( + $validated['month'], + (bool) ($validated['force'] ?? true), + (int) company_id(), + (int) user_id(), + ); + + return response()->json([ + 'success' => true, + ...$state, + 'message' => $state['queued'] + ? '发票抓取任务已进入队列。' + : '该月份已有发票抓取任务正在排队或处理中。', + ])->header('Cache-Control', 'no-store'); + } + + public function refreshStatus(string $token): JsonResponse + { + $status = app(DingInvoiceRefreshQueue::class)->status( + $token, + (int) company_id(), + (int) user_id(), + ); + abort_if($status === null, 404); + + return response() + ->json(['success' => true, 'refresh' => $status]) + ->header('Cache-Control', 'no-store'); + } + + /** @return array */ + private function filters(Request $request): array + { + $month = trim((string) $request->query('month', '')); + $view = $request->query('invoice_view') === DingInvoiceDataMirrorRepository::VIEW_FLOWS + ? DingInvoiceDataMirrorRepository::VIEW_FLOWS + : DingInvoiceDataMirrorRepository::VIEW_DETAIL; + $state = (string) $request->query('invoice_state', 'all'); + + return [ + 'month' => preg_match('/^\d{4}-\d{2}$/', $month) === 1 ? $month : '', + 'view' => $view, + 'invoice_state' => array_key_exists($state, DingInvoiceDataMirrorRepository::INVOICE_STATES) + ? $state + : 'all', + 'invoice_type' => mb_substr(trim((string) $request->query('invoice_type', '')), 0, 100), + 'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100), + ]; + } +} diff --git a/modules/EcommerceFinance/Providers/Main.php b/modules/EcommerceFinance/Providers/Main.php index f130a0ccb..ca48cf861 100644 --- a/modules/EcommerceFinance/Providers/Main.php +++ b/modules/EcommerceFinance/Providers/Main.php @@ -4,12 +4,15 @@ namespace Modules\EcommerceFinance\Providers; use Illuminate\Support\ServiceProvider as Provider; use Modules\EcommerceFinance\Console\ExportShengsuanAnomalyOrders; +use Modules\EcommerceFinance\Console\ImportDingInvoiceWorkbook; use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitDetails; use Modules\EcommerceFinance\Console\ProcessDingRefreshRequests; +use Modules\EcommerceFinance\Console\ProcessDingInvoiceRefreshRequests; use Modules\EcommerceFinance\Console\DiagnoseJushuitanPackage; use Modules\EcommerceFinance\Console\ImportShengsuanOrderProfitRows; use Modules\EcommerceFinance\Console\CalcShippingFreight; use Modules\EcommerceFinance\Console\SyncJushuitanShipping; +use Modules\EcommerceFinance\Console\SyncDingInvoices; use Modules\EcommerceFinance\Services\Freight\ShippingFreightService; use Modules\EcommerceFinance\Services\JianSunSnapshotRefresher; use Modules\EcommerceFinance\Services\OperationsReplicaSnapshotRefresher; @@ -29,7 +32,10 @@ class Main extends Provider $this->commands([ SyncJushuitanShipping::class, CalcShippingFreight::class, + ImportDingInvoiceWorkbook::class, ProcessDingRefreshRequests::class, + ProcessDingInvoiceRefreshRequests::class, + SyncDingInvoices::class, DiagnoseJushuitanPackage::class, ImportShengsuanOrderProfitRows::class, ImportShengsuanOrderProfitDetails::class, diff --git a/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php new file mode 100644 index 000000000..7d54ccac3 --- /dev/null +++ b/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php @@ -0,0 +1,452 @@ + '全部状态', + 'has_invoice' => '有发票', + 'no_invoice' => '无票', + 'needs_review' => '待复核', + ]; + + private ConnectionInterface $connection; + + public function __construct(DatabaseManager $database) + { + $this->connection = $database->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + public function scope(): string + { + return trim((string) config( + 'upstream_mirrors.ding_process_details.scope', + 'personal_permission', + )) ?: 'personal_permission'; + } + + public function ready(): bool + { + $schema = Schema::connection($this->connection->getName()); + if (! $schema->hasTable('ding_invoice_flow_mirror') + || ! $schema->hasTable('ding_invoice_record_mirror')) { + return false; + } + + $state = $this->state(); + + if ($state !== null && ($state['initial_completed_at'] ?? null) !== null) { + return true; + } + + return (int) $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $this->scope()) + ->count() > 0; + } + + /** @return array|null */ + public function state(): ?array + { + if (! Schema::connection($this->connection->getName()) + ->hasTable('business_mirror_table_states')) { + return null; + } + + $row = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', DingInvoiceWorkbookImporter::DATASET_KEY) + ->first(); + + return $row === null ? null : (array) $row; + } + + /** @return list */ + public function months(): array + { + if (! $this->ready()) { + return []; + } + + return $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $this->scope()) + ->whereNotNull('paid_month') + ->where('paid_month', '!=', '') + ->distinct() + ->orderByDesc('paid_month') + ->pluck('paid_month') + ->map(static fn (mixed $value): string => (string) $value) + ->values() + ->all(); + } + + /** + * @param array $filters + * @return array{data:list,total:int,summary:array,state:?array} + */ + public function paginate(array $filters, int $page, int $perPage): array + { + if (! $this->ready()) { + throw new RuntimeException('ding_invoice_mirror_not_ready'); + } + + $page = max(1, $page); + $perPage = in_array($perPage, self::PER_PAGE_OPTIONS, true) ? $perPage : 50; + $query = $filters['view'] === self::VIEW_FLOWS + ? $this->flowQuery($filters) + : $this->detailQuery($filters); + $total = (clone $query)->count(); + $data = $query + ->forPage($page, $perPage) + ->get() + ->all(); + + return [ + 'data' => $data, + 'total' => $total, + 'summary' => $this->summary($filters), + 'state' => $this->state(), + ]; + } + + /** @param array $filters */ + public function filterOptions(array $filters): array + { + if (! $this->ready()) { + return ['invoice_types' => []]; + } + + $query = $this->connection->table('ding_invoice_record_mirror') + ->where('source_scope', $this->scope()); + if (($filters['month'] ?? '') !== '') { + $query->where('paid_month', $filters['month']); + } + + return [ + 'invoice_types' => $query + ->whereNotNull('invoice_type') + ->where('invoice_type', '!=', '') + ->distinct() + ->orderBy('invoice_type') + ->pluck('invoice_type') + ->map(static fn (mixed $value): string => (string) $value) + ->values() + ->all(), + ]; + } + + /** @param array $filters */ + public function exportRows(array $filters): iterable + { + if (! $this->ready()) { + throw new RuntimeException('ding_invoice_mirror_not_ready'); + } + + $query = $filters['view'] === self::VIEW_FLOWS + ? $this->flowQuery($filters) + : $this->detailQuery($filters); + + foreach ($query->cursor() as $row) { + yield (array) $row; + } + } + + /** @param array $filters */ + private function flowQuery(array $filters): Builder + { + $query = $this->connection->table('ding_invoice_flow_mirror as f') + ->select([ + 'f.id', + 'f.business_id', + 'f.process_instance_id', + 'f.paid_month', + 'f.title', + 'f.originator_name', + 'f.document_type', + 'f.expense_type', + 'f.payee_name', + 'f.paid_at', + 'f.payment_amount', + 'f.payment_total', + 'f.invoice_count', + 'f.invoice_total', + 'f.scan_status', + 'f.attachment_count', + 'f.scanned_file_count', + 'f.last_error', + 'f.source_name', + 'f.scanned_at', + ]) + ->where('f.source_scope', $this->scope()); + + $this->applyFlowFilters($query, $filters); + + return $query + ->orderByDesc('f.paid_at') + ->orderByDesc('f.business_id'); + } + + /** @param array $filters */ + private function detailQuery(array $filters): Builder + { + $query = $this->connection->table('ding_invoice_record_mirror as r') + ->join('ding_invoice_flow_mirror as f', function ($join): void { + $join->on('f.business_id', '=', 'r.business_id') + ->on('f.source_scope', '=', 'r.source_scope'); + }) + ->select([ + 'r.id', + 'r.business_id', + 'r.process_instance_id', + 'r.paid_month', + 'r.invoice_type', + 'r.seller_name', + 'r.seller_tax_no', + 'r.buyer_name', + 'r.buyer_tax_no', + 'r.invoice_total', + 'r.invoice_number', + 'r.invoice_date', + 'r.item_name', + 'r.amount_without_tax', + 'r.tax_rate', + 'r.tax_amount', + 'r.source_file_id', + 'r.source_file_name', + 'r.source_file_type', + 'r.source_field', + 'r.ocr_provider', + 'f.title', + 'f.originator_name', + 'f.document_type', + 'f.expense_type', + 'f.payee_name', + 'f.paid_at', + 'f.payment_amount', + 'f.payment_total', + 'f.invoice_count', + 'f.invoice_total as flow_invoice_total', + 'f.scan_status', + 'f.last_error', + ]) + ->where('r.source_scope', $this->scope()); + + $this->applyFlowFilters($query, $filters, 'f'); + if (($filters['invoice_type'] ?? '') !== '') { + $query->where('r.invoice_type', $filters['invoice_type']); + } + if (($filters['keyword'] ?? '') !== '') { + $keyword = '%' . $filters['keyword'] . '%'; + $query->where(function (Builder $nested) use ($keyword, $filters): void { + foreach ([ + 'r.business_id', + 'r.invoice_number', + 'r.seller_name', + 'r.seller_tax_no', + 'r.buyer_name', + 'r.buyer_tax_no', + 'r.item_name', + 'f.title', + 'f.originator_name', + 'f.payee_name', + ] as $column) { + $nested->orWhere($column, 'like', $keyword); + } + }); + } + + return $query + ->orderByDesc('f.paid_at') + ->orderByDesc('f.business_id') + ->orderBy('r.id'); + } + + /** @param array $filters */ + private function applyFlowFilters(Builder $query, array $filters, string $alias = 'f'): void + { + $query->where("{$alias}.source_scope", $this->scope()); + if (($filters['month'] ?? '') !== '') { + $query->where("{$alias}.paid_month", $filters['month']); + } + match ($filters['invoice_state'] ?? 'all') { + 'has_invoice' => $query->where("{$alias}.invoice_count", '>', 0), + 'no_invoice' => $query + ->where("{$alias}.invoice_count", '=', 0) + ->where(function (Builder $nested) use ($alias): void { + $nested->whereNull("{$alias}.last_error") + ->orWhere("{$alias}.last_error", '=', ''); + }), + 'needs_review' => $query + ->where(function (Builder $nested) use ($alias): void { + $nested->whereIn("{$alias}.scan_status", ['partial', 'failed']) + ->orWhere(function (Builder $failed) use ($alias): void { + $failed->whereNotNull("{$alias}.last_error") + ->where("{$alias}.last_error", '!=', ''); + }); + }), + default => null, + }; + + if (($filters['invoice_type'] ?? '') !== '' + && $filters['view'] === self::VIEW_FLOWS) { + $query->whereExists(function (Builder $exists) use ($filters): void { + $exists->selectRaw('1') + ->from('ding_invoice_record_mirror as ri') + ->whereColumn('ri.source_scope', 'f.source_scope') + ->whereColumn('ri.business_id', 'f.business_id') + ->where('ri.invoice_type', $filters['invoice_type']); + }); + } + + if (($filters['keyword'] ?? '') !== '' + && $filters['view'] === self::VIEW_FLOWS) { + $keyword = '%' . $filters['keyword'] . '%'; + $query->where(function (Builder $nested) use ($keyword, $alias, $filters): void { + foreach ([ + "{$alias}.business_id", + "{$alias}.title", + "{$alias}.originator_name", + "{$alias}.document_type", + "{$alias}.expense_type", + "{$alias}.payee_name", + ] as $column) { + $nested->orWhere($column, 'like', $keyword); + } + if ($filters['view'] === self::VIEW_FLOWS) { + $nested->orWhereExists(function (Builder $exists) use ($keyword): void { + $exists->selectRaw('1') + ->from('ding_invoice_record_mirror as rk') + ->whereColumn('rk.source_scope', 'f.source_scope') + ->whereColumn('rk.business_id', 'f.business_id') + ->where(function (Builder $invoiceSearch) use ($keyword): void { + foreach (['invoice_number', 'seller_name', 'buyer_name', 'item_name'] as $column) { + $invoiceSearch->orWhere("rk.{$column}", 'like', $keyword); + } + }); + }); + } + }); + } + } + + /** @param array $filters */ + private function summary(array $filters): array + { + $query = $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $this->scope()); + if (($filters['month'] ?? '') !== '') { + $query->where('paid_month', $filters['month']); + } + if (($filters['invoice_state'] ?? 'all') === 'has_invoice') { + $query->where('invoice_count', '>', 0); + } elseif (($filters['invoice_state'] ?? 'all') === 'no_invoice') { + $query->where('invoice_count', 0) + ->where(function (Builder $nested): void { + $nested->whereNull('last_error')->orWhere('last_error', ''); + }); + } elseif (($filters['invoice_state'] ?? 'all') === 'needs_review') { + $query->where(function (Builder $nested): void { + $nested->whereIn('scan_status', ['partial', 'failed']) + ->orWhere(function (Builder $failed): void { + $failed->whereNotNull('last_error')->where('last_error', '!=', ''); + }); + }); + } + + if (($filters['invoice_type'] ?? '') !== '') { + $query->whereExists(function (Builder $exists) use ($filters): void { + $exists->selectRaw('1') + ->from('ding_invoice_record_mirror as summary_invoice') + ->whereColumn('summary_invoice.source_scope', 'ding_invoice_flow_mirror.source_scope') + ->whereColumn('summary_invoice.business_id', 'ding_invoice_flow_mirror.business_id') + ->where('summary_invoice.invoice_type', $filters['invoice_type']); + }); + } + + if (($filters['keyword'] ?? '') !== '') { + $keyword = '%' . $filters['keyword'] . '%'; + $query->where(function (Builder $nested) use ($keyword, $filters): void { + foreach ([ + 'business_id', + 'title', + 'originator_name', + 'document_type', + 'expense_type', + 'payee_name', + ] as $column) { + $nested->orWhere($column, 'like', $keyword); + } + if (($filters['view'] ?? self::VIEW_DETAIL) === self::VIEW_DETAIL) { + $nested->orWhereExists(function (Builder $exists) use ($keyword): void { + $exists->selectRaw('1') + ->from('ding_invoice_record_mirror as summary_invoice_search') + ->whereColumn( + 'summary_invoice_search.source_scope', + 'ding_invoice_flow_mirror.source_scope', + ) + ->whereColumn( + 'summary_invoice_search.business_id', + 'ding_invoice_flow_mirror.business_id', + ) + ->where(function (Builder $invoiceSearch) use ($keyword): void { + foreach ([ + 'invoice_number', + 'seller_name', + 'seller_tax_no', + 'buyer_name', + 'buyer_tax_no', + 'item_name', + ] as $column) { + $invoiceSearch->orWhere( + 'summary_invoice_search.' . $column, + 'like', + $keyword, + ); + } + }); + }); + } + }); + } + + $rows = (clone $query)->get([ + 'payment_amount', + 'invoice_count', + 'invoice_total', + 'scan_status', + 'last_error', + ]); + $payment = round((float) $rows->sum('payment_amount'), 2); + $invoice = round((float) $rows->sum('invoice_total'), 2); + + return [ + 'flows' => $rows->count(), + 'payment_amount' => $payment, + 'invoice_count' => (int) $rows->sum('invoice_count'), + 'invoice_total' => $invoice, + 'no_invoice_flows' => $rows->filter( + static fn (object $row): bool => (int) $row->invoice_count === 0 + && ($row->last_error === null || $row->last_error === ''), + )->count(), + 'needs_review_flows' => $rows->filter( + static fn (object $row): bool => in_array((string) $row->scan_status, ['partial', 'failed'], true) + || ($row->last_error !== null && $row->last_error !== ''), + )->count(), + 'invoice_rate' => $payment > 0 ? $invoice / $payment : 0, + ]; + } +} diff --git a/modules/EcommerceFinance/Routes/admin.php b/modules/EcommerceFinance/Routes/admin.php index 362176972..048794b3f 100644 --- a/modules/EcommerceFinance/Routes/admin.php +++ b/modules/EcommerceFinance/Routes/admin.php @@ -1,6 +1,7 @@ defaults('page', 'oa-process') ->name('business.process-details.pending-payment-summary'); + Route::get('workspace/process-data/invoice-data/export', [InvoiceData::class, 'export']) + ->middleware('business.page:process-data,invoice-data') + ->name('business.invoice-data.export'); + + Route::post('workspace/process-data/invoice-data/refresh', [InvoiceData::class, 'requestRefresh']) + ->middleware(['business.page:process-data,invoice-data', 'throttle:10,1']) + ->name('business.invoice-data.refresh'); + + Route::get( + 'workspace/process-data/invoice-data/refresh/{token}', + [InvoiceData::class, 'refreshStatus'], + ) + ->where('token', '[0-9a-f-]{36}') + ->middleware(['business.page:process-data,invoice-data', 'throttle:120,1']) + ->name('business.invoice-data.refresh-status'); + + Route::get( + 'workspace/process-data/invoice-data/invoices/{invoice}/attachment', + [InvoiceData::class, 'attachment'], + ) + ->whereNumber('invoice') + ->middleware('business.page:process-data,invoice-data') + ->name('business.invoice-data.attachment'); + Route::get('workspace/financial-operations/process-details', function (\Illuminate\Http\Request $request) { return redirect()->route('business.pages.show', array_merge($request->query(), [ 'section' => 'process-data', diff --git a/modules/EcommerceFinance/Services/DingInvoiceFileRecognizer.php b/modules/EcommerceFinance/Services/DingInvoiceFileRecognizer.php new file mode 100644 index 000000000..b764bd9b2 --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceFileRecognizer.php @@ -0,0 +1,257 @@ +>,errors:list,provider:string} + */ + public function recognize(string $path, string $fileName = ''): array + { + if (! is_file($path)) { + return ['invoices' => [], 'errors' => ['文件不存在'], 'provider' => '']; + } + + $extension = strtolower(pathinfo($fileName !== '' ? $fileName : $path, PATHINFO_EXTENSION)); + $tempDir = storage_path('app/temp/invoice-ocr/' . bin2hex(random_bytes(8))); + if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) { + throw new RuntimeException('无法创建发票临时目录。'); + } + + try { + return match ($extension) { + 'pdf' => $this->recognizePdf($path, $tempDir), + 'jpg', 'jpeg', 'png', 'webp', 'bmp' => $this->recognizeImage($path), + 'xlsx' => $this->recognizeXlsx($path, $tempDir), + 'zip' => $this->recognizeZip($path, $tempDir), + default => [ + 'invoices' => [], + 'errors' => ['暂不支持识别 .' . ($extension ?: '未知') . ' 附件'], + 'provider' => '', + ], + }; + } finally { + $this->removeDirectory($tempDir); + } + } + + /** @return array{invoices:list>,errors:list,provider:string} */ + private function recognizePdf(string $path, string $tempDir): array + { + $errors = []; + $text = $this->pdfText($path); + if ($text !== '') { + $parsed = $this->textParser->parse($text); + if ($parsed !== null) { + return ['invoices' => [$parsed], 'errors' => [], 'provider' => 'pdf_text']; + } + } + + if (! $this->vision->configured()) { + return [ + 'invoices' => [], + 'errors' => ['PDF 未提取到结构化发票,且未配置 OCR API。'], + 'provider' => 'pdf_text', + ]; + } + + $invoices = []; + for ($page = 1; $page <= max(1, (int) config('ding_invoice_data.max_pdf_pages', 5)); $page++) { + $prefix = $tempDir . '/page-' . $page; + if (! $this->renderPdfPage($path, $prefix, $page)) { + break; + } + $imagePath = $prefix . '.png'; + try { + $invoice = $this->vision->recognize( + (string) file_get_contents($imagePath), + 'image/png', + ); + if ($invoice !== null) { + $invoices[] = $invoice; + } + } catch (Throwable $exception) { + $errors[] = 'PDF 第 ' . $page . ' 页:' . $exception->getMessage(); + } + } + + return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'vision']; + } + + /** @return array{invoices:list>,errors:list,provider:string} */ + private function recognizeImage(string $path): array + { + if (! $this->vision->configured()) { + return [ + 'invoices' => [], + 'errors' => ['图片发票需要配置 OCR API。'], + 'provider' => 'vision', + ]; + } + + $mime = mime_content_type($path) ?: 'image/jpeg'; + $bytes = (string) file_get_contents($path); + $invoice = $this->vision->recognize($bytes, $mime); + + return [ + 'invoices' => $invoice === null ? [] : [$invoice], + 'errors' => [], + 'provider' => 'vision', + ]; + } + + /** @return array{invoices:list>,errors:list,provider:string} */ + private function recognizeXlsx(string $path, string $tempDir): array + { + $zip = new ZipArchive(); + if ($zip->open($path) !== true) { + return ['invoices' => [], 'errors' => ['无法打开 Excel 附件'], 'provider' => '']; + } + + $invoices = []; + $errors = []; + try { + for ($index = 0; $index < $zip->numFiles; $index++) { + $name = (string) $zip->getNameIndex($index); + if (! str_starts_with($name, 'xl/media/')) { + continue; + } + $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); + if (! in_array($extension, ['png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) { + continue; + } + $target = $tempDir . '/' . basename($name); + $stream = $zip->getStream($name); + if ($stream === false) { + continue; + } + file_put_contents($target, stream_get_contents($stream)); + fclose($stream); + + try { + $result = $this->recognizeImage($target); + array_push($invoices, ...$result['invoices']); + array_push($errors, ...$result['errors']); + } catch (Throwable $exception) { + $errors[] = $name . ':' . $exception->getMessage(); + } + } + } finally { + $zip->close(); + } + + return [ + 'invoices' => $invoices, + 'errors' => $errors, + 'provider' => 'xlsx_media', + ]; + } + + /** @return array{invoices:list>,errors:list,provider:string} */ + private function recognizeZip(string $path, string $tempDir): array + { + $zip = new ZipArchive(); + if ($zip->open($path) !== true) { + return ['invoices' => [], 'errors' => ['无法打开 ZIP 附件'], 'provider' => '']; + } + + $invoices = []; + $errors = []; + try { + for ($index = 0; $index < $zip->numFiles; $index++) { + $name = (string) $zip->getNameIndex($index); + $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); + if (! in_array($extension, ['pdf', 'png', 'jpg', 'jpeg', 'webp', 'bmp'], true)) { + continue; + } + $target = $tempDir . '/' . $index . '-' . basename($name); + $stream = $zip->getStream($name); + if ($stream === false) { + continue; + } + file_put_contents($target, stream_get_contents($stream)); + fclose($stream); + + try { + $result = $this->recognize($target, $name); + array_push($invoices, ...$result['invoices']); + array_push($errors, ...$result['errors']); + } catch (Throwable $exception) { + $errors[] = $name . ':' . $exception->getMessage(); + } + } + } finally { + $zip->close(); + } + + return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'zip']; + } + + private function pdfText(string $path): string + { + $binary = (string) config('ding_invoice_data.pdftotext_binary', '/usr/bin/pdftotext'); + if (! is_executable($binary)) { + return ''; + } + $process = new Process([$binary, '-layout', $path, '-']); + $process->setTimeout(45); + $process->run(); + + return $process->isSuccessful() ? $process->getOutput() : ''; + } + + private function renderPdfPage(string $path, string $prefix, int $page): bool + { + $binary = (string) config('ding_invoice_data.pdftoppm_binary', '/usr/bin/pdftoppm'); + if (! is_executable($binary)) { + return false; + } + $process = new Process([ + $binary, + '-png', + '-r', + '150', + '-f', + (string) $page, + '-l', + (string) $page, + '-singlefile', + $path, + $prefix, + ]); + $process->setTimeout(60); + $process->run(); + + return $process->isSuccessful() && is_file($prefix . '.png'); + } + + private function removeDirectory(string $directory): void + { + if (! is_dir($directory)) { + return; + } + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $item) { + if ($item->isDir()) { + @rmdir($item->getPathname()); + } else { + @unlink($item->getPathname()); + } + } + @rmdir($directory); + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceRefreshQueue.php b/modules/EcommerceFinance/Services/DingInvoiceRefreshQueue.php new file mode 100644 index 000000000..bf33c929f --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceRefreshQueue.php @@ -0,0 +1,247 @@ +makeDirectory(self::DIRECTORY); + foreach (array_merge( + Storage::disk('local')->files(self::DIRECTORY), + ) as $path) { + if (! str_ends_with($path, '.pending') && ! str_ends_with($path, '.processing')) { + continue; + } + $payload = $this->readJson($path); + if ($payload !== null + && (string) ($payload['month'] ?? '') === $month + && (int) ($payload['company_id'] ?? 0) === $companyId) { + return [ + 'queued' => false, + 'token' => (string) ($payload['token'] ?? pathinfo($path, PATHINFO_FILENAME)), + 'month' => $month, + ]; + } + } + + $token = (string) Str::uuid(); + $now = now(); + $this->writeJson($token . '.pending', [ + 'token' => $token, + 'status' => 'pending', + 'month' => $month, + 'force' => $force, + 'company_id' => $companyId, + 'user_id' => $userId, + 'created_at' => $now->toIso8601String(), + 'started_at' => null, + 'completed_at' => null, + 'error' => null, + ]); + + return ['queued' => true, 'token' => $token, 'month' => $month]; + } + + /** @return array|null */ + public function claimNext(): ?array + { + $this->failStaleProcessing(); + $paths = array_values(array_filter( + Storage::disk('local')->files(self::DIRECTORY), + static fn (string $path): bool => str_ends_with($path, '.pending'), + )); + usort($paths, fn (string $left, string $right): int => + Storage::disk('local')->lastModified($left) + <=> Storage::disk('local')->lastModified($right) + ); + + foreach ($paths as $pendingPath) { + $token = pathinfo($pendingPath, PATHINFO_FILENAME); + if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) { + continue; + } + $processingPath = self::DIRECTORY . '/' . $token . '.processing'; + if (! Storage::disk('local')->move($pendingPath, $processingPath)) { + continue; + } + $payload = $this->readJson($processingPath); + if ($payload === null) { + continue; + } + $payload['status'] = 'processing'; + $payload['started_at'] = now()->toIso8601String(); + $this->writeJson($token . '.processing', $payload); + + return $payload; + } + + return null; + } + + /** @param array $result */ + public function complete(string $token, array $result): void + { + $this->finish($token, 'completed', null, $result); + } + + public function fail(string $token, string $error): void + { + $this->finish($token, 'failed', $error, null); + } + + /** @param array $progress */ + public function defer(string $token, array $progress, ?bool $force = null): void + { + if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) { + return; + } + $processingPath = self::DIRECTORY . '/' . $token . '.processing'; + $payload = $this->readJson($processingPath); + if ($payload === null) { + return; + } + $payload['status'] = 'pending'; + $payload['progress'] = $progress; + if ($force !== null) { + $payload['force'] = $force; + } + $this->writeJson($token . '.pending', $payload); + Storage::disk('local')->delete($processingPath); + } + + /** @return array|null */ + public function status(string $token, int $companyId, int $userId): ?array + { + if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) { + return null; + } + $payload = null; + foreach (['completed', 'failed', 'processing', 'pending'] as $state) { + $payload = $this->readJson(self::DIRECTORY . '/' . $token . '.' . $state); + if ($payload !== null) { + break; + } + } + if ($payload === null + || (int) ($payload['company_id'] ?? 0) !== $companyId) { + return null; + } + + return [ + 'status' => (string) ($payload['status'] ?? 'pending'), + 'month' => (string) ($payload['month'] ?? ''), + 'force' => (bool) ($payload['force'] ?? false), + 'created_at' => $payload['created_at'] ?? null, + 'started_at' => $payload['started_at'] ?? null, + 'completed_at' => $payload['completed_at'] ?? null, + 'error' => $payload['error'] ?? null, + 'result' => $payload['result'] ?? null, + 'progress' => $payload['progress'] ?? null, + ]; + } + + public function pendingExists(): bool + { + $disk = Storage::disk('local'); + + return collect($disk->files(self::DIRECTORY)) + ->contains(static fn (string $path): bool => str_ends_with($path, '.pending')); + } + + public function cleanup(): void + { + $disk = Storage::disk('local'); + $cutoff = time() - self::RESULT_TTL_SECONDS; + foreach ($disk->files(self::DIRECTORY) as $path) { + if ((! str_ends_with($path, '.completed') && ! str_ends_with($path, '.failed')) + || $disk->lastModified($path) >= $cutoff) { + continue; + } + $disk->delete($path); + } + } + + private function failStaleProcessing(): void + { + $disk = Storage::disk('local'); + $cutoff = time() - self::STALE_PROCESSING_SECONDS; + foreach ($disk->files(self::DIRECTORY) as $path) { + if (! str_ends_with($path, '.processing') || $disk->lastModified($path) >= $cutoff) { + continue; + } + $token = pathinfo($path, PATHINFO_FILENAME); + $this->fail($token, '发票抓取任务处理超时,请重新发起。'); + } + } + + private function finish( + string $token, + string $status, + ?string $error, + ?array $result, + ): void { + if (preg_match('/^[0-9a-f-]{36}$/i', $token) !== 1) { + return; + } + $processingPath = self::DIRECTORY . '/' . $token . '.processing'; + $payload = $this->readJson($processingPath); + if ($payload === null) { + return; + } + $payload['status'] = $status; + $payload['completed_at'] = now()->toIso8601String(); + $payload['error'] = $error === null ? null : mb_substr($error, 0, 500); + $payload['result'] = $result; + $this->writeJson($token . '.' . $status, $payload); + Storage::disk('local')->delete($processingPath); + } + + /** @param array $payload */ + private function writeJson(string $path, array $payload): void + { + $disk = Storage::disk('local'); + $fullPath = self::DIRECTORY . '/' . ltrim($path, '/'); + $tempPath = $fullPath . '.' . Str::random(8) . '.tmp'; + $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); + if (! $disk->put($tempPath, $json) || ! $disk->move($tempPath, $fullPath)) { + throw new RuntimeException('发票抓取请求写入失败。'); + } + } + + /** @return array|null */ + private function readJson(string $path): ?array + { + $disk = Storage::disk('local'); + if (! $disk->exists($path)) { + return null; + } + try { + $payload = json_decode( + (string) $disk->get($path), + true, + 512, + JSON_THROW_ON_ERROR, + ); + } catch (Throwable) { + return null; + } + + return is_array($payload) ? $payload : null; + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceSyncService.php b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php new file mode 100644 index 000000000..6b340fdfd --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php @@ -0,0 +1,725 @@ +connection = $database->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array + */ + public function syncMonth(string $month, int $limit = 20, bool $force = false): array + { + if (preg_match('/^\d{4}-\d{2}$/', $month) !== 1) { + throw new RuntimeException('月份格式应为 YYYY-MM。'); + } + $limit = min(max($limit, 1), 100); + $this->assertReady(); + $scope = $this->scope(); + $this->ensureFlowsForMonth($month, $scope); + if ($force) { + $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->update([ + 'scan_status' => 'pending', + 'scanned_at' => null, + 'updated_at' => now(), + ]); + } + + $query = $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->whereNotNull('process_instance_id') + ->where('process_instance_id', '!=', '') + ->whereNull('scanned_at'); + $flows = $query + ->orderByDesc('paid_at') + ->orderByDesc('business_id') + ->limit($limit) + ->get() + ->all(); + + if ($flows === []) { + $remaining = (int) $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->whereNotNull('process_instance_id') + ->where('process_instance_id', '!=', '') + ->whereNull('scanned_at') + ->count(); + + return [ + 'status' => 'succeeded', + 'month' => $month, + 'processed_flows' => 0, + 'recognized_invoices' => 0, + 'failed_flows' => 0, + 'remaining_flows' => $remaining, + 'ocr_configured' => $this->recognizerOcrConfigured(), + ]; + } + + $businessIds = array_values(array_filter(array_column($flows, 'business_id'))); + [$workflows, $attachmentRows] = $this->loadUpstreamWorkflowsAndAttachments($businessIds); + $attachmentsByBusiness = $this->groupAttachmentsByBusiness($attachmentRows, $workflows); + $attachmentsByBusiness = $this->addCommentAttachmentFallback( + $businessIds, + $workflows, + $attachmentsByBusiness, + ); + + $metrics = [ + 'processed_flows' => 0, + 'recognized_invoices' => 0, + 'failed_flows' => 0, + 'remaining_flows' => 0, + 'ocr_configured' => $this->recognizerOcrConfigured(), + ]; + $tempRoot = storage_path('app/temp/invoice-sync/' . $month . '-' . bin2hex(random_bytes(6))); + if (! is_dir($tempRoot) && ! mkdir($tempRoot, 0755, true) && ! is_dir($tempRoot)) { + throw new RuntimeException('无法创建发票抓取临时目录。'); + } + + try { + foreach ($flows as $flow) { + $businessId = (string) $flow->business_id; + $workflow = $workflows[$businessId] ?? []; + $files = $attachmentsByBusiness[$businessId] ?? []; + $flowResult = $this->scanFlow( + $flow, + $workflow, + $files, + $tempRoot . '/' . preg_replace('/[^A-Za-z0-9_-]/', '_', $businessId), + ); + $metrics['processed_flows']++; + $metrics['recognized_invoices'] += $flowResult['invoice_count']; + if ($flowResult['scan_status'] === 'failed') { + $metrics['failed_flows']++; + } + } + } finally { + $this->removeDirectory($tempRoot); + } + + $metrics['remaining_flows'] = (int) $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->whereNotNull('process_instance_id') + ->where('process_instance_id', '!=', '') + ->whereNull('scanned_at') + ->count(); + $this->updateState($metrics); + + return [ + 'status' => 'succeeded', + 'month' => $month, + ...$metrics, + ]; + } + + private function assertReady(): void + { + if (! Schema::connection($this->connection->getName())->hasTable('ding_invoice_flow_mirror') + || ! Schema::connection($this->connection->getName())->hasTable('ding_invoice_record_mirror') + || ! Schema::connection($this->connection->getName())->hasTable('ding_process_payment_line_mirror') + || ! Schema::connection($this->connection->getName())->hasTable('ding_process_detail_mirror')) { + throw new RuntimeException('OA 流程镜像或发票镜像尚未准备完成。'); + } + } + + private function scope(): string + { + return trim((string) config( + 'upstream_mirrors.ding_process_details.scope', + 'personal_permission', + )) ?: 'personal_permission'; + } + + private function ensureFlowsForMonth(string $month, string $scope): void + { + $payments = $this->connection->table('ding_process_payment_line_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->get(); + if ($payments->isEmpty()) { + return; + } + + $details = $this->connection->table('ding_process_detail_mirror') + ->where('source_scope', $scope) + ->whereIn('business_id', $payments->pluck('business_id')->unique()->all()) + ->get() + ->groupBy('business_id'); + $existing = $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('paid_month', $month) + ->get() + ->keyBy('business_id'); + $now = now(); + + foreach ($payments->groupBy('business_id') as $businessId => $businessPayments) { + $businessId = trim((string) $businessId); + $detail = ($details->get($businessId) ?? collect())->first(); + $current = $existing->get($businessId); + $values = [ + 'source_scope' => $scope, + 'business_id' => $businessId, + 'process_instance_id' => trim((string) ( + $businessPayments->firstWhere('process_instance_id', '!=', '') + ?->process_instance_id + ?? '' + )), + 'paid_month' => $month, + 'title' => mb_substr($current?->title ?: ($detail?->purpose ?: ''), 0, 255) ?: null, + 'originator_name' => mb_substr($current?->originator_name ?: ($detail?->originator_name ?: ''), 0, 100) ?: null, + 'document_type' => mb_substr($current?->document_type ?: ($detail?->document_type ?: ''), 0, 100) ?: null, + 'expense_type' => mb_substr($current?->expense_type ?: ($detail?->account_name ?: ''), 0, 255) ?: null, + 'payee_name' => mb_substr($current?->payee_name ?: ($detail?->payee_name ?: ''), 0, 255) ?: null, + 'paid_at' => $current?->paid_at ?: $businessPayments->min('paid_at'), + 'payment_amount' => round((float) $businessPayments->sum('amount'), 2), + 'payment_total' => round((float) $businessPayments->sum('amount'), 2), + 'invoice_count' => (int) ($current?->invoice_count ?? 0), + 'invoice_total' => (float) ($current?->invoice_total ?? 0), + 'scan_status' => $current?->scan_status ?: 'pending', + 'attachment_count' => (int) ($current?->attachment_count ?? 0), + 'scanned_file_count' => (int) ($current?->scanned_file_count ?? 0), + 'last_error' => $current?->last_error, + 'source_name' => $current?->source_name ?: 'OA attachment scan', + 'scanned_at' => $current?->scanned_at, + 'updated_at' => $now, + ]; + + if ($current) { + $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('business_id', $businessId) + ->update($values); + } else { + $this->connection->table('ding_invoice_flow_mirror')->insert([ + ...$values, + 'created_at' => $now, + ]); + } + } + } + + /** + * @param list $businessIds + * @return array{0:array>,1:list>} + */ + private function loadUpstreamWorkflowsAndAttachments(array $businessIds): array + { + if ($businessIds === []) { + 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; + } + } + + $processIds = array_values(array_unique(array_filter(array_map( + static fn (array $row): string => trim((string) ($row['processInstanceId'] ?? '')), + $workflowRows, + )))); + if ($processIds === []) { + return [$workflows, []]; + } + $processPlaceholders = implode(',', array_fill(0, count($processIds), '?')); + $attachmentRows = $query->select( + 'SELECT processInstanceId, name, value ' + . 'FROM rpt.ding_WorkflowScheme ' + . "WHERE processInstanceId IN ({$processPlaceholders}) " + . "AND name LIKE N'%附件%' ORDER BY id", + $processIds, + ); + + return [$workflows, $attachmentRows]; + } + + /** + * @param list> $rows + * @param array> $workflows + * @return array>> + */ + private function groupAttachmentsByBusiness(array $rows, array $workflows): array + { + $byProcess = []; + foreach ($workflows as $businessId => $workflow) { + $byProcess[(string) ($workflow['processInstanceId'] ?? '')] = $businessId; + } + $result = []; + foreach ($rows as $row) { + $processId = trim((string) ($row['processInstanceId'] ?? '')); + $businessId = $byProcess[$processId] ?? ''; + if ($businessId === '') { + continue; + } + $value = $row['value'] ?? null; + if (is_string($value)) { + $decoded = json_decode($value, true); + $value = is_array($decoded) ? $decoded : []; + } + foreach ($this->extractFiles($value, trim((string) ($row['name'] ?? ''))) as $file) { + $key = $file['file_id'] !== '' + ? $file['file_id'] + : hash('sha256', (string) $file['download_url']); + $result[$businessId][$key] = $file; + } + } + + return array_map('array_values', $result); + } + + /** + * Some invoices are only present in approval comments. Use the official + * process snapshot API only for flows that have no form attachment, and cap + * the number of calls so the daily DingTalk quota remains usable. + * + * @param list $businessIds + * @param array> $workflows + * @param array>> $attachments + * @return array>> + */ + private function addCommentAttachmentFallback( + array $businessIds, + array $workflows, + array $attachments, + ): array { + $limit = max(0, (int) config('ding_invoice_data.comment_fallback_limit', 20)); + if ($limit === 0) { + return $attachments; + } + + $candidates = []; + foreach ($businessIds as $businessId) { + if (($attachments[$businessId] ?? []) !== []) { + continue; + } + $processId = trim((string) ($workflows[$businessId]['processInstanceId'] ?? '')); + if ($processId !== '') { + $candidates[$processId] = $businessId; + } + } + if ($candidates === []) { + return $attachments; + } + + try { + $result = $this->approvalClient->processSnapshots( + array_slice(array_keys($candidates), 0, $limit), + ); + } catch (Throwable) { + return $attachments; + } + + foreach ((array) ($result['snapshots'] ?? []) as $processId => $snapshot) { + $businessId = $candidates[(string) $processId] ?? ''; + if ($businessId === '') { + continue; + } + $files = []; + foreach ((array) ($snapshot['form_values'] ?? []) as $field => $value) { + foreach ($this->extractFiles($value, (string) $field) as $file) { + $key = $file['file_id'] !== '' + ? $file['file_id'] + : hash('sha256', (string) $file['download_url']); + $files[$key] = $file; + } + } + foreach ($this->extractFiles($snapshot['operation_records'] ?? [], '评论附件') as $file) { + $key = $file['file_id'] !== '' + ? $file['file_id'] + : hash('sha256', (string) $file['download_url']); + $files[$key] = $file; + } + if ($files !== []) { + $attachments[$businessId] = array_values($files); + } + } + + return $attachments; + } + + /** + * @return list + */ + private function extractFiles(mixed $value, string $sourceField): array + { + $files = []; + $walk = function (mixed $node) use (&$walk, &$files, $sourceField): void { + if (is_string($node)) { + $trimmed = trim($node); + if (str_starts_with($trimmed, '{') || str_starts_with($trimmed, '[')) { + $decoded = json_decode($trimmed, true); + if (is_array($decoded)) { + $walk($decoded); + } + } elseif (str_starts_with($trimmed, 'http://') || str_starts_with($trimmed, 'https://')) { + $files[] = [ + 'file_id' => '', + 'file_name' => basename((string) parse_url($trimmed, PHP_URL_PATH)), + 'file_type' => strtolower(pathinfo((string) parse_url($trimmed, PHP_URL_PATH), PATHINFO_EXTENSION)), + 'space_id' => '', + 'file_size' => 0, + 'source_field' => $sourceField, + 'download_url' => $trimmed, + ]; + } + return; + } + if (! is_array($node)) { + return; + } + $fileId = trim((string) ($node['fileId'] ?? $node['file_id'] ?? '')); + if ($fileId !== '') { + $files[] = [ + 'file_id' => $fileId, + 'file_name' => trim((string) ( + $node['fileName'] ?? $node['file_name'] ?? $sourceField + )), + 'file_type' => strtolower(trim((string) ( + $node['fileType'] ?? $node['file_type'] ?? '' + ))), + 'space_id' => trim((string) ($node['spaceId'] ?? $node['space_id'] ?? '')), + 'file_size' => (int) ($node['fileSize'] ?? $node['file_size'] ?? 0), + 'source_field' => $sourceField, + 'download_url' => '', + ]; + } + foreach ($node as $child) { + $walk($child); + } + }; + $walk($value); + + return $files; + } + + /** + * @param array $workflow + * @param list> $files + * @return array{scan_status:string,invoice_count:int,invoice_total:float,error:?string} + */ + private function scanFlow(object $flow, array $workflow, array $files, string $tempDir): array + { + if (! is_dir($tempDir) && ! mkdir($tempDir, 0755, true) && ! is_dir($tempDir)) { + throw new RuntimeException('无法创建流程发票临时目录。'); + } + $processInstanceId = trim((string) ( + $workflow['processInstanceId'] ?? $flow->process_instance_id ?? '' + )); + $files = array_slice( + $files, + 0, + max(1, (int) config('ding_invoice_data.max_files_per_flow', 30)), + ); + $invoices = []; + $errors = []; + $scannedFiles = 0; + + foreach ($files as $index => $file) { + if ((int) ($file['file_size'] ?? 0) > (int) config('ding_invoice_data.max_file_bytes')) { + $errors[] = $file['file_name'] . ':文件超过大小限制'; + continue; + } + try { + $uri = trim((string) ($file['download_url'] ?? '')); + if ($uri === '') { + $uri = $this->downloads->downloadUri($processInstanceId, $file['file_id']) ?? ''; + } + if ($uri === '') { + throw new RuntimeException('无法取得下载地址'); + } + $extension = strtolower(pathinfo($file['file_name'], PATHINFO_EXTENSION)); + if ($extension === '' && in_array( + strtolower((string) ($file['file_type'] ?? '')), + ['pdf', 'jpg', 'jpeg', 'png', 'webp', 'bmp', 'xlsx', 'zip'], + true, + )) { + $extension = strtolower((string) $file['file_type']); + } + $path = $tempDir . '/' . $index . ($extension !== '' ? '.' . $extension : ''); + $response = Http::timeout(120) + ->withOptions(['sink' => $path]) + ->get($uri); + if (! $response->successful() || ! is_file($path)) { + throw new RuntimeException('下载返回 HTTP ' . $response->status()); + } + if (filesize($path) > (int) config('ding_invoice_data.max_file_bytes')) { + @unlink($path); + throw new RuntimeException('下载文件超过大小限制'); + } + $scannedFiles++; + $hash = hash_file('sha256', $path) ?: null; + $recognized = $this->recognizer->recognize($path, $file['file_name']); + foreach ($recognized['invoices'] as $invoice) { + $invoice['_source'] = [ + 'file_id' => $file['file_id'], + 'file_name' => $file['file_name'], + 'file_type' => $extension ?: $file['file_type'], + 'source_field' => $file['source_field'], + 'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'], + 'source_hash' => $hash, + 'ocr_provider' => $recognized['provider'], + ]; + $invoices[] = $invoice; + } + array_push($errors, ...array_map( + static fn (string $error): string => $file['file_name'] . ':' . $error, + $recognized['errors'], + )); + } catch (Throwable $exception) { + $errors[] = $file['file_name'] . ':' . $exception->getMessage(); + } + } + + $invoices = $this->deduplicate($invoices); + $invoiceTotal = round(array_sum(array_map( + static fn (array $invoice): float => (float) $invoice['invoice_total'], + $invoices, + )), 2); + $scanStatus = match (true) { + $errors !== [] && $invoices !== [] => 'partial', + $errors !== [] && $invoices === [] => 'failed', + $invoices !== [] => 'recognized', + default => 'no_invoice', + }; + $error = $errors === [] ? null : mb_substr(implode("\n", array_slice($errors, 0, 8)), 0, 4000); + + $this->connection->transaction(function () use ( + $flow, + $invoices, + $invoiceTotal, + $scanStatus, + $error, + $files, + $scannedFiles, + $workflow, + ): void { + $scope = $this->scope(); + $businessId = (string) $flow->business_id; + $this->connection->table('ding_invoice_record_mirror') + ->where('source_scope', $scope) + ->where('business_id', $businessId) + ->delete(); + $now = now(); + $records = []; + foreach ($invoices as $invoice) { + $source = $invoice['_source']; + $records[] = [ + 'source_scope' => $scope, + 'business_id' => $businessId, + 'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''), + 'paid_month' => (string) $flow->paid_month, + 'invoice_key' => $this->invoiceKey($invoice), + 'invoice_type' => mb_substr((string) $invoice['invoice_type'], 0, 100), + 'seller_name' => mb_substr((string) $invoice['seller_name'], 0, 255), + 'seller_tax_no' => mb_substr((string) $invoice['seller_tax_no'], 0, 64), + 'buyer_name' => mb_substr((string) $invoice['buyer_name'], 0, 255), + 'buyer_tax_no' => mb_substr((string) $invoice['buyer_tax_no'], 0, 64), + 'invoice_total' => round((float) $invoice['invoice_total'], 2), + 'invoice_number' => mb_substr((string) $invoice['invoice_number'], 0, 32), + 'invoice_date' => $invoice['invoice_date'], + 'item_name' => (string) $invoice['item_name'], + 'amount_without_tax' => $invoice['amount_without_tax'], + 'tax_rate' => mb_substr((string) $invoice['tax_rate'], 0, 32), + 'tax_amount' => $invoice['tax_amount'], + 'source_file_id' => $source['file_id'], + 'source_file_name' => mb_substr((string) $source['file_name'], 0, 255), + 'source_file_type' => mb_substr((string) $source['file_type'], 0, 32), + 'source_field' => mb_substr((string) $source['source_field'], 0, 255), + 'source_path' => mb_substr((string) $source['source_path'], 0, 1024), + 'source_hash' => $source['source_hash'], + 'ocr_provider' => mb_substr((string) $source['ocr_provider'], 0, 32), + 'recognition_payload' => json_encode( + array_diff_key($invoice, ['_source' => true]), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, + ), + 'created_at' => $now, + 'updated_at' => $now, + ]; + } + if ($records !== []) { + $this->connection->table('ding_invoice_record_mirror')->insert($records); + } + $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->where('business_id', $businessId) + ->update([ + 'process_instance_id' => (string) ($workflow['processInstanceId'] ?? $flow->process_instance_id ?? ''), + 'title' => $flow->title ?: ($workflow['title'] ?? null), + 'invoice_count' => count($records), + 'invoice_total' => $invoiceTotal, + 'scan_status' => $scanStatus, + 'attachment_count' => count($files), + 'scanned_file_count' => $scannedFiles, + 'last_error' => $error, + 'scanned_at' => $now, + 'updated_at' => $now, + ]); + }); + + return [ + 'scan_status' => $scanStatus, + 'invoice_count' => count($invoices), + 'invoice_total' => $invoiceTotal, + 'error' => $error, + ]; + } + + /** @param list> $invoices @return list> */ + private function deduplicate(array $invoices): array + { + $unique = []; + foreach ($invoices as $invoice) { + $number = preg_replace( + '/[^0-9A-Za-z]/', + '', + (string) ($invoice['invoice_number'] ?? ''), + ) ?? ''; + $seller = trim((string) ($invoice['seller_name'] ?? '')); + $amount = number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''); + $key = $number !== '' + ? 'number:' . $number + : 'near:' . mb_strtolower($seller) . '|' . $amount; + foreach ($unique as $existingKey => $existing) { + $existingSeller = trim((string) ($existing['seller_name'] ?? '')); + $existingAmount = number_format((float) ($existing['invoice_total'] ?? 0), 2, '.', ''); + if ($seller !== '' + && $existingSeller !== '' + && mb_strtolower($seller) === mb_strtolower($existingSeller) + && $amount === $existingAmount) { + $key = $existingKey; + break; + } + } + if (! isset($unique[$key])) { + $unique[$key] = $invoice; + } else { + $unique[$key] = $this->mergeInvoice($unique[$key], $invoice); + } + } + + return array_values($unique); + } + + /** @param array $left @param array $right */ + private function mergeInvoice(array $left, array $right): array + { + foreach ($right as $key => $value) { + if (($left[$key] ?? null) === null + || (is_string($left[$key]) && trim($left[$key]) === '') + || (is_array($left[$key]) && $left[$key] === [])) { + $left[$key] = $value; + } + } + + return $left; + } + + /** @param array $invoice */ + private function invoiceKey(array $invoice): string + { + $number = preg_replace('/[^0-9A-Za-z]/', '', (string) ($invoice['invoice_number'] ?? '')) ?? ''; + + return hash('sha256', $number !== '' + ? 'number:' . $number + : implode('|', [ + 'near', + (string) ($invoice['seller_name'] ?? ''), + number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''), + (string) ($invoice['invoice_date'] ?? ''), + (string) ($invoice['item_name'] ?? ''), + ])); + } + + private function recognizerOcrConfigured(): bool + { + return trim((string) config('ding_invoice_data.ocr.api_key', '')) !== ''; + } + + /** @param array $metrics */ + private function updateState(array $metrics): void + { + if (! Schema::connection($this->connection->getName())->hasTable('business_mirror_table_states')) { + return; + } + $now = now(); + $state = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', DingInvoiceWorkbookImporter::DATASET_KEY) + ->first(); + $this->connection->table('business_mirror_table_states')->updateOrInsert( + ['dataset_key' => DingInvoiceWorkbookImporter::DATASET_KEY], + [ + 'source_key' => 'operations_replica', + 'source_object' => 'rpt.ding_Workflow + DingTalk attachments + invoice OCR', + 'target_table' => 'ding_invoice_record_mirror', + 'status' => 'succeeded', + 'run_mode' => 'incremental', + 'cursor' => json_encode($metrics, JSON_UNESCAPED_UNICODE), + 'initial_completed_at' => $state?->initial_completed_at ?? $now, + 'last_attempted_at' => $now, + 'last_succeeded_at' => $now, + 'last_upserted_rows' => (int) ($metrics['recognized_invoices'] ?? 0), + 'mirror_row_count' => (int) $this->connection->table('ding_invoice_record_mirror') + ->where('source_scope', $this->scope())->count(), + 'mirror_row_count_is_exact' => true, + 'last_error_code' => null, + 'created_at' => $state?->created_at ?? $now, + 'updated_at' => $now, + ], + ); + } + + private function removeDirectory(string $directory): void + { + if (! is_dir($directory)) { + return; + } + $iterator = new \RecursiveIteratorIterator( + new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS), + \RecursiveIteratorIterator::CHILD_FIRST, + ); + foreach ($iterator as $item) { + if ($item->isDir()) { + @rmdir($item->getPathname()); + } else { + @unlink($item->getPathname()); + } + } + @rmdir($directory); + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceTextParser.php b/modules/EcommerceFinance/Services/DingInvoiceTextParser.php new file mode 100644 index 000000000..5eae9b72a --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceTextParser.php @@ -0,0 +1,126 @@ +|null */ + public function parse(string $text): ?array + { + $text = trim(str_replace(["\r\n", "\r", "\u{3000}"], ["\n", "\n", ' '], $text)); + if ($text === '') { + return null; + } + + $invoiceNumber = $this->invoiceNumber($text); + $invoiceTotal = $this->invoiceTotal($text); + if ($invoiceNumber === '' && $invoiceTotal <= 0) { + return null; + } + + $taxNumbers = []; + if (preg_match_all( + '/(?:统一社会信用代码|纳税人识别号|税号)\s*[::]\s*([0-9A-Z]{15,20})/u', + $text, + $matches, + )) { + $taxNumbers = array_values(array_unique($matches[1])); + } + + $names = []; + if (preg_match_all('/名称\s*[::]\s*([^\n]{2,120})/u', $text, $matches)) { + $names = array_values(array_unique(array_filter(array_map( + static fn (string $value): string => trim( + preg_replace('/\s{2,}.*$/u', '', $value) ?? $value, + ), + $matches[1], + )))); + } + + $invoiceDate = null; + if (preg_match('/开票日期\s*[::]?\s*(\d{4})[年\-\/](\d{1,2})[月\-\/](\d{1,2})/u', $text, $matches)) { + try { + $invoiceDate = Carbon::createFromDate( + (int) $matches[1], + (int) $matches[2], + (int) $matches[3], + )->format('Y-m-d'); + } catch (Throwable) { + $invoiceDate = null; + } + } + + $items = []; + if (preg_match_all('/^\s*(\*[^\n]{2,180})$/mu', $text, $matches)) { + $items = array_values(array_unique(array_map('trim', $matches[1]))); + } + + $taxRate = ''; + if (preg_match('/(\d{1,2}(?:\.\d+)?%|免税|不征税|\*)/u', $text, $matches)) { + $taxRate = $matches[1]; + } + + return [ + 'is_invoice' => true, + 'invoice_type' => $this->invoiceType($text), + 'seller_name' => $names[1] ?? ($names[0] ?? ''), + 'seller_tax_no' => $taxNumbers[1] ?? ($taxNumbers[0] ?? ''), + 'buyer_name' => $names[0] ?? '', + 'buyer_tax_no' => $taxNumbers[0] ?? '', + 'invoice_total' => $invoiceTotal, + 'invoice_number' => $invoiceNumber, + 'invoice_date' => $invoiceDate, + 'item_name' => implode("\n", $items), + 'amount_without_tax' => null, + 'tax_rate' => $taxRate, + 'tax_amount' => null, + 'ocr_text' => $text, + ]; + } + + private function invoiceNumber(string $text): string + { + if (preg_match('/发票号码\s*[::]?\s*([0-9A-Z]{8,32})/u', $text, $matches)) { + return strtoupper($matches[1]); + } + + return ''; + } + + private function invoiceTotal(string $text): float + { + $values = []; + if (preg_match_all( + '/(?:价税合计(?:\s*(?:\(小写\)|(小写)))?|小写)\s*[::]?\s*[¥¥]?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/u', + $text, + $matches, + )) { + foreach ($matches[1] as $value) { + $values[] = round((float) str_replace(',', '', $value), 2); + } + } + if ($values !== []) { + return max($values); + } + + return 0.0; + } + + private function invoiceType(string $text): string + { + if (str_contains($text, '铁路电子客票') || str_contains($text, '铁路客票')) { + return '电子发票(铁路电子客票)'; + } + if (str_contains($text, '增值税专用发票') || str_contains($text, '专用发票')) { + return '电子发票(增值税专用发票)'; + } + if (str_contains($text, '普通发票')) { + return '电子发票(普通发票)'; + } + + return '其他'; + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceVisionClient.php b/modules/EcommerceFinance/Services/DingInvoiceVisionClient.php new file mode 100644 index 000000000..3fda666b4 --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceVisionClient.php @@ -0,0 +1,169 @@ +|null */ + public function recognize(string $bytes, string $mimeType): ?array + { + $apiKey = trim((string) config('ding_invoice_data.ocr.api_key', '')); + if ($apiKey === '') { + throw new RuntimeException( + '发票 OCR 未配置。请在服务器设置 DING_INVOICE_OCR_API_KEY 后重试。', + ); + } + if ($bytes === '') { + return null; + } + + $mimeType = str_starts_with($mimeType, 'image/') ? $mimeType : 'image/jpeg'; + $payload = [ + 'model' => (string) config('ding_invoice_data.ocr.model', 'deepseek-chat'), + 'temperature' => 0, + 'messages' => [[ + 'role' => 'user', + 'content' => [ + ['type' => 'text', 'text' => self::PROMPT], + [ + 'type' => 'image_url', + 'image_url' => [ + 'url' => 'data:' . $mimeType . ';base64,' . base64_encode($bytes), + ], + ], + ], + ]], + ]; + + try { + $response = Http::withToken($apiKey) + ->acceptJson() + ->timeout(max(15, (int) config('ding_invoice_data.ocr.timeout_seconds', 90))) + ->post((string) config('ding_invoice_data.ocr.base_url'), $payload); + } catch (ConnectionException|RequestException $exception) { + throw new RuntimeException('发票 OCR 请求失败:' . $exception->getMessage(), 0, $exception); + } + + if (! $response->successful()) { + throw new RuntimeException('发票 OCR 返回 HTTP ' . $response->status() . '。'); + } + + $content = (string) $response->json('choices.0.message.content', ''); + $decoded = $this->decodeJson($content); + if ($decoded === null || ($decoded['is_invoice'] ?? false) !== true) { + return null; + } + + $invoiceTotal = $this->number($decoded['invoice_total'] ?? null); + $invoiceNumber = preg_replace( + '/[^0-9A-Za-z]/', + '', + trim((string) ($decoded['invoice_number'] ?? '')), + ) ?? ''; + if ($invoiceTotal <= 0 && $invoiceNumber === '') { + return null; + } + + return [ + 'is_invoice' => true, + 'invoice_type' => trim((string) ($decoded['invoice_type'] ?? '')) ?: '其他', + 'seller_name' => trim((string) ($decoded['seller_name'] ?? '')), + 'seller_tax_no' => trim((string) ($decoded['seller_tax_no'] ?? '')), + 'buyer_name' => trim((string) ($decoded['buyer_name'] ?? '')), + 'buyer_tax_no' => trim((string) ($decoded['buyer_tax_no'] ?? '')), + 'invoice_total' => $invoiceTotal, + 'invoice_number' => $invoiceNumber, + 'invoice_date' => $this->date($decoded['invoice_date'] ?? null), + 'item_name' => trim((string) ($decoded['item_name'] ?? '')), + 'amount_without_tax' => $this->numberOrNull($decoded['amount_without_tax'] ?? null), + 'tax_rate' => trim((string) ($decoded['tax_rate'] ?? '')), + 'tax_amount' => $this->numberOrNull($decoded['tax_amount'] ?? null), + 'ocr_text' => $content, + ]; + } + + /** @return array|null */ + private function decodeJson(string $content): ?array + { + $content = trim($content); + $content = preg_replace('/^```(?:json)?\s*/i', '', $content) ?? $content; + $content = preg_replace('/\s*```$/', '', $content) ?? $content; + $decoded = json_decode($content, true); + if (is_array($decoded)) { + return $decoded; + } + + $start = strpos($content, '{'); + $end = strrpos($content, '}'); + if ($start !== false && $end !== false && $end > $start) { + $decoded = json_decode(substr($content, $start, $end - $start + 1), true); + } + + return is_array($decoded) ? $decoded : null; + } + + private function number(mixed $value): float + { + return $this->numberOrNull($value) ?? 0.0; + } + + private function numberOrNull(mixed $value): ?float + { + if ($value === null || trim((string) $value) === '') { + return null; + } + $normalized = str_replace([',', ',', '¥', '¥', ' '], '', (string) $value); + if (! is_numeric($normalized)) { + return null; + } + + return round((float) $normalized, 2); + } + + private function date(mixed $value): ?string + { + $value = trim((string) ($value ?? '')); + if (preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $value) !== 1) { + return null; + } + + [$year, $month, $day] = array_map('intval', explode('-', $value)); + + return checkdate($month, $day, $year) + ? sprintf('%04d-%02d-%02d', $year, $month, $day) + : null; + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceWorkbookImporter.php b/modules/EcommerceFinance/Services/DingInvoiceWorkbookImporter.php new file mode 100644 index 000000000..8765518ba --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoiceWorkbookImporter.php @@ -0,0 +1,395 @@ + '单号/标题', + 'business_id' => '流程号', + 'originator_name' => '提交人', + 'document_type' => '报销类型', + 'expense_type' => '费用类型', + 'payee_name' => '收款人', + 'paid_at' => '打款时间', + 'payment_amount' => '10月付款金额', + 'payment_total' => '付款合计', + 'invoice_type' => '发票类型', + 'seller_name' => '销售方名称', + 'seller_tax_no' => '销售方税号', + 'buyer_name' => '购买方名称', + 'buyer_tax_no' => '购买方税号', + 'invoice_total' => '发票价税合计', + 'invoice_number' => '发票号码', + 'invoice_date' => '开票日期', + 'item_name' => '项目名称', + 'amount_without_tax' => '金额', + 'tax_rate' => '税率', + 'tax_amount' => '税额', + ]; + + private ConnectionInterface $connection; + + public function __construct(DatabaseManager $database) + { + $this->connection = $database->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * @return array{ + * flows:int, + * invoices:int, + * months:list, + * payment_total:float, + * invoice_total:float + * } + */ + public function import( + string $path, + string $scope = 'personal_permission', + bool $replaceMonths = true, + ): array { + if (! is_file($path)) { + throw new RuntimeException('发票台账文件不存在。'); + } + + $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + $reader = PayablesWorkbookStreamReader::forFile($path, $extension); + $sheetIndex = array_search(self::SHEET_NAME, $reader->sheetNames(), true); + if ($sheetIndex === false) { + throw new RuntimeException('发票台账缺少“' . self::SHEET_NAME . '”工作表。'); + } + + $headers = []; + $rows = $reader->rows((int) $sheetIndex); + $headerSeen = false; + foreach ($rows as $rowValues) { + foreach ($rowValues as $columnIndex => $cellValue) { + $value = trim((string) $cellValue); + if ($value !== '') { + $headers[$value] = (int) $columnIndex; + } + } + $headerSeen = true; + break; + } + if (! $headerSeen) { + throw new RuntimeException('发票台账为空。'); + } + foreach (self::HEADERS as $field => $label) { + if (! isset($headers[$label])) { + throw new RuntimeException('发票台账缺少列:' . $label); + } + } + + $flows = []; + $invoices = []; + $current = array_fill_keys(array_keys(self::HEADERS), ''); + + foreach ($rows as $rowNumber => $rowValues) { + $row = []; + foreach (self::HEADERS as $field => $label) { + $row[$field] = $rowValues[$headers[$label]] ?? null; + } + if (! array_filter($row, static fn (mixed $value): bool => $value !== null && $value !== '')) { + continue; + } + + if ($this->text($row['business_id']) !== '') { + $current = array_fill_keys(array_keys(self::HEADERS), ''); + } + foreach ([ + 'title', + 'business_id', + 'originator_name', + 'document_type', + 'expense_type', + 'payee_name', + 'paid_at', + 'payment_amount', + 'payment_total', + ] as $field) { + $value = $this->text($row[$field]); + if ($value !== '') { + $current[$field] = $row[$field]; + } + } + + $businessId = $this->text($current['business_id']); + if (preg_match('/^[A-Za-z0-9_-]{1,32}$/', $businessId) !== 1) { + continue; + } + + $paidAt = $this->date($current['paid_at']); + $paidMonth = $paidAt?->format('Y-m') ?? ''; + if ($paidMonth === '') { + throw new RuntimeException('第 ' . $rowNumber . ' 行打款时间无法识别。'); + } + + $flows[$businessId] ??= [ + 'source_scope' => mb_substr($scope, 0, 40), + 'business_id' => $businessId, + 'process_instance_id' => null, + 'paid_month' => $paidMonth, + 'title' => $this->limit($this->text($current['title']), 255), + 'originator_name' => $this->limit($this->text($current['originator_name']), 100), + 'document_type' => $this->limit($this->text($current['document_type']), 100), + 'expense_type' => $this->limit($this->text($current['expense_type']), 255), + 'payee_name' => $this->limit($this->text($current['payee_name']), 255), + 'paid_at' => $paidAt?->format('Y-m-d H:i:s'), + 'payment_amount' => $this->decimal($current['payment_amount']), + 'payment_total' => $this->decimal($current['payment_total']), + 'invoice_count' => 0, + 'invoice_total' => 0.0, + 'scan_status' => 'no_invoice', + 'attachment_count' => 0, + 'scanned_file_count' => 0, + 'last_error' => null, + 'source_name' => $this->limit(basename($path), 255), + 'scanned_at' => now(), + 'created_at' => now(), + 'updated_at' => now(), + ]; + + $invoiceType = $this->text($row['invoice_type']); + if ($invoiceType === '' || $invoiceType === '无票') { + continue; + } + + $invoiceNumber = preg_replace('/[^0-9A-Za-z]/', '', $this->text($row['invoice_number'])) ?? ''; + $sellerName = $this->text($row['seller_name']); + $invoiceTotal = $this->decimal($row['invoice_total']); + $invoiceDate = $this->date($row['invoice_date']); + $invoiceKey = $invoiceNumber !== '' + ? hash('sha256', 'number:' . $invoiceNumber) + : hash('sha256', implode('|', [ + 'fallback', + $sellerName, + number_format($invoiceTotal, 2, '.', ''), + $invoiceDate?->format('Y-m-d') ?? '', + $this->text($row['item_name']), + ])); + + $record = [ + 'source_scope' => mb_substr($scope, 0, 40), + 'business_id' => $businessId, + 'process_instance_id' => null, + 'paid_month' => $paidMonth, + 'invoice_key' => $invoiceKey, + 'invoice_type' => $this->limit($invoiceType, 100), + 'seller_name' => $this->limit($sellerName, 255), + 'seller_tax_no' => $this->limit($this->text($row['seller_tax_no']), 64), + 'buyer_name' => $this->limit($this->text($row['buyer_name']), 255), + 'buyer_tax_no' => $this->limit($this->text($row['buyer_tax_no']), 64), + 'invoice_total' => $invoiceTotal, + 'invoice_number' => $this->limit($invoiceNumber, 32), + 'invoice_date' => $invoiceDate?->format('Y-m-d'), + 'item_name' => $this->text($row['item_name']), + 'amount_without_tax' => $this->decimalOrNull($row['amount_without_tax']), + 'tax_rate' => $this->limit($this->text($row['tax_rate']), 32), + 'tax_amount' => $this->decimalOrNull($row['tax_amount']), + 'source_file_id' => null, + 'source_file_name' => null, + 'source_file_type' => null, + 'source_field' => null, + 'source_path' => null, + 'source_hash' => null, + 'ocr_provider' => 'imported_workbook', + 'recognition_payload' => null, + 'created_at' => now(), + 'updated_at' => now(), + ]; + + $existing = $invoices[$businessId][$invoiceKey] ?? null; + $invoices[$businessId][$invoiceKey] = $existing === null + ? $record + : $this->mergeMissing($existing, $record); + } + + foreach ($invoices as $businessId => $records) { + $flows[$businessId]['invoice_count'] = count($records); + $flows[$businessId]['invoice_total'] = round(array_sum(array_map( + static fn (array $record): float => (float) $record['invoice_total'], + $records, + )), 2); + $flows[$businessId]['scan_status'] = $records === [] ? 'no_invoice' : 'recognized'; + } + + if ($flows === []) { + throw new RuntimeException('发票台账没有可导入的流程记录。'); + } + + $months = array_values(array_unique(array_column($flows, 'paid_month'))); + sort($months); + $invoiceRows = []; + foreach ($invoices as $businessInvoices) { + foreach ($businessInvoices as $invoice) { + $invoiceRows[] = $invoice; + } + } + $paymentTotal = round(array_sum(array_column($flows, 'payment_amount')), 2); + $invoiceTotal = round(array_sum(array_column($invoiceRows, 'invoice_total')), 2); + + $this->connection->transaction(function () use ( + $scope, + $months, + $replaceMonths, + $flows, + $invoiceRows, + $invoiceTotal, + ): void { + if ($replaceMonths) { + $this->connection->table('ding_invoice_record_mirror') + ->where('source_scope', $scope) + ->whereIn('paid_month', $months) + ->delete(); + $this->connection->table('ding_invoice_flow_mirror') + ->where('source_scope', $scope) + ->whereIn('paid_month', $months) + ->delete(); + } + + foreach (array_chunk(array_values($flows), 250) as $chunk) { + $this->connection->table('ding_invoice_flow_mirror')->insert($chunk); + } + foreach (array_chunk($invoiceRows, 250) as $chunk) { + $this->connection->table('ding_invoice_record_mirror')->insert($chunk); + } + + $this->updateState(count($invoiceRows), count($flows), $invoiceTotal); + }); + + return [ + 'flows' => count($flows), + 'invoices' => count($invoiceRows), + 'months' => $months, + 'payment_total' => $paymentTotal, + 'invoice_total' => $invoiceTotal, + ]; + } + + private function updateState(int $invoiceRows, int $flowRows, float $invoiceTotal): void + { + if (! $this->connection->getSchemaBuilder()->hasTable('business_mirror_table_states')) { + return; + } + + $now = now(); + $state = $this->connection->table('business_mirror_table_states') + ->where('dataset_key', self::DATASET_KEY) + ->first(); + $values = [ + 'source_key' => 'operations_replica', + 'source_object' => 'rpt.ding_Workflow + DingTalk attachments + invoice OCR', + 'target_table' => 'ding_invoice_record_mirror', + 'status' => 'succeeded', + 'run_mode' => 'import', + 'cursor' => json_encode([ + 'invoice_rows' => $invoiceRows, + 'flow_rows' => $flowRows, + 'invoice_total' => round($invoiceTotal, 2), + ], JSON_UNESCAPED_UNICODE), + 'initial_completed_at' => $state?->initial_completed_at ?? $now, + 'last_attempted_at' => $now, + 'last_succeeded_at' => $now, + 'last_upserted_rows' => $invoiceRows, + 'mirror_row_count' => $invoiceRows, + 'mirror_row_count_is_exact' => true, + 'last_error_code' => null, + 'updated_at' => $now, + 'created_at' => $state?->created_at ?? $now, + ]; + + $this->connection->table('business_mirror_table_states')->updateOrInsert( + ['dataset_key' => self::DATASET_KEY], + $values, + ); + } + + private function text(mixed $value): string + { + return trim((string) ($value ?? '')); + } + + private function limit(string $value, int $length): string + { + return mb_substr($value, 0, $length); + } + + private function decimal(mixed $value): float + { + return $this->decimalOrNull($value) ?? 0.0; + } + + private function decimalOrNull(mixed $value): ?float + { + if ($value === null || trim((string) $value) === '') { + return null; + } + $normalized = str_replace([',', ',', '¥', '¥', ' '], '', (string) $value); + if (! is_numeric($normalized)) { + return null; + } + + return round((float) $normalized, 2); + } + + private function date(mixed $value): ?Carbon + { + if ($value === null || $value === '') { + return null; + } + if (is_numeric($value)) { + try { + return Carbon::instance(ExcelDate::excelToDateTimeObject((float) $value))->startOfDay(); + } catch (Throwable) { + return null; + } + } + if ($value instanceof DateTimeInterface) { + return Carbon::instance($value)->startOfDay(); + } + + $text = trim((string) $value); + foreach (['Y-m-d H:i:s', 'Y-m-d H:i', 'Y-m-d', 'Y/m/d'] as $format) { + try { + return Carbon::createFromFormat($format, $text)->startOfDay(); + } catch (Throwable) { + // Try the next known ledger date format. + } + } + + try { + return Carbon::parse($text)->startOfDay(); + } catch (Throwable) { + return null; + } + } + + /** @param array $existing @param array $record */ + private function mergeMissing(array $existing, array $record): array + { + foreach ($record as $key => $value) { + if (($existing[$key] ?? null) === null + || (is_string($existing[$key]) && trim($existing[$key]) === '')) { + $existing[$key] = $value; + } + } + + return $existing; + } +} diff --git a/modules/EcommerceFinance/View/InvoiceDataPageData.php b/modules/EcommerceFinance/View/InvoiceDataPageData.php new file mode 100644 index 000000000..25c1e3f60 --- /dev/null +++ b/modules/EcommerceFinance/View/InvoiceDataPageData.php @@ -0,0 +1,173 @@ + */ + public function page(Request $request): array + { + try { + $months = $this->repository->months(); + } catch (Throwable $exception) { + report($exception); + $months = []; + } + $requestedMonth = trim((string) $request->query('month', '')); + $month = preg_match('/^\d{4}-\d{2}$/', $requestedMonth) === 1 + ? $requestedMonth + : (string) ($months[0] ?? ''); + $view = $request->query('invoice_view') === DingInvoiceDataMirrorRepository::VIEW_FLOWS + ? DingInvoiceDataMirrorRepository::VIEW_FLOWS + : DingInvoiceDataMirrorRepository::VIEW_DETAIL; + $invoiceState = array_key_exists( + (string) $request->query('invoice_state', 'all'), + DingInvoiceDataMirrorRepository::INVOICE_STATES, + ) ? (string) $request->query('invoice_state', 'all') : 'all'; + $filters = [ + 'month' => $month, + 'invoice_state' => $invoiceState, + 'invoice_type' => mb_substr(trim((string) $request->query('invoice_type', '')), 0, 100), + 'keyword' => mb_substr(trim((string) $request->query('keyword', '')), 0, 100), + ]; + $detailPage = max((int) $request->query('page', 1), 1); + $flowPage = max((int) $request->query('flow_page', 1), 1); + $perPage = self::normalizePerPage($request->query('per_page')); + + try { + $options = $this->repository->filterOptions($filters); + $detailFilters = [...$filters, 'view' => DingInvoiceDataMirrorRepository::VIEW_DETAIL]; + $flowFilters = [...$filters, 'view' => DingInvoiceDataMirrorRepository::VIEW_FLOWS]; + $detailResult = $this->repository->paginate($detailFilters, $detailPage, $perPage); + $flowResult = $this->repository->paginate($flowFilters, $flowPage, $perPage); + $detailPaginator = new LengthAwarePaginator( + $detailResult['data'], + $detailResult['total'], + $perPage, + $detailPage, + [ + 'path' => $request->url(), + 'query' => array_filter( + [...$filters, 'invoice_view' => 'detail', 'per_page' => $perPage], + static fn (mixed $value): bool => $value !== '' && $value !== null, + ), + ], + ); + $flowPaginator = new LengthAwarePaginator( + $flowResult['data'], + $flowResult['total'], + $perPage, + $flowPage, + [ + 'path' => $request->url(), + 'query' => array_filter( + [...$filters, 'invoice_view' => 'flows', 'per_page' => $perPage], + static fn (mixed $value): bool => $value !== '' && $value !== null, + ), + 'pageName' => 'flow_page', + ], + ); + $state = $detailResult['state']; + $mirrorStatus = (string) ( + $state['status'] + ?? ((int) ($detailResult['summary']['flows'] ?? 0) > 0 ? 'imported' : 'unavailable') + ); + + return [ + 'view' => 'business.pages.financial-operations.invoice-data', + 'invoiceDetailRows' => $detailPaginator, + 'invoiceFlowRows' => $flowPaginator, + 'invoiceActiveView' => $view, + 'invoiceFilters' => $filters, + 'invoiceMonths' => $months, + 'invoiceTypes' => $options['invoice_types'], + 'invoiceStates' => DingInvoiceDataMirrorRepository::INVOICE_STATES, + 'invoicePerPageOptions' => DingInvoiceDataMirrorRepository::PER_PAGE_OPTIONS, + 'invoicePerPage' => $perPage, + 'invoiceSummary' => $detailResult['summary'], + 'invoiceMirrorStatus' => $mirrorStatus, + 'invoiceMirrorSyncedAt' => $state['last_succeeded_at'] ?? null, + 'invoiceMirrorError' => null, + 'invoicePageUrl' => route('business.pages.show', [ + 'section' => 'process-data', + 'page' => 'invoice-data', + ]), + 'invoiceExportUrl' => route('business.invoice-data.export', array_filter([ + 'month' => $filters['month'], + 'invoice_view' => $view, + 'invoice_state' => $filters['invoice_state'], + 'invoice_type' => $filters['invoice_type'], + 'keyword' => $filters['keyword'], + ], static fn (mixed $value): bool => $value !== '' && $value !== null)), + 'invoiceRefreshUrl' => route('business.invoice-data.refresh'), + 'invoiceOcrConfigured' => trim((string) config( + 'ding_invoice_data.ocr.api_key', + '', + )) !== '', + 'invoiceScope' => $this->repository->scope(), + ]; + } catch (Throwable $exception) { + report($exception); + + return [ + 'view' => 'business.pages.financial-operations.invoice-data', + 'invoiceDetailRows' => new LengthAwarePaginator([], 0, $perPage, 1, [ + 'path' => $request->url(), + 'query' => $request->query(), + ]), + 'invoiceFlowRows' => new LengthAwarePaginator([], 0, $perPage, 1, [ + 'path' => $request->url(), + 'query' => $request->query(), + ]), + 'invoiceActiveView' => $view, + 'invoiceFilters' => $filters, + 'invoiceMonths' => $months, + 'invoiceTypes' => [], + 'invoiceStates' => DingInvoiceDataMirrorRepository::INVOICE_STATES, + 'invoicePerPageOptions' => DingInvoiceDataMirrorRepository::PER_PAGE_OPTIONS, + 'invoicePerPage' => $perPage, + 'invoiceSummary' => [ + 'flows' => 0, + 'payment_amount' => 0.0, + 'invoice_count' => 0, + 'invoice_total' => 0.0, + 'no_invoice_flows' => 0, + 'needs_review_flows' => 0, + 'invoice_rate' => 0.0, + ], + 'invoiceMirrorStatus' => 'unavailable', + 'invoiceMirrorSyncedAt' => null, + 'invoiceMirrorError' => '发票数据镜像尚未完成导入,请稍后重试。', + 'invoicePageUrl' => route('business.pages.show', [ + 'section' => 'process-data', + 'page' => 'invoice-data', + ]), + 'invoiceExportUrl' => '#', + 'invoiceRefreshUrl' => route('business.invoice-data.refresh'), + 'invoiceOcrConfigured' => trim((string) config( + 'ding_invoice_data.ocr.api_key', + '', + )) !== '', + 'invoiceScope' => $this->repository->scope(), + ]; + } + } +} diff --git a/resources/views/business/pages/financial-operations/invoice-data.blade.php b/resources/views/business/pages/financial-operations/invoice-data.blade.php new file mode 100644 index 000000000..921409938 --- /dev/null +++ b/resources/views/business/pages/financial-operations/invoice-data.blade.php @@ -0,0 +1,978 @@ +@php + $money = static fn (mixed $value): string => number_format((float) $value, 2); + $wan = static fn (mixed $value): string => number_format((float) $value / 10000, 2); + $summary = $invoiceSummary ?? []; + $detailRows = $invoiceDetailRows ?? collect(); + $flowRows = $invoiceFlowRows ?? collect(); + $filters = $invoiceFilters ?? []; + $activeView = $invoiceActiveView ?? 'detail'; + $statusLabels = [ + 'imported' => '已导入', + 'recognized' => '已识别', + 'no_invoice' => '无票', + 'partial' => '部分识别', + 'failed' => '识别失败', + ]; + $mirrorStatusLabels = [ + 'succeeded' => '已同步', + 'failed' => '同步失败', + 'pending' => '待同步', + 'running' => '同步中', + 'imported' => '已导入', + 'unavailable' => '未导入', + ]; + $filterQuery = array_filter($filters, static fn (mixed $value): bool => $value !== '' && $value !== null); + $detailTabUrl = $invoicePageUrl . '?' . http_build_query(array_merge($filterQuery, [ + 'invoice_view' => 'detail', + 'per_page' => $invoicePerPage, + ])); + $flowTabUrl = $invoicePageUrl . '?' . http_build_query(array_merge($filterQuery, [ + 'invoice_view' => 'flows', + 'per_page' => $invoicePerPage, + ])); +@endphp + +
+ + + @if (!empty($invoiceMirrorError)) + + @endif + +
+
+ + + + + + +
+ +
+ + + + 重置 + + + + 导出 + + +
+
+ + + +
+ + 数据口径:按打款时间归属月份 · 一张发票一行 · 无票流程保留 + + + 镜像状态:{{ $mirrorStatusLabels[$invoiceMirrorStatus] ?? $invoiceMirrorStatus }} + @if ($invoiceMirrorSyncedAt) + · 最近成功 {{ $invoiceMirrorSyncedAt }} + @endif + · OCR {{ $invoiceOcrConfigured ? '已配置' : '未配置' }} + · {{ $invoiceScope }} + +
+ +
+
+ 付款流程 + {{ number_format((int) ($summary['flows'] ?? 0)) }} +
+
+ 本月付款金额 + ¥{{ $wan($summary['payment_amount'] ?? 0) }} 万 +
+
+ 发票张数 + {{ number_format((int) ($summary['invoice_count'] ?? 0)) }} +
+
+ 发票价税合计 + ¥{{ $wan($summary['invoice_total'] ?? 0) }} 万 +
+
+ 无票流程 + {{ number_format((int) ($summary['no_invoice_flows'] ?? 0)) }} +
+
+ 开票金额覆盖率 + {{ number_format((float) ($summary['invoice_rate'] ?? 0) * 100, 1) }}% +
+
+ +
+ + +
+ + + + + +

+ 口径:按 OA 付款明细中的打款时间归入月份;一张发票一行,同一流程多张发票分别列示; + 无票流程在“按流程汇总”中保留。发票金额覆盖可能出现超过 100%,表示开票金额高于本月付款,需按具体流程复核。 +

+
+ + diff --git a/resources/views/business/pages/financial-operations/partials/invoice-data-pagination.blade.php b/resources/views/business/pages/financial-operations/partials/invoice-data-pagination.blade.php new file mode 100644 index 000000000..4a5dd72f5 --- /dev/null +++ b/resources/views/business/pages/financial-operations/partials/invoice-data-pagination.blade.php @@ -0,0 +1,22 @@ +@if ($paginator->total() > 0) +
+ + {{ $label }}共 {{ number_format($paginator->total()) }} 条 + · 第 {{ $paginator->currentPage() }} / {{ max(1, $paginator->lastPage()) }} 页 + + @if ($paginator->hasPages()) +
+ @if ($paginator->onFirstPage()) + 上一页 + @else + 上一页 + @endif + @if ($paginator->hasMorePages()) + 下一页 + @else + 下一页 + @endif +
+ @endif +
+@endif diff --git a/tests/Feature/Business/InvoiceDataPageTest.php b/tests/Feature/Business/InvoiceDataPageTest.php new file mode 100644 index 000000000..e943de86c --- /dev/null +++ b/tests/Feature/Business/InvoiceDataPageTest.php @@ -0,0 +1,296 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => true, + ], + 'upstream_mirrors.connection' => 'business_mirror', + 'upstream_mirrors.ding_process_details.scope' => 'personal_permission', + ]); + DB::purge('business_mirror'); + $this->createInvoiceMirrorTables(); + + $now = now(); + DB::connection('business_mirror')->table('business_mirror_table_states')->insert([ + 'dataset_key' => 'operations_replica.rpt.ding_invoices', + 'source_key' => 'operations_replica', + 'source_object' => 'test', + 'target_table' => 'ding_invoice_record_mirror', + 'status' => 'succeeded', + 'initial_completed_at' => $now, + 'last_succeeded_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ]); + + DB::connection('business_mirror')->table('ding_invoice_flow_mirror')->insert([ + [ + 'source_scope' => 'personal_permission', + 'business_id' => 'FLOW-INVOICE-1', + 'process_instance_id' => 'PROCESS-1', + 'paid_month' => '2026-10', + 'title' => '10月办公用品报销', + 'originator_name' => '张三', + 'document_type' => '公摊日常报销', + 'expense_type' => '办公用品', + 'payee_name' => '测试供应商', + 'paid_at' => '2026-10-12 00:00:00', + 'payment_amount' => 1000.00, + 'payment_total' => 1000.00, + 'invoice_count' => 1, + 'invoice_total' => 1000.00, + 'scan_status' => 'recognized', + 'attachment_count' => 1, + 'scanned_file_count' => 1, + 'last_error' => null, + 'source_name' => 'test.xlsx', + 'scanned_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + [ + 'source_scope' => 'personal_permission', + 'business_id' => 'FLOW-NO-INVOICE', + 'process_instance_id' => 'PROCESS-2', + 'paid_month' => '2026-10', + 'title' => '10月借支销账', + 'originator_name' => '李四', + 'document_type' => '公摊借支-销账', + 'expense_type' => '借支', + 'payee_name' => '员工', + 'paid_at' => '2026-10-13 00:00:00', + 'payment_amount' => 500.00, + 'payment_total' => 500.00, + 'invoice_count' => 0, + 'invoice_total' => 0, + 'scan_status' => 'no_invoice', + 'attachment_count' => 0, + 'scanned_file_count' => 0, + 'last_error' => null, + 'source_name' => 'test.xlsx', + 'scanned_at' => $now, + 'created_at' => $now, + 'updated_at' => $now, + ], + ]); + + DB::connection('business_mirror')->table('ding_invoice_record_mirror')->insert([ + 'source_scope' => 'personal_permission', + 'business_id' => 'FLOW-INVOICE-1', + 'process_instance_id' => 'PROCESS-1', + 'paid_month' => '2026-10', + 'invoice_key' => hash('sha256', 'number:26320000000000000001'), + 'invoice_type' => '电子发票(普通发票)', + 'seller_name' => '测试供应商', + 'seller_tax_no' => '913200000000000001', + 'buyer_name' => '测试主体', + 'buyer_tax_no' => '913200000000000002', + 'invoice_total' => 1000.00, + 'invoice_number' => '26320000000000000001', + 'invoice_date' => '2026-10-10', + 'item_name' => '*办公用品*打印纸', + 'amount_without_tax' => 884.96, + 'tax_rate' => '13%', + 'tax_amount' => 115.04, + 'source_file_id' => null, + 'source_file_name' => null, + 'source_file_type' => null, + 'source_field' => null, + 'source_path' => null, + 'source_hash' => null, + 'ocr_provider' => 'test', + 'recognition_payload' => null, + 'created_at' => $now, + 'updated_at' => $now, + ]); + } + + public function test_invoice_data_page_renders_detail_and_flow_views(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + + $response = $this->loginAs()->get(route('business.pages.show', [ + 'section' => 'process-data', + 'page' => 'invoice-data', + 'month' => '2026-10', + 'per_page' => 50, + ])); + + $response->assertOk() + ->assertSee('发票数据') + ->assertSee('付款月份') + ->assertSee('发票状态') + ->assertSee('发票明细') + ->assertSee('按流程汇总') + ->assertSee('抓取发票') + ->assertSee('data-invoice-refresh', false) + ->assertSee('付款流程') + ->assertSee('发票价税合计') + ->assertSee('开票金额覆盖率') + ->assertSee('FLOW-INVOICE-1') + ->assertSee('10月办公用品报销') + ->assertSee('26320000000000000001') + ->assertSee('测试供应商') + ->assertSee('FLOW-NO-INVOICE') + ->assertSee('无票'); + + $this->assertContains( + 'invoice-data', + array_column( + collect(\App\Utilities\BusinessNavigation::all()) + ->firstWhere('slug', 'process-data')['pages'] ?? [], + 'slug', + ), + ); + } + + public function test_repository_filters_invoice_type_and_state(): void + { + $repository = app(DingInvoiceDataMirrorRepository::class); + $this->assertSame( + '电子发票(普通发票)', + DB::connection('business_mirror')->table('ding_invoice_record_mirror')->value('invoice_type'), + ); + $this->assertSame( + 1, + DB::connection('business_mirror') + ->table('ding_invoice_record_mirror') + ->where('item_name', 'like', '%打印纸%') + ->count(), + ); + $invoiceResult = $repository->paginate([ + 'month' => '2026-10', + 'view' => DingInvoiceDataMirrorRepository::VIEW_DETAIL, + 'invoice_state' => 'has_invoice', + 'invoice_type' => '电子发票(普通发票)', + 'keyword' => '打印纸', + ], 1, 50); + $flowResult = $repository->paginate([ + 'month' => '2026-10', + 'view' => DingInvoiceDataMirrorRepository::VIEW_FLOWS, + 'invoice_state' => 'no_invoice', + 'invoice_type' => '', + 'keyword' => '', + ], 1, 50); + + $this->assertSame(1, $invoiceResult['total']); + $this->assertSame(1, $invoiceResult['summary']['flows']); + $this->assertSame(1, $invoiceResult['summary']['invoice_count']); + $this->assertSame(1, $flowResult['total']); + $this->assertSame('FLOW-NO-INVOICE', $flowResult['data'][0]->business_id); + $this->assertSame(1, $flowResult['summary']['flows']); + $this->assertSame(1, $flowResult['summary']['no_invoice_flows']); + } + + public function test_refresh_endpoint_queues_selected_month(): void + { + $this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail()); + Storage::fake('local'); + + $response = $this->loginAs()->postJson(route('business.invoice-data.refresh'), [ + 'month' => '2026-10', + 'force' => true, + ]); + $response->assertOk() + ->assertJsonPath('success', true) + ->assertJsonPath('queued', true) + ->assertJsonPath('month', '2026-10'); + + $token = $response->json('token'); + $this->getJson(route('business.invoice-data.refresh-status', ['token' => $token])) + ->assertOk() + ->assertJsonPath('refresh.status', 'pending') + ->assertJsonPath('refresh.month', '2026-10'); + } + + private function createInvoiceMirrorTables(): void + { + $schema = Schema::connection('business_mirror'); + $schema->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->string('source_key'); + $table->string('source_object'); + $table->string('target_table'); + $table->string('status')->default('pending'); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('last_upserted_rows')->default(0); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->boolean('mirror_row_count_is_exact')->default(false); + $table->timestamps(); + }); + $schema->create('ding_invoice_flow_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope'); + $table->string('business_id'); + $table->string('process_instance_id')->nullable(); + $table->string('paid_month'); + $table->string('title')->nullable(); + $table->string('originator_name')->nullable(); + $table->string('document_type')->nullable(); + $table->string('expense_type')->nullable(); + $table->string('payee_name')->nullable(); + $table->dateTime('paid_at')->nullable(); + $table->decimal('payment_amount', 18, 2)->default(0); + $table->decimal('payment_total', 18, 2)->default(0); + $table->unsignedInteger('invoice_count')->default(0); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('scan_status')->default('imported'); + $table->unsignedInteger('attachment_count')->default(0); + $table->unsignedInteger('scanned_file_count')->default(0); + $table->text('last_error')->nullable(); + $table->string('source_name')->nullable(); + $table->dateTime('scanned_at')->nullable(); + $table->timestamps(); + }); + $schema->create('ding_invoice_record_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope'); + $table->string('business_id'); + $table->string('process_instance_id')->nullable(); + $table->string('paid_month'); + $table->string('invoice_key'); + $table->string('invoice_type')->nullable(); + $table->string('seller_name')->nullable(); + $table->string('seller_tax_no')->nullable(); + $table->string('buyer_name')->nullable(); + $table->string('buyer_tax_no')->nullable(); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('invoice_number')->nullable(); + $table->date('invoice_date')->nullable(); + $table->text('item_name')->nullable(); + $table->decimal('amount_without_tax', 18, 2)->nullable(); + $table->string('tax_rate')->nullable(); + $table->decimal('tax_amount', 18, 2)->nullable(); + $table->string('source_file_id')->nullable(); + $table->string('source_file_name')->nullable(); + $table->string('source_file_type')->nullable(); + $table->string('source_field')->nullable(); + $table->string('source_path')->nullable(); + $table->string('source_hash')->nullable(); + $table->string('ocr_provider')->nullable(); + $table->json('recognition_payload')->nullable(); + $table->timestamps(); + }); + } +} diff --git a/tests/Feature/Business/InvoiceDataRefreshQueueTest.php b/tests/Feature/Business/InvoiceDataRefreshQueueTest.php new file mode 100644 index 000000000..b540a60cc --- /dev/null +++ b/tests/Feature/Business/InvoiceDataRefreshQueueTest.php @@ -0,0 +1,44 @@ +enqueue('2026-10', true, 1, 7); + $this->assertTrue($queued['queued']); + $this->assertNotNull($queued['token']); + + $duplicate = $queue->enqueue('2026-10', true, 1, 7); + $this->assertFalse($duplicate['queued']); + $this->assertSame($queued['token'], $duplicate['token']); + + $claimed = $queue->claimNext(); + $this->assertNotNull($claimed); + $this->assertSame('2026-10', $claimed['month']); + $this->assertTrue($claimed['force']); + + $queue->defer((string) $claimed['token'], ['remaining_flows' => 20], false); + $status = $queue->status((string) $claimed['token'], 1, 7); + $this->assertSame('pending', $status['status']); + $this->assertFalse($status['force'] ?? true); + $this->assertSame(20, $status['progress']['remaining_flows']); + + $claimedAgain = $queue->claimNext(); + $this->assertSame($queued['token'], $claimedAgain['token']); + $queue->complete((string) $claimedAgain['token'], ['remaining_flows' => 0]); + + $completed = $queue->status((string) $claimedAgain['token'], 1, 7); + $this->assertSame('completed', $completed['status']); + $this->assertSame(0, $completed['result']['remaining_flows']); + $this->assertNull($queue->status((string) $claimedAgain['token'], 2, 7)); + } +} diff --git a/tests/Feature/Business/ProcessDetailsNavigationTest.php b/tests/Feature/Business/ProcessDetailsNavigationTest.php index b9083601a..229cd4152 100644 --- a/tests/Feature/Business/ProcessDetailsNavigationTest.php +++ b/tests/Feature/Business/ProcessDetailsNavigationTest.php @@ -25,7 +25,10 @@ class ProcessDetailsNavigationTest extends FeatureTestCase $section = $navigation[$processDataIndex]; $this->assertSame('流程数据', $section['title']); $this->assertSame( - [['slug' => 'oa-process', 'title' => 'OA流程']], + [ + ['slug' => 'oa-process', 'title' => 'OA流程'], + ['slug' => 'invoice-data', 'title' => '发票数据'], + ], array_map( static fn (array $page): array => [ 'slug' => $page['slug'], diff --git a/tests/Feature/Console/ImportDingInvoiceWorkbookTest.php b/tests/Feature/Console/ImportDingInvoiceWorkbookTest.php new file mode 100644 index 000000000..3b97ed9a0 --- /dev/null +++ b/tests/Feature/Console/ImportDingInvoiceWorkbookTest.php @@ -0,0 +1,185 @@ + [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + 'foreign_key_constraints' => true, + ], + 'upstream_mirrors.connection' => 'business_mirror', + ]); + DB::purge('business_mirror'); + $this->createTables(); + + $spreadsheet = new Spreadsheet(); + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle('报销发票识别'); + $sheet->fromArray([ + [ + '单号/标题', '流程号', '提交人', '报销类型', '费用类型', '收款人', + '打款时间', '10月付款金额', '付款合计', '发票类型', '销售方名称', + '销售方税号', '购买方名称', '购买方税号', '发票价税合计', '发票号码', + '开票日期', '项目名称', '金额', '税率', '税额', '金额校对', '差异金额', + ], + [ + '10月办公用品报销', 'FLOW-INVOICE-1', '张三', '公摊日常报销', '办公用品', + '测试供应商', '2026-10-12', 1000, 1000, '电子发票(普通发票)', + '测试供应商', '913200000000000001', '测试主体', '913200000000000002', + 1000, '26320000000000000001', '2026-10-10', '*办公用品*打印纸', + 884.96, '13%', 115.04, '一致', 0, + ], + [ + null, null, null, null, null, null, null, null, null, + '电子发票(普通发票)', '测试供应商', '913200000000000001', + '测试主体', '913200000000000002', 1000, '26320000000000000001', + '2026-10-10', '*办公用品*打印纸', 884.96, '13%', 115.04, null, null, + ], + [ + '10月借支销账', 'FLOW-NO-INVOICE', '李四', '公摊借支-销账', '借支', + '员工', '2026-10-13', 500, 500, '无票', null, null, null, null, + 0, null, null, null, null, null, null, '无票', null, + ], + [ + '10月软件服务费', 'FLOW-INVOICE-2', '王五', '公摊日常报销', '软件服务费', + '测试服务商', '2026-10-14', 200, 200, '电子发票(普通发票)', + '测试服务商', '913200000000000003', '测试主体', '913200000000000002', + 200, '26320000000000000001', '2026-10-14', '*软件服务*服务费', + 188.68, '6%', 11.32, '一致', 0, + ], + ]); + $this->file = tempnam(sys_get_temp_dir(), 'invoice-import-') . '.xlsx'; + (new Xlsx($spreadsheet))->save($this->file); + $spreadsheet->disconnectWorksheets(); + } + + protected function tearDown(): void + { + if (isset($this->file) && is_file($this->file)) { + unlink($this->file); + } + parent::tearDown(); + } + + public function test_imports_one_invoice_row_per_invoice_and_keeps_no_invoice_flow(): void + { + $result = app(DingInvoiceWorkbookImporter::class)->import($this->file); + + $this->assertSame(3, $result['flows']); + $this->assertSame(2, $result['invoices']); + $this->assertSame(['2026-10'], $result['months']); + $this->assertEqualsWithDelta(1700.0, $result['payment_total'], 0.001); + $this->assertEqualsWithDelta(1200.0, $result['invoice_total'], 0.001); + $this->assertDatabaseHas('ding_invoice_flow_mirror', [ + 'business_id' => 'FLOW-INVOICE-1', + 'invoice_count' => 1, + 'scan_status' => 'recognized', + ], 'business_mirror'); + $this->assertDatabaseHas('ding_invoice_flow_mirror', [ + 'business_id' => 'FLOW-NO-INVOICE', + 'invoice_count' => 0, + 'scan_status' => 'no_invoice', + ], 'business_mirror'); + $this->assertDatabaseCount('ding_invoice_record_mirror', 2, 'business_mirror'); + } + + private function createTables(): void + { + $schema = Schema::connection('business_mirror'); + $schema->create('business_mirror_table_states', function (Blueprint $table): void { + $table->string('dataset_key')->primary(); + $table->string('source_key'); + $table->string('source_object'); + $table->string('target_table'); + $table->string('status')->default('pending'); + $table->string('run_mode')->nullable(); + $table->uuid('generation')->nullable(); + $table->json('cursor')->nullable(); + $table->json('high_watermark')->nullable(); + $table->dateTime('window_started_at')->nullable(); + $table->dateTime('window_ends_at')->nullable(); + $table->dateTime('initial_completed_at')->nullable(); + $table->dateTime('last_full_succeeded_at')->nullable(); + $table->dateTime('last_attempted_at')->nullable(); + $table->dateTime('last_succeeded_at')->nullable(); + $table->unsignedBigInteger('last_upserted_rows')->default(0); + $table->unsignedBigInteger('mirror_row_count')->default(0); + $table->boolean('mirror_row_count_is_exact')->default(false); + $table->string('last_error_code')->nullable(); + $table->timestamps(); + }); + $schema->create('ding_invoice_flow_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope'); + $table->string('business_id'); + $table->string('process_instance_id')->nullable(); + $table->string('paid_month'); + $table->string('title')->nullable(); + $table->string('originator_name')->nullable(); + $table->string('document_type')->nullable(); + $table->string('expense_type')->nullable(); + $table->string('payee_name')->nullable(); + $table->dateTime('paid_at')->nullable(); + $table->decimal('payment_amount', 18, 2)->default(0); + $table->decimal('payment_total', 18, 2)->default(0); + $table->unsignedInteger('invoice_count')->default(0); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('scan_status')->default('imported'); + $table->unsignedInteger('attachment_count')->default(0); + $table->unsignedInteger('scanned_file_count')->default(0); + $table->text('last_error')->nullable(); + $table->string('source_name')->nullable(); + $table->dateTime('scanned_at')->nullable(); + $table->timestamps(); + $table->unique(['source_scope', 'business_id']); + }); + $schema->create('ding_invoice_record_mirror', function (Blueprint $table): void { + $table->bigIncrements('id'); + $table->string('source_scope'); + $table->string('business_id'); + $table->string('process_instance_id')->nullable(); + $table->string('paid_month'); + $table->string('invoice_key'); + $table->string('invoice_type')->nullable(); + $table->string('seller_name')->nullable(); + $table->string('seller_tax_no')->nullable(); + $table->string('buyer_name')->nullable(); + $table->string('buyer_tax_no')->nullable(); + $table->decimal('invoice_total', 18, 2)->default(0); + $table->string('invoice_number')->nullable(); + $table->date('invoice_date')->nullable(); + $table->text('item_name')->nullable(); + $table->decimal('amount_without_tax', 18, 2)->nullable(); + $table->string('tax_rate')->nullable(); + $table->decimal('tax_amount', 18, 2)->nullable(); + $table->string('source_file_id')->nullable(); + $table->string('source_file_name')->nullable(); + $table->string('source_file_type')->nullable(); + $table->string('source_field')->nullable(); + $table->string('source_path')->nullable(); + $table->string('source_hash')->nullable(); + $table->string('ocr_provider')->nullable(); + $table->json('recognition_payload')->nullable(); + $table->timestamps(); + $table->unique(['source_scope', 'business_id', 'invoice_key']); + }); + } +} diff --git a/tests/Unit/DingInvoiceTextParserTest.php b/tests/Unit/DingInvoiceTextParserTest.php new file mode 100644 index 000000000..1b1fa2da0 --- /dev/null +++ b/tests/Unit/DingInvoiceTextParserTest.php @@ -0,0 +1,47 @@ +parse($text); + + $this->assertNotNull($invoice); + $this->assertSame('电子发票(普通发票)', $invoice['invoice_type']); + $this->assertSame('26320000000000000001', $invoice['invoice_number']); + $this->assertSame('2026-10-10', $invoice['invoice_date']); + $this->assertSame('常州测试家居有限公司', $invoice['buyer_name']); + $this->assertSame('常州测试供应商有限公司', $invoice['seller_name']); + $this->assertEqualsWithDelta(1000.0, $invoice['invoice_total'], 0.001); + $this->assertSame('*办公用品*打印纸', $invoice['item_name']); + } + + public function test_ignores_non_invoice_attachment_text(): void + { + $this->assertNull( + app(DingInvoiceTextParser::class)->parse('银行电子回单 金额 1000.00 无发票号码'), + ); + } +} -- 2.47.2