CaiWuXiTong/modules/EcommerceFinance/Services/SupplierStatementWorkbookExporter.php
苏木 aea68c2d2d feat(供应商对账): 原始账单支持 Excel 导出 (#1720)
原始账单支持按厂家流式导出完整 Excel,保持模板表头并限制为财务端权限。
Co-authored-by: 苏木 <594326199@qq.com>
Co-committed-by: 苏木 <594326199@qq.com>
2026-12-04 10:01:10 +08:00

97 lines
2.9 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 App\Support\CourierBills\StreamingWorkbook;
use RuntimeException;
use Symfony\Component\HttpFoundation\StreamedResponse;
/** 财务端导出厂家最新一版上传对账单。 */
class SupplierStatementWorkbookExporter
{
private const FIELDS = [
'expressName',
'expressNo',
'purchaseNo',
'createdAt',
'supplier',
'barcode',
'skuName',
'qty',
'unitPrice',
'amount',
];
/**
* @param iterable<int,array<string,mixed>> $rows
*/
public function download(
iterable $rows,
string $supplier,
string $uploadedAt = '',
): StreamedResponse {
$safeSupplier = preg_replace('/[\\\\\\/:*?"<>|]+/u', '_', $supplier) ?: '厂家';
$timestamp = $this->fileTimestamp($uploadedAt);
$filename = $safeSupplier . '_原始账单_' . $timestamp . '.xlsx';
return response()->streamDownload(function () use ($rows): void {
$writer = new StreamingWorkbook();
$writer->row('原始账单', array_values(SupplierStatementTemplate::COLUMNS), true);
foreach ($rows as $row) {
$cells = [];
foreach (self::FIELDS as $field) {
$value = $row[$field] ?? '';
$cells[] = in_array($field, ['qty', 'unitPrice', 'amount'], true)
? $this->numberCell($value)
: trim((string) $value);
}
$writer->row('原始账单', $cells);
}
$output = fopen('php://output', 'wb');
if ($output === false) {
throw new RuntimeException('无法创建原始账单导出文件。');
}
$writer->writeTo($output);
}, $filename, [
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Cache-Control' => 'private, no-store',
]);
}
private function numberCell(mixed $value): int|float|string
{
$text = str_replace([',', ',', ' '], '', trim((string) $value));
if ($text === '') {
return '';
}
if (preg_match('/^-?\d+$/', $text) === 1) {
return (int) $text;
}
if (is_numeric($text)) {
return (float) $text;
}
return (string) $value;
}
private function fileTimestamp(string $uploadedAt): string
{
$uploadedAt = trim($uploadedAt);
if ($uploadedAt === '') {
return now('Asia/Shanghai')->format('Ymd_His');
}
try {
return \Illuminate\Support\Carbon::createFromFormat(
'Y-m-d H:i:s',
$uploadedAt,
'Asia/Shanghai',
)->format('Ymd_His');
} catch (\Throwable) {
return now('Asia/Shanghai')->format('Ymd_His');
}
}
}