85 lines
3.8 KiB
PHP
85 lines
3.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Business;
|
|
|
|
use App\Business\CourierContractPageData;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
use ZipStream\CompressionMethod;
|
|
use ZipStream\ZipStream;
|
|
|
|
final class ContractExport
|
|
{
|
|
public function supplier(CourierContractPageData $contracts): StreamedResponse
|
|
{
|
|
return $this->download($contracts, 'supplier', '供应商');
|
|
}
|
|
|
|
public function courier(CourierContractPageData $contracts): StreamedResponse
|
|
{
|
|
return $this->download($contracts, 'courier', '快递');
|
|
}
|
|
|
|
private function download(CourierContractPageData $contracts, string $partnerType, string $label): StreamedResponse
|
|
{
|
|
$manifest = tmpfile();
|
|
abort_unless($manifest, 500, '无法创建合同清单。');
|
|
|
|
return response()->streamDownload(static function () use ($contracts, $manifest, $partnerType, $label): void {
|
|
$zip = new ZipStream(defaultCompressionMethod: CompressionMethod::STORE, sendHttpHeaders: false);
|
|
$disk = Storage::disk('uploads');
|
|
try {
|
|
fwrite($manifest, "\xEF\xBB\xBF");
|
|
$columns = [$label, '期限状态', '合同编号', '开始日期', '结束日期', '距到期天数',
|
|
'甲方签署主体', '乙方签署主体', '签署单号', '签署原件'];
|
|
if ($partnerType === 'courier') {
|
|
$columns = [...$columns, '乙方法定代表人', '创建人', '创建时间', '归档时间'];
|
|
}
|
|
fputcsv($manifest, $columns, ',', '"', '');
|
|
foreach ($contracts->exportRows($partnerType) as $row) {
|
|
$path = $row['signed_path'];
|
|
$attachment = '归档附件缺失';
|
|
if (filled($path) && $disk->exists($path)) {
|
|
$pdf = $disk->readStream($path);
|
|
if (is_resource($pdf)) {
|
|
$attachment = '签署原件/合同-' . $row['id'] . '.pdf';
|
|
try {
|
|
$zip->addFileFromStream($attachment, $pdf);
|
|
} finally {
|
|
fclose($pdf);
|
|
}
|
|
} else {
|
|
$attachment = '归档附件读取失败';
|
|
}
|
|
}
|
|
|
|
$values = [
|
|
$row['courier_name'], CourierContractPageData::STATUSES[$row['status']], $row['number'],
|
|
$row['start_date'], $row['end_date'], $row['days'], $row['party_a'], $row['party_b'], $row['business_no'], $attachment,
|
|
];
|
|
if ($partnerType === 'courier') {
|
|
$values = [...$values, $row['legal_representative'], $row['creator'],
|
|
$row['created_at']?->format('Y-m-d H:i'), $row['archived_at']?->format('Y-m-d H:i')];
|
|
}
|
|
$values = array_map(static function ($value): string|int {
|
|
if (is_int($value)) {
|
|
return $value;
|
|
}
|
|
$value = (string) $value;
|
|
return preg_match('/^[\s\x00-\x1f]*[=+@-]|^[\t\r\n]/u', $value) ? "'" . $value : $value;
|
|
}, $values);
|
|
fputcsv($manifest, $values, ',', '"', '');
|
|
}
|
|
|
|
rewind($manifest);
|
|
$zip->addFileFromStream($label . '合同清单.csv', $manifest);
|
|
$zip->finish();
|
|
} finally {
|
|
fclose($manifest);
|
|
}
|
|
}, $label . '合作合同-' . now()->format('Ymd-His') . '.zip', [
|
|
'Content-Type' => 'application/zip', 'Cache-Control' => 'private, no-store',
|
|
]);
|
|
}
|
|
}
|