Files
webstatement/app/Jobs/GenerateBiayaKartuCsvJob.php
Daeng Deni Mardaeni ec99361833 refactor(webstatement): ubah pengelolaan default biaya kartu
- Pindahkan pengelolaan default biaya kartu dari konstanta dalam job ke metode `JenisKartu::getDefaultFees`.
- Tambahkan metode `getDefaultFees` pada model `JenisKartu` untuk mengambil data biaya kartu dari database.
- Sesuaikan job `GenerateBiayaKartuCsvJob` agar menggunakan data biaya kartu dari metode `getDefaultFees`.
- Hapus konstanta `DEFAULT_FEES` dan ganti penggunaannya dengan data dari database.
- Tingkatkan fleksibilitas pengambilan data biaya kartu untuk mendukung perubahan data secara dinamis.

Signed-off-by: Daeng Deni Mardaeni <ddeni05@gmail.com>
2025-05-10 10:51:28 +07:00

254 lines
7.8 KiB
PHP

<?php
namespace Modules\Webstatement\Jobs;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Modules\Webstatement\Models\Atmcard;
use Modules\Webstatement\Models\JenisKartu;
use RuntimeException;
class GenerateBiayaKartuCsvJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
// Changed from const to property
private $csvFilename;
/**
* Create a new job instance.
*/
public function __construct()
{
$this->csvFilename = env('BIAYA_KARTU_CSV_FILENAME', 'biaya_kartu_atm.csv');
}
/**
* Get default fees from JenisKartu table
*
* @return array
*/
private function getDefaultFees(): array
{
return JenisKartu::getDefaultFees();
}
/**
* Execute the job.
*/
public function handle()
: void
{
try {
$result = $this->generateAtmCardCsv();
Log::info('Pembuatan dan upload file CSV biaya kartu ATM selesai', [
'file' => $result['localFilePath'],
'jumlah_kartu' => $result['recordCount'],
'upload_sftp' => $result['uploadToSftp'] ? 'Berhasil' : 'Gagal',
'waktu' => $result['timestamp']
]);
if (!$result['uploadToSftp']) {
Log::warning('File CSV biaya kartu ATM tidak berhasil diunggah ke SFTP, tetapi tersedia secara lokal di: ' . $result['localFilePath']);
}
} catch (Exception $e) {
Log::error('Gagal membuat atau mengunggah file CSV biaya kartu ATM: ' . $e->getMessage(), [
'file' => $e->getFile(),
'line' => $e->getLine()
]);
throw $e;
}
}
/**
* Generate CSV file with ATM card data and upload to SFTP
*
* @return array Information about the generated file and upload status
*/
private function generateAtmCardCsv()
: array
{
$cards = $this->getEligibleAtmCards();
$filename = storage_path('app/' . $this->csvFilename);
$handle = fopen($filename, 'w+');
if (!$handle) {
throw new RuntimeException("Tidak dapat membuat file CSV: $filename");
}
try {
foreach ($cards as $card) {
$fee = $this->determineCardFee($card);
$csvRow = $this->createCsvRow($card, $fee);
fputcsv($handle, $csvRow, '|');
}
} finally {
fclose($handle);
}
$this->cleanupCsvFile($filename);
// Upload file ke SFTP
$uploadSuccess = $this->uploadToSftpKartu($filename);
return [
'localFilePath' => $filename,
'recordCount' => count($cards),
'uploadToSftp' => $uploadSuccess,
'timestamp' => now()->format('Y-m-d H:i:s')
];
}
/**
* Get eligible ATM cards from database
*
* @return \Illuminate\Database\Eloquent\Collection
*/
private function getEligibleAtmCards()
{
$cardTypes = array_keys($this->getDefaultFees());
return Atmcard::where('crsts', 1)
->whereNotNull('accflag')
->where('accflag', '!=', '')
->whereNotNull('branch')
->where('branch', '!=', '')
->whereNotNull('currency')
->where('currency', '!=', '')
->whereIn('ctdesc', $cardTypes)
->get();
}
/**
* Determine fee for a card based on its type
*
* @param Atmcard $card
*
* @return int
*/
private function determineCardFee(Atmcard $card)
: int
{
if ($card->fee) {
return $card->fee;
}
$defaultFees = $this->getDefaultFees();
return $defaultFees[$card->ctdesc] ?? 0;
}
/**
* Create CSV row data for a card
*
* @param Atmcard $card
* @param int $fee
*
* @return array
*/
private function createCsvRow(Atmcard $card, int $fee)
: array
{
$today = date('Ymd');
return [
'',
$card->accflag,
$card->currency ?? 'IDR',
$fee,
'PL65129',
'',
'',
$card->branch,
$today,
$today,
'',
'',
'ADMIN FEE ATM::' . $card->crdno . '::' . $today,
'',
'',
'',
'',
'',
'',
'ACAT'
];
}
/**
* Remove double quotes from CSV file
*
* @param string $filename
*
* @return void
*/
private function cleanupCsvFile(string $filename)
: void
{
$fileContent = file_get_contents($filename);
if ($fileContent === false) {
throw new RuntimeException("Tidak dapat membaca file CSV: $filename");
}
$fileContent = str_replace('"', '', $fileContent);
if (file_put_contents($filename, $fileContent) === false) {
throw new RuntimeException("Tidak dapat menulis ke file CSV: $filename");
}
}
/**
* Upload the generated CSV file to SFTP server
*
* @param string $localFilePath Path to the local CSV file
*
* @return bool True if upload successful, false otherwise
*/
private function uploadToSftpKartu(string $localFilePath)
: bool
{
try {
// Ambil nama file dari path
$filename = basename($localFilePath);
// Ambil konten file
$fileContent = file_get_contents($localFilePath);
if ($fileContent === false) {
Log::error("Tidak dapat membaca file untuk upload: {$localFilePath}");
return false;
}
// Dapatkan disk SFTP
$disk = Storage::disk('sftpKartu');
// Tentukan path tujuan di server SFTP
$remotePath = env('BIAYA_KARTU_REMOTE_PATH', '/');
$remoteFilePath = rtrim($remotePath, '/') . '/' . $filename;
// Upload file ke server SFTP
$result = $disk->put($remoteFilePath, $fileContent);
if ($result) {
Log::info("File CSV biaya kartu ATM berhasil diunggah ke SFTP: {$remoteFilePath}");
return true;
} else {
Log::error("Gagal mengunggah file CSV biaya kartu ATM ke SFTP: {$remoteFilePath}");
return false;
}
} catch (Exception $e) {
Log::error("Error saat mengunggah file ke SFTP: " . $e->getMessage(), [
'file' => $e->getFile(),
'line' => $e->getLine()
]);
return false;
}
}
}