CaiWuXiTong/modules/EcommerceFinance/Services/DingInvoiceTextParser.php
yueyang cc204fbb97 feat(发票数据): 自动增量抓取并补入OA发票 (#1496)
自动识别 PDF、图片、XLS/XLSX、ZIP、RAR、7Z 发票附件,每 15 分钟补扫未处理、失败和部分识别流程。
2026-11-27 10:44:37 +08:00

190 lines
6.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace Modules\EcommerceFinance\Services;
use Illuminate\Support\Carbon;
use Throwable;
class DingInvoiceTextParser
{
/** @return array<string,mixed>|null */
public function parse(string $text): ?array
{
$text = trim(str_replace(["\r\n", "\r", "\u{3000}"], ["\n", "\n", ' '], $text));
if ($text === '') {
return null;
}
if (class_exists(\Normalizer::class)) {
$text = \Normalizer::normalize($text, \Normalizer::FORM_KC) ?: $text;
}
$text = preg_replace('/(?<=\d)\.\s+(?=\d{2})/u', '.', $text) ?? $text;
$invoiceNumber = $this->invoiceNumber($text);
$invoiceTotal = $this->invoiceTotal($text);
if ($invoiceNumber === ''
|| $invoiceTotal <= 0
|| ! in_array(strlen($invoiceNumber), [8, 20], true)) {
return null;
}
$taxNumbers = [];
$taxPatterns = [
'/(?:统一社会信用代码|纳税人识别号|税号)[^\nA-Z0-9]{0,16}([0-9A-Z]{15,20})/u',
'/(?<![0-9A-Z])([0-9A-Z]{18})(?![0-9A-Z])/u',
];
foreach ($taxPatterns as $pattern) {
if (preg_match_all($pattern, $text, $matches)) {
foreach ($matches[1] as $value) {
$taxNumbers[] = strtoupper($value);
}
}
if ($taxNumbers !== []) {
break;
}
}
$taxNumbers = array_values(array_unique($taxNumbers));
$names = [];
$segments = preg_split('/(?<!项目)名称\s*[::]/u', $text) ?: [];
foreach (array_slice($segments, 1) as $segment) {
$value = preg_split(
'/(?:\n|统一社会信用代码|纳税人识别号|税号)/u',
$segment,
2,
)[0] ?? '';
$value = preg_replace('/\s*\|.*$/u', '', $value) ?? $value;
$value = preg_replace('/\s+(?:SS|FS|OS|S)\s*$/u', '', $value) ?? $value;
$value = trim((string) preg_replace('/\s+/u', '', $value));
if ($value !== '' && mb_strlen($value) <= 120) {
$names[] = $value;
}
}
$names = array_values(array_unique($names));
$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;
}
}
if ($invoiceDate === null
&& preg_match('/(?<!\d)(20\d{2})[年\-\/](\d{1,2})[月\-\/](\d{1,2})(?!\d)/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] ?? '',
'seller_tax_no' => $taxNumbers[1] ?? '',
'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
{
foreach ([
'/发票号码\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u',
'/发[买米来][号玛码]?\s*[::]?\s*([0-9A-Z][0-9A-Z ::]{7,40})/u',
'/(?<!\\d)([0-9]{20})(?!\\d)/u',
] as $pattern) {
if (preg_match($pattern, $text, $matches)) {
$number = strtoupper((string) preg_replace(
'/[^0-9A-Z]/',
'',
$matches[1],
));
if (strlen($number) >= 8) {
return $number;
}
}
}
if ((str_contains($text, '发票号码') || str_contains($text, '定额发票'))
&& preg_match('/(?<!\\d)([0-9]{8})(?!\\d)/u', $text, $matches)) {
return $matches[1];
}
return '';
}
private function invoiceTotal(string $text): float
{
foreach ([
'/(?:\(小写\)|(小写))\s*[::]?\s*[^\n0-9]{0,4}([0-9][0-9,]*\.[0-9]{2})/u',
'/[零壹贰叁肆伍陆柒捌玖拾佰仟万圆元角分整]{4,}\s*[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
'/票价\s*[::]?\s*[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
'/(?:价税合计|合计)[^\n]{0,25}[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u',
] as $pattern) {
if (preg_match_all($pattern, $text, $matches) && $matches[1] !== []) {
$values = array_map(
static fn (string $value): float =>
round((float) str_replace(',', '', $value), 2),
$matches[1],
);
return max($values);
}
}
if (str_contains($text, '发票')
&& preg_match_all('/[¥¥]\s*([0-9][0-9,]*\.[0-9]{2})/u', $text, $matches)
&& $matches[1] !== []) {
return max(array_map(
static fn (string $value): float =>
round((float) str_replace(',', '', $value), 2),
$matches[1],
));
}
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 '其他';
}
}