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\Rayon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use App\Models\Region;
use App\Models\Cabang;
use App\Models\UserHasCabang;
@@ -23,16 +22,54 @@ use App\Mail\ExpenseCreated;
use App\Helpers\WhatsappHelper;
use App\Helpers\AuditTrailHelper;
use App\Models\Admin;
use App\Rules\FileType;
use App\Helpers\BudgetHelper;
use App\Helpers\NotificationHelper;
use App\Helpers\OutstandingHelper;
use Illuminate\Support\Facades\Log;
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;
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()
{
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
@@ -60,7 +97,7 @@ class FormEntertainmentPresentationController extends Controller
$forms = FormEntertaimentPresentation::whereBetween('tanggal', [$dataRetrievalStartDate, $currentPeriodClosingDate])
->orderBy('tanggal', 'desc')
->with('user')
->with(['user', 'attachments'])
->get();
$availableBudget = null;
@@ -105,6 +142,11 @@ class FormEntertainmentPresentationController extends Controller
);
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', [
'forms' => $forms,
'availableBudget' => $availableBudget,
@@ -118,8 +160,10 @@ class FormEntertainmentPresentationController extends Controller
{
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
$form = FormEntertaimentPresentation::with('user')->findOrFail($id);
$form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null;
$form = FormEntertaimentPresentation::with(['user', 'attachments'])->findOrFail($id);
$attachments = $this->formatAttachmentCollection($form);
$form->setAttribute('formatted_attachments', $attachments);
$form->bukti_total = $this->getAttachmentDownloadUrlByCategory($attachments, 'bukti_total');
return response()->json($form);
}
@@ -128,11 +172,13 @@ class FormEntertainmentPresentationController extends Controller
{
$this->checkAuthorization(auth()->user(), ['forms.entertainment.view']);
$form = FormEntertaimentPresentation::with('user')->findOrFail($id);
$form->bukti_total = $form->bukti_total ? NextCloudHelper::getFileUrl($form->bukti_total) : null;
$form = FormEntertaimentPresentation::with(['user', 'attachments'])->findOrFail($id);
$attachments = $this->formatAttachmentCollection($form);
$form->setAttribute('formatted_attachments', $attachments);
return view('backend.pages.forms.entertainment.view', [
'form' => $form,
'attachments' => $attachments,
]);
}
@@ -147,16 +193,20 @@ class FormEntertainmentPresentationController extends Controller
{
$this->checkAuthorization(auth()->user(), ['forms.entertainment.create']);
$request->validate([
'tanggal' => 'required',
$validator = Validator::make($request->all(), [
'tanggal' => 'required|date',
'jenis' => 'required|in:entertainment,presentation,sponsorship',
'keterangan' => 'required',
'keterangan' => 'required|string',
'total' => 'required|numeric|min:1',
'name' => 'required',
'alamat' => 'required',
'nik_or_npwp' => 'required',
'bukti_total' => ['nullable', 'file', 'max:51200'],
'name' => 'required|string',
'alamat' => 'required|string',
'nik_or_npwp' => 'required|string',
'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);
$startDay = (int) env('STARTING_DATE', 11);
@@ -177,7 +227,7 @@ class FormEntertainmentPresentationController extends Controller
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')}");
return redirect()->back();
return redirect()->back()->withInput();
}
// 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;
$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');
return redirect()->back();
return redirect()->back()->withInput();
}
$region = Region::where('id', $cabang->region_id)->first();
@@ -197,48 +247,68 @@ class FormEntertainmentPresentationController extends Controller
$kategori = "";
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
$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();
}elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
} elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
$kategori = Kategori::where('name', 'Sponsorship')->first();
}
$filePaths = [];
$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
$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);
$expense_number = $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . $formatted_sequence_number;
// Save the form data
$form = FormEntertaimentPresentation::create([
'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' => $filePaths['bukti_total'] ?? null,
'account_number' => $kategori->account_number,
'status' => 'On Progress',
]);
DB::beginTransaction();
try {
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
if (empty($attachmentsPayload)) {
throw ValidationException::withMessages([
'attachments.0.file_path' => 'Minimal satu lampiran diperlukan.',
]);
}
$primaryAttachmentPath = $attachmentsPayload[0]['file_path'] ?? null;
$form = FormEntertaimentPresentation::create([
'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;
$tanggal = $form->created_at;
@@ -262,7 +332,7 @@ class FormEntertainmentPresentationController extends Controller
if ($role === 'Marketing Information System') {
return true; // Tidak ada filter cabang untuk peran ini
}
if (!$user->cabang || !$user->cabang->cabang) {
return false; // Pastikan user memiliki cabang
}
@@ -325,14 +395,17 @@ class FormEntertainmentPresentationController extends Controller
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
$role = auth()->user()->getRoleNames()[0];
$form = FormEntertaimentPresentation::findOrfail($id);
$form = FormEntertaimentPresentation::with('attachments')->findOrFail($id);
if($form->status != 'On Progress' && $role == 'Medical Representatif') {
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
return redirect()->back();
}
$attachments = $this->formatAttachmentCollection($form);
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']);
$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;
if (!$cabang_id) {
@@ -364,18 +437,22 @@ class FormEntertainmentPresentationController extends Controller
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
$request->validate([
'tanggal' => 'required',
$validator = Validator::make($request->all(), [
'tanggal' => 'required|date',
'jenis' => 'required|in:entertainment,presentation,sponsorship',
'keterangan' => 'required',
'keterangan' => 'required|string',
'total' => 'required|numeric|min:1|max:' . $availableBudget,
'name' => 'required',
'alamat' => 'required',
'nik_or_npwp' => 'required',
'bukti_total' => ['nullable', 'file', 'max:51200'],
'name' => 'required|string',
'alamat' => 'required|string',
'nik_or_npwp' => 'required|string',
'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.');
return redirect()->back();
}
@@ -386,46 +463,90 @@ class FormEntertainmentPresentationController extends Controller
$kategori = "";
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
$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();
}elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
} elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
$kategori = Kategori::where('name', 'Sponsorship')->first();
}
$filePaths = [];
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment';
if ($request->hasFile('bukti_total')) {
$bukti_total = $request->file('bukti_total');
$filename = Str::uuid() . '.' . $bukti_total->extension();
DB::beginTransaction();
try {
$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(
$folderPath,
$bukti_total->getContent(),
$filename
);
if (!empty($attachmentsPayload)) {
$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 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 . ')');
session()->flash('success', 'Form has been updated.');
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)
{
$this->checkAuthorization(auth()->user(), ['approval.approve']);
@@ -830,4 +951,190 @@ class FormEntertainmentPresentationController extends Controller
session()->flash('success', 'Form has been deleted.');
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));
}
}