|null */ public function parse(string $text): ?array { $text = trim(str_replace(["\r\n", "\r", "\u{3000}"], ["\n", "\n", ' '], $text)); if ($text === '') { return null; } $invoiceNumber = $this->invoiceNumber($text); $invoiceTotal = $this->invoiceTotal($text); if ($invoiceNumber === '' && $invoiceTotal <= 0) { return null; } $taxNumbers = []; if (preg_match_all( '/(?:统一社会信用代码|纳税人识别号|税号)\s*[::]\s*([0-9A-Z]{15,20})/u', $text, $matches, )) { $taxNumbers = array_values(array_unique($matches[1])); } $names = []; if (preg_match_all('/名称\s*[::]\s*([^\n]{2,120})/u', $text, $matches)) { $names = array_values(array_unique(array_filter(array_map( static fn (string $value): string => trim( preg_replace('/\s{2,}.*$/u', '', $value) ?? $value, ), $matches[1], )))); } $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; } } $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] ?? ($names[0] ?? ''), 'seller_tax_no' => $taxNumbers[1] ?? ($taxNumbers[0] ?? ''), '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 { if (preg_match('/发票号码\s*[::]?\s*([0-9A-Z]{8,32})/u', $text, $matches)) { return strtoupper($matches[1]); } return ''; } private function invoiceTotal(string $text): float { $values = []; if (preg_match_all( '/(?:价税合计(?:\s*(?:\(小写\)|(小写)))?|小写)\s*[::]?\s*[¥¥]?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)/u', $text, $matches, )) { foreach ($matches[1] as $value) { $values[] = round((float) str_replace(',', '', $value), 2); } } if ($values !== []) { return max($values); } 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 '其他'; } }