- Menambahkan kolom `email` dan `email_sent_at` pada tabel `print_statement_logs`. - Menambah endpoint baru untuk mengirim statement via email (`/send-email`). - Mengupdate form request untuk validasi email pada `PrintStatementRequest`. - Menambah logika pengiriman email dengan menggunakan `Mailable` (`StatementEmail`). - Memvalidasi ketersediaan file statement sebelum dikirimkan via email. - Menambahkan tombol baru pada tampilan frontend untuk opsi `Send to Email`. - Mengupdate file zip untuk pengiriman email ketika ada statement dalam rentang waktu. - Refaktor dan perbaikan minor pada kode terkait check statement availability. - Menyesuaikan title menu pada `module.json` dari "Periode Statement" ke "Create Periode" dan "Print Statement" ke "Statement". Signed-off-by: Daeng Deni Mardaeni <ddeni05@gmail.com>
549 lines
24 KiB
PHP
549 lines
24 KiB
PHP
<?php
|
|
|
|
namespace Modules\Webstatement\Http\Controllers;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use Carbon\Carbon;
|
|
use Exception;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Auth;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Log;
|
|
use Modules\Basicdata\Models\Branch;
|
|
use Modules\Webstatement\Http\Requests\PrintStatementRequest;
|
|
use Modules\Webstatement\Mail\StatementEmail;
|
|
use Modules\Webstatement\Models\PrintStatementLog;
|
|
use ZipArchive;
|
|
|
|
class PrintStatementController extends Controller
|
|
{
|
|
/**
|
|
* Display a listing of the statements.
|
|
*/
|
|
public function index(Request $request)
|
|
{
|
|
$branches = Branch::orderBy('name')->get();
|
|
|
|
return view('webstatement::statements.index', compact('branches'));
|
|
}
|
|
|
|
/**
|
|
* Store a newly created statement request.
|
|
*/
|
|
public function store(PrintStatementRequest $request)
|
|
{
|
|
$validated = $request->validated();
|
|
|
|
// Add user tracking data
|
|
$validated['user_id'] = Auth::id();
|
|
$validated['created_by'] = Auth::id();
|
|
$validated['ip_address'] = $request->ip();
|
|
$validated['user_agent'] = $request->userAgent();
|
|
|
|
// Create the statement log
|
|
$statement = PrintStatementLog::create($validated);
|
|
|
|
// Process statement availability check (this would be implemented based on your system)
|
|
$this->checkStatementAvailability($statement);
|
|
|
|
return redirect()->route('statements.index')
|
|
->with('success', 'Statement request has been created successfully.');
|
|
}
|
|
|
|
/**
|
|
* Show the form for creating a new statement request.
|
|
*/
|
|
public function create()
|
|
{
|
|
$branches = Branch::orderBy('name')->get();
|
|
return view('webstatement::statements.create', compact('branches'));
|
|
}
|
|
|
|
/**
|
|
* Check if the statement is available in the system.
|
|
* This is a placeholder method - implement according to your system.
|
|
*/
|
|
protected function checkStatementAvailability(PrintStatementLog $statement)
|
|
{
|
|
// This would be implemented based on your system's logic
|
|
// For example, checking an API or database for statement availability
|
|
$disk = Storage::disk('sftpStatement');
|
|
|
|
//format folder /periode/Print/branch_code/account_number.pdf
|
|
$filePath = "{$statement->period_from}/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
// Check if the statement exists in the storage
|
|
if ($statement->is_period_range && $statement->period_to) {
|
|
$periodFrom = Carbon::createFromFormat('Ym', $statement->period_from);
|
|
$periodTo = Carbon::createFromFormat('Ym', $statement->period_to);
|
|
|
|
// Loop through each month in the range
|
|
$missingPeriods = [];
|
|
$availablePeriods = [];
|
|
|
|
for ($period = clone $periodFrom; $period->lte($periodTo); $period->addMonth()) {
|
|
$periodFormatted = $period->format('Ym');
|
|
$periodPath = $periodFormatted . "/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
if ($disk->exists($periodPath)) {
|
|
$availablePeriods[] = $periodFormatted;
|
|
} else {
|
|
$missingPeriods[] = $periodFormatted;
|
|
}
|
|
}
|
|
|
|
|
|
// If any period is missing, the statement is not available
|
|
if (count($missingPeriods) > 0) {
|
|
$notes = "Missing periods: " . implode(', ', $missingPeriods);
|
|
$statement->update([
|
|
'is_available' => false,
|
|
'remarks' => $notes,
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
return;
|
|
} else {
|
|
// All periods are available
|
|
$statement->update([
|
|
'is_available' => true,
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
return;
|
|
}
|
|
} else if ($disk->exists($filePath)) {
|
|
$statement->update([
|
|
'is_available' => true,
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
return;
|
|
}
|
|
|
|
$statement->update([
|
|
'is_available' => false,
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
return;
|
|
}
|
|
|
|
/**
|
|
* Display the specified statement.
|
|
*/
|
|
public function show(PrintStatementLog $statement)
|
|
{
|
|
$statement->load(['user', 'branch', 'creator', 'authorizer']);
|
|
return view('webstatement::statements.show', compact('statement'));
|
|
}
|
|
|
|
/**
|
|
* Download the statement if available and authorized.
|
|
*/
|
|
public function download(PrintStatementLog $statement)
|
|
{
|
|
// Check if statement is available and authorized
|
|
if (!$statement->is_available) {
|
|
return back()->with('error', 'Statement is not available for download.');
|
|
}
|
|
|
|
/* if ($statement->authorization_status !== 'approved') {
|
|
return back()->with('error', 'Statement download requires authorization.');
|
|
}*/
|
|
|
|
// Update download status
|
|
$statement->update([
|
|
'is_downloaded' => true,
|
|
'downloaded_at' => now(),
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
|
|
// Generate or fetch the statement file (implementation depends on your system)
|
|
$disk = Storage::disk('sftpStatement');
|
|
$filePath = "{$statement->period_from}/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
if ($statement->is_period_range && $statement->period_to) {
|
|
$periodFrom = Carbon::createFromFormat('Ym', $statement->period_from);
|
|
$periodTo = Carbon::createFromFormat('Ym', $statement->period_to);
|
|
|
|
// Loop through each month in the range
|
|
$missingPeriods = [];
|
|
$availablePeriods = [];
|
|
|
|
for ($period = clone $periodFrom; $period->lte($periodTo); $period->addMonth()) {
|
|
$periodFormatted = $period->format('Ym');
|
|
$periodPath = $periodFormatted . "/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
if ($disk->exists($periodPath)) {
|
|
$availablePeriods[] = $periodFormatted;
|
|
} else {
|
|
$missingPeriods[] = $periodFormatted;
|
|
}
|
|
}
|
|
|
|
// If any period is missing, the statement is not available
|
|
if (count($availablePeriods) > 0) {
|
|
// Create a temporary zip file
|
|
$zipFileName = "{$statement->account_number}_{$statement->period_from}_to_{$statement->period_to}.zip";
|
|
$zipFilePath = storage_path("app/temp/{$zipFileName}");
|
|
|
|
// Ensure the temp directory exists
|
|
if (!file_exists(storage_path('app/temp'))) {
|
|
mkdir(storage_path('app/temp'), 0755, true);
|
|
}
|
|
|
|
// Create a new zip archive
|
|
$zip = new ZipArchive();
|
|
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
|
|
// Add each available statement to the zip
|
|
foreach ($availablePeriods as $period) {
|
|
$filePath = "{$period}/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
$localFilePath = storage_path("app/temp/{$statement->account_number}_{$period}.pdf");
|
|
|
|
// Download the file from SFTP to local storage temporarily
|
|
file_put_contents($localFilePath, $disk->get($filePath));
|
|
|
|
// Add the file to the zip
|
|
$zip->addFile($localFilePath, "{$statement->account_number}_{$period}.pdf");
|
|
}
|
|
|
|
$zip->close();
|
|
|
|
// Clean up temporary files
|
|
foreach ($availablePeriods as $period) {
|
|
$localFilePath = storage_path("app/temp/{$statement->account_number}_{$period}.pdf");
|
|
if (file_exists($localFilePath)) {
|
|
unlink($localFilePath);
|
|
}
|
|
}
|
|
|
|
// Return the zip file for download
|
|
return response()->download($zipFilePath, $zipFileName)->deleteFileAfterSend(true);
|
|
} else {
|
|
return back()->with('error', 'Failed to create zip archive.');
|
|
}
|
|
} else {
|
|
return back()->with('error', 'No statements available for download.');
|
|
}
|
|
} else if ($disk->exists($filePath)) {
|
|
return $disk->download($filePath, "{$statement->account_number}_{$statement->period_from}.pdf");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Authorize a statement request.
|
|
*/
|
|
public function authorize(Request $request, PrintStatementLog $statement)
|
|
{
|
|
$request->validate([
|
|
'authorization_status' => ['required', Rule::in(['approved', 'rejected'])],
|
|
'remarks' => ['nullable', 'string', 'max:255'],
|
|
]);
|
|
|
|
// Update authorization status
|
|
$statement->update([
|
|
'authorization_status' => $request->authorization_status,
|
|
'authorized_by' => Auth::id(),
|
|
'authorized_at' => now(),
|
|
'remarks' => $request->remarks,
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
|
|
$statusText = $request->authorization_status === 'approved' ? 'approved' : 'rejected';
|
|
|
|
return redirect()->route('statements.show', $statement->id)
|
|
->with('success', "Statement request has been {$statusText} successfully.");
|
|
|
|
}
|
|
|
|
/**
|
|
* Provide data for datatables.
|
|
*/
|
|
public function dataForDatatables(Request $request)
|
|
{
|
|
// Check permissions if needed
|
|
// if (!auth()->user()->can('view_statements')) {
|
|
// abort(403, 'Sorry! You are not allowed to view statements.');
|
|
// }
|
|
|
|
// Retrieve data from the database
|
|
$query = PrintStatementLog::query();
|
|
|
|
// Apply search filter if provided
|
|
if ($request->has('search') && !empty($request->get('search'))) {
|
|
$search = $request->get('search');
|
|
$query->where(function ($q) use ($search) {
|
|
$q->where('account_number', 'LIKE', "%$search%")
|
|
->orWhere('branch_code', 'LIKE', "%$search%")
|
|
->orWhere('period_from', 'LIKE', "%$search%")
|
|
->orWhere('period_to', 'LIKE', "%$search%")
|
|
->orWhere('authorization_status', 'LIKE', "%$search%");
|
|
});
|
|
}
|
|
|
|
// Apply column filters if provided
|
|
if ($request->has('filters') && !empty($request->get('filters'))) {
|
|
$filters = json_decode($request->get('filters'), true);
|
|
|
|
foreach ($filters as $filter) {
|
|
if (!empty($filter['value'])) {
|
|
if ($filter['column'] === 'branch_code') {
|
|
$query->where('branch_code', $filter['value']);
|
|
} else if ($filter['column'] === 'authorization_status') {
|
|
$query->where('authorization_status', $filter['value']);
|
|
} else if ($filter['column'] === 'is_downloaded') {
|
|
$query->where('is_downloaded', filter_var($filter['value'], FILTER_VALIDATE_BOOLEAN));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Apply sorting if provided
|
|
if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
|
|
$order = $request->get('sortOrder');
|
|
$column = $request->get('sortField');
|
|
|
|
// Map frontend column names to database column names if needed
|
|
$columnMap = [
|
|
'branch' => 'branch_code',
|
|
'account' => 'account_number',
|
|
'period' => 'period_from',
|
|
'status' => 'authorization_status',
|
|
'remarks' => 'remarks',
|
|
// Add more mappings as needed
|
|
];
|
|
|
|
$dbColumn = $columnMap[$column] ?? $column;
|
|
$query->orderBy($dbColumn, $order);
|
|
} else {
|
|
// Default sorting
|
|
$query->latest('created_at');
|
|
}
|
|
|
|
// Get the total count of records
|
|
$totalRecords = $query->count();
|
|
|
|
// Apply pagination if provided
|
|
if ($request->has('page') && $request->has('size')) {
|
|
$page = $request->get('page');
|
|
$size = $request->get('size');
|
|
$offset = ($page - 1) * $size; // Calculate the offset
|
|
|
|
$query->skip($offset)->take($size);
|
|
}
|
|
|
|
// Get the filtered count of records
|
|
$filteredRecords = $query->count();
|
|
|
|
// Eager load relationships to avoid N+1 query problems
|
|
$query->with(['user', 'branch', 'authorizer']);
|
|
|
|
// Get the data for the current page
|
|
$data = $query->get()->map(function ($item) {
|
|
// Transform data for frontend if needed
|
|
return [
|
|
'id' => $item->id,
|
|
'branch_code' => $item->branch_code,
|
|
'branch_name' => $item->branch->name ?? 'N/A',
|
|
'account_number' => $item->account_number,
|
|
'period_from' => $item->period_from,
|
|
'period_to' => $item->is_period_range ? $item->period_to : null,
|
|
'authorization_status' => $item->authorization_status,
|
|
'is_available' => $item->is_available,
|
|
'is_downloaded' => $item->is_downloaded,
|
|
'created_at' => dateFormat($item->created_at, 1, 1),
|
|
'created_by' => $item->user->name ?? 'N/A',
|
|
'authorized_by' => $item->authorizer ? $item->authorizer->name : null,
|
|
'authorized_at' => $item->authorized_at ? $item->authorized_at->format('Y-m-d H:i:s') : null,
|
|
'remarks' => $item->remarks,
|
|
];
|
|
});
|
|
|
|
// Calculate the page count
|
|
$pageCount = ceil($filteredRecords / ($request->get('size') ?: 1));
|
|
|
|
// Calculate the current page number
|
|
$currentPage = $request->get('page') ?: 1;
|
|
|
|
// Return the response data as a JSON object
|
|
return response()->json([
|
|
'draw' => $request->get('draw'),
|
|
'recordsTotal' => $totalRecords,
|
|
'recordsFiltered' => $filteredRecords,
|
|
'pageCount' => $pageCount,
|
|
'page' => $currentPage,
|
|
'totalCount' => $totalRecords,
|
|
'data' => $data,
|
|
]);
|
|
}
|
|
|
|
public function destroy(PrintStatementLog $statement)
|
|
{
|
|
// Delete the statement
|
|
$statement->delete();
|
|
|
|
return response()->json([
|
|
'message' => 'Statement deleted successfully.',
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Send statement to email
|
|
*/
|
|
public function sendEmail($id)
|
|
{
|
|
$statement = PrintStatementLog::findOrFail($id);
|
|
// Check if statement has email
|
|
if (empty($statement->email)) {
|
|
return redirect()->back()->with('error', 'No email address provided for this statement.');
|
|
}
|
|
|
|
// Check if statement is available
|
|
if (!$statement->is_available) {
|
|
return redirect()->back()->with('error', 'Statement is not available for sending.');
|
|
}
|
|
|
|
try {
|
|
$disk = Storage::disk('sftpStatement');
|
|
$filePath = "{$statement->period_from}/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
if ($statement->is_period_range && $statement->period_to) {
|
|
$periodFrom = Carbon::createFromFormat('Ym', $statement->period_from);
|
|
$periodTo = Carbon::createFromFormat('Ym', $statement->period_to);
|
|
|
|
// Loop through each month in the range
|
|
$missingPeriods = [];
|
|
$availablePeriods = [];
|
|
|
|
for ($period = clone $periodFrom; $period->lte($periodTo); $period->addMonth()) {
|
|
$periodFormatted = $period->format('Ym');
|
|
$periodPath = $periodFormatted . "/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
|
|
if ($disk->exists($periodPath)) {
|
|
$availablePeriods[] = $periodFormatted;
|
|
} else {
|
|
$missingPeriods[] = $periodFormatted;
|
|
}
|
|
}
|
|
|
|
// If any period is available, create a zip and send it
|
|
if (count($availablePeriods) > 0) {
|
|
// Create a temporary zip file
|
|
$zipFileName = "{$statement->account_number}_{$statement->period_from}_to_{$statement->period_to}.zip";
|
|
$zipFilePath = storage_path("app/temp/{$zipFileName}");
|
|
|
|
// Ensure the temp directory exists
|
|
if (!file_exists(storage_path('app/temp'))) {
|
|
mkdir(storage_path('app/temp'), 0755, true);
|
|
}
|
|
|
|
// Create a new zip archive
|
|
$zip = new ZipArchive();
|
|
if ($zip->open($zipFilePath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
|
|
// Add each available statement to the zip
|
|
foreach ($availablePeriods as $period) {
|
|
$filePath = "{$period}/Print/{$statement->branch_code}/{$statement->account_number}.pdf";
|
|
$localFilePath = storage_path("app/temp/{$statement->account_number}_{$period}.pdf");
|
|
|
|
// Download the file from SFTP to local storage temporarily
|
|
file_put_contents($localFilePath, $disk->get($filePath));
|
|
|
|
// Add the file to the zip
|
|
$zip->addFile($localFilePath, "{$statement->account_number}_{$period}.pdf");
|
|
}
|
|
|
|
$zip->close();
|
|
|
|
// Send email with zip attachment
|
|
Mail::to($statement->email)
|
|
->send(new StatementEmail($statement, $zipFilePath, true));
|
|
|
|
// Clean up temporary files
|
|
foreach ($availablePeriods as $period) {
|
|
$localFilePath = storage_path("app/temp/{$statement->account_number}_{$period}.pdf");
|
|
if (file_exists($localFilePath)) {
|
|
unlink($localFilePath);
|
|
}
|
|
}
|
|
|
|
// Delete the zip file after sending
|
|
if (file_exists($zipFilePath)) {
|
|
unlink($zipFilePath);
|
|
}
|
|
} else {
|
|
return redirect()->back()->with('error', 'Failed to create zip archive for email.');
|
|
}
|
|
} else {
|
|
return redirect()->back()->with('error', 'No statements available for sending.');
|
|
}
|
|
} else if ($disk->exists($filePath)) {
|
|
// For single period statements
|
|
$localFilePath = storage_path("app/temp/{$statement->account_number}_{$statement->period_from}.pdf");
|
|
|
|
// Ensure the temp directory exists
|
|
if (!file_exists(storage_path('app/temp'))) {
|
|
mkdir(storage_path('app/temp'), 0755, true);
|
|
}
|
|
|
|
// Download the file from SFTP to local storage temporarily
|
|
file_put_contents($localFilePath, $disk->get($filePath));
|
|
|
|
// Send email with PDF attachment
|
|
Mail::to($statement->email)
|
|
->send(new StatementEmail($statement, $localFilePath, false));
|
|
|
|
// Delete the temporary file
|
|
if (file_exists($localFilePath)) {
|
|
unlink($localFilePath);
|
|
}
|
|
} else {
|
|
return redirect()->back()->with('error', 'Statement file not found.');
|
|
}
|
|
|
|
// Update statement record to mark as emailed
|
|
$statement->update([
|
|
'email_sent_at' => now(),
|
|
'updated_by' => Auth::id()
|
|
]);
|
|
|
|
return redirect()->back()->with('success', 'Statement has been sent to ' . $statement->email);
|
|
} catch (Exception $e) {
|
|
// Log the error
|
|
Log::error('Failed to send statement email: ' . $e->getMessage());
|
|
|
|
return redirect()->back()->with('error', 'Failed to send email: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Generate or fetch the statement file.
|
|
* This is a placeholder method - implement according to your system.
|
|
*/
|
|
protected function generateStatementFile(PrintStatementLog $statement)
|
|
{
|
|
// This would be implemented based on your system's logic
|
|
// For example, calling an API to generate a PDF or fetching from storage
|
|
|
|
// Placeholder implementation - return a dummy path
|
|
$tempFile = tempnam(sys_get_temp_dir(), 'statement_');
|
|
file_put_contents($tempFile, 'Statement content would go here');
|
|
return $tempFile;
|
|
}
|
|
|
|
/**
|
|
* Send statement to email
|
|
*/
|
|
|
|
/**
|
|
* Generate a filename for the statement download.
|
|
*/
|
|
protected function generateFileName(PrintStatementLog $statement)
|
|
{
|
|
$accountNumber = $statement->account_number;
|
|
|
|
if ($statement->is_period_range) {
|
|
return "statement_{$accountNumber}_{$statement->period_from}_to_{$statement->period_to}.pdf";
|
|
}
|
|
|
|
return "statement_{$accountNumber}_{$statement->period_from}.pdf";
|
|
}
|
|
}
|