CaiWuXiTong/modules/EcommerceFinance/Services/DingInvoicePreviewStore.php

207 lines
6.8 KiB
PHP

<?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
{
return $this->ensureRecordStored($invoice, 'ding_invoice_record_mirror');
}
/**
* Cache a historical raw attachment on first preview request.
*
* @return array{path:string,mime:string,extension:string}|null
*/
public function ensureAttachmentStored(object $attachment): ?array
{
return $this->ensureRecordStored($attachment, 'ding_invoice_attachment_mirror');
}
/** @return array{path:string,mime:string,extension:string}|null */
private function ensureRecordStored(object $record, string $table): ?array
{
$existingPath = trim((string) ($record->preview_path ?? ''));
$existingMime = trim((string) ($record->preview_mime ?? ''));
if ($existingPath !== ''
&& $existingMime !== ''
&& Storage::disk('uploads')->exists($existingPath)) {
return [
'path' => $existingPath,
'mime' => $existingMime,
'extension' => pathinfo($existingPath, PATHINFO_EXTENSION),
];
}
$processInstanceId = trim((string) ($record->process_instance_id ?? ''));
$fileId = trim((string) ($record->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) ($record->source_file_name ?? ''),
'file_type' => (string) ($record->source_file_type ?? ''),
],
trim((string) ($record->source_hash ?? '')),
);
if ($preview === null) {
return null;
}
$this->connection->table($table)
->where('id', (int) $record->id)
->where('source_scope', (string) $record->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;
}
}