> $invoices * @return list> */ public function deduplicate(array $invoices): array { $unique = []; foreach ($invoices as $invoice) { $key = $this->invoiceKey($invoice); $unique[$key] = isset($unique[$key]) ? $this->mergeMissing($unique[$key], $invoice) : $invoice; } return array_values($unique); } /** @param array $invoice */ public function invoiceKey(array $invoice): string { $number = $this->invoiceNumber($invoice); if ($number !== '') { return hash('sha256', 'number:' . $number); } return hash('sha256', implode('|', [ 'fallback', mb_strtolower($this->text($invoice['seller_name'] ?? '')), number_format((float) ($invoice['invoice_total'] ?? 0), 2, '.', ''), $this->text($invoice['invoice_date'] ?? ''), $this->text($invoice['item_name'] ?? ''), ])); } /** @param array $invoice */ public function invoiceNumber(array $invoice): string { return mb_strtoupper((string) preg_replace( '/[^0-9A-Za-z]/', '', $this->text($invoice['invoice_number'] ?? ''), )); } /** * @param array $existing * @param array $incoming * @return array */ public function mergeScanned(array $existing, array $incoming): array { $provider = (string) ($existing['ocr_provider'] ?? ''); if (str_starts_with($provider, 'imported_workbook')) { $merged = $existing; foreach ([ 'invoice_type', 'seller_name', 'seller_tax_no', 'buyer_name', 'buyer_tax_no', 'invoice_total', 'invoice_number', 'invoice_date', 'item_name', 'amount_without_tax', 'tax_rate', 'tax_amount', ] as $field) { if ($this->empty($merged[$field] ?? null) && ! $this->empty($incoming[$field] ?? null)) { $merged[$field] = $incoming[$field]; } } foreach ([ 'process_instance_id', 'source_file_id', 'source_file_name', 'source_file_type', 'source_field', 'source_path', 'source_hash', ] as $field) { if (! $this->empty($incoming[$field] ?? null)) { $merged[$field] = $incoming[$field]; } } $merged['updated_at'] = $incoming['updated_at']; return $merged; } $merged = $existing; foreach ($incoming as $field => $value) { if (in_array($field, ['id', 'created_at'], true)) { continue; } if ($field === 'invoice_total' && (float) $value <= 0) { continue; } if (! $this->empty($value)) { $merged[$field] = $value; } } return $merged; } /** * @param array $left * @param array $right * @return array */ private function mergeMissing(array $left, array $right): array { foreach ($right as $key => $value) { if ($this->empty($left[$key] ?? null) && ! $this->empty($value)) { $left[$key] = $value; } } return $left; } private function empty(mixed $value): bool { return $value === null || (is_string($value) && trim($value) === '') || (is_array($value) && $value === []); } private function text(mixed $value): string { return trim((string) ($value ?? '')); } }