You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

663 lines
22 KiB

3 months ago
<?php
namespace App\Services;
use App\Models\Application;
use App\Models\ApplicationFile;
use App\Models\Competition;
1 month ago
use App\Models\ReviewerScope;
3 months ago
use App\Support\ProjectCode;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
3 months ago
use Illuminate\Validation\ValidationException;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Writer\XLSX\Writer;
3 months ago
use ZipArchive;
3 months ago
class AdminApplicationExportService
{
3 months ago
public const MODE_XLSX = 'xlsx';
public const MODE_SELECTED = 'selected';
public const MODE_ALL = 'all';
3 months ago
public function partSize(): int
{
return max(1, (int) config('contest.export.part_size', 10));
}
/**
* @param array<string, mixed> $filters
*/
public function countFiltered(Competition $competition, array $filters): int
{
return $this->buildFilteredQuery($competition, $filters)->count();
}
/**
* @param array<string, mixed> $filters
*/
3 months ago
public function partCount(Competition $competition, array $filters, string $mode = self::MODE_ALL): int
3 months ago
{
3 months ago
if ($mode === self::MODE_XLSX) {
return $this->countFiltered($competition, $filters) > 0 ? 1 : 0;
}
$attachmentIds = $this->attachmentApplicationIds($competition, $filters, $mode);
if (count($attachmentIds) === 0) {
3 months ago
return 0;
}
3 months ago
return (int) ceil(count($attachmentIds) / $this->partSize());
}
public function modeIncludesAttachments(string $mode): bool
{
return in_array($mode, [self::MODE_SELECTED, self::MODE_ALL], true);
3 months ago
}
3 months ago
/**
* @param array<string, mixed> $filters
*/
3 months ago
public function assertExportable(Competition $competition, array $filters, string $mode = self::MODE_ALL): void
3 months ago
{
3 months ago
$applicationCount = $this->countFiltered($competition, $filters);
3 months ago
3 months ago
if ($applicationCount === 0) {
throw ValidationException::withMessages([
'export' => ['当前筛选条件下没有可导出的报名记录'],
]);
3 months ago
}
3 months ago
if ($mode === self::MODE_SELECTED) {
$selectedIds = $this->normalizeApplicationIds($filters['application_ids'] ?? []);
if (count($selectedIds) === 0) {
throw ValidationException::withMessages([
'application_ids' => ['请至少选择一个项目以导出附件'],
]);
}
$validCount = $this->buildFilteredQuery($competition, $filters)
->whereIn('id', $selectedIds)
->count();
if ($validCount !== count($selectedIds)) {
throw ValidationException::withMessages([
'application_ids' => ['所选项目不在当前筛选结果内或不存在'],
]);
}
}
if (! $this->modeIncludesAttachments($mode)) {
return;
}
$attachmentIds = $this->attachmentApplicationIds($competition, $filters, $mode);
3 months ago
$stats = ApplicationFile::query()
3 months ago
->whereIn('application_id', $attachmentIds)
3 months ago
->selectRaw('COUNT(*) as file_count, COALESCE(SUM(size), 0) as total_bytes')
->first();
$maxFiles = (int) config('contest.export.max_files', 5000);
$maxBytes = (int) config('contest.export.max_total_bytes', 2 * 1024 * 1024 * 1024);
$fileCount = (int) ($stats->file_count ?? 0);
$totalBytes = (int) ($stats->total_bytes ?? 0);
if ($fileCount > $maxFiles) {
throw ValidationException::withMessages([
'export' => ["附件数量过多({$fileCount} 个),超过导出上限 {$maxFiles},请缩小筛选范围"],
]);
3 months ago
}
3 months ago
if ($totalBytes > $maxBytes) {
$maxLabel = $this->formatBytes($maxBytes);
throw ValidationException::withMessages([
'export' => ["附件总体积过大({$this->formatBytes($totalBytes)}),超过导出上限 {$maxLabel},请缩小筛选范围"],
]);
}
}
3 months ago
3 months ago
/**
* @param array<string, mixed> $filters
*/
3 months ago
public function buildXlsxExportPath(Competition $competition, array $filters): string
3 months ago
{
$timeLimit = (int) config('contest.export.time_limit', 0);
if ($timeLimit >= 0) {
@set_time_limit($timeLimit);
}
3 months ago
3 months ago
$trackTitles = $competition->tracks()->pluck('title', 'track_code');
return $this->buildXlsxPathForAllFiltered($competition, $filters, $trackTitles);
}
public function buildXlsxFilename(Competition $competition): string
{
$prefix = preg_replace('/[\\\\\\/:*?"<>|]/u', '_', $competition->name) ?: '赛事';
return sprintf('%s报名信息_%s.xlsx', $prefix, now()->format('Ymd_His'));
}
/**
* @param array<string, mixed> $filters
*/
public function buildPartZipPath(Competition $competition, array $filters, int $part, string $mode = self::MODE_ALL): string
{
$timeLimit = (int) config('contest.export.time_limit', 0);
if ($timeLimit >= 0) {
@set_time_limit($timeLimit);
}
$applications = $this->applicationsForPart($competition, $filters, $part, $mode);
3 months ago
if ($applications->isEmpty()) {
throw ValidationException::withMessages([
'part' => ['导出分卷不存在或已无数据'],
]);
}
3 months ago
$trackTitles = $competition->tracks()->pluck('title', 'track_code');
3 months ago
$xlsxPath = $part === 1
? $this->buildXlsxPathForAllFiltered($competition, $filters, $trackTitles)
: null;
$tmp = tempnam(sys_get_temp_dir(), 'app_export_zip_');
if ($tmp === false) {
if ($xlsxPath !== null) {
@unlink($xlsxPath);
}
throw new \RuntimeException('无法创建 ZIP 临时文件');
}
$zipPath = $tmp.'.zip';
@unlink($tmp);
$zip = new ZipArchive;
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
if ($xlsxPath !== null) {
@unlink($xlsxPath);
}
throw new \RuntimeException('无法创建 ZIP 文件');
}
3 months ago
try {
3 months ago
if ($xlsxPath !== null) {
$zip->addFile($xlsxPath, '报名信息.xlsx');
}
3 months ago
$usedFolderNames = [];
$usedZipEntryNames = [];
3 months ago
foreach ($applications as $application) {
$this->appendApplicationFilesToZipArchive(
$zip,
$application,
$usedFolderNames,
$usedZipEntryNames,
);
}
if ($zip->close() !== true) {
throw new \RuntimeException('ZIP 文件写入失败');
}
} catch (\Throwable $e) {
$zip->close();
@unlink($zipPath);
if ($xlsxPath !== null) {
@unlink($xlsxPath);
}
throw $e;
}
if ($xlsxPath !== null) {
3 months ago
@unlink($xlsxPath);
3 months ago
}
3 months ago
return $zipPath;
}
public function buildPartFilename(Competition $competition, int $part, int $partCount): string
{
$prefix = preg_replace('/[\\\\\\/:*?"<>|]/u', '_', $competition->name) ?: '赛事';
return sprintf(
'%s报名信息导出_第%d-%d部分_%s.zip',
$prefix,
$part,
$partCount,
now()->format('Ymd_His')
);
3 months ago
}
3 months ago
3 months ago
/**
* @param array<string, mixed> $filters
* @return list<int>
*/
private function attachmentApplicationIds(Competition $competition, array $filters, string $mode): array
{
if ($mode === self::MODE_SELECTED) {
return $this->normalizeApplicationIds($filters['application_ids'] ?? []);
}
return $this->buildFilteredQuery($competition, $filters)
->orderBy('id')
->pluck('id')
->map(fn ($id) => (int) $id)
->all();
}
/**
* @param mixed $raw
* @return list<int>
*/
private function normalizeApplicationIds(mixed $raw): array
{
if (! is_array($raw)) {
return [];
}
$ids = [];
foreach ($raw as $id) {
if (is_numeric($id)) {
$ids[] = (int) $id;
}
}
return array_values(array_unique(array_filter($ids, fn (int $id) => $id > 0)));
}
3 months ago
/**
3 months ago
* @param array<string, mixed> $filters
* @return Collection<int, Application>
3 months ago
*/
3 months ago
private function applicationsForPart(Competition $competition, array $filters, int $part, string $mode): Collection
3 months ago
{
if ($part < 1) {
return collect();
}
3 months ago
3 months ago
$attachmentIds = $this->attachmentApplicationIds($competition, $filters, $mode);
if (count($attachmentIds) === 0) {
return collect();
}
3 months ago
$partSize = $this->partSize();
$offset = ($part - 1) * $partSize;
3 months ago
$ids = array_slice($attachmentIds, $offset, $partSize);
3 months ago
if (count($ids) === 0) {
return collect();
3 months ago
}
3 months ago
return Application::query()
->whereIn('id', $ids)
->with(['files'])
->orderBy('id')
->get();
3 months ago
}
/**
* @param Collection<string, string> $trackTitles
3 months ago
* @param array<string, mixed> $filters
3 months ago
*/
3 months ago
private function buildXlsxPathForAllFiltered(Competition $competition, array $filters, Collection $trackTitles): string
3 months ago
{
3 months ago
$tmp = tempnam(sys_get_temp_dir(), 'app_export_xlsx_');
if ($tmp === false) {
throw new \RuntimeException('无法创建 Excel 临时文件');
}
$xlsxPath = $tmp.'.xlsx';
@unlink($tmp);
$writer = new Writer;
$writer->openToFile($xlsxPath);
$writer->addRow(Row::fromValues([
3 months ago
'项目编号',
'状态',
'项目名称',
'负责人',
'学校',
'学历',
'手机号',
'邮箱',
'组别',
'企业名称',
'赛道',
'所在地',
'报名渠道',
3 months ago
'推荐方',
3 months ago
'项目简介',
'提交时间',
'附件数量',
1 month ago
'进程',
1 month ago
'总分',
'平均分',
1 month ago
'评分详情',
3 months ago
]));
1 month ago
$reviewersByTrack = $this->reviewersByTrackForCompetition($competition);
3 months ago
$chunkSize = max(20, (int) config('contest.export.chunk_size', 20));
$this->buildFilteredQuery($competition, $filters)
1 month ago
->with(['signupChannel', 'reviewScores.reviewer'])
3 months ago
->withCount('files')
->orderBy('id')
1 month ago
->chunkById($chunkSize, function ($applications) use ($writer, $trackTitles, $reviewersByTrack): void {
3 months ago
foreach ($applications as $app) {
1 month ago
$writer->addRow(Row::fromValues(
$this->applicationExportRow($app, $trackTitles, $reviewersByTrack)
));
3 months ago
}
}, 'id');
3 months ago
3 months ago
$writer->close();
3 months ago
return $xlsxPath;
}
3 months ago
/**
* @param array<string, true> $usedFolderNames
* @param array<string, true> $usedZipEntryNames
*/
private function appendApplicationFilesToZipArchive(
ZipArchive $zip,
Application $application,
array &$usedFolderNames,
array &$usedZipEntryNames,
): void {
$folder = $this->uniqueFolderName($application, $usedFolderNames);
$usedFolderNames[$folder] = true;
$zip->addEmptyDir($folder);
foreach ($application->files as $file) {
$absolutePath = $this->resolveFileAbsolutePath($file);
if ($absolutePath === null) {
continue;
}
$entryName = $this->uniqueFileNameInFolderTracked($folder, $file, $usedZipEntryNames);
$zip->addFile($absolutePath, $entryName);
}
}
1 month ago
/**
* 按赛道预加载评委名单(含姓名),用于导出进程与评分详情。
*
* @return Collection<string, list<array{id: int, name: string}>>
*/
private function reviewersByTrackForCompetition(Competition $competition): Collection
{
$grouped = [];
ReviewerScope::query()
->with('reviewer')
->where('competition_id', $competition->id)
->orderBy('id')
->get()
->each(function (ReviewerScope $scope) use (&$grouped): void {
$track = (string) ($scope->track_code ?? '');
if ($track === '') {
return;
}
$reviewerId = (int) $scope->reviewer_id;
$name = trim((string) ($scope->reviewer?->name ?? ''));
if ($name === '') {
$name = '评委#'.$reviewerId;
}
$grouped[$track] ??= [];
$grouped[$track][$reviewerId] = [
'id' => $reviewerId,
'name' => $name,
];
});
return collect($grouped)->map(fn (array $rows) => array_values($rows));
}
3 months ago
/**
3 months ago
* @param Collection<string, string> $trackTitles
1 month ago
* @param Collection<string, list<array{id: int, name: string}>> $reviewersByTrack
3 months ago
* @return list<scalar|null>
3 months ago
*/
1 month ago
private function applicationExportRow(Application $app, Collection $trackTitles, Collection $reviewersByTrack): array
3 months ago
{
3 months ago
$channel = $app->signupChannel
? $app->signupChannel->channel_name.''.$app->signupChannel->channel_code.''
: ($app->signup_channel_code ?: '');
1 month ago
$trackReviewers = $reviewersByTrack->get((string) ($app->track ?? '')) ?? [];
$required = count($trackReviewers);
$scoresByReviewerId = [];
if ($app->relationLoaded('reviewScores')) {
foreach ($app->reviewScores as $score) {
$scoresByReviewerId[(int) $score->reviewer_id] = $score;
}
}
$completed = count($scoresByReviewerId);
$progress = $required > 0 ? ($completed.'/'.$required) : '-';
1 month ago
$fullyCompleted = $required > 0 && $completed >= $required;
$numericScores = [];
foreach ($scoresByReviewerId as $score) {
if ($score->line_total !== null && is_numeric($score->line_total)) {
$numericScores[] = (float) $score->line_total;
}
}
$teamSum = $numericScores === [] ? null : array_sum($numericScores);
$teamAvg = $numericScores === [] ? null : ($teamSum / count($numericScores));
$totalCell = $fullyCompleted ? $this->formatExportScore($teamSum) : '待评审';
$avgCell = $fullyCompleted ? $this->formatExportScore($teamAvg) : '-';
1 month ago
$scoreDetails = collect($trackReviewers)
->map(function (array $reviewer) use ($scoresByReviewerId): string {
$name = $reviewer['name'];
$score = $scoresByReviewerId[$reviewer['id']] ?? null;
if ($score === null) {
return $name.' 未评审';
}
return $name.' '.$this->formatExportScore($score->line_total);
})
->implode('');
3 months ago
return [
ProjectCode::resolve($app),
$app->status === 'submitted' ? '已提交' : '草稿',
$app->project_name ?? '',
$app->player_name ?? '',
$app->school ?? '',
$app->degree ?? '',
$app->contact_mobile ?? '',
$app->contact_email ?? '',
$app->entry_group ?? '',
$app->company_name ?? '',
$trackTitles->get($app->track ?? '') ?? ($app->track ?? ''),
$this->formatLocation($app),
$channel,
3 months ago
$app->recommend ?? '',
3 months ago
$app->intro ?? '',
$app->submitted_at?->format('Y-m-d H:i:s') ?? '',
3 months ago
(int) ($app->files_count ?? $app->files->count()),
1 month ago
$progress,
1 month ago
$totalCell,
$avgCell,
1 month ago
$scoreDetails,
3 months ago
];
3 months ago
}
1 month ago
private function formatExportScore(mixed $value): string
{
if ($value === null || $value === '') {
return '—';
}
if (! is_numeric($value)) {
return (string) $value;
}
return rtrim(rtrim(number_format((float) $value, 2, '.', ''), '0'), '.') ?: '0';
}
3 months ago
/**
* @param array<string, mixed> $filters
*/
public function buildFilteredQuery(Competition $competition, array $filters): Builder
{
$query = Application::query()->where('competition_id', $competition->id);
$status = trim((string) ($filters['status'] ?? ''));
if ($status !== '') {
$query->where('status', $status);
}
$track = trim((string) ($filters['track'] ?? ''));
if ($track !== '') {
$query->where('track', $track);
}
2 months ago
$entryGroup = trim((string) ($filters['entry_group'] ?? ''));
if ($entryGroup !== '') {
$query->where('entry_group', $entryGroup);
}
3 months ago
$channelId = $filters['signup_channel_id'] ?? null;
if ($channelId !== null && $channelId !== '') {
$query->where('signup_channel_id', (int) $channelId);
}
$publicSourceChannelId = $filters['public_source_channel_id'] ?? null;
if ($publicSourceChannelId !== null && $publicSourceChannelId !== '') {
$query->whereHas('user', function (Builder $userQuery) use ($publicSourceChannelId): void {
$userQuery->where('public_source_channel_id', (int) $publicSourceChannelId);
});
}
3 months ago
$keyword = trim((string) ($filters['keyword'] ?? ''));
if ($keyword !== '') {
$like = '%'.str_replace(['%', '_'], ['\\%', '\\_'], $keyword).'%';
$query->where(function ($q) use ($like): void {
$q->where('player_name', 'like', $like)
->orWhere('project_name', 'like', $like)
->orWhere('school', 'like', $like)
->orWhere('contact_mobile', 'like', $like)
->orWhere('company_name', 'like', $like)
3 months ago
->orWhere('project_code', 'like', $like)
->orWhere('recommend', 'like', $like);
3 months ago
});
}
3 months ago
$reviewResult = trim((string) ($filters['review_result'] ?? ''));
if ($reviewResult === 'pending') {
$query->whereNull('review_result');
} elseif ($reviewResult !== '') {
$query->where('review_result', $reviewResult);
}
2 months ago
if (array_key_exists('review_eligible', $filters) && $filters['review_eligible'] !== null && $filters['review_eligible'] !== '') {
$query->where('review_eligible', filter_var($filters['review_eligible'], FILTER_VALIDATE_BOOLEAN));
}
3 months ago
return $query;
}
private function resolveFileAbsolutePath(ApplicationFile $file): ?string
{
$disk = Storage::disk($file->disk);
if (! $disk->exists($file->path)) {
return null;
}
$absolutePath = $disk->path($file->path);
if (! is_file($absolutePath)) {
return null;
}
return $absolutePath;
}
private function formatLocation(Application $app): string
{
$country = trim((string) ($app->location_country ?? ''));
if ($country === '海外' && ($app->oversea_country ?? '') !== '') {
return '海外 / '.$app->oversea_country;
}
return implode(' / ', array_values(array_filter([
$app->location_country,
$app->location_province,
$app->location_city,
], fn ($v) => $v !== null && trim((string) $v) !== '')));
}
/**
* @param array<string, true> $usedFolderNames
*/
private function uniqueFolderName(Application $application, array &$usedFolderNames): string
{
$base = $this->sanitizePathSegment(
ProjectCode::resolve($application).($application->player_name ?? '未知')
);
$folder = $base;
$suffix = 2;
while (isset($usedFolderNames[$folder])) {
$folder = $base.'_'.$suffix;
$suffix++;
}
return $folder;
}
3 months ago
/**
* @param array<string, true> $usedZipEntryNames
*/
private function uniqueFileNameInFolderTracked(
string $folder,
ApplicationFile $file,
array &$usedZipEntryNames,
): string {
3 months ago
$name = $file->clientDownloadName();
$candidate = $folder.'/'.$name;
3 months ago
if (! isset($usedZipEntryNames[$candidate])) {
$usedZipEntryNames[$candidate] = true;
3 months ago
return $candidate;
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
$base = pathinfo($name, PATHINFO_FILENAME);
$suffix = 2;
while (true) {
$next = $folder.'/'.($ext !== '' ? $base.'_'.$suffix.'.'.$ext : $base.'_'.$suffix);
3 months ago
if (! isset($usedZipEntryNames[$next])) {
$usedZipEntryNames[$next] = true;
3 months ago
return $next;
}
$suffix++;
}
}
private function sanitizePathSegment(string $value): string
{
$value = trim(str_replace(['\\', '/'], '_', $value));
$value = preg_replace('/[<>:"|?*]/u', '_', $value) ?? $value;
$value = preg_replace('/[\x00-\x1F\x7F]/u', '', $value) ?? $value;
return $value !== '' ? $value : '未命名';
}
3 months ago
private function formatBytes(int $bytes): string
{
if ($bytes < 1024) {
return $bytes.'B';
}
if ($bytes < 1024 * 1024) {
return round($bytes / 1024, 1).'KB';
}
if ($bytes < 1024 * 1024 * 1024) {
return round($bytes / 1024 / 1024, 1).'MB';
}
return round($bytes / 1024 / 1024 / 1024, 2).'GB';
}
3 months ago
}