fix show page document pbg

This commit is contained in:
arifal
2025-04-10 15:44:51 +07:00
parent 7737fee30f
commit d95676d477
7 changed files with 246 additions and 235 deletions

View File

@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Models\PbgTaskAttachment; use App\Models\PbgTaskAttachment;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
class PbgTaskAttachmentsController extends Controller class PbgTaskAttachmentsController extends Controller
{ {
@@ -28,14 +29,18 @@ class PbgTaskAttachmentsController extends Controller
'pbg_type' => 'string' 'pbg_type' => 'string'
]); ]);
$file = $request->file('file');
$path = $file->store("uploads/pbg-tasks/{$pbg_task_id}", "public");
$attachment = PbgTaskAttachment::create([ $attachment = PbgTaskAttachment::create([
'pbg_task_id' => $pbg_task_id, 'pbg_task_id' => $pbg_task_id,
'file_name' => $file->getClientOriginalName(), 'file_name' => $request->file('file')->getClientOriginalName(),
'file_path' => '', // empty path initially
'pbg_type' => $request->pbg_type == 'bukti_bayar' ? 'bukti_bayar' : 'berita_acara'
]);
$file = $request->file('file');
$path = $file->store("uploads/pbg-tasks/{$pbg_task_id}/{$attachment->id}", "public");
$attachment->update([
'file_path' => $path, 'file_path' => $path,
'pbg_type' => $request->pbg_type
]); ]);
return response()->json([ return response()->json([
@@ -79,4 +84,26 @@ class PbgTaskAttachmentsController extends Controller
{ {
// //
} }
public function download(string $id)
{
try {
$data = PbgTaskAttachment::findOrFail($id);
$filePath = $data->file_path; // already relative to 'public' disk
if (!Storage::disk('public')->exists($filePath)) {
return response()->json([
"success" => false,
"message" => "File not found on server"
], Response::HTTP_NOT_FOUND);
}
return Storage::disk('public')->download($filePath, $data->file_name);
} catch (\Exception $e) {
return response()->json([
"success" => false,
"message" => $e->getMessage()
]);
}
}
} }

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers;
use App\Models\PbgTask;
use App\Models\PbgTaskAttachment;
use Illuminate\Http\Request;
class PbgTaskAttachmentsController extends Controller
{
public function show(string $id, Request $request){
try{
$title = $request->get('type') == "berita-acara" ? "Berita Acara" : "Bukti Bayar";
$data = PbgTaskAttachment::findOrFail($id);
$pbg = PbgTask::findOrFail($data->pbg_task_id);
return view('pbg-task-attachment.show', compact('data', 'pbg', 'title'));
}catch(\Exception $e){
return view('pages.404');
}
}
}

View File

@@ -11,10 +11,31 @@ class PbgTasks {
} }
init() { init() {
this.setupFileUploadModal({
modalId: "modalBuktiBayar",
dropzoneId: "dropzoneBuktiBayar",
uploadBtnClass: "upload-btn-bukti-bayar",
removeBtnId: "removeFileBtnBuktiBayar",
submitBtnId: "submitBuktiBayar",
fileNameSpanId: "uploadedFileNameBuktiBayar",
fileInfoId: "fileInfoBuktiBayar",
pbgType: "bukti_bayar",
bindFlag: "uploadHandlerBoundBuktiBayar",
});
this.setupFileUploadModal({
modalId: "modalBeritaAcara",
dropzoneId: "dropzoneBeritaAcara",
uploadBtnClass: "upload-btn-berita-acara",
removeBtnId: "removeFileBtnBeritaAcara",
submitBtnId: "submitBeritaAcara",
fileNameSpanId: "uploadedFileNameBeritaAcara",
fileInfoId: "fileInfoBeritaAcara",
pbgType: "berita_acara",
bindFlag: "uploadHandlerBoundBeritaAcara",
});
this.initTableRequestAssignment(); this.initTableRequestAssignment();
this.handleSendNotification(); this.handleSendNotification();
this.handleUploadBuktiBayar();
this.handleUploadBeritaAcara();
} }
initTableRequestAssignment() { initTableRequestAssignment() {
@@ -58,10 +79,11 @@ class PbgTasks {
${ ${
cell.attachment_berita_acara cell.attachment_berita_acara
? ` ? `
<a href="/storage/${cell.attachment_berita_acara.file_path}" target="_blank" <a href="/pbg-task-attachment/${cell.attachment_berita_acara.id}?type=berita-acara"
class="btn btn-success btn-sm d-inline-flex align-items-center justify-content-center" class="btn btn-success btn-sm d-inline-flex align-items-center justify-content-center"
style="white-space: nowrap; line-height: 1;"> style="white-space: nowrap; line-height: 1;"
<iconify-icon icon="mingcute:download-2-fill" width="15" height="15" style="vertical-align: middle;"></iconify-icon> target="_blank">
<iconify-icon icon="mingcute:eye-2-fill" width="15" height="15" style="vertical-align: middle;"></iconify-icon>
<span class="ms-1">Berita Acara</span> <span class="ms-1">Berita Acara</span>
</a> </a>
` `
@@ -78,10 +100,11 @@ class PbgTasks {
${ ${
cell.attachment_bukti_bayar cell.attachment_bukti_bayar
? ` ? `
<a href="/storage/${cell.attachment_bukti_bayar.file_path}" target="_blank" <a href="/pbg-task-attachment/${cell.attachment_bukti_bayar.id}?type=bukti-bayar"
class="btn btn-success btn-sm d-inline-flex align-items-center justify-content-center" class="btn btn-success btn-sm d-inline-flex align-items-center justify-content-center"
style="white-space: nowrap; line-height: 1;"> style="white-space: nowrap; line-height: 1;"
<iconify-icon icon="mingcute:download-2-fill" width="15" height="15" style="vertical-align: middle;"></iconify-icon> target="_blank">
<iconify-icon icon="mingcute:eye-2-fill" width="15" height="15" style="vertical-align: middle;"></iconify-icon>
<span class="ms-1">Bukti Bayar</span> <span class="ms-1">Bukti Bayar</span>
</a> </a>
` `
@@ -173,95 +196,77 @@ class PbgTasks {
}); });
} }
handleUploadBuktiBayar() { setupFileUploadModal({
const modalEl = document.getElementById("modalBuktiBayar"); modalId,
dropzoneId,
uploadBtnClass,
removeBtnId,
submitBtnId,
fileNameSpanId,
fileInfoId,
pbgType,
bindFlag,
}) {
const modalEl = document.getElementById(modalId);
const modalInstance = new bootstrap.Modal(modalEl); const modalInstance = new bootstrap.Modal(modalEl);
const modalTaskIdSpan = modalEl.querySelector("#modal-task-id span"); let taskId;
// Blur-fix for modal
modalEl.addEventListener("hide.bs.modal", () => { modalEl.addEventListener("hide.bs.modal", () => {
if ( if (
document.activeElement && document.activeElement &&
modalEl.contains(document.activeElement) modalEl.contains(document.activeElement)
) { ) {
document.activeElement.blur(); document.activeElement.blur();
setTimeout(() => { setTimeout(() => document.body.focus(), 10);
document.body.focus();
}, 10);
} }
}); });
// Only bind once // Bind click listener only once
if (!window.uploadHandlerBoundBuktiBayar) { if (!window[bindFlag]) {
document.addEventListener("click", (event) => { document.addEventListener("click", (e) => {
const uploadBtn = event.target.closest( const btn = e.target.closest(`.${uploadBtnClass}`);
".upload-btn-bukti-bayar" if (btn) {
); taskId = btn.getAttribute("data-id");
if (uploadBtn) {
const taskId = uploadBtn.getAttribute("data-id");
modalTaskIdSpan.textContent = taskId;
// Set task ID on the form element so Dropzone can read it
document.getElementById(
"dropzoneBuktiBayar"
).dataset.taskId = taskId;
modalInstance.show(); modalInstance.show();
} }
}); });
window[bindFlag] = true;
window.uploadHandlerBoundBuktiBayar = true;
} }
// Prevent multiple Dropzone instances // Avoid reinitializing Dropzone
if ( if (!Dropzone.instances.some((dz) => dz.element.id === dropzoneId)) {
!Dropzone.instances.some(
(dz) => dz.element.id === "dropzoneBuktiBayar"
)
) {
const self = this; const self = this;
new Dropzone("#dropzoneBuktiBayar", {
url: function () { new Dropzone(`#${dropzoneId}`, {
const taskId = url: () => `/api/pbg-task-attachment/${taskId}`,
document.getElementById("dropzoneBuktiBayar").dataset
.taskId;
return `/api/pbg-task-attachment/${taskId}`;
},
maxFiles: 1, maxFiles: 1,
maxFilesize: 5, maxFilesize: 5, // MB
acceptedFiles: ".jpg,.png,.pdf", acceptedFiles: ".jpg,.png,.pdf",
autoProcessQueue: false, autoProcessQueue: false,
addRemoveLinks: false,
priviewsContainer: null,
paramName: "file", paramName: "file",
headers: { headers: {
"X-CSRF-TOKEN": document.querySelector( "X-CSRF-TOKEN": document.querySelector(
'meta[name="csrf-token"]' 'meta[name="csrf-token"]'
).content, ).content,
Authorization: `Bearer ${document Authorization: `Bearer ${
.querySelector('meta[name="api-token"]') document.querySelector('meta[name="api-token"]').content
.getAttribute("content")}`, }`,
Accept: "application/json", Accept: "application/json",
}, },
params: { params: { pbg_type: pbgType },
pbg_type: "bukti_bayar",
},
dictDefaultMessage: "Drop your file here or click to upload.", dictDefaultMessage: "Drop your file here or click to upload.",
init: function () { init: function () {
const dz = this; const dz = this;
dz.on("addedfile", function (file) {
// Always ensure only one file
if (dz.files.length > 1) {
dz.removeFile(dz.files[0]);
}
// Small delay helps ensure UI updates even with same file dz.on("addedfile", (file) => {
if (dz.files.length > 1) dz.removeFile(dz.files[0]);
setTimeout(() => { setTimeout(() => {
document.getElementById( document.getElementById(
"uploadedFileNameBuktiBayar" fileNameSpanId
).textContent = file.name; ).textContent = file.name;
document document
.getElementById("fileInfoBuktiBayar") .getElementById(fileInfoId)
.classList.remove("d-none"); .classList.remove("d-none");
document document
.querySelector(".dz-message") .querySelector(".dz-message")
@@ -269,26 +274,23 @@ class PbgTasks {
}, 10); }, 10);
}); });
dz.on("removedfile", function () { dz.on("removedfile", () => {
document document
.getElementById("fileInfoBuktiBayar") .getElementById(fileInfoId)
.classList.add("d-none"); .classList.add("d-none");
document.getElementById( document.getElementById(fileNameSpanId).textContent =
"uploadedFileNameBuktiBayar" "";
).textContent = "";
document document
.querySelector(".dz-message") .querySelector(".dz-message")
.classList.remove("d-none"); .classList.remove("d-none");
}); });
document document
.getElementById("removeFileBtnBuktiBayar") .getElementById(removeBtnId)
.addEventListener("click", function () { .addEventListener("click", () => dz.removeAllFiles());
dz.removeAllFiles();
});
document document
.getElementById("submitBuktiBayar") .getElementById(submitBtnId)
.addEventListener("click", () => { .addEventListener("click", () => {
if (dz.getQueuedFiles().length > 0) { if (dz.getQueuedFiles().length > 0) {
dz.processQueue(); dz.processQueue();
@@ -301,20 +303,18 @@ class PbgTasks {
dz.on("success", () => { dz.on("success", () => {
dz.removeAllFiles(true); dz.removeAllFiles(true);
// Reset UI
document document
.getElementById("fileInfoBuktiBayar") .getElementById(fileInfoId)
.classList.add("d-none"); .classList.add("d-none");
document.getElementById( document.getElementById(fileNameSpanId).textContent =
"uploadedFileNameBuktiBayar" "";
).textContent = "";
document.querySelector(".dz-message").style.display = document.querySelector(".dz-message").style.display =
"block"; "block";
document.activeElement.blur(); // Lepas fokus dari tombol document.activeElement.blur();
setTimeout(() => { setTimeout(() => {
document.body.focus(); // Atau fokus ke tombol lain kalau mau document.body.focus();
modalInstance.hide(); // Tutup modal SETELAH fokus dipindah modalInstance.hide();
}, 50); // Delay singkat biar aman }, 50);
self.toastMessage.innerText = self.toastMessage.innerText =
"File uploaded successfully!"; "File uploaded successfully!";
self.toast.show(); self.toast.show();
@@ -331,67 +331,23 @@ class PbgTasks {
} }
} }
handleUploadBeritaAcara() { handleDownloadButtons(buttonClass) {
const modalEl = document.getElementById("modalBeritaAcara"); const buttons = document.querySelectorAll(`.${buttonClass}`);
const modalInstance = new bootstrap.Modal(modalEl);
const modalTaskIdSpan = modalEl.querySelector("#modal-task-id span");
modalEl.addEventListener("hide.bs.modal", () => { buttons.forEach((button) => {
if ( button.addEventListener("click", () => {
document.activeElement && const attachmentId = button.getAttribute("data-id");
modalEl.contains(document.activeElement) const originalContent = button.innerHTML;
) {
document.activeElement.blur();
setTimeout(() => {
document.body.focus();
}, 10);
}
});
// Only bind once // Disable button & show loading
if (!window.uploadHandlerBoundBeritaAcara) { button.disabled = true;
document.addEventListener("click", (event) => { button.innerHTML = `
const uploadBtn = event.target.closest( <span class="spinner-border spinner-border-sm me-1" role="status" aria-hidden="true"></span>
".upload-btn-berita-acara" Loading...
); `;
if (uploadBtn) { fetch(`/api/pbg-task-attachment/${attachmentId}/download`, {
const taskId = uploadBtn.getAttribute("data-id"); method: "GET",
modalTaskIdSpan.textContent = taskId;
// Set task ID on the form element so Dropzone can read it
document.getElementById(
"dropzoneBeritaAcara"
).dataset.taskId = taskId;
modalInstance.show();
}
});
window.uploadHandlerBoundBeritaAcara = true;
}
// Prevent multiple Dropzone instances
if (
!Dropzone.instances.some(
(dz) => dz.element.id === "dropzoneBeritaAcara"
)
) {
const self = this;
new Dropzone("#dropzoneBeritaAcara", {
url: function () {
const taskId = document.getElementById(
"dropzoneBeritaAcara"
).dataset.taskId;
return `/api/pbg-task-attachment/${taskId}`;
},
maxFiles: 1,
maxFilesize: 5,
acceptedFiles: ".jpg,.png,.pdf",
autoProcessQueue: false,
addRemoveLinks: false,
priviewsContainer: null,
paramName: "file",
headers: { headers: {
"X-CSRF-TOKEN": document.querySelector( "X-CSRF-TOKEN": document.querySelector(
'meta[name="csrf-token"]' 'meta[name="csrf-token"]'
@@ -401,92 +357,48 @@ class PbgTasks {
.getAttribute("content")}`, .getAttribute("content")}`,
Accept: "application/json", Accept: "application/json",
}, },
params: { })
pbg_type: "berita_acara", .then((response) => {
}, if (!response.ok) {
dictDefaultMessage: "Drop your file here or click to upload.", throw new Error("File not found or server error.");
init: function () { }
const dz = this; return response
dz.on("addedfile", function (file) { .blob()
// Always ensure only one file .then((blob) => ({ blob, response }));
if (dz.files.length > 1) { })
dz.removeFile(dz.files[0]); .then(({ blob, response }) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
const contentDisposition = response.headers.get(
"Content-Disposition"
);
let fileName = "downloaded-file";
if (contentDisposition?.includes("filename=")) {
fileName = contentDisposition
.split("filename=")[1]
.replace(/"/g, "")
.trim();
} }
// Small delay helps ensure UI updates even with same file a.download = fileName;
setTimeout(() => { document.body.appendChild(a);
document.getElementById( a.click();
"uploadedFileNameBeritaAcara" a.remove();
).textContent = file.name; window.URL.revokeObjectURL(url);
document })
.getElementById("fileInfoBeritaAcara") .catch((error) => {
.classList.remove("d-none"); console.error("Download failed:", error);
document alert("Failed to download file.");
.querySelector(".dz-message") })
.classList.add("d-none"); .finally(() => {
}, 10); button.disabled = false;
button.innerHTML = originalContent;
}); });
dz.on("removedfile", function () {
document
.getElementById("fileInfoBeritaAcara")
.classList.add("d-none");
document.getElementById(
"uploadedFileNameBeritaAcara"
).textContent = "";
document
.querySelector(".dz-message")
.classList.remove("d-none");
}); });
document
.getElementById("removeFileBtnBeritaAcara")
.addEventListener("click", function () {
dz.removeAllFiles();
}); });
document
.getElementById("submitBeritaAcara")
.addEventListener("click", () => {
if (dz.getQueuedFiles().length > 0) {
dz.processQueue();
} else {
self.toastMessage.innerText =
"Please select a file to upload.";
self.toast.show();
}
});
dz.on("success", () => {
dz.removeAllFiles(true);
// Reset UI
document
.getElementById("fileInfoBeritaAcara")
.classList.add("d-none");
document.getElementById(
"uploadedFileNameBeritaAcara"
).textContent = "";
document.querySelector(".dz-message").style.display =
"block";
document.activeElement.blur(); // Lepas fokus dari tombol
setTimeout(() => {
document.body.focus(); // Atau fokus ke tombol lain kalau mau
modalInstance.hide(); // Tutup modal SETELAH fokus dipindah
}, 50); // Delay singkat biar aman
self.toastMessage.innerText =
"File uploaded successfully!";
self.toast.show();
self.initTableRequestAssignment();
});
dz.on("error", (file, message) => {
self.toastMessage.innerText =
message || "Upload failed!";
self.toast.show();
});
},
});
}
} }
} }

View File

@@ -0,0 +1,50 @@
@extends('layouts.vertical', ['subtitle' => $title])
@section('content')
@include('layouts.partials.page-title', ['title' => 'Data', 'subtitle' => 'PBG'])
<div class="row mb-4">
<div class="col-sm-12">
<div class="card border shadow-sm">
<div class="card-body">
<h5 class="mb-3">{{ $title }}</h5>
<p><strong>Document Number:</strong> {{ $pbg->document_number }}</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="card border shadow-sm">
<div class="card-body">
@php
$extension = strtolower(pathinfo($data->file_name, PATHINFO_EXTENSION));
@endphp
@if (in_array($extension, ['jpg', 'jpeg', 'png']))
<div class="text-center">
<img
src="{{ asset('storage/' . $data->file_path) }}"
alt="{{ $data->file_name }}"
class="img-fluid border rounded"
style="max-height: 600px;"
>
</div>
@elseif ($extension === 'pdf')
<iframe
src="{{ asset('storage/' . $data->file_path) }}"
width="100%"
height="700px"
style="border: none;"
></iframe>
@else
<div class="alert alert-warning">
Unsupported file type: <strong>{{ $extension }}</strong>
</div>
@endif
</div>
</div>
</div>
</div>
@endsection

View File

@@ -99,7 +99,6 @@
<button type="button" class="btn-close" data-bs-dismiss="modal"></button> <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<p id="modal-task-id">Task ID: <span></span></p>
<div class="mb-3"> <div class="mb-3">
<form action="/upload-bukti-bayar" method="POST" class="dropzone" id="dropzoneBuktiBayar"> <form action="/upload-bukti-bayar" method="POST" class="dropzone" id="dropzoneBuktiBayar">
<div class="dz-message needsclick"> <div class="dz-message needsclick">
@@ -137,7 +136,6 @@
<button type="button" class="btn-close" data-bs-dismiss="modal"></button> <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div> </div>
<div class="modal-body"> <div class="modal-body">
<p id="modal-task-id">Task ID: <span></span></p>
<div class="mb-3"> <div class="mb-3">
<form action="/upload-berita-acara" method="POST" class="dropzone" id="dropzoneBeritaAcara"> <form action="/upload-berita-acara" method="POST" class="dropzone" id="dropzoneBeritaAcara">
<div class="dz-message needsclick"> <div class="dz-message needsclick">

View File

@@ -185,5 +185,6 @@ Route::group(['middleware' => 'auth:sanctum'], function (){
Route::controller(PbgTaskAttachmentsController::class)->group(function (){ Route::controller(PbgTaskAttachmentsController::class)->group(function (){
Route::post('/pbg-task-attachment/{pbg_task_id}', 'store')->name('api.pbg-task.upload'); Route::post('/pbg-task-attachment/{pbg_task_id}', 'store')->name('api.pbg-task.upload');
Route::get('/pbg-task-attachment/{attachment_id}/download', 'download')->name('api.pbg-task.download');
}); });
}); });

View File

@@ -14,6 +14,7 @@ use App\Http\Controllers\InvitationsController;
use App\Http\Controllers\Master\UsersController; use App\Http\Controllers\Master\UsersController;
use App\Http\Controllers\MenusController; use App\Http\Controllers\MenusController;
use App\Http\Controllers\PaymentRecapsController; use App\Http\Controllers\PaymentRecapsController;
use App\Http\Controllers\PbgTaskAttachmentsController;
use App\Http\Controllers\ReportPaymentRecapsController; use App\Http\Controllers\ReportPaymentRecapsController;
use App\Http\Controllers\ReportPbgPTSPController; use App\Http\Controllers\ReportPbgPTSPController;
use App\Http\Controllers\RequestAssignment\PbgTaskController; use App\Http\Controllers\RequestAssignment\PbgTaskController;
@@ -64,6 +65,7 @@ Route::group(['middleware' => 'auth'], function(){
// data - PBG // data - PBG
Route::resource('/pbg-task', PbgTaskController::class); Route::resource('/pbg-task', PbgTaskController::class);
Route::get('/pbg-task-attachment/{attachment_id}', [PbgTaskAttachmentsController::class, 'show'])->name('pbg-task-attachment.show');
// data settings // data settings
Route::resource('/data-settings', DataSettingController::class); Route::resource('/data-settings', DataSettingController::class);