91 lines
2.4 KiB
PHP
91 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\HasilSaw;
|
|
use App\Models\Tes;
|
|
use App\Models\TesPdf;
|
|
use App\Models\Upload;
|
|
use Barryvdh\DomPDF\Facade\Pdf;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class TesPdfService
|
|
{
|
|
public function ensureAvailable(Tes $tes): ?TesPdf
|
|
{
|
|
$tesPdf = TesPdf::with('upload')->where('tes_id', $tes->id)->first();
|
|
|
|
if ($tesPdf?->upload && $tesPdf->upload->existsOnPublicDisk()) {
|
|
return $tesPdf;
|
|
}
|
|
|
|
if (!$this->generateAndStore($tes)) {
|
|
return null;
|
|
}
|
|
|
|
return TesPdf::with('upload')->where('tes_id', $tes->id)->first();
|
|
}
|
|
|
|
public function generateAndStore(Tes $tes): bool
|
|
{
|
|
$tes->loadMissing('penyakit');
|
|
|
|
$hasilList = HasilSaw::where('tes_id', $tes->id)
|
|
->with('jurusan')
|
|
->orderBy('peringkat')
|
|
->get();
|
|
|
|
$siswa = $tes->siswa()->with('user')->first();
|
|
|
|
$html = view('pages.siswa.hasil-pdf', [
|
|
'siswa' => $siswa,
|
|
'tesTerakhir' => $tes,
|
|
'hasilList' => $hasilList,
|
|
])->render();
|
|
|
|
$fileName = 'hasil_tes_' . $tes->id . '.pdf';
|
|
$relativePath = 'hasil_pdf/' . $fileName;
|
|
|
|
try {
|
|
$binary = Pdf::loadHTML($html)
|
|
->setPaper('a4')
|
|
->output();
|
|
} catch (\Throwable $e) {
|
|
Log::error('DomPDF gagal generate PDF hasil tes', [
|
|
'tes_id' => $tes->id,
|
|
'message' => $e->getMessage(),
|
|
]);
|
|
|
|
return false;
|
|
}
|
|
|
|
Storage::disk('public')->put($relativePath, $binary);
|
|
|
|
$uploadData = [
|
|
'uploader_user_id' => $siswa?->user_id,
|
|
'file_name' => $fileName,
|
|
'ext' => 'PDF',
|
|
'mime_type' => 'application/pdf',
|
|
'size_mb' => round(strlen($binary) / 1048576, 2),
|
|
'storage_path' => $relativePath,
|
|
];
|
|
|
|
$tesPdf = TesPdf::with('upload')->where('tes_id', $tes->id)->first();
|
|
|
|
if ($tesPdf?->upload) {
|
|
$tesPdf->upload->update($uploadData);
|
|
$upload = $tesPdf->upload->fresh();
|
|
} else {
|
|
$upload = Upload::create($uploadData);
|
|
}
|
|
|
|
TesPdf::updateOrCreate(
|
|
['tes_id' => $tes->id],
|
|
['upload_id' => $upload->id, 'generated_at' => now()]
|
|
);
|
|
|
|
return true;
|
|
}
|
|
}
|