feat(发票数据): 增加发票图片与PDF页内预览 (#1513)

图片和 PDF 发票原件缓存到私有业务存储,页面通过预览弹窗查看;历史附件首次点击时按需缓存。
This commit is contained in:
yueyang 2026-11-27 15:42:22 +08:00
parent 92f88fb60b
commit 66639e19c1
8 changed files with 570 additions and 19 deletions

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
private function connection(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
public function up(): 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;
}
$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);
});
}
}
};

View File

@ -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

View File

@ -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',

View File

@ -0,0 +1,190 @@
<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use RuntimeException;
class DingInvoicePreviewStore
{
private const PREVIEW_MIMES = [
'application/pdf' => '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<string,mixed> $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<string,mixed> $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;
}
}

View File

@ -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];

View File

@ -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,

View File

@ -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 @@
<thead>
<tr>
<th scope="col">流程号</th>
<th scope="col">发票预览</th>
<th scope="col">发票类型</th>
<th scope="col">发票号码</th>
<th scope="col">开票日期</th>
@ -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
<tr>
<td class="is-nowrap">
@ -760,6 +909,30 @@
<span class="material-icons-outlined" aria-hidden="true">open_in_new</span>
</a>
</td>
<td>
@if ($canPreview)
<button
type="button"
class="invoice-preview-trigger"
data-invoice-preview
data-preview-url="{{ $previewUrl }}"
data-preview-kind="{{ $previewKind }}"
data-preview-title="{{ $row->invoice_number ?: $row->source_file_name }}"
title="{{ $previewKind === 'pdf' ? '预览发票 PDF' : '预览发票图片' }}"
>
@if ($storedImagePreview)
<img src="{{ $previewUrl }}" alt="发票 {{ $row->invoice_number }}" loading="lazy">
@else
<span class="material-icons-outlined" aria-hidden="true">
{{ $previewKind === 'pdf' ? 'picture_as_pdf' : 'image' }}
</span>
<span>{{ $previewKind === 'pdf' ? 'PDF' : '图片' }}</span>
@endif
</button>
@else
<span class="invoice-data-secondary">仅识别字段</span>
@endif
</td>
<td>
<span class="invoice-data-tag">{{ $row->invoice_type ?: '未分类' }}</span>
</td>
@ -793,7 +966,7 @@
</tr>
@empty
<tr>
<td colspan="19" class="invoice-data-empty">当前筛选条件下没有发票明细。</td>
<td colspan="20" class="invoice-data-empty">当前筛选条件下没有发票明细。</td>
</tr>
@endforelse
</tbody>
@ -886,11 +1059,27 @@
</section>
<p class="invoice-data-note">
口径:统计从 {{ $startMonth }} 开始。发票附件只由服务端临时下载并识别,页面直接展示识别结果,
不提供附件下载。发票按打款时间归入月份,一张发票一行,同一流程多张发票分别列示。
口径:统计从 {{ $startMonth }} 开始。发票附件由服务端下载并缓存用于识别;
图片和 PDF 可在页面内预览,不再跳转钉钉临时地址。发票按打款时间归入月份,
一张发票一行,同一流程多张发票分别列示。
无票流程在“按流程汇总”中保留。开票金额覆盖率可能超过 100%,表示开票金额高于本月付款,
需要按具体流程复核。
</p>
<div class="invoice-preview-modal" data-invoice-preview-modal hidden>
<div class="invoice-preview-dialog" role="dialog" aria-modal="true" aria-labelledby="invoice-preview-title">
<div class="invoice-preview-head">
<strong id="invoice-preview-title" data-invoice-preview-title>发票预览</strong>
<button type="button" class="invoice-preview-close" data-invoice-preview-close aria-label="关闭预览">
<span class="material-icons-outlined" aria-hidden="true">close</span>
</button>
</div>
<div class="invoice-preview-body">
<img data-invoice-preview-image alt="发票预览" hidden>
<iframe data-invoice-preview-frame title="发票 PDF 预览" hidden></iframe>
</div>
</div>
</div>
</div>
<script>
@ -913,6 +1102,67 @@
var refreshLabel = root.querySelector('[data-invoice-refresh-label]');
var exportLink = root.querySelector('[data-invoice-export]');
var csrfToken = @json(csrf_token());
var previewModal = root.querySelector('[data-invoice-preview-modal]');
var previewTitle = root.querySelector('[data-invoice-preview-title]');
var previewImage = root.querySelector('[data-invoice-preview-image]');
var previewFrame = root.querySelector('[data-invoice-preview-frame]');
function closePreview() {
if (!previewModal) {
return;
}
previewModal.hidden = true;
if (previewImage) {
previewImage.removeAttribute('src');
previewImage.hidden = true;
}
if (previewFrame) {
previewFrame.src = 'about:blank';
previewFrame.hidden = true;
}
}
function openPreview(trigger) {
if (!previewModal || !previewImage || !previewFrame) {
return;
}
var kind = trigger.dataset.previewKind === 'pdf' ? 'pdf' : 'image';
previewTitle.textContent = trigger.dataset.previewTitle || '发票预览';
previewImage.hidden = kind !== 'image';
previewFrame.hidden = kind !== 'pdf';
if (kind === 'pdf') {
previewFrame.src = trigger.dataset.previewUrl;
} else {
previewImage.src = trigger.dataset.previewUrl;
}
previewModal.hidden = false;
var closeButton = previewModal.querySelector('[data-invoice-preview-close]');
if (closeButton) {
closeButton.focus();
}
}
root.querySelectorAll('[data-invoice-preview]').forEach(function (trigger) {
trigger.addEventListener('click', function () {
openPreview(trigger);
});
});
if (previewModal) {
previewModal.querySelectorAll('[data-invoice-preview-close]').forEach(function (button) {
button.addEventListener('click', closePreview);
});
previewModal.addEventListener('click', function (event) {
if (event.target === previewModal) {
closePreview();
}
});
document.addEventListener('keydown', function (event) {
if (event.key === 'Escape' && !previewModal.hidden) {
closePreview();
}
});
}
function selectTab(view, updateUrl) {
tabs.forEach(function (tab) {

View File

@ -113,13 +113,15 @@ class InvoiceDataPageTest extends FeatureTestCase
'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_file_id' => 'FILE-1',
'source_file_name' => '测试发票.pdf',
'source_file_type' => 'application/pdf',
'source_field' => null,
'source_path' => null,
'source_hash' => null,
'ocr_provider' => 'test',
'preview_path' => null,
'preview_mime' => null,
'recognition_payload' => null,
'created_at' => $now,
'updated_at' => $now,
@ -154,6 +156,8 @@ class InvoiceDataPageTest extends FeatureTestCase
->assertSee('10月办公用品报销')
->assertSee('26320000000000000001')
->assertSee('测试供应商')
->assertSee('data-invoice-preview', false)
->assertSee('data-invoice-preview-modal', false)
->assertSee('*办公用品*打印纸')
->assertSee('2026-10-10')
->assertSee('FLOW-NO-INVOICE')
@ -346,6 +350,32 @@ class InvoiceDataPageTest extends FeatureTestCase
}
}
public function test_invoice_attachment_preview_is_served_inline(): void
{
Storage::fake('uploads');
Storage::disk('uploads')->put(
'invoice-previews/aa/preview.pdf',
"%PDF-1.4\npreview",
);
$invoiceId = (int) DB::connection('business_mirror')
->table('ding_invoice_record_mirror')
->value('id');
DB::connection('business_mirror')->table('ding_invoice_record_mirror')
->where('id', $invoiceId)
->update([
'preview_path' => 'invoice-previews/aa/preview.pdf',
'preview_mime' => 'application/pdf',
]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.invoice-data.attachment', ['invoice' => $invoiceId]))
->assertOk()
->assertHeader('Content-Type', 'application/pdf')
->assertHeader('X-Content-Type-Options', 'nosniff');
}
public function test_refresh_endpoint_queues_selected_month(): void
{
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
@ -532,6 +562,8 @@ class InvoiceDataPageTest extends FeatureTestCase
$table->string('source_path')->nullable();
$table->string('source_hash')->nullable();
$table->string('ocr_provider')->nullable();
$table->string('preview_path', 1024)->nullable();
$table->string('preview_mime')->nullable();
$table->json('recognition_payload')->nullable();
$table->timestamps();
});