goodsFilters($request); abort_unless( $repository->syncStatus()['ready'], 503, '采购入库共享镜像尚未就绪,暂不能导出。', ); $fields = $registry->fields( PayablesFinalRegistry::SECTION_SUPPLIER, 'payment-reconciliation', ); return response()->streamDownload(function () use ($fields, $filters, $repository): void { $stream = fopen('php://output', 'w'); if ($stream === false) { throw new \RuntimeException('无法创建供应商货款明细导出文件。'); } fwrite($stream, "\xEF\xBB\xBF"); fputcsv($stream, array_map( static fn (array $field): string => (string) ($field['label'] ?? ''), $fields, )); foreach ($repository->goodsRowsForExport($filters) as $row) { $values = []; foreach ($fields as $key => $field) { $value = $row[$key] ?? ''; $values[] = ($field['type'] ?? '') === 'number' ? number_format((float) $value, 2, '.', '') : $this->textCell($value); } fputcsv($stream, $values); } fclose($stream); }, $this->filename($filters), [ 'Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store', ]); } /** @param array{date_from:string,date_to:string,keyword:string} $filters */ private function filename(array $filters): string { $from = Carbon::parse($filters['date_from'])->format('Ymd_His'); $to = $filters['date_to'] !== '' ? Carbon::parse($filters['date_to'])->format('Ymd_His') : '不限'; return '供应商货款明细_' . $from . '_' . $to . '_' . now()->format('Ymd_His') . '.csv'; } private function textCell(mixed $value): string { $text = trim((string) $value); if ($text === '') { return ''; } return preg_match('/^[=+\-@\t\r\n]/u', $text) === 1 || preg_match('/^\d{12,}$/D', $text) === 1 ? "'" . $text : $text; } }