fix(发票数据): 修复表格附件发票预览回填 (#1519)

This commit is contained in:
yueyang 2026-11-27 16:33:32 +08:00
parent e0a3b8fd1f
commit 414d4fd3ee
5 changed files with 286 additions and 27 deletions

View File

@ -157,6 +157,8 @@ class InvoiceData extends Controller
$name = trim((string) ($invoiceRow->source_file_name ?? ''));
if ($name === '') {
$name = 'invoice-preview.' . $preview['extension'];
} elseif (strtolower((string) pathinfo($name, PATHINFO_EXTENSION)) !== $preview['extension']) {
$name = pathinfo($name, PATHINFO_FILENAME) . '.' . $preview['extension'];
}
return $disk->response($preview['path'], basename($name), [

View File

@ -12,6 +12,7 @@ class DingInvoiceFileRecognizer
public function __construct(
private readonly DingInvoiceTextParser $textParser,
private readonly DingInvoiceVisionClient $vision,
private readonly DingInvoicePreviewStore $previewStore,
) {}
/**
@ -270,38 +271,26 @@ class DingInvoiceFileRecognizer
'provider' => '',
];
}
$outputDir = $tempDir . '/xls-pdf';
if (! is_dir($outputDir) && ! mkdir($outputDir, 0755, true) && ! is_dir($outputDir)) {
throw new RuntimeException('无法创建 XLS 转换临时目录。');
}
$process = new Process([
$binary,
'--headless',
'--convert-to',
'pdf',
'--outdir',
$outputDir,
$path,
]);
$process->setTimeout(180);
$process->run();
$pdf = $outputDir . '/' . pathinfo($path, PATHINFO_FILENAME) . '.pdf';
if (! $process->isSuccessful() || ! is_file($pdf)) {
$converted = $this->convertOfficeFileToPdf($binary, $path, $tempDir);
if ($converted === null) {
return [
'invoices' => [],
'errors' => [
trim($process->getErrorOutput())
?: 'XLS 转换为 PDF 失败。',
],
'errors' => ['XLS 转换为 PDF 失败。'],
'provider' => 'libreoffice',
];
}
$pdf = $converted['path'];
$result = $this->recognizePdf($pdf, $outputDir);
$result = $this->recognizePdf($pdf, $converted['output_dir']);
$result['provider'] = $this->joinProviders([
'libreoffice',
$result['provider'],
]);
$preview = $this->persistPreview($pdf, 'converted-invoice.pdf');
if ($preview !== null) {
$result['previews'] = [$preview];
$result['invoices'] = $this->attachPreviewToInvoices($result['invoices'], $preview);
}
return $result;
}
@ -361,6 +350,7 @@ class DingInvoiceFileRecognizer
$invoices = [];
$errors = [];
$previews = [];
if (! $process->isSuccessful()) {
$errors[] = trim($process->getErrorOutput())
?: '压缩附件部分文件解压失败。';
@ -394,6 +384,18 @@ class DingInvoiceFileRecognizer
}
try {
$result = $this->recognize($item->getPathname(), $item->getFilename());
$preview = $this->persistPreview($item->getPathname(), $item->getFilename());
if ($preview !== null) {
if (($result['previews'] ?? []) === []) {
$result['previews'] = [$preview];
}
if (($result['invoices'] ?? []) !== []) {
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...array_map(
static fn (string $error): string =>
@ -401,6 +403,7 @@ class DingInvoiceFileRecognizer
$result['errors'],
));
$providers[] = $result['provider'];
array_push($previews, ...($result['previews'] ?? []));
} catch (Throwable $exception) {
$errors[] = $item->getFilename() . ':' . $exception->getMessage();
}
@ -410,6 +413,7 @@ class DingInvoiceFileRecognizer
'invoices' => $invoices,
'errors' => $errors,
'provider' => $this->joinProviders($providers),
'previews' => $previews,
];
}
@ -431,6 +435,7 @@ class DingInvoiceFileRecognizer
$invoices = [];
$errors = [];
$previews = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
@ -451,6 +456,14 @@ class DingInvoiceFileRecognizer
try {
$result = $this->recognizeImage($target);
$preview = $this->persistPreview($target, basename($name));
if ($preview !== null) {
$previews[] = $preview;
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
} catch (Throwable $exception) {
@ -461,10 +474,47 @@ class DingInvoiceFileRecognizer
$zip->close();
}
return [
$result = [
'invoices' => $invoices,
'errors' => $errors,
'provider' => 'xlsx_media',
'previews' => $previews,
];
if ($invoices !== []) {
return $result;
}
$binary = (string) config(
'ding_invoice_data.libreoffice_binary',
'/usr/bin/libreoffice',
);
if (! is_executable($binary)) {
return $result;
}
$converted = $this->convertOfficeFileToPdf($binary, $path, $tempDir);
if ($converted === null) {
return $result;
}
$pdfResult = $this->recognizePdf($converted['path'], $converted['output_dir']);
$preview = $this->persistPreview($converted['path'], 'converted-invoice.pdf');
if ($preview !== null) {
$pdfResult['previews'] = [$preview];
$pdfResult['invoices'] = $this->attachPreviewToInvoices(
$pdfResult['invoices'],
$preview,
);
$previews[] = $preview;
}
return [
'invoices' => $pdfResult['invoices'],
'errors' => [...$errors, ...$pdfResult['errors']],
'provider' => $this->joinProviders([
'xlsx_media',
'libreoffice',
$pdfResult['provider'],
]),
'previews' => $previews,
];
}
@ -478,6 +528,7 @@ class DingInvoiceFileRecognizer
$invoices = [];
$errors = [];
$previews = [];
try {
for ($index = 0; $index < $zip->numFiles; $index++) {
$name = (string) $zip->getNameIndex($index);
@ -495,8 +546,21 @@ class DingInvoiceFileRecognizer
try {
$result = $this->recognize($target, $name);
$preview = $this->persistPreview($target, basename($name));
if ($preview !== null) {
if (($result['previews'] ?? []) === []) {
$result['previews'] = [$preview];
}
if (($result['invoices'] ?? []) !== []) {
$result['invoices'] = $this->attachPreviewToInvoices(
$result['invoices'],
$preview,
);
}
}
array_push($invoices, ...$result['invoices']);
array_push($errors, ...$result['errors']);
array_push($previews, ...($result['previews'] ?? []));
} catch (Throwable $exception) {
$errors[] = $name . ':' . $exception->getMessage();
}
@ -505,7 +569,91 @@ class DingInvoiceFileRecognizer
$zip->close();
}
return ['invoices' => $invoices, 'errors' => $errors, 'provider' => 'zip'];
return [
'invoices' => $invoices,
'errors' => $errors,
'provider' => 'zip',
'previews' => $previews,
];
}
/**
* @param list<array<string,mixed>> $invoices
* @param array{path:string,mime:string,extension:string} $preview
* @return list<array<string,mixed>>
*/
private function attachPreviewToInvoices(array $invoices, array $preview): array
{
foreach ($invoices as &$invoice) {
$invoice['_preview'] = $preview;
}
return $invoices;
}
/** @return array{path:string,mime:string,extension:string}|null */
private function persistPreview(string $path, string $fileName): ?array
{
try {
return $this->previewStore->persistLocalFile(
$path,
[
'file_name' => $fileName,
'file_type' => strtolower(pathinfo($fileName, PATHINFO_EXTENSION)),
],
hash_file('sha256', $path) ?: null,
);
} catch (Throwable $exception) {
report($exception);
return null;
}
}
/** @return array{path:string,output_dir:string}|null */
private function convertOfficeFileToPdf(
string $binary,
string $path,
string $tempDir,
): ?array {
$outputDir = $tempDir . '/office-pdf';
$profileDir = $tempDir . '/libreoffice-profile';
foreach ([
$outputDir,
$profileDir,
$tempDir . '/cache',
$tempDir . '/config',
] as $directory) {
if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) {
throw new RuntimeException('无法创建 Office 转换临时目录。');
}
}
$process = new Process([
$binary,
'--headless',
'--nologo',
'--nodefault',
'--nofirststartwizard',
'-env:UserInstallation=file://' . $profileDir,
'--convert-to',
'pdf',
'--outdir',
$outputDir,
$path,
]);
$process->setEnv([
'HOME' => $tempDir,
'TMPDIR' => $tempDir,
'XDG_CACHE_HOME' => $tempDir . '/cache',
'XDG_CONFIG_HOME' => $tempDir . '/config',
]);
$process->setTimeout(180);
$process->run();
$pdf = $outputDir . '/' . pathinfo($path, PATHINFO_FILENAME) . '.pdf';
return $process->isSuccessful() && is_file($pdf)
? ['path' => $pdf, 'output_dir' => $outputDir]
: null;
}
private function pdfText(string $path): string

View File

@ -533,6 +533,7 @@ class DingInvoiceSyncService
$invoices = [];
$errors = [];
$scannedFiles = 0;
$flowPreviewFallbacks = [];
foreach ($files as $index => $file) {
if ((int) ($file['file_size'] ?? 0) > (int) config('ding_invoice_data.max_file_bytes')) {
@ -587,7 +588,36 @@ class DingInvoiceSyncService
report($exception);
}
$recognized = $this->recognizer->recognize($path, $file['file_name']);
if ($preview !== null && ($recognized['invoices'] ?? []) !== []) {
$flowPreviewFallbacks[$preview['path']] = [
'preview_path' => $preview['path'],
'preview_mime' => $preview['mime'],
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach (($recognized['previews'] ?? []) as $derivedPreview) {
if (! is_array($derivedPreview) || empty($derivedPreview['path'])) {
continue;
}
$flowPreviewFallbacks[$derivedPreview['path']] = [
'preview_path' => $derivedPreview['path'],
'preview_mime' => $derivedPreview['mime'] ?? null,
'source_file_id' => $file['file_id'],
'source_file_name' => $file['file_name'],
'source_file_type' => $extension ?: $file['file_type'],
'source_field' => $file['source_field'],
'source_path' => 'dingtalk:' . $processInstanceId . '/' . $file['file_id'],
'source_hash' => $hash,
];
}
foreach ($recognized['invoices'] as $invoice) {
$invoicePreview = $invoice['_preview'] ?? $preview;
unset($invoice['_preview']);
$invoice['_source'] = [
'file_id' => $file['file_id'],
'file_name' => $file['file_name'],
@ -596,8 +626,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,
'preview_path' => $invoicePreview['path'] ?? null,
'preview_mime' => $invoicePreview['mime'] ?? null,
];
$invoices[] = $invoice;
}
@ -646,6 +676,7 @@ class DingInvoiceSyncService
$businessId,
$processInstanceId,
$existingRows,
$flowPreviewFallbacks,
&$invoiceCount,
&$invoiceTotal,
&$preservedInvoices,
@ -709,6 +740,28 @@ class DingInvoiceSyncService
if ($newRecords !== []) {
$this->connection->table('ding_invoice_record_mirror')->insert($newRecords);
}
if (count($flowPreviewFallbacks) === 1) {
$fallback = reset($flowPreviewFallbacks);
foreach ($remainingExisting as $existing) {
if (! str_starts_with((string) ($existing['ocr_provider'] ?? ''), 'imported_workbook')
|| ! empty($existing['preview_path'])) {
continue;
}
$this->connection->table('ding_invoice_record_mirror')
->where('id', (int) $existing['id'])
->update([
'source_file_id' => $fallback['source_file_id'],
'source_file_name' => $fallback['source_file_name'],
'source_file_type' => $fallback['source_file_type'],
'source_field' => $fallback['source_field'],
'source_path' => mb_substr((string) $fallback['source_path'], 0, 1024),
'source_hash' => $fallback['source_hash'],
'preview_path' => $fallback['preview_path'],
'preview_mime' => $fallback['preview_mime'],
'updated_at' => $now,
]);
}
}
$persistedRows = $this->connection->table('ding_invoice_record_mirror')
->where('source_scope', $scope)
->where('business_id', $businessId)

View File

@ -878,7 +878,10 @@
PATHINFO_EXTENSION,
));
$previewSourceType = strtolower((string) $row->source_file_type);
$storedPreviewMime = strtolower((string) ($row->preview_mime ?? ''));
$previewKind = match (true) {
str_contains($storedPreviewMime, 'pdf') => 'pdf',
str_starts_with($storedPreviewMime, 'image/') => 'image',
$previewExtension === 'pdf',
str_contains($previewSourceType, 'pdf') => 'pdf',
in_array($previewExtension, ['jpg', 'jpeg', 'png', 'webp', 'bmp'], true),
@ -887,6 +890,9 @@
};
$canPreview = $previewKind !== ''
&& ($row->source_file_id || $row->preview_path);
$hasSourceAttachment = trim((string) $row->source_file_id) !== ''
|| trim((string) $row->source_file_name) !== ''
|| trim((string) ($row->source_path ?? '')) !== '';
$storedImagePreview = $canPreview
&& $previewKind === 'image'
&& $row->preview_path;
@ -930,7 +936,14 @@
@endif
</button>
@else
<span class="invoice-data-secondary">仅识别字段</span>
<span
class="invoice-data-secondary"
title="{{ $hasSourceAttachment
? '原始附件已识别,但该文件格式暂不支持页内预览'
: '该发票来自工作台账导入,未保存原 OA 附件关联信息' }}"
>
{{ $hasSourceAttachment ? '原件暂不支持预览' : '原票未关联' }}
</span>
@endif
</td>
<td>
@ -1062,6 +1075,7 @@
口径:统计从 {{ $startMonth }} 开始。发票附件由服务端下载并缓存用于识别;
图片和 PDF 可在页面内预览,不再跳转钉钉临时地址。发票按打款时间归入月份,
一张发票一行,同一流程多张发票分别列示。
“原票未关联”表示该行来自早期汇总表导入,原数据没有保存 OA 附件文件信息,需要重新补扫后恢复预览。
无票流程在“按流程汇总”中保留。开票金额覆盖率可能超过 100%,表示开票金额高于本月付款,
需要按具体流程复核。
</p>

View File

@ -232,6 +232,48 @@ class InvoiceDataPageTest extends FeatureTestCase
->assertSee('/1/workspace/process-data/invoice-data', false);
}
public function test_invoice_page_previews_office_derived_pdf_and_explains_missing_source(): void
{
$connection = DB::connection('business_mirror');
$connection->table('ding_invoice_record_mirror')->update([
'source_file_name' => '报销附件.xls',
'source_file_type' => 'xls',
'preview_path' => 'invoice-previews/aa/office.pdf',
'preview_mime' => 'application/pdf',
]);
$connection->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:26320000000000000002'),
'invoice_type' => '电子发票(普通发票)',
'invoice_total' => 20.00,
'invoice_number' => '26320000000000000002',
'invoice_date' => '2026-10-11',
'source_file_id' => null,
'source_file_name' => null,
'source_file_type' => null,
'ocr_provider' => 'imported_workbook',
'preview_path' => null,
'preview_mime' => null,
'created_at' => now(),
'updated_at' => now(),
]);
$this->user->attachPermission(Permission::where('name', 'read-admin-panel')->firstOrFail());
$this->loginAs()
->get(route('business.pages.show', [
'section' => 'process-data',
'page' => 'invoice-data',
'month' => '2026-10',
]))
->assertOk()
->assertSee('data-preview-kind="pdf"', false)
->assertSee('原票未关联')
->assertDontSee('原件暂不支持预览');
}
public function test_invoice_data_page_stays_forbidden_without_oa_process_permission(): void
{
$this->user->roles()->sync([Role::where('name', 'user')->firstOrFail()->id]);