feat(webstatement): tambah fungsi generatePdf ke ExportStatementPeriodJob

Perubahan yang dilakukan:
- Menambahkan fungsi generatePdf() untuk proses generate PDF dalam job ExportStatementPeriodJob.
- Mengintegrasikan logika PDF generation dari PrintStatementController ke dalam job.
- Menggunakan data ProcessedStatement yang telah diproses sebagai sumber untuk pembuatan PDF.
- Menambahkan import statement untuk Browsershot, Account, Customer, dan Branch.
- Mengimplementasikan fungsi prepareHeaderTableBackground() untuk mengonversi gambar header menjadi base64.
- Menggunakan database transaction untuk menjaga konsistensi saat generate dan menyimpan PDF.
- Menyimpan PDF ke storage dengan struktur direktori yang terorganisir berdasarkan parameter tertentu.
- Memperbarui PrintStatementLog dengan status akhir dan path file PDF yang dihasilkan.
- Menambahkan error handling dan logging secara menyeluruh untuk memantau proses.
- Menghapus file sementara (temporary) setelah PDF berhasil disimpan ke storage.
- Menambahkan dukungan timeout dan konfigurasi Browsershot yang optimal.
- Melakukan validasi terhadap data account, customer, dan branch sebelum proses generate PDF dilakukan.

Tujuan perubahan:
- Memindahkan logika generate PDF ke dalam background job agar lebih efisien dan terstruktur.
- Menjamin integritas data dan hasil PDF yang valid melalui proses terstandarisasi.
- Mengurangi beban proses di controller serta mendukung proses batch secara asynchronous.
This commit is contained in:
Daeng Deni Mardaeni
2025-07-10 13:15:47 +07:00
parent 5ea8136c13
commit 0aa7d22094
2 changed files with 227 additions and 53 deletions

View File

@@ -16,7 +16,7 @@ use Modules\Webstatement\Models\{Account, AccountBalance, PrintStatementLog, Pro
use Spatie\Browsershot\Browsershot;
use ZipArchive;
ini_set('memory_limit', '2G'); // Atau '1G' untuk data yang sangat besar
ini_set('max_execution_time', 300000);
ini_set('max_execution_time', 300000);
class PrintStatementController extends Controller
{
@@ -49,7 +49,7 @@ ini_set('max_execution_time', 300000);
if($request->input('branch_code') && !empty($request->input('stmt_sent_type'))){
$request_type = 'multi_account'; // Default untuk request manual
}
if($request_type=='single_account'){
$account = Account::where('account_number', $accountNumber)->first();
if ($account) {
@@ -101,7 +101,7 @@ ini_set('max_execution_time', 300000);
$validated['created_by'] = Auth::id();
$validated['ip_address'] = $request->ip();
$validated['user_agent'] = $request->userAgent();
$validated['status'] = 'pending'; // Status awal
$validated['authorization_status'] = 'approved'; // Status otorisasi awal
$validated['total_accounts'] = 1; // Untuk single account
@@ -110,7 +110,7 @@ ini_set('max_execution_time', 300000);
$validated['failed_count'] = 0;
$validated['stmt_sent_type'] = $request->input('stmt_sent_type') ? implode(",",$request->input('stmt_sent_type')) : '';
$validated['branch_code'] = $validated['branch_code'] ?? $branch_code; // Awal tidak tersedia
// Create the statement log
$statement = PrintStatementLog::create($validated);
@@ -825,9 +825,6 @@ ini_set('max_execution_time', 300000);
$period = $statement->period_from;
$format='pdf';
// Generate nama file PDF
$filename = $this->generatePdfFileName($norek, $period);
@@ -967,10 +964,11 @@ ini_set('max_execution_time', 300000);
Browsershot::html($html)
->showBackground()
->setOption('addStyleTag', json_encode(['content' => '@page { margin: 0; }']))
->setOption('protocolTimeout', 2147483) // 120000 ms = 2 menit
->format('A4')
->margins(0, 0, 0, 0)
->waitUntilNetworkIdle()
->timeout(6000)
->waitUntil('load')
->timeout(2147483)
->save($tempPath);
// Verifikasi file berhasil dibuat
@@ -1281,30 +1279,30 @@ ini_set('max_execution_time', 300000);
try {
// DB::beginTransaction();
Log::info('Starting statement processing', [
'statement_id' => $statement->id,
'request_type' => $statement->request_type,
'stmt_sent_type' => $statement->stmt_sent_type,
'branch_code' => $statement->branch_code
]);
if ($statement->request_type === 'multi_account') {
return $this->processMultiAccountStatement($statement);
} else {
return $this->processSingleAccountStatement($statement);
}
} catch (\Exception $e) {
//DB::rollBack();
Log::error('Failed to process statement', [
'error' => $e->getMessage(),
'statement_id' => $statement->id,
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Failed to process statement',
@@ -1323,22 +1321,22 @@ ini_set('max_execution_time', 300000);
{
try {
$period = $statement->period_from ?? date('Ym');
// Validasi stmt_sent_type
if (empty($statement->stmt_sent_type)) {
throw new \Exception('stmt_sent_type is required for multi account processing');
}
// Decode stmt_sent_type jika dalam format JSON array
$stmtSentTypes = explode(',', $statement->stmt_sent_type);
Log::info('Processing multi account statement', [
'statement_id' => $statement->id,
'branch_code' => $statement->branch_code,
'stmt_sent_types' => $stmtSentTypes,
'period' => $period
]);
$clientName = $statement->branch_code.'_'.$period.'_';//.implode('_'.$stmtSentTypes);
@@ -1352,13 +1350,13 @@ ini_set('max_execution_time', 300000);
if ($accounts->isEmpty()) {
throw new \Exception('No accounts found for the specified criteria');
}
Log::info('Found accounts for processing', [
'total_accounts' => $accounts->count(),
'branch_code' => $statement->branch_code,
'stmt_sent_types' => $stmtSentTypes
]);
// Update statement log dengan informasi accounts
$accountNumbers = $accounts->pluck('account_number')->toArray();
@@ -1368,7 +1366,7 @@ ini_set('max_execution_time', 300000);
'status' => 'processing',
'started_at' => now()
]);
// Dispatch job untuk generate PDF multi account
$job = GenerateMultiAccountPdfJob::dispatch(
$statement,
@@ -1376,16 +1374,16 @@ ini_set('max_execution_time', 300000);
$period,
$clientName
);
DB::commit();
Log::info('Multi account PDF generation job dispatched', [
'job_id' => $job->job_id ?? null,
'statement_id' => $statement->id,
'total_accounts' => $accounts->count(),
'period' => $period
]);
return response()->json([
'success' => true,
'message' => 'Multi account statement processing queued successfully',
@@ -1398,16 +1396,16 @@ ini_set('max_execution_time', 300000);
'client_name' => $clientName
]
]);
} catch (\Exception $e) {
DB::rollBack();
Log::error('Failed to process multi account statement', [
'error' => $e->getMessage(),
'statement_id' => $statement->id,
'trace' => $e->getTraceAsString()
]);
throw $e;
}
}
@@ -1491,24 +1489,24 @@ ini_set('max_execution_time', 300000);
{
try {
$statement = PrintStatementLog::findOrFail($statementId);
if ($statement->request_type !== 'multi_account') {
return response()->json([
'success' => false,
'message' => 'This statement is not a multi account request'
], 400);
}
if (!$statement->is_available) {
return response()->json([
'success' => false,
'message' => 'Statement files are not available for download'
], 404);
}
// Find ZIP file
$zipFiles = Storage::disk('local')->files("statements/{$statement->period_from}/multi_account/{$statementId}");
$zipFile = null;
foreach ($zipFiles as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'zip') {
@@ -1516,39 +1514,39 @@ ini_set('max_execution_time', 300000);
break;
}
}
if (!$zipFile || !Storage::disk('local')->exists($zipFile)) {
return response()->json([
'success' => false,
'message' => 'ZIP file not found'
], 404);
}
$zipPath = Storage::disk('local')->path($zipFile);
$filename = basename($zipFile);
// Update download status
$statement->update([
'is_downloaded' => true,
'downloaded_at' => now()
]);
Log::info('Multi account ZIP downloaded', [
'statement_id' => $statementId,
'zip_file' => $zipFile,
'user_id' => Auth::id()
]);
return response()->download($zipPath, $filename, [
'Content-Type' => 'application/zip'
]);
} catch (Exception $e) {
Log::error('Failed to download multi account ZIP', [
'statement_id' => $statementId,
'error' => $e->getMessage()
]);
return response()->json([
'success' => false,
'message' => 'Failed to download ZIP file',