final upload form

This commit is contained in:
Fiqh Pratama
2025-10-13 17:28:34 +07:00
parent e8acdd3303
commit 8321df6d2b
13 changed files with 1966 additions and 244 deletions
@@ -7,7 +7,6 @@ use App\Http\Controllers\Controller;
use App\Models\FormEntertaimentPresentation; use App\Models\FormEntertaimentPresentation;
use App\Models\Rayon; use App\Models\Rayon;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Region; use App\Models\Region;
use App\Models\Cabang; use App\Models\Cabang;
use App\Models\UserHasCabang; use App\Models\UserHasCabang;
@@ -23,16 +22,54 @@ use App\Mail\ExpenseCreated;
use App\Helpers\WhatsappHelper; use App\Helpers\WhatsappHelper;
use App\Helpers\AuditTrailHelper; use App\Helpers\AuditTrailHelper;
use App\Models\Admin; use App\Models\Admin;
use App\Rules\FileType;
use App\Helpers\BudgetHelper; use App\Helpers\BudgetHelper;
use App\Helpers\NotificationHelper; use App\Helpers\NotificationHelper;
use App\Helpers\OutstandingHelper; use App\Helpers\OutstandingHelper;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use App\Services\BrevoService; use App\Services\BrevoService;
use App\Services\AttachmentService;
use App\Enums\AttachmentTableName;
use App\Models\AttachmentForm;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Carbon\Carbon; use Carbon\Carbon;
class FormEntertainmentPresentationController extends Controller class FormEntertainmentPresentationController extends Controller
{ {
protected AttachmentService $attachmentService;
/**
* Attachment categories for Entertainment & Presentation.
*
* @var array<string,string>
*/
protected array $attachmentCategories = [
'bukti_total' => 'Bukti Total',
];
/**
* Blocked extensions to avoid dangerous uploads.
*
* @var array<int,string>
*/
protected array $blockedExtensions = ['exe', 'dll', 'sh', 'bat', 'cmd', 'msi'];
/**
* Supported image extensions for inline preview.
*
* @var array<int,string>
*/
protected array $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
public function __construct(AttachmentService $attachmentService)
{
$this->attachmentService = $attachmentService;
view()->share('entertainmentAttachmentCategories', $this->attachmentCategories);
view()->share('entertainmentAttachmentCategoryKeys', array_keys($this->attachmentCategories));
view()->share('entertainmentBlockedExtensions', $this->blockedExtensions);
}
public function index() public function index()
{ {
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
@@ -60,7 +97,7 @@ class FormEntertainmentPresentationController extends Controller
$forms = FormEntertaimentPresentation::whereBetween('tanggal', [$dataRetrievalStartDate, $currentPeriodClosingDate]) $forms = FormEntertaimentPresentation::whereBetween('tanggal', [$dataRetrievalStartDate, $currentPeriodClosingDate])
->orderBy('tanggal', 'desc') ->orderBy('tanggal', 'desc')
->with('user') ->with(['user', 'attachments'])
->get(); ->get();
$availableBudget = null; $availableBudget = null;
@@ -105,6 +142,11 @@ class FormEntertainmentPresentationController extends Controller
); );
session()->put('redirect_url', route('forms.entertainment')); session()->put('redirect_url', route('forms.entertainment'));
$forms->each(function (FormEntertaimentPresentation $form) {
$form->setAttribute('formatted_attachments', $this->formatAttachmentCollection($form));
});
return view('backend.pages.forms.entertainment.index', [ return view('backend.pages.forms.entertainment.index', [
'forms' => $forms, 'forms' => $forms,
'availableBudget' => $availableBudget, 'availableBudget' => $availableBudget,
@@ -118,8 +160,10 @@ class FormEntertainmentPresentationController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
$form = FormEntertaimentPresentation::with('user')->findOrFail($id); $form = FormEntertaimentPresentation::with(['user', 'attachments'])->findOrFail($id);
$form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null; $attachments = $this->formatAttachmentCollection($form);
$form->setAttribute('formatted_attachments', $attachments);
$form->bukti_total = $this->getAttachmentDownloadUrlByCategory($attachments, 'bukti_total');
return response()->json($form); return response()->json($form);
} }
@@ -128,11 +172,13 @@ class FormEntertainmentPresentationController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
$form = FormEntertaimentPresentation::with('user')->findOrFail($id); $form = FormEntertaimentPresentation::with(['user', 'attachments'])->findOrFail($id);
$form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null; $attachments = $this->formatAttachmentCollection($form);
$form->setAttribute('formatted_attachments', $attachments);
return view('backend.pages.forms.entertainment.view', [ return view('backend.pages.forms.entertainment.view', [
'form' => $form, 'form' => $form,
'attachments' => $attachments,
]); ]);
} }
@@ -147,16 +193,20 @@ class FormEntertainmentPresentationController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.entertainment.create']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.create']);
$request->validate([ $validator = Validator::make($request->all(), [
'tanggal' => 'required', 'tanggal' => 'required|date',
'jenis' => 'required|in:entertainment,presentation,sponsorship', 'jenis' => 'required|in:entertainment,presentation,sponsorship',
'keterangan' => 'required', 'keterangan' => 'required|string',
'total' => 'required|numeric|min:1', 'total' => 'required|numeric|min:1',
'name' => 'required', 'name' => 'required|string',
'alamat' => 'required', 'alamat' => 'required|string',
'nik_or_npwp' => 'required', 'nik_or_npwp' => 'required|string',
'bukti_total' => ['nullable', 'file', 'max:51200'], 'attachments' => 'nullable|array',
'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
'attachments.*.file_path' => 'nullable|file|max:10240',
]); ]);
$this->addAttachmentValidationRules($validator, $request);
$validator->validate();
$tanggal = Carbon::parse($request->tanggal); $tanggal = Carbon::parse($request->tanggal);
$startDay = (int) env('STARTING_DATE', 11); $startDay = (int) env('STARTING_DATE', 11);
@@ -177,7 +227,7 @@ class FormEntertainmentPresentationController extends Controller
if ($tanggal->lt($startDate) || $tanggal->gt($closingDate)) { if ($tanggal->lt($startDate) || $tanggal->gt($closingDate)) {
session()->flash('error', "Gagal, tanggal tidak berada dalam periode input: {$startDate->format('d M')} - {$closingDate->format('d M')}"); session()->flash('error', "Gagal, tanggal tidak berada dalam periode input: {$startDate->format('d M')} - {$closingDate->format('d M')}");
return redirect()->back(); return redirect()->back()->withInput();
} }
// Hitung periode budget dari tanggal form // Hitung periode budget dari tanggal form
@@ -187,9 +237,9 @@ class FormEntertainmentPresentationController extends Controller
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang; $cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang;
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear); $availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
if($request->total > $availableBudget) { if ($request->total > $availableBudget) {
session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya'); session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya');
return redirect()->back(); return redirect()->back()->withInput();
} }
$region = Region::where('id', $cabang->region_id)->first(); $region = Region::where('id', $cabang->region_id)->first();
@@ -197,48 +247,68 @@ class FormEntertainmentPresentationController extends Controller
$kategori = ""; $kategori = "";
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') { if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
$kategori = Kategori::where('name', 'Entertainment')->first(); $kategori = Kategori::where('name', 'Entertainment')->first();
}elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') { } elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') {
$kategori = Kategori::where('name', 'Presentation')->first(); $kategori = Kategori::where('name', 'Presentation')->first();
}elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') { } elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
$kategori = Kategori::where('name', 'Sponsorship')->first(); $kategori = Kategori::where('name', 'Sponsorship')->first();
} }
$filePaths = [];
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment'; $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment';
if ($request->hasFile('bukti_total')) {
$bukti_total = $request->file('bukti_total');
$filename = Str::uuid() . '.' . $bukti_total->extension();
$filePaths['bukti_total'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile(
$folderPath,
$bukti_total->getContent(),
$filename
);
}
// Generate sequence number and expense number // Generate sequence number and expense number
$sequence_number = FormEntertaimentPresentation::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . '%')->count() + 1; $sequence_number = FormEntertaimentPresentation::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . '%')->count() + 1;
$formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT); $formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT);
$expense_number = $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . $formatted_sequence_number; $expense_number = $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . $formatted_sequence_number;
// Save the form data DB::beginTransaction();
$form = FormEntertaimentPresentation::create([ try {
'expense_number' => $expense_number, $attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
'user_id' => auth()->user()->id,
'tanggal' => $request->tanggal, if (empty($attachmentsPayload)) {
'jenis' => $request->jenis, throw ValidationException::withMessages([
'keterangan' => $request->keterangan, 'attachments.0.file_path' => 'Minimal satu lampiran diperlukan.',
'total' => $request->total, ]);
'name' => $request->name, }
'alamat' => $request->alamat,
'nik_or_npwp' => $request->nik_or_npwp, $primaryAttachmentPath = $attachmentsPayload[0]['file_path'] ?? null;
'bukti_total' => $filePaths['bukti_total'] ?? null,
'account_number' => $kategori->account_number, $form = FormEntertaimentPresentation::create([
'status' => 'On Progress', 'expense_number' => $expense_number,
]); 'user_id' => auth()->user()->id,
'tanggal' => $request->tanggal,
'jenis' => $request->jenis,
'keterangan' => $request->keterangan,
'total' => $request->total,
'name' => $request->name,
'alamat' => $request->alamat,
'nik_or_npwp' => $request->nik_or_npwp,
'bukti_total' => $primaryAttachmentPath,
'account_number' => $kategori->account_number,
'status' => 'On Progress',
]);
$this->attachmentService->addMultipleAttachments(
$form->id,
AttachmentTableName::FORM_ENTERTAINMENT_PRESENTATION,
$attachmentsPayload
);
DB::commit();
} catch (ValidationException $exception) {
DB::rollBack();
throw $exception;
} catch (\Throwable $th) {
DB::rollBack();
Log::error('Failed to create Entertainment Presentation form', [
'user_id' => auth()->id(),
'message' => $th->getMessage(),
'trace' => $th->getTraceAsString(),
]);
session()->flash('error', 'Terjadi kesalahan saat menyimpan data, silakan coba lagi.');
return redirect()->back()->withInput();
}
$name = auth()->user()->name; $name = auth()->user()->name;
$tanggal = $form->created_at; $tanggal = $form->created_at;
@@ -262,7 +332,7 @@ class FormEntertainmentPresentationController extends Controller
if ($role === 'Marketing Information System') { if ($role === 'Marketing Information System') {
return true; // Tidak ada filter cabang untuk peran ini return true; // Tidak ada filter cabang untuk peran ini
} }
if (!$user->cabang || !$user->cabang->cabang) { if (!$user->cabang || !$user->cabang->cabang) {
return false; // Pastikan user memiliki cabang return false; // Pastikan user memiliki cabang
} }
@@ -325,14 +395,17 @@ class FormEntertainmentPresentationController extends Controller
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
$role = auth()->user()->getRoleNames()[0]; $role = auth()->user()->getRoleNames()[0];
$form = FormEntertaimentPresentation::findOrfail($id); $form = FormEntertaimentPresentation::with('attachments')->findOrFail($id);
if($form->status != 'On Progress' && $role == 'Medical Representatif') { if($form->status != 'On Progress' && $role == 'Medical Representatif') {
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.'); session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
return redirect()->back(); return redirect()->back();
} }
$attachments = $this->formatAttachmentCollection($form);
return view('backend.pages.forms.entertainment.edit', [ return view('backend.pages.forms.entertainment.edit', [
'form' => $form 'form' => $form,
'attachments' => $attachments,
]); ]);
} }
@@ -340,7 +413,7 @@ class FormEntertainmentPresentationController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']); $this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
$role = auth()->user()->getRoleNames()[0]; $role = auth()->user()->getRoleNames()[0];
$form = FormEntertaimentPresentation::findOrFail($id); $form = FormEntertaimentPresentation::with('attachments')->findOrFail($id);
$cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()?->cabang_id; $cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()?->cabang_id;
if (!$cabang_id) { if (!$cabang_id) {
@@ -364,18 +437,22 @@ class FormEntertainmentPresentationController extends Controller
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear); $availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
$request->validate([ $validator = Validator::make($request->all(), [
'tanggal' => 'required', 'tanggal' => 'required|date',
'jenis' => 'required|in:entertainment,presentation,sponsorship', 'jenis' => 'required|in:entertainment,presentation,sponsorship',
'keterangan' => 'required', 'keterangan' => 'required|string',
'total' => 'required|numeric|min:1|max:' . $availableBudget, 'total' => 'required|numeric|min:1|max:' . $availableBudget,
'name' => 'required', 'name' => 'required|string',
'alamat' => 'required', 'alamat' => 'required|string',
'nik_or_npwp' => 'required', 'nik_or_npwp' => 'required|string',
'bukti_total' => ['nullable', 'file', 'max:51200'], 'attachments' => 'nullable|array',
'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
'attachments.*.file_path' => 'nullable|file|max:10240',
]); ]);
$this->addAttachmentValidationRules($validator, $request);
$validator->validate();
if($form->status != 'On Progress' && $role == 'Medical Representatif') { if ($form->status != 'On Progress' && $role == 'Medical Representatif') {
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.'); session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
return redirect()->back(); return redirect()->back();
} }
@@ -386,46 +463,90 @@ class FormEntertainmentPresentationController extends Controller
$kategori = ""; $kategori = "";
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') { if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
$kategori = Kategori::where('name', 'Entertainment')->first(); $kategori = Kategori::where('name', 'Entertainment')->first();
}elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') { } elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') {
$kategori = Kategori::where('name', 'Presentation')->first(); $kategori = Kategori::where('name', 'Presentation')->first();
}elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') { } elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
$kategori = Kategori::where('name', 'Sponsorship')->first(); $kategori = Kategori::where('name', 'Sponsorship')->first();
} }
$filePaths = [];
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment'; $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment';
if ($request->hasFile('bukti_total')) { DB::beginTransaction();
$bukti_total = $request->file('bukti_total'); try {
$filename = Str::uuid() . '.' . $bukti_total->extension(); $attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
$primaryAttachmentPath = !empty($attachmentsPayload)
? $attachmentsPayload[0]['file_path']
: $form->bukti_total;
$filePaths['bukti_total'] = $folderPath . '/' . $filename; $form->update([
'tanggal' => $request->tanggal,
'jenis' => $request->jenis,
'keterangan' => $request->keterangan,
'total' => $request->total,
'name' => $request->name,
'alamat' => $request->alamat,
'nik_or_npwp' => $request->nik_or_npwp,
'bukti_total' => $primaryAttachmentPath,
'account_number' => $kategori->account_number,
]);
NextCloudHelper::uploadFile( if (!empty($attachmentsPayload)) {
$folderPath, $this->attachmentService->addMultipleAttachments(
$bukti_total->getContent(), $form->id,
$filename AttachmentTableName::FORM_ENTERTAINMENT_PRESENTATION,
); $attachmentsPayload
);
}
DB::commit();
} catch (ValidationException $exception) {
DB::rollBack();
throw $exception;
} catch (\Throwable $th) {
DB::rollBack();
Log::error('Failed to update Entertainment Presentation form', [
'form_id' => $form->id,
'message' => $th->getMessage(),
'trace' => $th->getTraceAsString(),
]);
session()->flash('error', 'Terjadi kesalahan saat memperbarui data, silakan coba lagi.');
return redirect()->back()->withInput();
} }
// Save the form data
$form->update([
'tanggal' => $request->tanggal,
'jenis' => $request->jenis,
'keterangan' => $request->keterangan,
'total' => $request->total,
'name' => $request->name,
'alamat' => $request->alamat,
'nik_or_npwp' => $request->nik_or_npwp,
'bukti_total' => $filePaths['bukti_total'] ?? $form->bukti_total,
'account_number' => $kategori->account_number,
]);
AuditTrailHelper::AddAuditTrail('Update', 'Update Expense at Form Entertainment Presentation (' . $form->expense_number . ')'); AuditTrailHelper::AddAuditTrail('Update', 'Update Expense at Form Entertainment Presentation (' . $form->expense_number . ')');
session()->flash('success', 'Form has been updated.'); session()->flash('success', 'Form has been updated.');
return redirect()->back(); return redirect()->back();
} }
public function deleteAttachment(Request $request, $formId, $attachmentId)
{
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
$form = FormEntertaimentPresentation::findOrFail($formId);
$role = auth()->user()->getRoleNames()[0];
if (($form->status !== 'On Progress' && $form->status !== 'Rejected') && $role === 'Medical Representatif') {
return response()->json(['message' => 'You cannot modify attachments once the form is approved or closed.'], 403);
}
$attachment = AttachmentForm::where('id', $attachmentId)
->where('form_id', $form->id)
->where('table_name', AttachmentTableName::FORM_ENTERTAINMENT_PRESENTATION)
->first();
if (!$attachment) {
return response()->json(['message' => 'Attachment not found.'], 404);
}
$this->attachmentService->deleteAttachment($attachment->id);
AuditTrailHelper::AddAuditTrail('Delete Attachment', 'Delete Attachment at Form Entertainment Presentation (' . $form->expense_number . ')');
return response()->json(['message' => 'Attachment deleted successfully.']);
}
public function approve($id) public function approve($id)
{ {
$this->checkAuthorization(auth()->user(), ['approval.approve']); $this->checkAuthorization(auth()->user(), ['approval.approve']);
@@ -830,4 +951,190 @@ class FormEntertainmentPresentationController extends Controller
session()->flash('success', 'Form has been deleted.'); session()->flash('success', 'Form has been deleted.');
return redirect()->back(); return redirect()->back();
} }
protected function addAttachmentValidationRules(\Illuminate\Validation\Validator $validator, Request $request): void
{
$validator->after(function ($validator) use ($request) {
$inputAttachments = $request->input('attachments', []);
$fileAttachments = $request->file('attachments', []);
foreach ($inputAttachments as $index => $input) {
$category = $input['file_category'] ?? null;
$file = $fileAttachments[$index]['file_path'] ?? null;
if ($file && !$category) {
$validator->errors()->add("attachments.{$index}.file_category", 'Attachment category is required.');
}
if ($category && !$file) {
$validator->errors()->add("attachments.{$index}.file_path", 'Attachment file is required.');
continue;
}
if (!$file) {
continue;
}
$extension = strtolower((string) $file->getClientOriginalExtension());
if ($this->isBlockedExtension($extension)) {
$validator->errors()->add("attachments.{$index}.file_path", 'File type is not allowed.');
continue;
}
$mimeType = (string) $file->getMimeType();
if (in_array($extension, $this->imageExtensions, true) && strpos($mimeType, 'image/') !== 0) {
$validator->errors()->add("attachments.{$index}.file_path", 'Invalid image file.');
}
if ($extension === 'pdf' && $mimeType !== 'application/pdf') {
$validator->errors()->add("attachments.{$index}.file_path", 'Invalid PDF file.');
}
}
foreach ($fileAttachments as $index => $files) {
$file = $files['file_path'] ?? null;
if ($file && !isset($inputAttachments[$index])) {
$validator->errors()->add("attachments.{$index}.file_category", 'Attachment category is required.');
}
}
});
}
protected function buildAttachmentPayload(Request $request, string $folderPath): array
{
$payload = [];
$inputs = $request->input('attachments', []);
$files = $request->file('attachments', []);
foreach ($inputs as $index => $input) {
$category = $input['file_category'] ?? null;
$file = $files[$index]['file_path'] ?? null;
if (!$category || !$file) {
continue;
}
$extension = strtolower((string) $file->getClientOriginalExtension());
if ($this->isBlockedExtension($extension)) {
throw ValidationException::withMessages([
"attachments.{$index}.file_path" => 'File type is not allowed.',
]);
}
$filename = Str::uuid() . '.' . $extension;
$filePath = rtrim($folderPath, '/') . '/' . $filename;
$uploadResponse = NextCloudHelper::uploadFile(
$folderPath,
$file->getContent(),
$filename
);
if (is_array($uploadResponse) && isset($uploadResponse['success']) && $uploadResponse['success'] === false) {
throw ValidationException::withMessages([
"attachments.{$index}.file_path" => $uploadResponse['message'] ?? 'Failed to upload attachment.',
]);
}
$payload[] = [
'file_category' => $category,
'file_path' => $filePath,
];
}
return $payload;
}
protected function formatAttachmentCollection(FormEntertaimentPresentation $form): array
{
if (!$form->relationLoaded('attachments')) {
$form->load('attachments');
}
$attachments = $form->attachments->map(function (AttachmentForm $attachment) {
if (!$attachment->file_path) {
return null;
}
return $this->formatAttachmentData(
$attachment->id,
$attachment->file_category,
$attachment->file_path
);
})->filter()->values()->all();
$hasLegacyPath = collect($attachments)->contains(function ($attachment) use ($form) {
return isset($attachment['file_path']) && $attachment['file_path'] === $form->bukti_total;
});
if ($form->bukti_total && !$hasLegacyPath) {
$attachments[] = $this->formatAttachmentData(null, 'bukti_total', $form->bukti_total, false);
}
return $attachments;
}
protected function formatAttachmentData(?int $id, ?string $category, string $filePath, bool $canDelete = true): array
{
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$previewType = $this->determinePreviewType($extension);
return [
'id' => $id,
'file_category' => $category,
'category_label' => $this->getCategoryLabel($category),
'file_path' => $filePath,
'download_url' => NextCloudHelper::getFileUrl($filePath),
'preview_url' => in_array($previewType, ['image', 'pdf'], true) ? NextCloudHelper::getPreviewUrl($filePath) : null,
'preview_type' => $previewType,
'filename' => basename($filePath),
'extension' => $extension,
'can_delete' => $canDelete && !is_null($id),
];
}
protected function determinePreviewType(?string $extension): string
{
$extension = strtolower((string) $extension);
if (in_array($extension, $this->imageExtensions, true)) {
return 'image';
}
if ($extension === 'pdf') {
return 'pdf';
}
return 'other';
}
protected function isBlockedExtension(?string $extension): bool
{
return in_array(strtolower((string) $extension), $this->blockedExtensions, true);
}
protected function getAttachmentDownloadUrlByCategory(array $attachments, string $category): ?string
{
foreach ($attachments as $attachment) {
if (($attachment['file_category'] ?? null) === $category) {
return $attachment['download_url'] ?? null;
}
}
return null;
}
protected function getCategoryLabel(?string $category): string
{
if (!$category) {
return 'Lampiran';
}
if (isset($this->attachmentCategories[$category])) {
return $this->attachmentCategories[$category];
}
return ucwords(str_replace('_', ' ', $category));
}
} }
@@ -7,7 +7,6 @@ use App\Http\Controllers\Controller;
use App\Models\FormMeetingSeminar; use App\Models\FormMeetingSeminar;
use App\Models\Rayon; use App\Models\Rayon;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Region; use App\Models\Region;
use App\Models\Cabang; use App\Models\Cabang;
use App\Models\UserHasCabang; use App\Models\UserHasCabang;
@@ -22,17 +21,54 @@ use App\Mail\ExpenseCreated;
use App\Mail\FinalApprove; use App\Mail\FinalApprove;
use App\Helpers\WhatsappHelper; use App\Helpers\WhatsappHelper;
use App\Helpers\AuditTrailHelper; use App\Helpers\AuditTrailHelper;
use App\Rules\FileType;
use App\Models\Admin; use App\Models\Admin;
use App\Helpers\BudgetHelper; use App\Helpers\BudgetHelper;
use App\Helpers\NotificationHelper; use App\Helpers\NotificationHelper;
use App\Helpers\OutstandingHelper; use App\Helpers\OutstandingHelper;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use App\Services\BrevoService; use App\Services\BrevoService;
use App\Services\AttachmentService;
use App\Enums\AttachmentTableName;
use App\Models\AttachmentForm;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Carbon\Carbon; use Carbon\Carbon;
class FormMeetingSeminarController extends Controller class FormMeetingSeminarController extends Controller
{ {
protected AttachmentService $attachmentService;
/**
* @var array<string,string>
*/
protected array $attachmentCategories = [
'bukti_allowance' => 'Bukti Allowance',
'bukti_transport_ankot' => 'Bukti Transport Antar Kota',
'bukti_hotel' => 'Bukti Hotel',
];
/**
* Blocked file extensions (case insensitive).
*
* @var array<int,string>
*/
protected array $blockedExtensions = ['exe', 'dll', 'sh', 'bat', 'cmd', 'msi'];
/**
* Image extensions that can be previewed inline.
*
* @var array<int,string>
*/
protected array $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
public function __construct(AttachmentService $attachmentService)
{
$this->attachmentService = $attachmentService;
view()->share('meetingAttachmentCategories', $this->attachmentCategories);
view()->share('meetingAttachmentCategoryKeys', array_keys($this->attachmentCategories));
view()->share('meetingBlockedExtensions', $this->blockedExtensions);
}
public function index() public function index()
{ {
$this->checkAuthorization(auth()->user(), ['forms.meeting.view']); $this->checkAuthorization(auth()->user(), ['forms.meeting.view']);
@@ -120,10 +156,13 @@ class FormMeetingSeminarController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.meeting.view']); $this->checkAuthorization(auth()->user(), ['forms.meeting.view']);
$form = FormMeetingSeminar::with('user')->findOrFail($id); $form = FormMeetingSeminar::with(['user', 'attachments'])->findOrFail($id);
$form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null; $attachments = $this->formatAttachmentCollection($form);
$form->bukti_transport_ankot = $form->bukti_transport_ankot ? NextCloudHelper::getFileUrl($form->bukti_transport_ankot) : null;
$form->bukti_hotel = $form->bukti_hotel ? NextCloudHelper::getFileUrl($form->bukti_hotel) : null; $form->bukti_allowance = $this->getAttachmentDownloadUrlByCategory($attachments, 'bukti_allowance');
$form->bukti_transport_ankot = $this->getAttachmentDownloadUrlByCategory($attachments, 'bukti_transport_ankot');
$form->bukti_hotel = $this->getAttachmentDownloadUrlByCategory($attachments, 'bukti_hotel');
$form->setAttribute('formatted_attachments', $attachments);
return response()->json($form); return response()->json($form);
} }
@@ -132,13 +171,12 @@ class FormMeetingSeminarController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.meeting.view']); $this->checkAuthorization(auth()->user(), ['forms.meeting.view']);
$form = FormMeetingSeminar::with('user')->findOrFail($id); $form = FormMeetingSeminar::with(['user', 'attachments'])->findOrFail($id);
$form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null; $attachments = $this->formatAttachmentCollection($form);
$form->bukti_transport_ankot = $form->bukti_transport_ankot ? NextCloudHelper::getFileUrl($form->bukti_transport_ankot) : null;
$form->bukti_hotel = $form->bukti_hotel ? NextCloudHelper::getFileUrl($form->bukti_hotel) : null;
return view('backend.pages.forms.meeting.view', [ return view('backend.pages.forms.meeting.view', [
'form' => $form, 'form' => $form,
'attachments' => $attachments,
]); ]);
} }
@@ -153,15 +191,17 @@ class FormMeetingSeminarController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.meeting.create']); $this->checkAuthorization(auth()->user(), ['forms.meeting.create']);
$request->validate([ $validator = Validator::make($request->all(), [
'tanggal' => 'required|date', 'tanggal' => 'required|date',
'allowance' => 'nullable|numeric', 'allowance' => 'nullable|numeric|min:0',
'transport_ankot' => 'nullable|numeric', 'transport_ankot' => 'nullable|numeric|min:0',
'hotel' => 'nullable|numeric', 'hotel' => 'nullable|numeric|min:0',
'bukti_allowance' => ['nullable', 'file', 'max:51200'], 'attachments' => 'nullable|array',
'bukti_transport_ankot' => ['nullable', 'file', 'max:51200'], 'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
'bukti_hotel' => ['nullable', 'file', 'max:51200'], 'attachments.*.file_path' => 'nullable|file', // 10 MB
]); ]);
$this->addAttachmentValidationRules($validator, $request);
$validator->validate();
$tanggal = Carbon::parse($request->tanggal); $tanggal = Carbon::parse($request->tanggal);
$startDay = (int) env('STARTING_DATE', 11); $startDay = (int) env('STARTING_DATE', 11);
@@ -202,31 +242,8 @@ class FormMeetingSeminarController extends Controller
$periodeMonth = strtolower($periodeDate->format('F')); $periodeMonth = strtolower($periodeDate->format('F'));
$periodeYear = (int) $periodeDate->format('Y'); $periodeYear = (int) $periodeDate->format('Y');
// Upload bukti file ke Nextcloud
$filePaths = [];
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/meeting'; $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/meeting';
if ($request->hasFile('bukti_allowance')) {
$bukti_allowance = $request->file('bukti_allowance');
$filename = Str::uuid() . '.' . $bukti_allowance->extension();
$filePaths['bukti_allowance'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_allowance->getContent(), $filename);
}
if ($request->hasFile('bukti_transport_ankot')) {
$bukti_transport_ankot = $request->file('bukti_transport_ankot');
$filename = Str::uuid() . '.' . $bukti_transport_ankot->extension();
$filePaths['bukti_transport_ankot'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_transport_ankot->getContent(), $filename);
}
if ($request->hasFile('bukti_hotel')) {
$bukti_hotel = $request->file('bukti_hotel');
$filename = Str::uuid() . '.' . $bukti_hotel->extension();
$filePaths['bukti_hotel'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_hotel->getContent(), $filename);
}
// Generate nomor expense // Generate nomor expense
$sequence_number = FormMeetingSeminar::withTrashed() $sequence_number = FormMeetingSeminar::withTrashed()
->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-MTG-' . date('ym') . '%') ->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-MTG-' . date('ym') . '%')
@@ -237,35 +254,64 @@ class FormMeetingSeminarController extends Controller
// Hitung nominal // Hitung nominal
$data_nominal = [ $data_nominal = [
'allowance' => $request->allowance ?? 0, 'allowance' => (float) ($request->allowance ?? 0),
'transport_ankot' => $request->transport_ankot ?? 0, 'transport_ankot' => (float) ($request->transport_ankot ?? 0),
'hotel' => $request->hotel ?? 0, 'hotel' => (float) ($request->hotel ?? 0),
]; ];
$totalNominal = array_sum($data_nominal);
// Validasi budget // Validasi budget
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear); $availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
// Check if the total nominal exceeds the available budget // Check if the total nominal exceeds the available budget
if(array_sum($data_nominal) > $availableBudget) { if ($totalNominal > $availableBudget) {
session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya'); session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya');
return redirect()->back(); return redirect()->back();
} }
// Save the form data DB::beginTransaction();
$form = FormMeetingSeminar::create([ try {
'expense_number' => $expense_number, $attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
'user_id' => auth()->user()->id,
'tanggal' => $request->tanggal, $form = FormMeetingSeminar::create([
'allowance' => $data_nominal['allowance'], 'expense_number' => $expense_number,
'transport_ankot' => $data_nominal['transport_ankot'], 'user_id' => auth()->user()->id,
'hotel' => $data_nominal['hotel'], 'tanggal' => $request->tanggal,
'total' => array_sum($data_nominal), 'allowance' => $data_nominal['allowance'],
'bukti_allowance' => $filePaths['bukti_allowance'] ?? null, 'transport_ankot' => $data_nominal['transport_ankot'],
'bukti_transport_ankot' => $filePaths['bukti_transport_ankot'] ?? null, 'hotel' => $data_nominal['hotel'],
'bukti_hotel' => $filePaths['bukti_hotel'] ?? null, 'total' => $totalNominal,
'account_number' => $kategori->account_number, 'bukti_allowance' => null,
'status' => 'On Progress', 'bukti_transport_ankot' => null,
]); 'bukti_hotel' => null,
'account_number' => $kategori?->account_number,
'status' => 'On Progress',
]);
if (!empty($attachmentsPayload)) {
$this->attachmentService->addMultipleAttachments(
$form->id,
AttachmentTableName::FORM_MEETING_SEMINAR,
$attachmentsPayload
);
}
DB::commit();
} catch (ValidationException $exception) {
DB::rollBack();
throw $exception;
} catch (\Throwable $th) {
DB::rollBack();
Log::error('Failed to create Meeting Seminar form', [
'user_id' => auth()->user()->id,
'message' => $th->getMessage(),
'trace' => $th->getTraceAsString(),
]);
session()->flash('error', 'Terjadi kesalahan saat menyimpan data, silakan coba lagi.');
return redirect()->back()->withInput();
}
$name = auth()->user()->name; $name = auth()->user()->name;
$tanggal = $form->tanggal; $tanggal = $form->tanggal;
@@ -352,14 +398,17 @@ class FormMeetingSeminarController extends Controller
$this->checkAuthorization(auth()->user(), ['forms.meeting.edit']); $this->checkAuthorization(auth()->user(), ['forms.meeting.edit']);
$role = auth()->user()->getRoleNames()[0]; $role = auth()->user()->getRoleNames()[0];
$form = FormMeetingSeminar::findOrfail($id); $form = FormMeetingSeminar::with('attachments')->findOrFail($id);
if($form->status != 'On Progress' && $role == 'Medical Representatif') { if($form->status != 'On Progress' && $role == 'Medical Representatif') {
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.'); session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
return redirect()->back(); return redirect()->back();
} }
$attachments = $this->formatAttachmentCollection($form);
return view('backend.pages.forms.meeting.edit', [ return view('backend.pages.forms.meeting.edit', [
'form' => $form 'form' => $form,
'attachments' => $attachments,
]); ]);
} }
@@ -367,17 +416,19 @@ class FormMeetingSeminarController extends Controller
{ {
$this->checkAuthorization(auth()->user(), ['forms.meeting.edit']); $this->checkAuthorization(auth()->user(), ['forms.meeting.edit']);
$role = auth()->user()->getRoleNames()[0]; $role = auth()->user()->getRoleNames()[0];
$form = FormMeetingSeminar::findOrFail($id); $form = FormMeetingSeminar::with('attachments')->findOrFail($id);
$request->validate([ $validator = Validator::make($request->all(), [
'tanggal' => 'required|date', 'tanggal' => 'required|date',
'allowance' => 'nullable|numeric', 'allowance' => 'nullable|numeric|min:0',
'transport_ankot' => 'nullable|numeric', 'transport_ankot' => 'nullable|numeric|min:0',
'hotel' => 'nullable|numeric', 'hotel' => 'nullable|numeric|min:0',
'bukti_allowance' => ['nullable', 'file', 'max:51200'], 'attachments' => 'nullable|array',
'bukti_transport_ankot' => ['nullable', 'file', 'max:51200'], 'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
'bukti_hotel' => ['nullable', 'file', 'max:51200'], 'attachments.*.file_path' => 'nullable|file', // 10 MB
]); ]);
$this->addAttachmentValidationRules($validator, $request);
$validator->validate();
if ($form->status != 'On Progress' && $role == 'Medical Representatif') { if ($form->status != 'On Progress' && $role == 'Medical Representatif') {
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.'); session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
@@ -393,35 +444,15 @@ class FormMeetingSeminarController extends Controller
$region = Region::find($cabang->region_id); $region = Region::find($cabang->region_id);
$kategori = Kategori::where('name', 'Meeting / Seminar')->first(); $kategori = Kategori::where('name', 'Meeting / Seminar')->first();
$filePaths = [];
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/meeting'; $folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/meeting';
if ($request->hasFile('bukti_allowance')) { $attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
$bukti_allowance = $request->file('bukti_allowance');
$filename = Str::uuid() . '.' . $bukti_allowance->extension();
$filePaths['bukti_allowance'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_allowance->getContent(), $filename);
}
if ($request->hasFile('bukti_transport_ankot')) {
$bukti_transport_ankot = $request->file('bukti_transport_ankot');
$filename = Str::uuid() . '.' . $bukti_transport_ankot->extension();
$filePaths['bukti_transport_ankot'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_transport_ankot->getContent(), $filename);
}
if ($request->hasFile('bukti_hotel')) {
$bukti_hotel = $request->file('bukti_hotel');
$filename = Str::uuid() . '.' . $bukti_hotel->extension();
$filePaths['bukti_hotel'] = $folderPath . '/' . $filename;
NextCloudHelper::uploadFile($folderPath, $bukti_hotel->getContent(), $filename);
}
// Hitung nominal total // Hitung nominal total
$data_nominal = [ $data_nominal = [
'allowance' => $request->allowance ?? 0, 'allowance' => (float) ($request->allowance ?? 0),
'transport_ankot' => $request->transport_ankot ?? 0, 'transport_ankot' => (float) ($request->transport_ankot ?? 0),
'hotel' => $request->hotel ?? 0, 'hotel' => (float) ($request->hotel ?? 0),
]; ];
$totalNominal = array_sum($data_nominal); $totalNominal = array_sum($data_nominal);
@@ -440,29 +471,76 @@ class FormMeetingSeminarController extends Controller
// Ambil budget tersedia // Ambil budget tersedia
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear); $availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
if(array_sum($data_nominal) > $availableBudget) { if ($totalNominal > $availableBudget) {
session()->flash('error', 'The total nominal exceeds the available budget.'); session()->flash('error', 'The total nominal exceeds the available budget.');
return redirect()->back(); return redirect()->back();
} }
// Save the form data DB::beginTransaction();
$form->update([ try {
'tanggal' => $request->tanggal, $form->update([
'allowance' => $data_nominal['allowance'], 'tanggal' => $request->tanggal,
'transport_ankot' => $data_nominal['transport_ankot'], 'allowance' => $data_nominal['allowance'],
'hotel' => $data_nominal['hotel'], 'transport_ankot' => $data_nominal['transport_ankot'],
'total' => $request->allowance + $request->transport_ankot + $request->hotel, 'hotel' => $data_nominal['hotel'],
'bukti_allowance' => $filePaths['bukti_allowance'] ?? $form->bukti_allowance, 'total' => $totalNominal,
'bukti_transport_ankot' => $filePaths['bukti_transport_ankot'] ?? $form->bukti_transport_ankot, 'account_number' => $kategori?->account_number,
'bukti_hotel' => $filePaths['bukti_hotel'] ?? $form->bukti_hotel, ]);
'account_number' => $kategori->account_number,
]); if (!empty($attachmentsPayload)) {
$this->attachmentService->addMultipleAttachments(
$form->id,
AttachmentTableName::FORM_MEETING_SEMINAR,
$attachmentsPayload
);
}
DB::commit();
} catch (\Throwable $th) {
DB::rollBack();
Log::error('Failed to update Meeting Seminar form', [
'form_id' => $form->id,
'message' => $th->getMessage(),
'trace' => $th->getTraceAsString(),
]);
session()->flash('error', 'Terjadi kesalahan saat memperbarui data, silakan coba lagi.');
return redirect()->back()->withInput();
}
AuditTrailHelper::AddAuditTrail('Update', 'Update Expense at Form Meeting Seminar (' . $form->expense_number . ')'); AuditTrailHelper::AddAuditTrail('Update', 'Update Expense at Form Meeting Seminar (' . $form->expense_number . ')');
session()->flash('success', 'Form has been updated.'); session()->flash('success', 'Form has been updated.');
return redirect()->back(); return redirect()->back();
} }
public function deleteAttachment(Request $request, $formId, $attachmentId)
{
$this->checkAuthorization(auth()->user(), ['forms.meeting.edit']);
$form = FormMeetingSeminar::findOrFail($formId);
$role = auth()->user()->getRoleNames()[0];
if (($form->status !== 'On Progress' && $form->status !== 'Rejected') && $role === 'Medical Representatif') {
return response()->json(['message' => 'You cannot modify attachments once the form is approved or closed.'], 403);
}
$attachment = AttachmentForm::where('id', $attachmentId)
->where('form_id', $form->id)
->where('table_name', AttachmentTableName::FORM_MEETING_SEMINAR)
->first();
if (!$attachment) {
return response()->json(['message' => 'Attachment not found.'], 404);
}
$this->attachmentService->deleteAttachment($attachment->id);
AuditTrailHelper::AddAuditTrail('Delete Attachment', 'Delete Attachment at Form Meeting Seminar (' . $form->expense_number . ')');
return response()->json(['message' => 'Attachment deleted successfully.']);
}
public function approve(Request $request, $id) public function approve(Request $request, $id)
{ {
$this->checkAuthorization(auth()->user(), ['approval.approve']); $this->checkAuthorization(auth()->user(), ['approval.approve']);
@@ -869,4 +947,194 @@ class FormMeetingSeminarController extends Controller
session()->flash('success', 'Form has been deleted.'); session()->flash('success', 'Form has been deleted.');
return redirect()->back(); return redirect()->back();
} }
protected function addAttachmentValidationRules(\Illuminate\Validation\Validator $validator, Request $request): void
{
$validator->after(function ($validator) use ($request) {
$inputAttachments = $request->input('attachments', []);
$fileAttachments = $request->file('attachments', []);
foreach ($inputAttachments as $index => $input) {
$category = $input['file_category'] ?? null;
$file = $fileAttachments[$index]['file_path'] ?? null;
if ($file && !$category) {
$validator->errors()->add("attachments.{$index}.file_category", 'Attachment category is required.');
}
if ($category && !$file) {
$validator->errors()->add("attachments.{$index}.file_path", 'Attachment file is required.');
continue;
}
if (!$file) {
continue;
}
$extension = strtolower((string) $file->getClientOriginalExtension());
if ($this->isBlockedExtension($extension)) {
$validator->errors()->add("attachments.{$index}.file_path", 'File type is not allowed.');
continue;
}
$mimeType = (string) $file->getMimeType();
if (in_array($extension, $this->imageExtensions, true) && strpos($mimeType, 'image/') !== 0) {
$validator->errors()->add("attachments.{$index}.file_path", 'Invalid image file.');
}
if ($extension === 'pdf' && $mimeType !== 'application/pdf') {
$validator->errors()->add("attachments.{$index}.file_path", 'Invalid PDF file.');
}
}
foreach ($fileAttachments as $index => $files) {
$file = $files['file_path'] ?? null;
if ($file && !isset($inputAttachments[$index])) {
$validator->errors()->add("attachments.{$index}.file_category", 'Attachment category is required.');
}
}
});
}
protected function buildAttachmentPayload(Request $request, string $folderPath): array
{
$payload = [];
$inputs = $request->input('attachments', []);
$files = $request->file('attachments', []);
foreach ($inputs as $index => $input) {
$category = $input['file_category'] ?? null;
$file = $files[$index]['file_path'] ?? null;
if (!$category || !$file) {
continue;
}
$extension = strtolower((string) $file->getClientOriginalExtension());
if ($this->isBlockedExtension($extension)) {
throw ValidationException::withMessages([
"attachments.{$index}.file_path" => 'File type is not allowed.',
]);
}
$filename = Str::uuid() . '.' . $extension;
$filePath = rtrim($folderPath, '/') . '/' . $filename;
$uploadResponse = NextCloudHelper::uploadFile(
$folderPath,
$file->getContent(),
$filename
);
if (is_array($uploadResponse) && isset($uploadResponse['success']) && $uploadResponse['success'] === false) {
throw ValidationException::withMessages([
"attachments.{$index}.file_path" => $uploadResponse['message'] ?? 'Failed to upload attachment.',
]);
}
$payload[] = [
'file_category' => $category,
'file_path' => $filePath,
];
}
return $payload;
}
protected function formatAttachmentCollection(FormMeetingSeminar $form): array
{
if (!$form->relationLoaded('attachments')) {
$form->load('attachments');
}
$attachments = $form->attachments->map(function (AttachmentForm $attachment) {
if (!$attachment->file_path) {
return null;
}
return $this->formatAttachmentData(
$attachment->id,
$attachment->file_category,
$attachment->file_path
);
})->filter()->values()->all();
$legacySources = [
'bukti_allowance' => $form->bukti_allowance,
'bukti_transport_ankot' => $form->bukti_transport_ankot,
'bukti_hotel' => $form->bukti_hotel,
];
foreach ($legacySources as $category => $path) {
if ($path) {
$attachments[] = $this->formatAttachmentData(null, $category, $path, false);
}
}
return $attachments;
}
protected function formatAttachmentData(?int $id, ?string $category, string $filePath, bool $canDelete = true): array
{
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$previewType = $this->determinePreviewType($extension);
return [
'id' => $id,
'file_category' => $category,
'category_label' => $this->getCategoryLabel($category),
'file_path' => $filePath,
'download_url' => NextCloudHelper::getFileUrl($filePath),
'preview_url' => in_array($previewType, ['image', 'pdf'], true) ? NextCloudHelper::getPreviewUrl($filePath) : null,
'preview_type' => $previewType,
'filename' => basename($filePath),
'extension' => $extension,
'can_delete' => $canDelete && !is_null($id),
];
}
protected function determinePreviewType(?string $extension): string
{
$extension = strtolower((string) $extension);
if (in_array($extension, $this->imageExtensions, true)) {
return 'image';
}
if ($extension === 'pdf') {
return 'pdf';
}
return 'other';
}
protected function isBlockedExtension(?string $extension): bool
{
return in_array(strtolower((string) $extension), $this->blockedExtensions, true);
}
protected function getAttachmentDownloadUrlByCategory(array $attachments, string $category): ?string
{
foreach ($attachments as $attachment) {
if (($attachment['file_category'] ?? null) === $category) {
return $attachment['download_url'] ?? null;
}
}
return null;
}
protected function getCategoryLabel(?string $category): string
{
if (!$category) {
return 'Lampiran';
}
if (isset($this->attachmentCategories[$category])) {
return $this->attachmentCategories[$category];
}
return ucwords(str_replace('_', ' ', $category));
}
} }
@@ -82,17 +82,45 @@
<label class="form-label">Total <span class="font-italic font-weight-normal">(required)</span></label> <label class="form-label">Total <span class="font-italic font-weight-normal">(required)</span></label>
<input type="string" class="form-control" name="total" id="total" required value="{{ old('total') }}"> <input type="string" class="form-control" name="total" id="total" required value="{{ old('total') }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Total <span class="font-italic font-weight-normal">(required)</span></label>
<input type="file" class="form-control" name="bukti_total" value="{{ old('bukti_total') }}" required>
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Keterangan <span class="font-italic font-weight-normal">(required)</span></label> <label class="form-label">Keterangan <span class="font-italic font-weight-normal">(required)</span></label>
<textarea class="form-control" name="keterangan" required>{{ old('keterangan') }}</textarea> <textarea class="form-control" name="keterangan" required>{{ old('keterangan') }}</textarea>
</div> </div>
</div> </div>
<button type="submit" class="btn btn-primary ml-2">Submit</button> <div class="col-12">
<hr class="my-4">
<div class="d-flex justify-content-between align-items-center mb-2">
<h5 class="mb-0">Lampiran</h5>
<button type="button" class="btn btn-sm btn-primary" id="entertainment-add-attachment-row">
<i class="fas fa-plus mr-1"></i> Tambah Attachment
</button>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="entertainment-new-attachments-table" data-next-index="0">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 80px;" class="text-center">Aksi</th>
</tr>
</thead>
<tbody>
<tr class="entertainment-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
</tbody>
</table>
</div>
<small class="text-muted d-block mt-2">
Maksimum 10 MB per file. Tidak diperbolehkan: {{ implode(', ', $entertainmentBlockedExtensions ?? []) }}.
</small>
</div>
<div class="col-12 text-right mt-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div> </div>
</form> </form>
@@ -123,4 +151,7 @@
spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering
}); });
</script> </script>
@include('backend.pages.forms.entertainment.partials.attachment-modal')
@include('backend.pages.forms.entertainment.partials.attachment-scripts')
@endsection @endsection
@@ -83,17 +83,103 @@
<label class="form-label">Total <span class="font-italic font-weight-normal">(required)</span></label> <label class="form-label">Total <span class="font-italic font-weight-normal">(required)</span></label>
<input type="string" class="form-control" name="total" id="total" required value="{{ $form->total }}"> <input type="string" class="form-control" name="total" id="total" required value="{{ $form->total }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Total <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_total" value="{{ old('bukti_total') }}">
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Keterangan <span class="font-italic font-weight-normal">(required)</span></label> <label class="form-label">Keterangan <span class="font-italic font-weight-normal">(required)</span></label>
<textarea class="form-control" name="keterangan" required>{{ $form->keterangan }}</textarea> <textarea class="form-control" name="keterangan" required>{{ $form->keterangan }}</textarea>
</div> </div>
</div> </div>
<button type="submit" class="btn btn-primary ml-2">Update</button> <div class="col-12">
<hr class="my-4">
<h5 class="mb-3">Lampiran Saat Ini</h5>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="entertainment-existing-attachments-table">
<thead class="bg-light">
<tr>
<th style="width: 25%;">Kategori</th>
<th>Nama File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 120px;" class="text-center">Download</th>
<th style="width: 100px;" class="text-center">Delete</th>
</tr>
</thead>
<tbody>
@forelse ($attachments as $attachment)
<tr class="entertainment-attachment-row">
<td>{{ $attachment['category_label'] ?? '-' }}</td>
<td>{{ $attachment['filename'] }}</td>
<td class="text-center">
<button type="button"
class="btn btn-sm btn-outline-secondary entertainment-preview-trigger"
data-preview-type="{{ $attachment['preview_type'] }}"
data-preview-source="{{ $attachment['preview_url'] ?? '' }}"
data-download-url="{{ $attachment['download_url'] ?? '' }}"
data-filename="{{ $attachment['filename'] }}">
Preview
</button>
</td>
<td class="text-center">
@if (!empty($attachment['download_url']))
<a href="{{ $attachment['download_url'] }}" class="btn btn-sm btn-outline-success" target="_blank" rel="noopener">Download</a>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
<td class="text-center">
@if (!empty($attachment['can_delete']))
<button type="button"
class="btn btn-sm btn-outline-danger entertainment-delete-existing-attachment"
data-delete-url="{{ route('forms.entertainment.attachments.destroy', [$form->id, $attachment['id']]) }}">
<i class="fas fa-trash"></i>
</button>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
</tr>
@empty
<tr class="entertainment-empty-row">
<td colspan="5" class="text-center text-muted">Belum ada attachment.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
<div class="col-12">
<hr class="my-4">
<div class="d-flex justify-content-between align-items-center mb-2">
<h5 class="mb-0">Tambah Lampiran Baru</h5>
<button type="button" class="btn btn-sm btn-primary" id="entertainment-add-attachment-row">
<i class="fas fa-plus mr-1"></i> Tambah Attachment
</button>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="entertainment-new-attachments-table" data-next-index="0">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 80px;" class="text-center">Aksi</th>
</tr>
</thead>
<tbody>
<tr class="entertainment-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
</tbody>
</table>
</div>
<small class="text-muted d-block mt-2">
Maksimum 10 MB per file. Tidak diperbolehkan: {{ implode(', ', $entertainmentBlockedExtensions ?? []) }}.
</small>
</div>
<div class="col-12 text-right mt-4">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div> </div>
</form> </form>
@@ -124,4 +210,7 @@
spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering
}); });
</script> </script>
@include('backend.pages.forms.entertainment.partials.attachment-modal')
@include('backend.pages.forms.entertainment.partials.attachment-scripts')
@endsection @endsection
@@ -0,0 +1,24 @@
<div class="modal fade" id="entertainmentAttachmentPreviewModal" tabindex="-1" role="dialog" aria-labelledby="entertainmentAttachmentPreviewModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mb-0" id="entertainmentAttachmentPreviewModalLabel">Preview Lampiran</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="entertainment-preview-image d-none text-center">
<img src="" alt="Preview Lampiran" class="img-fluid">
</div>
<div class="entertainment-preview-pdf d-none">
<object data="" type="application/pdf" width="100%" height="500px"></object>
</div>
<div class="entertainment-preview-fallback d-none text-center">
<p class="mb-2">Preview tidak tersedia untuk file ini.</p>
<button type="button" class="btn btn-primary entertainment-preview-download-direct">Download</button>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,394 @@
@php
$entertainmentAttachmentScriptConfig = [
'blockedExtensions' => array_map('strtolower', $entertainmentBlockedExtensions ?? []),
'categoryOptions' => $entertainmentAttachmentCategories ?? [],
];
@endphp
<script>
(function ($) {
'use strict';
const config = @json($entertainmentAttachmentScriptConfig);
const categoryOptions = config.categoryOptions || {};
const blockedExtensions = (config.blockedExtensions || []).map(function (ext) {
return (ext || '').toString().toLowerCase();
});
const maxFileSizeBytes = 10 * 1024 * 1024; // 10 MB
let attachmentIndex = Number($('#entertainment-new-attachments-table').data('next-index')) || 0;
const previewModal = $('#entertainmentAttachmentPreviewModal');
const imageWrapper = previewModal.find('.entertainment-preview-image');
const pdfWrapper = previewModal.find('.entertainment-preview-pdf');
const fallbackWrapper = previewModal.find('.entertainment-preview-fallback');
const pdfObject = pdfWrapper.find('object');
const modalImage = imageWrapper.find('img');
const fallbackDownloadBtn = fallbackWrapper.find('.entertainment-preview-download-direct');
function showAlert(message, icon) {
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: icon || 'error',
title: icon === 'success' ? 'Berhasil' : 'Perhatian',
text: message,
});
} else {
alert(message);
}
}
function renderCategoryOptions(selectedValue) {
let optionsHtml = '<option value="" disabled' + (selectedValue ? '' : ' selected') + '>Pilih kategori</option>';
Object.keys(categoryOptions).forEach(function (value) {
const label = categoryOptions[value];
const selected = value === selectedValue ? ' selected' : '';
optionsHtml += '<option value="' + value + '"' + selected + '>' + label + '</option>';
});
return optionsHtml;
}
function ensureEmptyRowState($tbody) {
if ($tbody.find('.entertainment-attachment-row').length === 0) {
$tbody.html(
'<tr class="entertainment-empty-row">' +
'<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>' +
'</tr>'
);
}
}
function cleanupPreviewButton($button) {
const objectUrl = $button.data('objectUrl');
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
$button
.data('previewType', null)
.data('previewSource', null)
.data('downloadUrl', null)
.data('objectUrl', null)
.data('filename', null);
}
function resetAttachmentRow($row) {
const $previewButton = $row.find('.entertainment-preview-trigger');
cleanupPreviewButton($previewButton);
$previewButton.addClass('d-none');
$row.find('.entertainment-selected-filename').text('');
$row.find('.entertainment-new-attachment-file').val('');
}
function getFileExtension(filename) {
const parts = filename.split('.');
return parts.length > 1 ? parts.pop().toLowerCase() : '';
}
function getPreviewType(extension) {
if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].indexOf(extension) !== -1) {
return 'image';
}
if (extension === 'pdf') {
return 'pdf';
}
return 'other';
}
function validateFile(file) {
if (!file) {
return { valid: false, message: 'File tidak ditemukan.' };
}
if (file.size > maxFileSizeBytes) {
return { valid: false, message: 'Ukuran file melebihi 10 MB.' };
}
const extension = getFileExtension(file.name);
if (blockedExtensions.indexOf(extension) !== -1) {
return { valid: false, message: 'Tipe file tidak diperbolehkan.' };
}
return { valid: true, message: '' };
}
function downloadFile(url, filename) {
if (!url) {
showAlert('File tidak tersedia untuk diunduh.');
return;
}
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
if (filename) {
link.download = filename;
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function showPreviewModal() {
if (!previewModal.length) {
return false;
}
if (typeof previewModal.modal === 'function') {
previewModal.modal('show');
return true;
}
if (window.bootstrap && typeof window.bootstrap.Modal === 'function') {
let modalInstance = null;
if (typeof window.bootstrap.Modal.getOrCreateInstance === 'function') {
modalInstance = window.bootstrap.Modal.getOrCreateInstance(previewModal[0]);
} else {
modalInstance = new window.bootstrap.Modal(previewModal[0]);
}
if (modalInstance && typeof modalInstance.show === 'function') {
modalInstance.show();
return true;
}
}
return false;
}
function openPreviewModal(config) {
const filename = config.filename || 'Lampiran';
modalImage.attr('src', '');
pdfObject.attr('data', '');
fallbackDownloadBtn.data('downloadUrl', null).data('filename', filename);
imageWrapper.addClass('d-none');
pdfWrapper.addClass('d-none');
fallbackWrapper.addClass('d-none');
if (config.type === 'image' && config.source) {
modalImage.attr('src', config.source);
imageWrapper.removeClass('d-none');
} else if (config.type === 'pdf' && config.source) {
pdfObject.attr('data', config.source);
pdfWrapper.removeClass('d-none');
} else {
fallbackDownloadBtn.data('downloadUrl', config.downloadUrl || null);
fallbackWrapper.removeClass('d-none');
}
$('#entertainmentAttachmentPreviewModalLabel').text(filename);
const isModalShown = showPreviewModal();
if (!isModalShown) {
if (config.downloadUrl) {
downloadFile(config.downloadUrl, filename);
} else {
showAlert('Preview tidak tersedia tanpa dukungan Bootstrap modal.');
}
}
}
fallbackDownloadBtn.on('click', function () {
const url = $(this).data('downloadUrl');
const filename = $(this).data('filename');
downloadFile(url, filename);
});
window.addAttachmentRow = function () {
const $table = $('#entertainment-new-attachments-table');
if (!$table.length) {
return;
}
const $tbody = $table.find('tbody');
if ($tbody.find('.entertainment-empty-row').length) {
$tbody.empty();
}
const index = attachmentIndex++;
const optionsHtml = renderCategoryOptions(null);
const rowHtml =
'<tr class="entertainment-attachment-row" data-index="' + index + '">' +
'<td>' +
'<select class="form-control" name="attachments[' + index + '][file_category]">' +
optionsHtml +
'</select>' +
'</td>' +
'<td>' +
'<input type="file" class="form-control entertainment-new-attachment-file" name="attachments[' + index + '][file_path]">' +
'<small class="form-text text-muted entertainment-selected-filename"></small>' +
'</td>' +
'<td class="text-center">' +
'<button type="button" class="btn btn-sm btn-outline-secondary entertainment-preview-trigger d-none">' +
'Preview' +
'</button>' +
'</td>' +
'<td class="text-center">' +
'<button type="button" class="btn btn-sm btn-outline-danger entertainment-remove-attachment-row">' +
'<i class="fas fa-trash"></i>' +
'</button>' +
'</td>' +
'</tr>';
$tbody.append(rowHtml);
};
window.removeAttachmentRow = function (trigger) {
const $row = $(trigger).closest('tr');
const $tbody = $row.closest('tbody');
resetAttachmentRow($row);
$row.remove();
ensureEmptyRowState($tbody);
};
window.previewAttachment = function (trigger) {
const $button = $(trigger);
const type = $button.data('previewType');
const source = $button.data('previewSource');
const downloadUrl = $button.data('downloadUrl');
const filename = $button.data('filename');
if (type === 'image' && source) {
openPreviewModal({ type: 'image', source: source, filename: filename });
return;
}
if (type === 'pdf' && source) {
openPreviewModal({ type: 'pdf', source: source, filename: filename });
return;
}
if (downloadUrl) {
downloadFile(downloadUrl, filename);
return;
}
showAlert('Preview tidak tersedia untuk lampiran ini.');
};
$(document).on('change', '.entertainment-new-attachment-file', function () {
const file = this.files && this.files[0];
const $row = $(this).closest('tr');
const $previewButton = $row.find('.entertainment-preview-trigger');
cleanupPreviewButton($previewButton);
$previewButton.addClass('d-none');
$row.find('.entertainment-selected-filename').text('');
if (!file) {
return;
}
const validation = validateFile(file);
if (!validation.valid) {
showAlert(validation.message);
$(this).val('');
return;
}
const filename = file.name;
$row.find('.entertainment-selected-filename').text(filename);
const extension = getFileExtension(filename);
const previewType = getPreviewType(extension);
$previewButton.data('previewType', previewType);
$previewButton.data('filename', filename);
if (previewType === 'image') {
const reader = new FileReader();
reader.onload = function (event) {
$previewButton.data('previewSource', event.target.result);
};
reader.readAsDataURL(file);
} else if (previewType === 'pdf') {
const objectUrl = URL.createObjectURL(file);
$previewButton.data('previewSource', objectUrl);
$previewButton.data('downloadUrl', objectUrl);
$previewButton.data('objectUrl', objectUrl);
} else {
const objectUrl = URL.createObjectURL(file);
$previewButton.data('downloadUrl', objectUrl);
$previewButton.data('objectUrl', objectUrl);
// Non-media files should trigger download immediately on preview click.
}
$previewButton.removeClass('d-none');
});
$(document).on('click', '.entertainment-preview-trigger', function () {
previewAttachment(this);
});
$(document).on('click', '#entertainment-add-attachment-row', function () {
addAttachmentRow();
});
$(document).on('click', '.entertainment-remove-attachment-row', function () {
removeAttachmentRow(this);
});
$(document).on('click', '.entertainment-delete-existing-attachment', function () {
const $button = $(this);
const deleteUrl = $button.data('deleteUrl');
const $row = $button.closest('tr');
if (!deleteUrl) {
return;
}
const proceed = function () {
$.ajax({
url: deleteUrl,
method: 'DELETE',
data: {
_token: $('meta[name="csrf-token"]').attr('content')
},
success: function (response) {
showAlert(response.message || 'Attachment berhasil dihapus.', 'success');
$row.remove();
ensureEmptyRowState($('#entertainment-existing-attachments-table tbody'));
},
error: function (xhr) {
const message = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Gagal menghapus attachment.';
showAlert(message);
}
});
};
if (typeof Swal !== 'undefined') {
Swal.fire({
title: 'Hapus lampiran?',
text: 'Lampiran akan dihapus secara permanen.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Ya, hapus',
cancelButtonText: 'Batal',
}).then(function (result) {
if (result.isConfirmed) {
proceed();
}
});
} else if (confirm('Hapus lampiran ini?')) {
proceed();
}
});
$(function () {
const $newAttachmentsTable = $('#entertainment-new-attachments-table');
if ($newAttachmentsTable.length) {
const $tbody = $newAttachmentsTable.find('tbody');
if (!$tbody.find('.entertainment-attachment-row').length) {
addAttachmentRow();
}
}
ensureEmptyRowState($('#entertainment-existing-attachments-table tbody'));
});
})(jQuery);
</script>
@@ -66,16 +66,58 @@
<label class="form-label">Total</label> <label class="form-label">Total</label>
<input type="string" class="form-control" name="total" id="total" readonly value="{{ $form->total }}"> <input type="string" class="form-control" name="total" id="total" readonly value="{{ $form->total }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Total</label><br>
<a href="{{ $form->bukti_total }}" target="_blank">Lihat Bukti</a>
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Keterangan</label> <label class="form-label">Keterangan</label>
<textarea class="form-control" name="keterangan" readonly>{{ $form->keterangan }}</textarea> <textarea class="form-control" name="keterangan" readonly>{{ $form->keterangan }}</textarea>
</div> </div>
</div> </div>
<div class="col-lg-12">
<hr class="my-4">
<h5 class="mb-3">Lampiran</h5>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="entertainment-existing-attachments-table">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>Nama File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 120px;" class="text-center">Download</th>
</tr>
</thead>
<tbody>
@forelse ($attachments ?? [] as $attachment)
<tr class="entertainment-attachment-row">
<td>{{ $attachment['category_label'] ?? '-' }}</td>
<td>{{ $attachment['filename'] }}</td>
<td class="text-center">
<button type="button"
class="btn btn-sm btn-outline-secondary entertainment-preview-trigger"
data-preview-type="{{ $attachment['preview_type'] }}"
data-preview-source="{{ $attachment['preview_url'] ?? '' }}"
data-download-url="{{ $attachment['download_url'] ?? '' }}"
data-filename="{{ $attachment['filename'] }}">
Preview
</button>
</td>
<td class="text-center">
@if (!empty($attachment['download_url']))
<a href="{{ $attachment['download_url'] }}" class="btn btn-sm btn-outline-success" target="_blank" rel="noopener">Download</a>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
</tr>
@empty
<tr class="entertainment-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
<div class="col-lg-12"> <div class="col-lg-12">
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Status</label> <label class="form-label">Status</label>
@@ -433,4 +475,7 @@
$('#total').val('0'); // Reset total to 0 $('#total').val('0'); // Reset total to 0
}); });
</script> </script>
@include('backend.pages.forms.entertainment.partials.attachment-modal')
@include('backend.pages.forms.entertainment.partials.attachment-scripts')
@endsection @endsection
@@ -58,10 +58,6 @@
<label class="form-label">Allowance <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Allowance <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="allowance" id="allowance" value="{{ old('allowance') }}"> <input type="text" class="form-control" name="allowance" id="allowance" value="{{ old('allowance') }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Allowance <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_allowance" value="{{ old('bukti_allowance') }}">
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ old('transport_ankot') }}"> <input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ old('transport_ankot') }}">
@@ -69,21 +65,45 @@
</div> </div>
<div class="col-lg-6"> <div class="col-lg-6">
<div class="mb-3">
<label class="form-label">Bukti Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_transport_ankot" value="{{ old('bukti_transport_ankot') }}">
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Hotel <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Hotel <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="hotel" id="hotel" value="{{ old('hotel') }}"> <input type="text" class="form-control" name="hotel" id="hotel" value="{{ old('hotel') }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Hotel <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_hotel" value="{{ old('bukti_hotel') }}">
</div>
</div> </div>
<button type="submit" class="btn btn-primary ml-2">Submit</button> <div class="col-12">
<hr class="my-4">
<div class="d-flex justify-content-between align-items-center mb-2">
<h5 class="mb-0">Lampiran</h5>
<button type="button" class="btn btn-sm btn-primary" id="meeting-add-attachment-row">
<i class="fas fa-plus mr-1"></i> Tambah Attachment
</button>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="meeting-new-attachments-table" data-next-index="0">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 80px;" class="text-center">Aksi</th>
</tr>
</thead>
<tbody>
<tr class="meeting-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
</tbody>
</table>
</div>
<small class="text-muted d-block mt-2">
Maksimum 10 MB per file. Tidak diperbolehkan: {{ implode(', ', $meetingBlockedExtensions ?? []) }}.
</small>
</div>
<div class="col-12 text-right mt-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div> </div>
</form> </form>
@@ -130,4 +150,7 @@
spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering
}); });
</script> </script>
@include('backend.pages.forms.meeting.partials.attachment-modal')
@include('backend.pages.forms.meeting.partials.attachment-scripts')
@endsection @endsection
@@ -59,10 +59,6 @@
<label class="form-label">Allowance <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Allowance <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="allowance" id="allowance" value="{{ $form->allowance }}"> <input type="text" class="form-control" name="allowance" id="allowance" value="{{ $form->allowance }}">
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Allowance <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_allowance" value="{{ old('bukti_allowance') }}">
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ $form->transport_ankot }}"> <input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ $form->transport_ankot }}">
@@ -70,21 +66,105 @@
</div> </div>
<div class="col-lg-6"> <div class="col-lg-6">
<div class="mb-3">
<label class="form-label">Bukti Transport Antar Kota <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_transport_ankot" value="{{ old('bukti_transport_ankot') }}">
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Hotel <span class="font-italic font-weight-normal">(optional)</span></label> <label class="form-label">Hotel <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="text" class="form-control" name="hotel" id="hotel" value="{{ $form->hotel }}"> <input type="text" class="form-control" name="hotel" id="hotel" value="{{ $form->hotel }}">
</div> </div>
<div class="mb-3"> </div>
<label class="form-label">Bukti Hotel <span class="font-italic font-weight-normal">(optional)</span></label>
<input type="file" class="form-control" name="bukti_hotel" value="{{ old('bukti_hotel') }}"> <div class="col-12">
<hr class="my-4">
<h5 class="mb-3">Lampiran Saat Ini</h5>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="meeting-existing-attachments-table">
<thead class="bg-light">
<tr>
<th style="width: 25%;">Kategori</th>
<th>Nama File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 120px;" class="text-center">Download</th>
<th style="width: 100px;" class="text-center">Delete</th>
</tr>
</thead>
<tbody>
@forelse ($attachments as $attachment)
<tr class="meeting-attachment-row">
<td>{{ $attachment['category_label'] ?? '-' }}</td>
<td>{{ $attachment['filename'] }}</td>
<td class="text-center">
<button type="button"
class="btn btn-sm btn-outline-secondary meeting-preview-trigger"
data-preview-type="{{ $attachment['preview_type'] }}"
data-preview-source="{{ $attachment['preview_url'] ?? '' }}"
data-download-url="{{ $attachment['download_url'] ?? '' }}"
data-filename="{{ $attachment['filename'] }}">
Preview
</button>
</td>
<td class="text-center">
@if (!empty($attachment['download_url']))
<a href="{{ $attachment['download_url'] }}" class="btn btn-sm btn-outline-success" target="_blank" rel="noopener">
Download
</a>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
<td class="text-center">
@if (!empty($attachment['can_delete']))
<button type="button"
class="btn btn-sm btn-outline-danger meeting-delete-existing-attachment"
data-delete-url="{{ route('forms.meeting.attachments.destroy', [$form->id, $attachment['id']]) }}">
<i class="fas fa-trash"></i>
</button>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
</tr>
@empty
<tr class="meeting-empty-row">
<td colspan="5" class="text-center text-muted">Belum ada attachment.</td>
</tr>
@endforelse
</tbody>
</table>
</div> </div>
</div> </div>
<button type="submit" class="btn btn-primary ml-2">Update</button> <div class="col-12">
<hr class="my-4">
<div class="d-flex justify-content-between align-items-center mb-2">
<h5 class="mb-0">Tambah Lampiran Baru</h5>
<button type="button" class="btn btn-sm btn-primary" id="meeting-add-attachment-row">
<i class="fas fa-plus mr-1"></i> Tambah Attachment
</button>
</div>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="meeting-new-attachments-table" data-next-index="0">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 80px;" class="text-center">Aksi</th>
</tr>
</thead>
<tbody>
<tr class="meeting-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
</tbody>
</table>
</div>
<small class="text-muted d-block mt-2">
Maksimum 10 MB per file. Tidak diperbolehkan: {{ implode(', ', $meetingBlockedExtensions ?? []) }}.
</small>
</div>
<div class="col-12 text-right mt-4">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div> </div>
</form> </form>
@@ -131,4 +211,7 @@
spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering spinnerOverlay.classList.add('d-flex'); // Use flexbox for centering
}); });
</script> </script>
@include('backend.pages.forms.meeting.partials.attachment-modal')
@include('backend.pages.forms.meeting.partials.attachment-scripts')
@endsection @endsection
@@ -0,0 +1,24 @@
<div class="modal fade" id="meetingAttachmentPreviewModal" tabindex="-1" role="dialog" aria-labelledby="meetingAttachmentPreviewModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title mb-0" id="meetingAttachmentPreviewModalLabel">Preview Lampiran</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="meeting-preview-image d-none text-center">
<img src="" alt="Preview Lampiran" class="img-fluid">
</div>
<div class="meeting-preview-pdf d-none">
<object data="" type="application/pdf" width="100%" height="500px"></object>
</div>
<div class="meeting-preview-fallback d-none text-center">
<p class="mb-2">Preview tidak tersedia untuk file ini.</p>
<button type="button" class="btn btn-primary meeting-preview-download-direct">Download</button>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,395 @@
@php
$meetingAttachmentScriptConfig = [
'blockedExtensions' => array_map('strtolower', $meetingBlockedExtensions ?? []),
'categoryOptions' => $meetingAttachmentCategories ?? [],
];
@endphp
<script>
(function ($) {
'use strict';
const config = @json($meetingAttachmentScriptConfig);
const categoryOptions = config.categoryOptions || {};
const blockedExtensions = (config.blockedExtensions || []).map(function (ext) {
return (ext || '').toString().toLowerCase();
});
const maxFileSizeBytes = 10 * 1024 * 1024; // 10 MB
let attachmentIndex = Number($('#meeting-new-attachments-table').data('next-index')) || 0;
const previewModal = $('#meetingAttachmentPreviewModal');
const imageWrapper = previewModal.find('.meeting-preview-image');
const pdfWrapper = previewModal.find('.meeting-preview-pdf');
const fallbackWrapper = previewModal.find('.meeting-preview-fallback');
const pdfObject = pdfWrapper.find('object');
const modalImage = imageWrapper.find('img');
const fallbackDownloadBtn = fallbackWrapper.find('.meeting-preview-download-direct');
function showAlert(message, icon) {
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: icon || 'error',
title: icon === 'success' ? 'Berhasil' : 'Perhatian',
text: message,
});
} else {
alert(message);
}
}
function renderCategoryOptions(selectedValue) {
let optionsHtml = '<option value="" disabled' + (selectedValue ? '' : ' selected') + '>Pilih kategori</option>';
Object.keys(categoryOptions).forEach(function (value) {
const label = categoryOptions[value];
const selected = value === selectedValue ? ' selected' : '';
optionsHtml += '<option value="' + value + '"' + selected + '>' + label + '</option>';
});
return optionsHtml;
}
function ensureEmptyRowState($tbody) {
if ($tbody.find('.meeting-attachment-row').length === 0) {
$tbody.html(
'<tr class="meeting-empty-row">' +
'<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>' +
'</tr>'
);
}
}
function cleanupPreviewButton($button) {
const objectUrl = $button.data('objectUrl');
if (objectUrl) {
URL.revokeObjectURL(objectUrl);
}
$button
.data('previewType', null)
.data('previewSource', null)
.data('downloadUrl', null)
.data('objectUrl', null)
.data('filename', null);
}
function resetAttachmentRow($row) {
const $previewButton = $row.find('.meeting-preview-trigger');
cleanupPreviewButton($previewButton);
$previewButton.addClass('d-none');
$row.find('.meeting-selected-filename').text('');
const $fileInput = $row.find('.meeting-new-attachment-file');
$fileInput.val('');
}
function getFileExtension(filename) {
const parts = filename.split('.');
return parts.length > 1 ? parts.pop().toLowerCase() : '';
}
function getPreviewType(extension) {
if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].indexOf(extension) !== -1) {
return 'image';
}
if (extension === 'pdf') {
return 'pdf';
}
return 'other';
}
function validateFile(file) {
if (!file) {
return { valid: false, message: 'File tidak ditemukan.' };
}
if (file.size > maxFileSizeBytes) {
return { valid: false, message: 'Ukuran file melebihi 10 MB.' };
}
const extension = getFileExtension(file.name);
if (blockedExtensions.indexOf(extension) !== -1) {
return { valid: false, message: 'Tipe file tidak diperbolehkan.' };
}
return { valid: true, message: '' };
}
function downloadFile(url, filename) {
if (!url) {
showAlert('File tidak tersedia untuk diunduh.');
return;
}
const link = document.createElement('a');
link.href = url;
link.target = '_blank';
link.rel = 'noopener noreferrer';
if (filename) {
link.download = filename;
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function showPreviewModal() {
if (!previewModal.length) {
return false;
}
if (typeof previewModal.modal === 'function') {
previewModal.modal('show');
return true;
}
if (window.bootstrap && typeof window.bootstrap.Modal === 'function') {
let modalInstance = null;
if (typeof window.bootstrap.Modal.getOrCreateInstance === 'function') {
modalInstance = window.bootstrap.Modal.getOrCreateInstance(previewModal[0]);
} else {
modalInstance = new window.bootstrap.Modal(previewModal[0]);
}
if (modalInstance && typeof modalInstance.show === 'function') {
modalInstance.show();
return true;
}
}
return false;
}
function openPreviewModal(config) {
const filename = config.filename || 'Lampiran';
modalImage.attr('src', '');
pdfObject.attr('data', '');
fallbackDownloadBtn.data('downloadUrl', null).data('filename', filename);
imageWrapper.addClass('d-none');
pdfWrapper.addClass('d-none');
fallbackWrapper.addClass('d-none');
if (config.type === 'image' && config.source) {
modalImage.attr('src', config.source);
imageWrapper.removeClass('d-none');
} else if (config.type === 'pdf' && config.source) {
pdfObject.attr('data', config.source);
pdfWrapper.removeClass('d-none');
} else {
fallbackDownloadBtn.data('downloadUrl', config.downloadUrl || null);
fallbackWrapper.removeClass('d-none');
}
$('#meetingAttachmentPreviewModalLabel').text(filename);
const isModalShown = showPreviewModal();
if (!isModalShown) {
if (config.downloadUrl) {
downloadFile(config.downloadUrl, filename);
} else {
showAlert('Preview tidak tersedia tanpa dukungan Bootstrap modal.');
}
}
}
fallbackDownloadBtn.on('click', function () {
const url = $(this).data('downloadUrl');
const filename = $(this).data('filename');
downloadFile(url, filename);
});
window.addAttachmentRow = function () {
const $table = $('#meeting-new-attachments-table');
if (!$table.length) {
return;
}
const $tbody = $table.find('tbody');
if ($tbody.find('.meeting-empty-row').length) {
$tbody.empty();
}
const index = attachmentIndex++;
const optionsHtml = renderCategoryOptions(null);
const rowHtml =
'<tr class="meeting-attachment-row" data-index="' + index + '">' +
'<td>' +
'<select class="form-control" name="attachments[' + index + '][file_category]">' +
optionsHtml +
'</select>' +
'</td>' +
'<td>' +
'<input type="file" class="form-control meeting-new-attachment-file" name="attachments[' + index + '][file_path]">' +
'<small class="form-text text-muted meeting-selected-filename"></small>' +
'</td>' +
'<td class="text-center">' +
'<button type="button" class="btn btn-sm btn-outline-secondary meeting-preview-trigger d-none">' +
'Preview' +
'</button>' +
'</td>' +
'<td class="text-center">' +
'<button type="button" class="btn btn-sm btn-outline-danger meeting-remove-attachment-row">' +
'<i class="fas fa-trash"></i>' +
'</button>' +
'</td>' +
'</tr>';
$tbody.append(rowHtml);
};
window.removeAttachmentRow = function (trigger) {
const $row = $(trigger).closest('tr');
const $tbody = $row.closest('tbody');
resetAttachmentRow($row);
$row.remove();
ensureEmptyRowState($tbody);
};
window.previewAttachment = function (trigger) {
const $button = $(trigger);
const type = $button.data('previewType');
const source = $button.data('previewSource');
const downloadUrl = $button.data('downloadUrl');
const filename = $button.data('filename');
if (type === 'image' && source) {
openPreviewModal({ type: 'image', source: source, filename: filename });
return;
}
if (type === 'pdf' && source) {
openPreviewModal({ type: 'pdf', source: source, filename: filename });
return;
}
if (downloadUrl) {
downloadFile(downloadUrl, filename);
return;
}
showAlert('Preview tidak tersedia untuk lampiran ini.');
};
$(document).on('change', '.meeting-new-attachment-file', function () {
const file = this.files && this.files[0];
const $row = $(this).closest('tr');
const $previewButton = $row.find('.meeting-preview-trigger');
cleanupPreviewButton($previewButton);
$previewButton.addClass('d-none');
$row.find('.meeting-selected-filename').text('');
if (!file) {
return;
}
const validation = validateFile(file);
if (!validation.valid) {
showAlert(validation.message);
$(this).val('');
return;
}
const filename = file.name;
$row.find('.meeting-selected-filename').text(filename);
const extension = getFileExtension(filename);
const previewType = getPreviewType(extension);
$previewButton.data('previewType', previewType);
$previewButton.data('filename', filename);
if (previewType === 'image') {
const reader = new FileReader();
reader.onload = function (event) {
$previewButton.data('previewSource', event.target.result);
};
reader.readAsDataURL(file);
} else if (previewType === 'pdf') {
const objectUrl = URL.createObjectURL(file);
$previewButton.data('previewSource', objectUrl);
$previewButton.data('downloadUrl', objectUrl);
$previewButton.data('objectUrl', objectUrl);
} else {
const objectUrl = URL.createObjectURL(file);
$previewButton.data('downloadUrl', objectUrl);
$previewButton.data('objectUrl', objectUrl);
}
$previewButton.removeClass('d-none');
});
$(document).on('click', '.meeting-preview-trigger', function () {
previewAttachment(this);
});
$(document).on('click', '#meeting-add-attachment-row', function () {
addAttachmentRow();
});
$(document).on('click', '.meeting-remove-attachment-row', function () {
removeAttachmentRow(this);
});
$(document).on('click', '.meeting-delete-existing-attachment', function () {
const $button = $(this);
const deleteUrl = $button.data('deleteUrl');
const $row = $button.closest('tr');
if (!deleteUrl) {
return;
}
const proceed = function () {
$.ajax({
url: deleteUrl,
method: 'DELETE',
data: {
_token: $('meta[name="csrf-token"]').attr('content')
},
success: function (response) {
showAlert(response.message || 'Attachment berhasil dihapus.', 'success');
$row.remove();
ensureEmptyRowState($('#meeting-existing-attachments-table tbody'));
},
error: function (xhr) {
const message = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Gagal menghapus attachment.';
showAlert(message);
}
});
};
if (typeof Swal !== 'undefined') {
Swal.fire({
title: 'Hapus lampiran?',
text: 'Lampiran akan dihapus secara permanen.',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Ya, hapus',
cancelButtonText: 'Batal',
}).then(function (result) {
if (result.isConfirmed) {
proceed();
}
});
} else {
if (confirm('Hapus lampiran ini?')) {
proceed();
}
}
});
$(function () {
const $newAttachmentsTable = $('#meeting-new-attachments-table');
if ($newAttachmentsTable.length) {
const $tbody = $newAttachmentsTable.find('tbody');
if (!$tbody.find('.meeting-attachment-row').length) {
addAttachmentRow();
}
}
ensureEmptyRowState($('#meeting-existing-attachments-table tbody'));
});
})(jQuery);
</script>
@@ -42,10 +42,6 @@
<label class="form-label">Allowance</label> <label class="form-label">Allowance</label>
<input type="text" class="form-control" name="allowance" id="allowance" value="{{ $form->allowance }}" readonly> <input type="text" class="form-control" name="allowance" id="allowance" value="{{ $form->allowance }}" readonly>
</div> </div>
<div class="mb-3">
<label class="form-label">Bukti Allowance</label><br>
<a href="{{ $form->bukti_allowance }}" target="_blank">Lihat Bukti</a>
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Transport Antar Kota</label> <label class="form-label">Transport Antar Kota</label>
<input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ $form->transport_ankot }}" readonly> <input type="text" class="form-control" name="transport_ankot" id="transport_ankot" value="{{ $form->transport_ankot }}" readonly>
@@ -53,17 +49,9 @@
</div> </div>
<div class="col-lg-6"> <div class="col-lg-6">
<div class="mb-3">
<label class="form-label">Bukti Transport Antar Kota</label><br>
<a href="{{ $form->bukti_transport_ankot }}" target="_blank">Lihat Bukti</a>
</div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Hotel</label> <label class="form-label">Hotel</label>
<input type="text" class="form-control" name="hotel" id="hotel" value="{{ $form->hotel }}" readonly> <input type="text" class="form-control" name="hotel" id="hotel" value="{{ $form->hotel }}" readonly>
</div>
<div class="mb-3">
<label class="form-label">Bukti Hotel</label><br>
<a href="{{ $form->bukti_hotel }}" target="_blank">Lihat Bukti</a>
</div> </div>
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Total</label> <label class="form-label">Total</label>
@@ -71,6 +59,52 @@
</div> </div>
</div> </div>
<div class="col-lg-12">
<hr class="my-4">
<h5 class="mb-3">Lampiran</h5>
<div class="table-responsive">
<table class="table table-bordered table-striped mb-0" id="meeting-existing-attachments-table">
<thead class="bg-light">
<tr>
<th style="width: 30%;">Kategori</th>
<th>Nama File</th>
<th style="width: 120px;" class="text-center">Preview</th>
<th style="width: 120px;" class="text-center">Download</th>
</tr>
</thead>
<tbody>
@forelse ($attachments as $attachment)
<tr class="meeting-attachment-row">
<td>{{ $attachment['category_label'] ?? '-' }}</td>
<td>{{ $attachment['filename'] }}</td>
<td class="text-center">
<button type="button"
class="btn btn-sm btn-outline-secondary meeting-preview-trigger"
data-preview-type="{{ $attachment['preview_type'] }}"
data-preview-source="{{ $attachment['preview_url'] ?? '' }}"
data-download-url="{{ $attachment['download_url'] ?? '' }}"
data-filename="{{ $attachment['filename'] }}">
Preview
</button>
</td>
<td class="text-center">
@if (!empty($attachment['download_url']))
<a href="{{ $attachment['download_url'] }}" class="btn btn-sm btn-outline-success" target="_blank" rel="noopener">Download</a>
@else
<span class="text-muted">Tidak tersedia</span>
@endif
</td>
</tr>
@empty
<tr class="meeting-empty-row">
<td colspan="4" class="text-center text-muted">Belum ada attachment.</td>
</tr>
@endforelse
</tbody>
</table>
</div>
</div>
<div class="col-lg-12"> <div class="col-lg-12">
<div class="mb-3"> <div class="mb-3">
<label class="form-label">Status</label> <label class="form-label">Status</label>
@@ -475,4 +509,7 @@
$('#total2').val('0'); // Reset total to 0 $('#total2').val('0'); // Reset total to 0
}); });
</script> </script>
@include('backend.pages.forms.meeting.partials.attachment-modal')
@include('backend.pages.forms.meeting.partials.attachment-scripts')
@endsection @endsection
+2
View File
@@ -163,6 +163,7 @@ Route::middleware(['auth:admin', 'menu'])->group(function () {
Route::post('/entertainment-presentation/store', [FormEntertainmentPresentationController::class, 'store'])->name('forms.entertainment.store'); Route::post('/entertainment-presentation/store', [FormEntertainmentPresentationController::class, 'store'])->name('forms.entertainment.store');
Route::get('/entertainment-presentation/edit/{id}', [FormEntertainmentPresentationController::class, 'edit'])->name('forms.entertainment.edit'); Route::get('/entertainment-presentation/edit/{id}', [FormEntertainmentPresentationController::class, 'edit'])->name('forms.entertainment.edit');
Route::put('/entertainment-presentation/update/{id}', [FormEntertainmentPresentationController::class, 'update'])->name('forms.entertainment.update'); Route::put('/entertainment-presentation/update/{id}', [FormEntertainmentPresentationController::class, 'update'])->name('forms.entertainment.update');
Route::delete('/entertainment-presentation/{form}/attachments/{attachment}', [FormEntertainmentPresentationController::class, 'deleteAttachment'])->name('forms.entertainment.attachments.destroy');
Route::delete('/entertainment-presentation/destroy/{id}', [FormEntertainmentPresentationController::class, 'destroy'])->name('forms.entertainment.destroy'); Route::delete('/entertainment-presentation/destroy/{id}', [FormEntertainmentPresentationController::class, 'destroy'])->name('forms.entertainment.destroy');
Route::put('/entertainment-presentation/approve/{id}', [FormEntertainmentPresentationController::class, 'approve'])->name('forms.entertainment.approve'); Route::put('/entertainment-presentation/approve/{id}', [FormEntertainmentPresentationController::class, 'approve'])->name('forms.entertainment.approve');
Route::put('/entertainment-presentation/approve2/{id}', [FormEntertainmentPresentationController::class, 'approve2'])->name('forms.entertainment.approve2'); Route::put('/entertainment-presentation/approve2/{id}', [FormEntertainmentPresentationController::class, 'approve2'])->name('forms.entertainment.approve2');
@@ -178,6 +179,7 @@ Route::middleware(['auth:admin', 'menu'])->group(function () {
Route::post('/meeting-seminar/store', [FormMeetingSeminarController::class, 'store'])->name('forms.meeting.store'); Route::post('/meeting-seminar/store', [FormMeetingSeminarController::class, 'store'])->name('forms.meeting.store');
Route::get('/meeting-seminar/edit/{id}', [FormMeetingSeminarController::class, 'edit'])->name('forms.meeting.edit'); Route::get('/meeting-seminar/edit/{id}', [FormMeetingSeminarController::class, 'edit'])->name('forms.meeting.edit');
Route::put('/meeting-seminar/update/{id}', [FormMeetingSeminarController::class, 'update'])->name('forms.meeting.update'); Route::put('/meeting-seminar/update/{id}', [FormMeetingSeminarController::class, 'update'])->name('forms.meeting.update');
Route::delete('/meeting-seminar/{form}/attachments/{attachment}', [FormMeetingSeminarController::class, 'deleteAttachment'])->name('forms.meeting.attachments.destroy');
Route::delete('/meeting-seminar/destroy/{id}', [FormMeetingSeminarController::class, 'destroy'])->name('forms.meeting.destroy'); Route::delete('/meeting-seminar/destroy/{id}', [FormMeetingSeminarController::class, 'destroy'])->name('forms.meeting.destroy');
Route::put('/meeting-seminar/approve/{id}', [FormMeetingSeminarController::class, 'approve'])->name('forms.meeting.approve'); Route::put('/meeting-seminar/approve/{id}', [FormMeetingSeminarController::class, 'approve'])->name('forms.meeting.approve');
Route::put('/meeting-seminar/approve2/{id}', [FormMeetingSeminarController::class, 'approve2'])->name('forms.meeting.approve2'); Route::put('/meeting-seminar/approve2/{id}', [FormMeetingSeminarController::class, 'approve2'])->name('forms.meeting.approve2');