供应商合同管理支持导出原件 #1401
@ -24,16 +24,7 @@ class CourierContractPageData
|
||||
|
||||
public function page(bool $includeRows = true, string $partnerType = 'courier'): array
|
||||
{
|
||||
$search = mb_substr(trim((string) request()->query('contract_search', '')), 0, 255);
|
||||
$status = (string) request()->query('contract_status', '');
|
||||
$status = array_key_exists($status, self::STATUSES) ? $status : '';
|
||||
$from = $this->date(request()->query('contract_end_from'));
|
||||
$to = $this->date(request()->query('contract_end_to'));
|
||||
if ($from && $to && $from > $to) {
|
||||
[$from, $to] = [$to, $from];
|
||||
}
|
||||
$filters = ['contract_search' => $search, 'contract_status' => $status,
|
||||
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
|
||||
$filters = $this->filters();
|
||||
$limit = min(max((int) setting('default.list_limit', 25), 1), 100);
|
||||
$page = max((int) request()->query('page', 1), 1);
|
||||
$options = ['path' => request()->url(), 'query' => request()->except('page')];
|
||||
@ -52,39 +43,14 @@ class CourierContractPageData
|
||||
}
|
||||
|
||||
$matched = [];
|
||||
$today = Carbon::today(config('app.timezone'));
|
||||
// Dates and partner types are encrypted. Stream bounded chunks instead of SQL JSON queries
|
||||
// or persisting a second, potentially stale copy of the signed business snapshot.
|
||||
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
|
||||
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
|
||||
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
|
||||
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
|
||||
->lazyById(250);
|
||||
foreach ($signatures as $signature) {
|
||||
$payload = $signature->archivedContractPayload($partnerType);
|
||||
if ($payload === null) {
|
||||
try {
|
||||
$signature->payload;
|
||||
} catch (Throwable) {
|
||||
$data['courierContractUnreadable']++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$row = $this->snapshot($signature, $payload, $today);
|
||||
$recordUnreadable = static function () use (&$data): void {
|
||||
$data['courierContractUnreadable']++;
|
||||
};
|
||||
foreach ($this->contractRows($partnerType, $recordUnreadable) as $row) {
|
||||
$data['courierContractCounts'][$row['status']]++;
|
||||
if (! $includeRows || ($status !== '' && $status !== $row['status'])) {
|
||||
continue;
|
||||
if ($includeRows && $this->matchesFilters($row, $filters)) {
|
||||
$matched[] = $row;
|
||||
}
|
||||
if (($from && (! $row['end_date'] || $row['end_date'] < $from))
|
||||
|| ($to && (! $row['end_date'] || $row['end_date'] > $to))) {
|
||||
continue;
|
||||
}
|
||||
if ($search !== '' && ! str_contains(mb_strtolower(implode(' ', [
|
||||
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
|
||||
])), mb_strtolower($search))) {
|
||||
continue;
|
||||
}
|
||||
$matched[] = $row;
|
||||
}
|
||||
if ($includeRows) {
|
||||
$priority = ['due' => 0, 'expired' => 1, 'unknown' => 2, 'active' => 3, 'upcoming' => 4];
|
||||
@ -113,6 +79,71 @@ class CourierContractPageData
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function supplierExportRows(): iterable
|
||||
{
|
||||
$filters = $this->filters();
|
||||
foreach ($this->contractRows('supplier') as $row) {
|
||||
if ($this->matchesFilters($row, $filters)) {
|
||||
yield $row;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function filters(): array
|
||||
{
|
||||
$search = request()->query('contract_search');
|
||||
$search = is_string($search) ? mb_substr(trim($search), 0, 255) : '';
|
||||
$status = request()->query('contract_status');
|
||||
$status = is_string($status) && array_key_exists($status, self::STATUSES) ? $status : '';
|
||||
$from = $this->date(request()->query('contract_end_from'));
|
||||
$to = $this->date(request()->query('contract_end_to'));
|
||||
if ($from && $to && $from > $to) {
|
||||
[$from, $to] = [$to, $from];
|
||||
}
|
||||
return ['contract_search' => $search, 'contract_status' => $status,
|
||||
'contract_end_from' => $from ?? '', 'contract_end_to' => $to ?? ''];
|
||||
}
|
||||
|
||||
private function matchesFilters(array $row, array $filters): bool
|
||||
{
|
||||
$status = $filters['contract_status'];
|
||||
$from = $filters['contract_end_from'];
|
||||
$to = $filters['contract_end_to'];
|
||||
if (($status !== '' && $status !== $row['status'])
|
||||
|| ($from !== '' && (! $row['end_date'] || $row['end_date'] < $from))
|
||||
|| ($to !== '' && (! $row['end_date'] || $row['end_date'] > $to))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$search = $filters['contract_search'];
|
||||
return $search === '' || str_contains(mb_strtolower(implode(' ', [
|
||||
$row['courier_name'], $row['number'], $row['business_no'], $row['party_a'], $row['party_b'],
|
||||
])), mb_strtolower($search));
|
||||
}
|
||||
|
||||
private function contractRows(string $partnerType, ?callable $recordUnreadable = null): iterable
|
||||
{
|
||||
$today = Carbon::today(config('app.timezone'));
|
||||
// The dates and partner type live in encrypted snapshots.
|
||||
$signatures = CourierAgreementSignature::query()->where('company_id', (int) company_id())
|
||||
->where('document_type', 'cooperation-contract')->where('status', CourierAgreementSignature::STATUS_ARCHIVED)
|
||||
->select(['id', 'company_id', 'business_no', 'courier_name', 'payload', 'document_type', 'status',
|
||||
'signed_pdf_path', 'certificate_path', 'archived_at', 'created_by', 'created_at'])
|
||||
->lazyById(250);
|
||||
foreach ($signatures as $signature) {
|
||||
$payload = $signature->archivedContractPayload($partnerType);
|
||||
if ($payload !== null) {
|
||||
yield $this->snapshot($signature, $payload, $today);
|
||||
} elseif ($recordUnreadable !== null) {
|
||||
try {
|
||||
$signature->payload;
|
||||
} catch (Throwable) {
|
||||
$recordUnreadable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function snapshot(CourierAgreementSignature $signature, array $payload, Carbon $today): array
|
||||
{
|
||||
$start = $this->date($payload['cooperation_start_date'] ?? null);
|
||||
|
||||
65
app/Http/Controllers/Business/SupplierContractExport.php
Normal file
65
app/Http/Controllers/Business/SupplierContractExport.php
Normal file
@ -0,0 +1,65 @@
|
||||
<?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 SupplierContractExport
|
||||
{
|
||||
public function download(CourierContractPageData $contracts): StreamedResponse
|
||||
{
|
||||
$manifest = tmpfile();
|
||||
abort_unless($manifest, 500, '无法创建供应商合同清单。');
|
||||
|
||||
return response()->streamDownload(static function () use ($contracts, $manifest): void {
|
||||
$zip = new ZipStream(defaultCompressionMethod: CompressionMethod::STORE, sendHttpHeaders: false);
|
||||
$disk = Storage::disk('uploads');
|
||||
try {
|
||||
fwrite($manifest, "\xEF\xBB\xBF");
|
||||
fputcsv($manifest, ['供应商', '期限状态', '合同编号', '开始日期', '结束日期', '距到期天数',
|
||||
'甲方签署主体', '乙方签署主体', '签署单号', '签署原件'], ',', '"', '');
|
||||
foreach ($contracts->supplierExportRows() 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 = 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;
|
||||
}, [
|
||||
$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,
|
||||
]);
|
||||
fputcsv($manifest, $values, ',', '"', '');
|
||||
}
|
||||
|
||||
rewind($manifest);
|
||||
$zip->addFileFromStream('供应商合同清单.csv', $manifest);
|
||||
$zip->finish();
|
||||
} finally {
|
||||
fclose($manifest);
|
||||
}
|
||||
}, '供应商合作合同-' . now()->format('Ymd-His') . '.zip', [
|
||||
'Content-Type' => 'application/zip', 'Cache-Control' => 'private, no-store',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@ -22,6 +22,8 @@
|
||||
</div>
|
||||
<div class="supplier-management-actions">
|
||||
<button type="submit" class="supplier-management-button is-primary">查询</button>
|
||||
<button type="submit" class="supplier-management-button" data-supplier-contract-export
|
||||
title="按当前筛选导出合同清单和已签署 PDF" formaction="{{ route('business.supplier-contracts.export') }}">导出合同</button>
|
||||
<a href="{{ $contractUrl() }}" class="supplier-management-button" data-supplier-local>重置</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@ -335,7 +335,7 @@
|
||||
});
|
||||
document.addEventListener('submit', event => {
|
||||
const form = event.target.closest('[data-supplier-query]');
|
||||
if (!form) return;
|
||||
if (!form || event.submitter?.hasAttribute('data-supplier-contract-export')) return;
|
||||
event.preventDefault();
|
||||
load(form.action + '?' + new URLSearchParams(new FormData(form)).toString());
|
||||
});
|
||||
|
||||
@ -258,6 +258,10 @@ Route::get('workspace/supplier-payables/supplier-management/contracts/{agreement
|
||||
->middleware('business.page:supplier-payables,supplier-management')
|
||||
->name('business.supplier-contracts.download');
|
||||
|
||||
Route::get('workspace/supplier-payables/supplier-management/contracts/export', [\App\Http\Controllers\Business\SupplierContractExport::class, 'download'])
|
||||
->middleware('business.page:supplier-payables,supplier-management')
|
||||
->name('business.supplier-contracts.export');
|
||||
|
||||
Route::get('workspace/product-inventory/normal-products/export', 'Business\Pages@exportNormalProducts')
|
||||
->middleware('business.page:product-inventory,normal-products')
|
||||
->name('business.product-inventory.normal-products.export');
|
||||
|
||||
@ -206,6 +206,55 @@ class CourierContractManagementTest extends FeatureTestCase
|
||||
$this->getJson($fileUrl($today), ['X-Requested-With' => 'XMLHttpRequest'])->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_supplier_export_includes_filtered_contracts_across_pages_and_their_signed_originals(): void
|
||||
{
|
||||
$supplier = ['partner_type' => 'supplier'];
|
||||
$first = $this->signature('批量导出供应商', $supplier);
|
||||
$pdf = '%PDF-1.4 ' . str_repeat('a', 1024 * 1024);
|
||||
Storage::disk('uploads')->put($first->signed_pdf_path, $pdf);
|
||||
for ($i = 0; $i < 60; $i++) {
|
||||
$last = $this->signature('批量导出供应商', $supplier);
|
||||
}
|
||||
Storage::disk('uploads')->delete($last->signed_pdf_path);
|
||||
$expired = $this->signature('批量导出供应商', $supplier + ['cooperation_end_date' => '2026-10-14']);
|
||||
$otherCompany = $this->signature('批量导出供应商', $supplier, ['company_id' => $this->company->id + 10]);
|
||||
$courier = $this->signature('批量导出供应商');
|
||||
$otherSupplier = $this->signature('排除此供应商', $supplier);
|
||||
|
||||
$this->loginAs();
|
||||
$url = route('business.supplier-contracts.export', [
|
||||
'contract_status' => 'due', 'contract_search' => '批量导出', 'page' => 2,
|
||||
]);
|
||||
$this->get(route('business.pages.show', [
|
||||
'section' => 'supplier-payables', 'page' => 'supplier-management', 'supplier_view' => 'contracts',
|
||||
]))->assertOk()->assertSeeText('导出合同');
|
||||
$response = $this->get($url)->assertOk()->assertHeader('content-type', 'application/zip');
|
||||
$zipFile = tmpfile();
|
||||
fwrite($zipFile, $response->streamedContent());
|
||||
$zip = new \ZipArchive();
|
||||
$this->assertTrue($zip->open(stream_get_meta_data($zipFile)['uri']));
|
||||
try {
|
||||
$manifest = $zip->getFromName('供应商合同清单.csv');
|
||||
$this->assertSame(61, substr_count($manifest, '批量导出供应商'));
|
||||
$this->assertSame(hash('sha256', $pdf), hash('sha256', $zip->getFromName("签署原件/合同-{$first->id}.pdf")));
|
||||
$this->assertStringContainsString($last->business_no . ',归档附件缺失', $manifest);
|
||||
foreach ([$expired, $otherCompany, $courier, $otherSupplier] as $excluded) {
|
||||
$this->assertStringNotContainsString($excluded->business_no, $manifest);
|
||||
}
|
||||
} finally {
|
||||
$zip->close();
|
||||
fclose($zipFile);
|
||||
}
|
||||
|
||||
$this->user->syncRoles([\App\Models\Auth\Role::where('name', 'user')->firstOrFail()->id]);
|
||||
setting()->set('system.sidebar_permissions', json_encode([
|
||||
'configured' => ['user_' . $this->user->id],
|
||||
'subjects' => ['user_' . $this->user->id => ['courier-payables/courier-information']],
|
||||
]));
|
||||
setting()->save();
|
||||
$this->withExceptionHandling()->getJson($url, ['X-Requested-With' => 'XMLHttpRequest'])->assertForbidden();
|
||||
}
|
||||
|
||||
private function page(array $query = [])
|
||||
{
|
||||
return $this->loginAs()->get(route('business.pages.show', ['section' => 'courier-payables',
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user