68 lines
2.4 KiB
PHP
68 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Submission;
|
|
use App\Models\SubmissionDocument;
|
|
use App\Models\User;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class DocumentService
|
|
{
|
|
/**
|
|
* Simpan laporan PDF baharu untuk serahan dengan versi & hash.
|
|
* Versi sebelumnya ditanda tidak aktif tetapi dikekalkan (sejarah versi).
|
|
* Fail disimpan pada disk 'local' (di luar direktori public).
|
|
*/
|
|
public function store(Submission $submission, UploadedFile $file, User $user): SubmissionDocument
|
|
{
|
|
return DB::transaction(function () use ($submission, $file, $user) {
|
|
$nextVersion = (int) $submission->documents()->max('version') + 1;
|
|
|
|
$hash = hash_file('sha256', $file->getRealPath());
|
|
$path = $file->storeAs(
|
|
"reports/{$submission->id}",
|
|
'v'.$nextVersion.'_'.uniqid().'.pdf',
|
|
'local'
|
|
);
|
|
|
|
// Nyahaktifkan versi aktif sebelumnya.
|
|
$submission->documents()->where('is_active', true)->update(['is_active' => false]);
|
|
|
|
$document = $submission->documents()->create([
|
|
'original_filename' => $file->getClientOriginalName(),
|
|
'stored_path' => $path,
|
|
'file_hash' => $hash,
|
|
'mime_type' => $file->getClientMimeType(),
|
|
'size' => $file->getSize(),
|
|
'version' => $nextVersion,
|
|
'is_active' => true,
|
|
'uploaded_by' => $user->id,
|
|
]);
|
|
|
|
activity('dokumen')
|
|
->performedOn($submission)
|
|
->causedBy($user)
|
|
->withProperties(['version' => $nextVersion, 'filename' => $document->original_filename])
|
|
->log('Laporan PDF dimuat naik');
|
|
|
|
return $document;
|
|
});
|
|
}
|
|
|
|
public function setActiveVersion(Submission $submission, SubmissionDocument $document): void
|
|
{
|
|
$submission->documents()->where('is_active', true)->update(['is_active' => false]);
|
|
$document->update(['is_active' => true]);
|
|
}
|
|
|
|
public function download(SubmissionDocument $document)
|
|
{
|
|
abort_unless(Storage::disk('local')->exists($document->stored_path), 404, 'Fail laporan tidak dijumpai.');
|
|
|
|
return Storage::disk('local')->download($document->stored_path, $document->original_filename);
|
|
}
|
|
}
|