diff --git a/database/migrations/2026_11_27_170000_add_preview_fields_to_ding_invoice_record_mirror.php b/database/migrations/2026_11_27_170000_add_preview_fields_to_ding_invoice_record_mirror.php new file mode 100644 index 00000000..54540f85 --- /dev/null +++ b/database/migrations/2026_11_27_170000_add_preview_fields_to_ding_invoice_record_mirror.php @@ -0,0 +1,60 @@ +environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('ding_invoice_record_mirror')) { + return; + } + + $schema->table('ding_invoice_record_mirror', function (Blueprint $table) use ($schema): void { + if (! $schema->hasColumn('ding_invoice_record_mirror', 'preview_path')) { + $table->string('preview_path', 1024)->nullable(); + } + if (! $schema->hasColumn('ding_invoice_record_mirror', 'preview_mime')) { + $table->string('preview_mime', 100)->nullable(); + } + }); + } + + public function down(): void + { + if (app()->environment('testing') + || (string) config('system_database.mode', 'bootstrap') === 'bootstrap') { + return; + } + + $schema = Schema::connection($this->connection()); + if (! $schema->hasTable('ding_invoice_record_mirror')) { + return; + } + + $columns = []; + foreach (['preview_path', 'preview_mime'] as $column) { + if ($schema->hasColumn('ding_invoice_record_mirror', $column)) { + $columns[] = $column; + } + } + if ($columns !== []) { + $schema->table('ding_invoice_record_mirror', function (Blueprint $table) use ($columns): void { + $table->dropColumn($columns); + }); + } + } +}; diff --git a/modules/EcommerceFinance/Http/Controllers/InvoiceData.php b/modules/EcommerceFinance/Http/Controllers/InvoiceData.php index 52319d70..a4d55017 100644 --- a/modules/EcommerceFinance/Http/Controllers/InvoiceData.php +++ b/modules/EcommerceFinance/Http/Controllers/InvoiceData.php @@ -2,12 +2,12 @@ namespace Modules\EcommerceFinance\Http\Controllers; -use Illuminate\Http\RedirectResponse; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; +use Illuminate\Support\Facades\Storage; use Modules\EcommerceFinance\Repositories\DingInvoiceDataMirrorRepository; -use Modules\EcommerceFinance\Services\DingTalkApprovalAttachmentDownloader; +use Modules\EcommerceFinance\Services\DingInvoicePreviewStore; use Modules\EcommerceFinance\Services\DingInvoiceRefreshQueue; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -138,11 +138,8 @@ class InvoiceData extends Controller ]); } - public function attachment(int $invoice): RedirectResponse + public function attachment(int $invoice): StreamedResponse { - // 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') @@ -151,15 +148,22 @@ class InvoiceData extends Controller ->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, '该发票没有可下载的原始附件。'); + $preview = app(DingInvoicePreviewStore::class)->ensureStored($invoiceRow); + abort_if($preview === null, 404, '该发票暂无图片或 PDF 原件可预览。'); - $uri = app(DingTalkApprovalAttachmentDownloader::class) - ->downloadUri($processInstanceId, $fileId); - abort_if($uri === null, 404, '原始发票附件暂时无法下载。'); + $disk = Storage::disk('uploads'); + abort_unless($disk->exists($preview['path']), 404); - return redirect()->away($uri); + $name = trim((string) ($invoiceRow->source_file_name ?? '')); + if ($name === '') { + $name = 'invoice-preview.' . $preview['extension']; + } + + return $disk->response($preview['path'], basename($name), [ + 'Content-Type' => $preview['mime'], + 'Cache-Control' => 'private, max-age=300', + 'X-Content-Type-Options' => 'nosniff', + ], 'inline'); } public function requestRefresh(Request $request): JsonResponse diff --git a/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php b/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php index 1ac17573..e5b543ac 100644 --- a/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php +++ b/modules/EcommerceFinance/Repositories/DingInvoiceDataMirrorRepository.php @@ -233,6 +233,8 @@ class DingInvoiceDataMirrorRepository 'r.source_file_type', 'r.source_field', 'r.ocr_provider', + 'r.preview_path', + 'r.preview_mime', 'f.title', 'f.originator_name', 'f.document_type', diff --git a/modules/EcommerceFinance/Services/DingInvoicePreviewStore.php b/modules/EcommerceFinance/Services/DingInvoicePreviewStore.php new file mode 100644 index 00000000..df7d6655 --- /dev/null +++ b/modules/EcommerceFinance/Services/DingInvoicePreviewStore.php @@ -0,0 +1,190 @@ + 'pdf', + 'image/jpeg' => 'jpg', + 'image/png' => 'png', + 'image/webp' => 'webp', + 'image/bmp' => 'bmp', + ]; + + private ConnectionInterface $connection; + + public function __construct( + DatabaseManager $database, + private readonly DingTalkApprovalAttachmentDownloader $downloads, + ) { + $this->connection = $database->connection( + (string) config('upstream_mirrors.connection', 'business_mirror'), + ); + } + + /** + * Cache image/PDF source attachments in the private business file store. + * + * @param array $file + * @return array{path:string,mime:string,extension:string}|null + */ + public function persistLocalFile(string $localPath, array $file, ?string $hash = null): ?array + { + $mime = $this->previewMime($localPath, $file); + if ($mime === null) { + return null; + } + + $hash = $hash ?: (hash_file('sha256', $localPath) ?: ''); + if ($hash === '') { + return null; + } + + $extension = self::PREVIEW_MIMES[$mime]; + $path = implode('/', [ + 'invoice-previews', + substr($hash, 0, 2), + $hash . '.' . $extension, + ]); + $disk = Storage::disk('uploads'); + if (! $disk->exists($path)) { + $stream = fopen($localPath, 'rb'); + if ($stream === false) { + return null; + } + try { + if (! $disk->put($path, $stream)) { + return null; + } + } finally { + fclose($stream); + } + } + + return [ + 'path' => $path, + 'mime' => $mime, + 'extension' => $extension, + ]; + } + + /** + * Cache a historical invoice attachment on first preview request. + * + * @return array{path:string,mime:string,extension:string}|null + */ + public function ensureStored(object $invoice): ?array + { + $existingPath = trim((string) ($invoice->preview_path ?? '')); + $existingMime = trim((string) ($invoice->preview_mime ?? '')); + if ($existingPath !== '' + && $existingMime !== '' + && Storage::disk('uploads')->exists($existingPath)) { + return [ + 'path' => $existingPath, + 'mime' => $existingMime, + 'extension' => pathinfo($existingPath, PATHINFO_EXTENSION), + ]; + } + + $processInstanceId = trim((string) ($invoice->process_instance_id ?? '')); + $fileId = trim((string) ($invoice->source_file_id ?? '')); + if ($processInstanceId === '' || $fileId === '') { + return null; + } + + $uri = $this->downloads->downloadUri($processInstanceId, $fileId); + if ($uri === null) { + return null; + } + + $tempRoot = storage_path('app/temp/invoice-preview'); + if (! is_dir($tempRoot) && ! mkdir($tempRoot, 0755, true) && ! is_dir($tempRoot)) { + throw new RuntimeException('无法创建发票预览临时目录。'); + } + $tempPath = $tempRoot . '/' . bin2hex(random_bytes(8)); + + try { + $response = Http::timeout(120) + ->withOptions(['sink' => $tempPath]) + ->get($uri); + if (! $response->successful() || ! is_file($tempPath)) { + return null; + } + if (filesize($tempPath) > (int) config('ding_invoice_data.max_file_bytes')) { + return null; + } + + $preview = $this->persistLocalFile( + $tempPath, + [ + 'file_name' => (string) ($invoice->source_file_name ?? ''), + 'file_type' => (string) ($invoice->source_file_type ?? ''), + ], + trim((string) ($invoice->source_hash ?? '')), + ); + if ($preview === null) { + return null; + } + + $this->connection->table('ding_invoice_record_mirror') + ->where('id', (int) $invoice->id) + ->where('source_scope', (string) $invoice->source_scope) + ->update([ + 'preview_path' => $preview['path'], + 'preview_mime' => $preview['mime'], + 'updated_at' => now(), + ]); + + return $preview; + } finally { + if (is_file($tempPath)) { + @unlink($tempPath); + } + } + } + + /** @param array $file */ + private function previewMime(string $path, array $file): ?string + { + $mime = ''; + if (function_exists('finfo_open')) { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + if ($finfo !== false) { + $mime = strtolower((string) finfo_file($finfo, $path)); + finfo_close($finfo); + } + } + if (! isset(self::PREVIEW_MIMES[$mime])) { + $fileType = strtolower((string) ($file['file_type'] ?? '')); + $extension = strtolower(pathinfo( + (string) ($file['file_name'] ?? ''), + PATHINFO_EXTENSION, + )); + $mime = match ($extension) { + 'pdf' => 'application/pdf', + 'jpg', 'jpeg' => 'image/jpeg', + 'png' => 'image/png', + 'webp' => 'image/webp', + 'bmp' => 'image/bmp', + default => match (true) { + $fileType === 'pdf' || str_contains($fileType, 'pdf') => 'application/pdf', + in_array($fileType, ['jpg', 'jpeg', 'image/jpeg'], true) => 'image/jpeg', + in_array($fileType, ['png', 'image/png'], true) => 'image/png', + in_array($fileType, ['webp', 'image/webp'], true) => 'image/webp', + in_array($fileType, ['bmp', 'image/bmp'], true) => 'image/bmp', + default => '', + }, + }; + } + + return isset(self::PREVIEW_MIMES[$mime]) ? $mime : null; + } +} diff --git a/modules/EcommerceFinance/Services/DingInvoiceRecordNormalizer.php b/modules/EcommerceFinance/Services/DingInvoiceRecordNormalizer.php index d51d7048..69675d05 100644 --- a/modules/EcommerceFinance/Services/DingInvoiceRecordNormalizer.php +++ b/modules/EcommerceFinance/Services/DingInvoiceRecordNormalizer.php @@ -85,6 +85,8 @@ class DingInvoiceRecordNormalizer 'source_field', 'source_path', 'source_hash', + 'preview_path', + 'preview_mime', ] as $field) { if (! $this->empty($incoming[$field] ?? null)) { $merged[$field] = $incoming[$field]; diff --git a/modules/EcommerceFinance/Services/DingInvoiceSyncService.php b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php index 309961a5..4f6b4cce 100644 --- a/modules/EcommerceFinance/Services/DingInvoiceSyncService.php +++ b/modules/EcommerceFinance/Services/DingInvoiceSyncService.php @@ -22,6 +22,7 @@ class DingInvoiceSyncService private readonly DingTalkApprovalAttachmentDownloader $downloads, private readonly DingInvoiceFileRecognizer $recognizer, private readonly DingInvoiceRecordNormalizer $normalizer, + private readonly DingInvoicePreviewStore $previewStore, private readonly DingTalkProcessInstanceClient $approvalClient, ) { $this->connection = $database->connection( @@ -579,6 +580,12 @@ class DingInvoiceSyncService } $scannedFiles++; $hash = hash_file('sha256', $path) ?: null; + $preview = null; + try { + $preview = $this->previewStore->persistLocalFile($path, $file, $hash); + } catch (Throwable $exception) { + report($exception); + } $recognized = $this->recognizer->recognize($path, $file['file_name']); foreach ($recognized['invoices'] as $invoice) { $invoice['_source'] = [ @@ -589,6 +596,8 @@ class DingInvoiceSyncService 'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'], 'source_hash' => $hash, 'ocr_provider' => $recognized['provider'], + 'preview_path' => $preview['path'] ?? null, + 'preview_mime' => $preview['mime'] ?? null, ]; $invoices[] = $invoice; } @@ -672,6 +681,8 @@ class DingInvoiceSyncService '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), + 'preview_path' => $source['preview_path'] ?? null, + 'preview_mime' => $source['preview_mime'] ?? null, 'recognition_payload' => json_encode( array_diff_key($invoice, ['_source' => true]), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES, diff --git a/resources/views/business/pages/financial-operations/invoice-data.blade.php b/resources/views/business/pages/financial-operations/invoice-data.blade.php index 62801055..8debf3e3 100644 --- a/resources/views/business/pages/financial-operations/invoice-data.blade.php +++ b/resources/views/business/pages/financial-operations/invoice-data.blade.php @@ -393,6 +393,134 @@ font-size: 0.875rem; } + .invoice-preview-trigger { + display: inline-flex; + min-width: 4.75rem; + min-height: 2.5rem; + align-items: center; + justify-content: center; + gap: 0.3rem; + padding: 0.25rem; + overflow: hidden; + border: 1px solid var(--invoice-border); + border-radius: 0.5rem; + background: var(--invoice-surface); + color: var(--invoice-accent-dark); + cursor: zoom-in; + font: inherit; + font-size: 0.6875rem; + font-weight: 600; + } + + .invoice-preview-trigger:hover, + .invoice-preview-trigger:focus-visible { + border-color: var(--invoice-accent-dark); + background: var(--invoice-soft); + } + + .invoice-preview-trigger img { + display: block; + width: 4rem; + height: 2.75rem; + border-radius: 0.3rem; + object-fit: cover; + } + + .invoice-preview-trigger .material-icons-outlined { + font-size: 1rem; + } + + .invoice-preview-modal { + position: fixed; + inset: 0; + z-index: 10080; + display: grid; + place-items: center; + padding: 1.25rem; + background: rgba(5, 5, 6, 0.78); + } + + .invoice-preview-modal[hidden] { + display: none; + } + + .invoice-preview-dialog { + position: relative; + display: flex; + width: min(72rem, 96vw); + height: min(52rem, 92vh); + flex-direction: column; + overflow: hidden; + border: 1px solid #4a4337; + border-radius: 0.75rem; + background: #111110; + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.38); + } + + .invoice-preview-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 1rem; + padding: 0.75rem 1rem; + border-bottom: 1px solid #34312b; + color: #f2e7c5; + } + + .invoice-preview-head strong { + overflow: hidden; + font-size: 0.8125rem; + text-overflow: ellipsis; + white-space: nowrap; + } + + .invoice-preview-close { + display: inline-flex; + width: 2rem; + height: 2rem; + align-items: center; + justify-content: center; + border: 1px solid #5d5547; + border-radius: 0.4rem; + background: transparent; + color: #f2e7c5; + cursor: pointer; + } + + .invoice-preview-close:hover, + .invoice-preview-close:focus-visible { + background: #2a2927; + } + + .invoice-preview-body { + position: relative; + display: grid; + flex: 1; + min-height: 0; + place-items: center; + overflow: auto; + background: #1d1d1f; + } + + .invoice-preview-body img { + display: block; + max-width: 100%; + max-height: 100%; + object-fit: contain; + } + + .invoice-preview-body iframe { + width: 100%; + height: 100%; + border: 0; + background: #ffffff; + } + + .invoice-preview-body img[hidden], + .invoice-preview-body iframe[hidden] { + display: none; + } + .invoice-data-tag { display: inline-flex; min-height: 1.4rem; @@ -717,6 +845,7 @@ 流程号 + 发票预览 发票类型 发票号码 开票日期 @@ -744,6 +873,26 @@ (float) $row->payment_amount - (float) $row->flow_invoice_total, 2, ); + $previewExtension = strtolower((string) pathinfo( + (string) $row->source_file_name, + PATHINFO_EXTENSION, + )); + $previewSourceType = strtolower((string) $row->source_file_type); + $previewKind = match (true) { + $previewExtension === 'pdf', + str_contains($previewSourceType, 'pdf') => 'pdf', + in_array($previewExtension, ['jpg', 'jpeg', 'png', 'webp', 'bmp'], true), + str_starts_with($previewSourceType, 'image/') => 'image', + default => '', + }; + $canPreview = $previewKind !== '' + && ($row->source_file_id || $row->preview_path); + $storedImagePreview = $canPreview + && $previewKind === 'image' + && $row->preview_path; + $previewUrl = route('business.invoice-data.attachment', [ + 'invoice' => $row->id, + ]); @endphp @@ -760,6 +909,30 @@ + + @if ($canPreview) + + @else + 仅识别字段 + @endif + {{ $row->invoice_type ?: '未分类' }} @@ -793,7 +966,7 @@ @empty - 当前筛选条件下没有发票明细。 + 当前筛选条件下没有发票明细。 @endforelse @@ -886,11 +1059,27 @@

- 口径:统计从 {{ $startMonth }} 开始。发票附件只由服务端临时下载并识别,页面直接展示识别结果, - 不提供附件下载。发票按打款时间归入月份,一张发票一行,同一流程多张发票分别列示。 + 口径:统计从 {{ $startMonth }} 开始。发票附件由服务端下载并缓存用于识别; + 图片和 PDF 可在页面内预览,不再跳转钉钉临时地址。发票按打款时间归入月份, + 一张发票一行,同一流程多张发票分别列示。 无票流程在“按流程汇总”中保留。开票金额覆盖率可能超过 100%,表示开票金额高于本月付款, 需要按具体流程复核。

+ +