1064 lines
39 KiB
PHP
1064 lines
39 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Forms;
|
|
|
|
use Illuminate\Http\Request;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\FormUpCountry;
|
|
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;
|
|
use App\Models\Kategori;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Support\Facades\Mail;
|
|
use App\Mail\ExpenseApproved;
|
|
use App\Mail\ExpenseApproved2;
|
|
use App\Mail\ExpenseRejected;
|
|
use App\Mail\FinalApprove;
|
|
use App\Mail\ExpenseCreated;
|
|
use App\Helpers\WhatsappHelper;
|
|
use App\Helpers\AuditTrailHelper;
|
|
use App\Helpers\NextCloudHelper;
|
|
use App\Rules\FileType;
|
|
use App\Models\Admin;
|
|
use App\Models\AttachmentForm;
|
|
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 Carbon\Carbon;
|
|
use Illuminate\Container\Attributes\Auth;
|
|
|
|
class FormUpCountryController extends Controller
|
|
{
|
|
protected AttachmentService $attachmentService;
|
|
protected array $attachmentCategories = [
|
|
'bukti_allowance',
|
|
'bukti_transport_dalkot',
|
|
'bukti_transport_ankot',
|
|
'bukti_hotel',
|
|
'bukti_total',
|
|
'bukti_lainnya',
|
|
];
|
|
|
|
public function __construct(AttachmentService $attachmentService)
|
|
{
|
|
$this->attachmentService = $attachmentService;
|
|
view()->share('upCountryAttachmentCategories', $this->attachmentCategories);
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.view']);
|
|
|
|
$role = auth()->user()->getRoleNames()[0];
|
|
$startDay = (int) env('STARTING_DATE', 11);
|
|
$closingDay = (int) env('CLOSING_DATE', 10);
|
|
|
|
// Current time reference
|
|
$now = Carbon::now();
|
|
|
|
// Determine the period
|
|
if ($now->day >= $startDay) {
|
|
$currentPeriodStartDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
|
$currentPeriodClosingDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $closingDay)->endOfDay();
|
|
} else {
|
|
$currentPeriodStartDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
|
$currentPeriodClosingDate = Carbon::create($now->year, $now->month, $closingDay)->endOfDay();
|
|
}
|
|
|
|
// Calculate the actual start date for data retrieval (1 month before currentPeriodStartDate)
|
|
$dataRetrievalStartDate = $currentPeriodStartDate->copy()->subMonth()->subDay()->startOfDay();
|
|
|
|
$forms = FormUpCountry::whereBetween('tanggal', [$dataRetrievalStartDate, $currentPeriodClosingDate])
|
|
->orderBy('tanggal', 'desc')
|
|
->with(['rayon', 'user'])
|
|
->get();
|
|
|
|
$availableBudget = null;
|
|
$userRegionData = auth()->user()->getMyCabangAndRegionId();
|
|
$regionContextId = $userRegionData['region'] !== '-' ? $userRegionData['region'] : null;
|
|
$cabangContextId = $userRegionData['cabang'] !== '-' ? $userRegionData['cabang'] : null;
|
|
$periodeMonth = strtolower($currentPeriodStartDate->format('F'));
|
|
$periodeYear = (int) $currentPeriodStartDate->format('Y');
|
|
|
|
if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
|
|
if ($regionContextId) {
|
|
$users = UserHasCabang::whereHas('cabang', function ($query) use ($regionContextId) {
|
|
$query->where('region_id', $regionContextId);
|
|
})->get();
|
|
|
|
$userIds = $users->pluck('user_id')->toArray();
|
|
$forms = $forms->whereIn('user_id', $userIds);
|
|
}
|
|
} else if ($role == 'Area Manager Cabang') {
|
|
if ($cabangContextId) {
|
|
$users = UserHasCabang::where('cabang_id', $cabangContextId)->get();
|
|
$userIds = $users->pluck('user_id')->toArray();
|
|
$forms = $forms->whereIn('user_id', $userIds);
|
|
|
|
$availableBudget = BudgetHelper::getAvailableBudget($cabangContextId, $periodeMonth, $periodeYear);
|
|
}
|
|
} else if ($role == 'Medical Representatif') {
|
|
$forms = $forms->where('user_id', auth()->user()->id);
|
|
$cabang_id = UserHasCabang::where('user_id', auth()->user()->id)->first()->cabang_id;
|
|
|
|
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
|
} else {
|
|
$forms = $forms;
|
|
}
|
|
|
|
$outstandingForms = OutstandingHelper::filterForms(
|
|
$forms,
|
|
$role,
|
|
$currentPeriodStartDate,
|
|
$currentPeriodClosingDate,
|
|
[
|
|
'region_id' => $regionContextId,
|
|
'cabang_id' => $cabangContextId,
|
|
]
|
|
);
|
|
|
|
session()->put('redirect_url', route('forms.up-country'));
|
|
return view('backend.pages.forms.upcountry.index', [
|
|
'forms' => $forms,
|
|
'availableBudget' => $availableBudget,
|
|
'outstandingCount' => $outstandingForms->count(),
|
|
'outstandingTotal' => $outstandingForms->sum('total'),
|
|
'outstandingIds' => $outstandingForms->pluck('id')->toArray(),
|
|
]);
|
|
}
|
|
|
|
public function detail($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.view']);
|
|
|
|
$form = FormUpCountry::with(['rayon', 'user'])->findOrFail($id);
|
|
$form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null;
|
|
$form->bukti_transport_dalkot = $form->bukti_transport_dalkot ? NextCloudHelper::getFileUrl($form->bukti_transport_dalkot) : null;
|
|
$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->uc_plan = $form->uc_plan ? NextCloudHelper::getFileUrl($form->uc_plan) : null;
|
|
|
|
return response()->json($form);
|
|
}
|
|
|
|
public function view($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.view']);
|
|
|
|
$form = FormUpCountry::with(['rayon', 'user', 'attachments'])->findOrFail($id);
|
|
$form->bukti_allowance = $form->bukti_allowance ? NextCloudHelper::getFileUrl($form->bukti_allowance) : null;
|
|
$form->bukti_transport_dalkot = $form->bukti_transport_dalkot ? NextCloudHelper::getFileUrl($form->bukti_transport_dalkot) : null;
|
|
$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->uc_plan = $form->uc_plan ? NextCloudHelper::getFileUrl($form->uc_plan) : null;
|
|
|
|
$attachments = $form->attachments->map(function ($attachment) {
|
|
$filePath = $attachment->file_path;
|
|
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
|
|
|
|
return [
|
|
'id' => $attachment->id,
|
|
'file_category' => $attachment->file_category,
|
|
'file_path' => $filePath,
|
|
'download_url' => $filePath ? NextCloudHelper::getFileUrl($filePath) : null,
|
|
'preview_url' => $filePath ? NextCloudHelper::getPreviewUrl($filePath) : null,
|
|
'preview_type' => in_array($extension, ['jpg', 'jpeg', 'png']) ? 'image' : 'pdf',
|
|
'filename' => $filePath ? basename($filePath) : null,
|
|
'extension' => $extension,
|
|
];
|
|
})->values();
|
|
|
|
return view('backend.pages.forms.upcountry.view', [
|
|
'form' => $form,
|
|
'rayons' => Rayon::all(),
|
|
'attachments' => $attachments,
|
|
]);
|
|
}
|
|
|
|
public function create()
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.create']);
|
|
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang;
|
|
|
|
return view('backend.pages.forms.upcountry.create', [
|
|
'rayons' => Rayon::where('cabang_id', $cabang->id)->get(),
|
|
'attachmentCategories' => $this->attachmentCategories,
|
|
]);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.create']);
|
|
$request->validate([
|
|
'rayon_id' => 'required|exists:rayon,id',
|
|
'tanggal' => 'required',
|
|
'tujuan' => 'required',
|
|
'jarak' => 'required',
|
|
'allowance' => 'nullable|numeric',
|
|
'transport_dalkot' => 'nullable|numeric',
|
|
'transport_ankot' => 'nullable|numeric',
|
|
'hotel' => 'nullable|numeric',
|
|
'attachments' => 'nullable|array',
|
|
'attachments.*.file_category' => 'required|string|in:' . implode(',', $this->attachmentCategories),
|
|
'attachments.*.file_path' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:5120'],
|
|
'uc_plan' => 'nullable|file|max:51200',
|
|
]);
|
|
|
|
$tanggal = Carbon::parse($request->tanggal);
|
|
$startDay = (int) env('STARTING_DATE', 11);
|
|
$closingDay = (int) env('CLOSING_DATE', 10);
|
|
$now = Carbon::now();
|
|
|
|
// Tentukan periode aktif saat ini
|
|
if ($now->day >= $startDay) {
|
|
$startDate = Carbon::create($now->year, $now->month, $startDay);
|
|
$closingDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $closingDay);
|
|
} else {
|
|
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
|
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
|
}
|
|
|
|
// Validasi apakah tanggal input berada di periode aktif
|
|
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();
|
|
}
|
|
|
|
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()?->cabang;
|
|
if (!$cabang) {
|
|
session()->flash('error', 'Cabang tidak ditemukan.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$region = Region::find($cabang->region_id);
|
|
$kategori = Kategori::where('name', 'Up Country')->first();
|
|
|
|
// Hitung periode budget dari tanggal input
|
|
if ($tanggal->day >= $startDay) {
|
|
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
|
} else {
|
|
$periodeDate = Carbon::create($tanggal->copy()->subMonth()->year, $tanggal->copy()->subMonth()->month, $startDay);
|
|
}
|
|
|
|
$periodeMonth = strtolower($periodeDate->format('F'));
|
|
$periodeYear = (int) $periodeDate->format('Y');
|
|
|
|
$data_nominal = [
|
|
'allowance' => $request->allowance ?? 0,
|
|
'transport_dalkot' => $request->transport_dalkot ?? 0,
|
|
'transport_ankot' => $request->transport_ankot ?? 0,
|
|
'hotel' => $request->hotel ?? 0,
|
|
];
|
|
|
|
$totalNominal = array_sum($data_nominal);
|
|
|
|
// Validasi budget berdasarkan periode
|
|
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
|
if($totalNominal > $availableBudget) {
|
|
session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/upcountry';
|
|
|
|
$ucPlanPath = null;
|
|
|
|
if ($request->hasFile('uc_plan')) {
|
|
$ucPlan = $request->file('uc_plan');
|
|
$filename = Str::uuid() . '.' . $ucPlan->extension();
|
|
$ucPlanPath = $folderPath . '/' . $filename;
|
|
NextCloudHelper::uploadFile($folderPath, $ucPlan->getContent(), $filename);
|
|
}
|
|
|
|
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
|
|
|
|
// Generate expense number
|
|
DB::beginTransaction();
|
|
try {
|
|
$sequence_number = FormUpCountry::withTrashed()
|
|
->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-UPC-' . date('ym') . '%')
|
|
->count() + 1;
|
|
|
|
$formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT);
|
|
$expense_number = $region->code . '-' . $cabang->code . '-UPC-' . date('ym') . $formatted_sequence_number;
|
|
|
|
$form = FormUpCountry::create([
|
|
'expense_number' => $expense_number,
|
|
'user_id' => auth()->user()->id,
|
|
'rayon_id' => $request->rayon_id,
|
|
'tanggal' => $request->tanggal,
|
|
'tujuan' => $request->tujuan,
|
|
'jarak' => $request->jarak,
|
|
'allowance' => $data_nominal['allowance'],
|
|
'transport_dalkot' => $data_nominal['transport_dalkot'],
|
|
'transport_ankot' => $data_nominal['transport_ankot'],
|
|
'hotel' => $data_nominal['hotel'],
|
|
'total' => $totalNominal,
|
|
'bukti_allowance' => null,
|
|
'bukti_transport_dalkot' => null,
|
|
'bukti_transport_ankot' => null,
|
|
'bukti_hotel' => null,
|
|
'uc_plan' => $ucPlanPath,
|
|
'account_number' => $kategori->account_number,
|
|
'status' => 'On Progress',
|
|
]);
|
|
|
|
if (!empty($attachmentsPayload)) {
|
|
$this->attachmentService->addMultipleAttachments(
|
|
$form->id,
|
|
AttachmentTableName::FORM_UP_COUNTRY,
|
|
$attachmentsPayload
|
|
);
|
|
}
|
|
|
|
DB::commit();
|
|
} catch (\Throwable $th) {
|
|
DB::rollBack();
|
|
Log::error('Failed to store Form Up Country', [
|
|
'message' => $th->getMessage(),
|
|
'trace' => $th->getTraceAsString(),
|
|
]);
|
|
|
|
session()->flash('error', 'Terjadi kesalahan saat menyimpan data, silakan coba lagi.');
|
|
return redirect()->back()->withInput();
|
|
}
|
|
|
|
// Send notification to MIS and Admin Region and Area Manager Cabang
|
|
$roles = ['Marketing Information System', 'Admin Region', 'Area Manager Cabang'];
|
|
$recipients = [$form->user->email, auth()->user()->email];
|
|
$phoneNumbers = [$form->user->phone, auth()->user()->phone];
|
|
$receiver_ids = [];
|
|
|
|
$name = auth()->user()->name;
|
|
$tanggal = $form->tanggal;
|
|
$total = $form->total;
|
|
|
|
// Collect all recipients (emails and phone numbers) for the specified roles
|
|
$cabang = UserHasCabang::where('user_id', $form->user_id)->first();
|
|
$cabang_id = $cabang ? $cabang->cabang_id : null;
|
|
|
|
$cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
|
|
$region_id = $cabangData ? $cabangData->region->id : null;
|
|
|
|
foreach ($roles as $role) {
|
|
$users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
|
|
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
|
|
}
|
|
|
|
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
|
return $user->cabang->cabang->region->id === $region_id;
|
|
}
|
|
|
|
return $user->cabang->cabang->id === $cabang_id;
|
|
});
|
|
|
|
foreach ($users as $user) {
|
|
$recipients[] = $user->email;
|
|
$phoneNumbers[] = $user->phone;
|
|
$receiver_ids[] = $user->id;
|
|
}
|
|
}
|
|
|
|
// Remove duplicate email addresses, if any
|
|
$recipients = array_unique($recipients);
|
|
$phoneNumbers = array_unique($phoneNumbers);
|
|
$receiver_ids = array_unique($receiver_ids);
|
|
|
|
// Generate URL and send WhatsApp notification
|
|
$url = route('forms.up-country.view', $form->id);
|
|
WhatsappHelper::newExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
|
|
|
// Send bulk email
|
|
$brevoService = app(BrevoService::class);
|
|
foreach ($recipients as $recipient) {
|
|
try {
|
|
$mail = new ExpenseCreated(
|
|
$name,
|
|
$expense_number,
|
|
$tanggal,
|
|
$total,
|
|
$url
|
|
);
|
|
|
|
$response = $brevoService->expenseCreated($recipient, $name, $mail);
|
|
|
|
if (isset($response['success']) && $response['success'] === false) {
|
|
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
NotificationHelper::newExpense('up-country', $form->id, $form->user_id, $expense_number, $receiver_ids);
|
|
|
|
AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Up Country (' . $expense_number . ')');
|
|
session()->flash('success', 'Form has been created.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function edit($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.edit']);
|
|
$role = auth()->user()->getRoleNames()[0];
|
|
|
|
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()->cabang;
|
|
$regionId = Cabang::where('id', 1)->value('region_id');
|
|
$rayonData = Rayon::where('cabang_id', $cabang->id)->get();
|
|
|
|
if ($role == "Admin Region") {
|
|
$rayonData = DB::table('rayon')
|
|
->join('cabang', 'rayon.cabang_id', '=', 'cabang.id')
|
|
->join('region', 'cabang.region_id', '=', 'region.id')
|
|
->where('region.id', $regionId)
|
|
->select('rayon.*')
|
|
->get();
|
|
} elseif ($role == "Marketing Information System" || $role == "Superadmin") {
|
|
$rayonData = DB::table('rayon')
|
|
->join('cabang', 'rayon.cabang_id', '=', 'cabang.id')
|
|
->join('region', 'cabang.region_id', '=', 'region.id')
|
|
->whereNotNull('region.id')
|
|
->select('rayon.*')
|
|
->get();
|
|
}
|
|
|
|
$form = FormUpCountry::with(['rayon', 'attachments'])->findOrfail($id);
|
|
if (($form->status != 'On Progress' && $form->status != 'Rejected') && $role == 'Medical Representatif') {
|
|
session()->flash('error', 'You cannot edit this form because it has been approved or closed.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$existingAttachments = $form->attachments->map(function ($attachment) {
|
|
$filePath = $attachment->file_path;
|
|
$extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
|
|
|
|
return [
|
|
'id' => $attachment->id,
|
|
'file_category' => $attachment->file_category,
|
|
'file_path' => $filePath,
|
|
'download_url' => $filePath ? NextCloudHelper::getFileUrl($filePath) : null,
|
|
'preview_url' => $filePath ? NextCloudHelper::getPreviewUrl($filePath) : null,
|
|
'preview_type' => in_array($extension, ['jpg', 'jpeg', 'png']) ? 'image' : 'pdf',
|
|
'filename' => $filePath ? basename($filePath) : null,
|
|
'extension' => $extension,
|
|
];
|
|
})->values();
|
|
|
|
return view('backend.pages.forms.upcountry.edit', [
|
|
'rayons' => $rayonData,
|
|
'form' => $form,
|
|
'attachments' => $existingAttachments,
|
|
'attachmentCategories' => $this->attachmentCategories,
|
|
]);
|
|
}
|
|
|
|
public function update(Request $request, $id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.edit']);
|
|
$role = auth()->user()->getRoleNames()[0];
|
|
|
|
$request->validate([
|
|
'rayon_id' => 'required|exists:rayon,id',
|
|
'tanggal' => 'required',
|
|
'tujuan' => 'required',
|
|
'jarak' => 'required',
|
|
'allowance' => 'nullable|numeric',
|
|
'transport_dalkot' => 'nullable|numeric',
|
|
'transport_ankot' => 'nullable|numeric',
|
|
'hotel' => 'nullable|numeric',
|
|
'attachments' => 'nullable|array',
|
|
'attachments.*.file_category' => 'required|string|in:' . implode(',', $this->attachmentCategories),
|
|
'attachments.*.file_path' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:5120'],
|
|
'uc_plan' => 'nullable|file|max:51200',
|
|
]);
|
|
|
|
$form = FormUpCountry::findOrFail($id);
|
|
if (($form->status !== 'On Progress' && $form->status !== 'Rejected') && $role === 'Medical Representatif') {
|
|
session()->flash('error', 'You cannot edit this form because it has been approved or closed.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()?->cabang;
|
|
if (!$cabang) {
|
|
session()->flash('error', 'Cabang tidak ditemukan.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$region = Region::find($cabang->region_id);
|
|
$kategori = Kategori::where('name', 'Up Country')->first();
|
|
|
|
// Hitung periode dari tanggal input
|
|
$tanggal = Carbon::parse($request->tanggal);
|
|
$startDay = (int) env('STARTING_DATE', 11);
|
|
if ($tanggal->day >= $startDay) {
|
|
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
|
} else {
|
|
$periodeDate = Carbon::create($tanggal->copy()->subMonth()->year, $tanggal->copy()->subMonth()->month, $startDay);
|
|
}
|
|
|
|
$periodeMonth = strtolower($periodeDate->format('F'));
|
|
$periodeYear = (int) $periodeDate->format('Y');
|
|
|
|
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/upcountry';
|
|
|
|
$ucPlanPath = null;
|
|
|
|
if ($request->hasFile('uc_plan')) {
|
|
$file = $request->file('uc_plan');
|
|
$filename = Str::uuid() . '.' . $file->extension();
|
|
$ucPlanPath = $folderPath . '/' . $filename;
|
|
NextCloudHelper::uploadFile($folderPath, $file->getContent(), $filename);
|
|
}
|
|
|
|
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
|
|
|
|
// Hitung total nominal
|
|
$data_nominal = [
|
|
'allowance' => $request->allowance ?? 0,
|
|
'transport_dalkot' => $request->transport_dalkot ?? 0,
|
|
'transport_ankot' => $request->transport_ankot ?? 0,
|
|
'hotel' => $request->hotel ?? 0,
|
|
];
|
|
$totalNominal = array_sum($data_nominal);
|
|
|
|
// Validasi budget dengan periode
|
|
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
|
if(array_sum($data_nominal) > $availableBudget) {
|
|
session()->flash('error', 'The total nominal exceeds the available budget.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
// Save the form data
|
|
DB::beginTransaction();
|
|
try {
|
|
$form->update([
|
|
'rayon_id' => $request->rayon_id,
|
|
'tanggal' => $request->tanggal,
|
|
'tujuan' => $request->tujuan,
|
|
'jarak' => $request->jarak,
|
|
'allowance' => $data_nominal['allowance'],
|
|
'transport_dalkot' => $data_nominal['transport_dalkot'],
|
|
'transport_ankot' => $data_nominal['transport_ankot'],
|
|
'hotel' => $data_nominal['hotel'],
|
|
'total' => $totalNominal,
|
|
'uc_plan' => $ucPlanPath ?? $form->uc_plan,
|
|
'account_number' => $kategori->account_number,
|
|
]);
|
|
|
|
if (!empty($attachmentsPayload)) {
|
|
$this->attachmentService->addMultipleAttachments(
|
|
$form->id,
|
|
AttachmentTableName::FORM_UP_COUNTRY,
|
|
$attachmentsPayload
|
|
);
|
|
}
|
|
|
|
DB::commit();
|
|
} catch (\Throwable $th) {
|
|
DB::rollBack();
|
|
Log::error('Failed to update Form Up Country', [
|
|
'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 Record at Form Up Country (' . $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.country.edit']);
|
|
|
|
$form = FormUpCountry::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_UP_COUNTRY)
|
|
->first();
|
|
|
|
if (!$attachment) {
|
|
return response()->json(['message' => 'Attachment not found.'], 404);
|
|
}
|
|
|
|
$this->attachmentService->deleteAttachment($attachment->id);
|
|
|
|
AuditTrailHelper::AddAuditTrail('Delete Attachment', 'Delete Attachment at Form Up Country (' . $form->expense_number . ')');
|
|
|
|
return response()->json(['message' => 'Attachment deleted successfully.']);
|
|
}
|
|
|
|
protected function buildAttachmentPayload(Request $request, string $folderPath): array
|
|
{
|
|
$payload = [];
|
|
$attachmentInputs = $request->input('attachments', []);
|
|
$attachmentFiles = $request->file('attachments', []);
|
|
|
|
foreach ($attachmentFiles as $index => $fileGroup) {
|
|
$uploadedFile = $fileGroup['file_path'] ?? null;
|
|
|
|
if (!$uploadedFile) {
|
|
continue;
|
|
}
|
|
|
|
$category = $attachmentInputs[$index]['file_category'] ?? null;
|
|
|
|
if (!$category) {
|
|
continue;
|
|
}
|
|
|
|
$filename = Str::uuid() . '.' . $uploadedFile->extension();
|
|
$filePath = $folderPath . '/' . $filename;
|
|
|
|
NextCloudHelper::uploadFile($folderPath, $uploadedFile->getContent(), $filename);
|
|
|
|
$payload[] = [
|
|
'file_category' => $category,
|
|
'file_path' => $filePath,
|
|
];
|
|
}
|
|
|
|
return $payload;
|
|
}
|
|
|
|
public function approve(Request $request, $id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['approval.approve']);
|
|
|
|
$form = FormUpCountry::findOrfail($id);
|
|
|
|
$approved_data = [
|
|
'allowance' => $request->allowance ? $form->allowance : 0,
|
|
'transport_dalkot' => $request->transport_dalkot ? $form->transport_dalkot : 0,
|
|
'transport_ankot' => $request->transport_ankot ? $form->transport_ankot : 0,
|
|
'hotel' => $request->hotel ? $form->hotel : 0,
|
|
];
|
|
|
|
$form->update([
|
|
'approved_at' => now(),
|
|
'approved_by' => auth()->user()->id,
|
|
'status' => 'Approved 1',
|
|
|
|
'approved_allowance' => $approved_data['allowance'],
|
|
'approved_transport_dalkot' => $approved_data['transport_dalkot'],
|
|
'approved_transport_ankot' => $approved_data['transport_ankot'],
|
|
'approved_hotel' => $approved_data['hotel'],
|
|
'approved_total' => array_sum($approved_data),
|
|
]);
|
|
|
|
$name = $form->user->name;
|
|
$expense_number = $form->expense_number;
|
|
$tanggal = $form->tanggal;
|
|
$total = $form->total;
|
|
|
|
// Collect all recipients
|
|
$roles = ['Marketing Information System', 'Admin Region', 'Area Manager Cabang', 'Marketing Operational Manager Region'];
|
|
$recipients = [$form->user->email, auth()->user()->email];
|
|
$phoneNumbers = [$form->user->phone, auth()->user()->phone];
|
|
$receiver_ids = [];
|
|
|
|
// Collect all recipients (emails and phone numbers) for the specified roles
|
|
$cabang = UserHasCabang::where('user_id', $form->user_id)->first();
|
|
$cabang_id = $cabang ? $cabang->cabang_id : null;
|
|
|
|
$cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
|
|
$region_id = $cabangData ? $cabangData->region->id : null;
|
|
|
|
foreach ($roles as $role) {
|
|
$users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
|
|
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
|
|
}
|
|
|
|
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
|
return $user->cabang->cabang->region->id === $region_id;
|
|
}
|
|
|
|
return $user->cabang->cabang->id === $cabang_id;
|
|
});
|
|
|
|
foreach ($users as $user) {
|
|
$recipients[] = $user->email;
|
|
$phoneNumbers[] = $user->phone;
|
|
$receiver_ids[] = $user->id;
|
|
}
|
|
}
|
|
|
|
// Remove duplicate data, if any
|
|
$recipients = array_unique($recipients);
|
|
$phoneNumbers = array_unique($phoneNumbers);
|
|
$receiver_ids = array_unique($receiver_ids);
|
|
|
|
// send whatsapp message
|
|
$url = route('forms.up-country.view', $form->id);
|
|
WhatsappHelper::approveExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
|
|
|
// Send bulk email
|
|
$brevoService = app(BrevoService::class);
|
|
foreach ($recipients as $recipient) {
|
|
try {
|
|
$mail = new ExpenseApproved(
|
|
$name,
|
|
$expense_number,
|
|
$tanggal,
|
|
$total,
|
|
$url
|
|
);
|
|
|
|
$response = $brevoService->expenseApproved($recipient, $name, $mail);
|
|
|
|
if (isset($response['success']) && $response['success'] === false) {
|
|
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
NotificationHelper::approveExpense('up-country', $form->id, $form->user_id, $expense_number, $receiver_ids);
|
|
|
|
AuditTrailHelper::AddAuditTrail('Approve', 'Approve Expense at Form Up Country (' . $form->expense_number . ')');
|
|
session()->flash('success', 'Form has been approved.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function approve2($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['approval2.approve']);
|
|
|
|
$form = FormUpCountry::findOrfail($id);
|
|
$form->update([
|
|
'approved2_at' => now(),
|
|
'approved2_by' => auth()->user()->id,
|
|
'status' => 'Approved 2',
|
|
]);
|
|
|
|
$name = $form->user->name;
|
|
$expense_number = $form->expense_number;
|
|
$tanggal = $form->tanggal;
|
|
$total = $form->total;
|
|
|
|
$roles = ['Marketing Information System', 'Area Manager Cabang', 'Marketing Operational Manager Region', 'Head of Sales Marketing'];
|
|
$recipients = [$form->user->email, auth()->user()->email];
|
|
$phoneNumbers = [$form->user->phone, auth()->user()->phone];
|
|
$receiver_ids = [];
|
|
|
|
// Collect all recipients (emails and phone numbers) for the specified roles
|
|
$cabang = UserHasCabang::where('user_id', $form->user_id)->first();
|
|
$cabang_id = $cabang ? $cabang->cabang_id : null;
|
|
|
|
$cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
|
|
$region_id = $cabangData ? $cabangData->region->id : null;
|
|
|
|
foreach ($roles as $role) {
|
|
$users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
|
|
if ($role === 'Marketing Information System' || $role === 'Head of Sales Marketing') {
|
|
return true; // Tidak ada filter cabang untuk peran ini
|
|
}
|
|
|
|
if (!$user->cabang || !$user->cabang->cabang) {
|
|
return false; // Pastikan user memiliki cabang
|
|
}
|
|
|
|
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
|
return $user->cabang->cabang->region->id === $region_id;
|
|
}
|
|
|
|
return $user->cabang->cabang->id === $cabang_id;
|
|
});
|
|
|
|
foreach ($users as $user) {
|
|
$recipients[] = $user->email;
|
|
$phoneNumbers[] = $user->phone;
|
|
$receiver_ids[] = $user->id;
|
|
}
|
|
}
|
|
|
|
// Remove duplicate data, if any
|
|
$recipients = array_unique($recipients);
|
|
$phoneNumbers = array_unique($phoneNumbers);
|
|
|
|
// send whatsapp message
|
|
$url = route('forms.up-country.view', $form->id);
|
|
WhatsappHelper::approve2Expense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
|
|
|
// Send bulk email
|
|
$brevoService = app(BrevoService::class);
|
|
foreach ($recipients as $recipient) {
|
|
try {
|
|
$mail = new ExpenseApproved2(
|
|
$name,
|
|
$expense_number,
|
|
$tanggal,
|
|
$total,
|
|
$url
|
|
);
|
|
|
|
$response = $brevoService->expenseApproved2($recipient, $name, $mail);
|
|
|
|
if (isset($response['success']) && $response['success'] === false) {
|
|
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
NotificationHelper::approve2Expense('up-country', $form->id, $form->user_id, $expense_number, $receiver_ids);
|
|
|
|
AuditTrailHelper::AddAuditTrail('Approve', 'Approve Expense at Form Up Country (' . $form->expense_number . ')');
|
|
session()->flash('success', 'Form has been approved.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function finalApprove($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
|
$form = FormUpCountry::findOrFail($id);
|
|
|
|
if ($form->approved_at === null || $form->approved2_at === null) {
|
|
session()->flash('error', 'Form must be approved by both approvers before final approval.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
// Ambil cabang_id dari user yang mengisi form
|
|
$cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()?->cabang_id;
|
|
if (!$cabang_id) {
|
|
session()->flash('error', 'Data cabang tidak ditemukan.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
// Hitung periode berdasarkan tanggal form
|
|
$tanggal = Carbon::parse($form->tanggal);
|
|
$startDay = (int) env('STARTING_DATE', 11);
|
|
if ($tanggal->day >= $startDay) {
|
|
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
|
} else {
|
|
$periodeDate = Carbon::create($tanggal->copy()->subMonth()->year, $tanggal->copy()->subMonth()->month, $startDay);
|
|
}
|
|
|
|
$periodeMonth = strtolower($periodeDate->format('F'));
|
|
$periodeYear = (int) $periodeDate->format('Y');
|
|
|
|
// Ambil sisa budget sesuai periode
|
|
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
|
if($form->approved_total > $availableBudget) {
|
|
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
|
return redirect()->back();
|
|
}
|
|
|
|
$form->update([
|
|
'final_approved_at' => now(),
|
|
'final_approved_by' => auth()->user()->id,
|
|
'status' => 'Closed',
|
|
]);
|
|
|
|
$name = $form->user->name;
|
|
$expense_number = $form->expense_number;
|
|
$tanggal = $form->tanggal;
|
|
$total = $form->approved_total;
|
|
|
|
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
|
$recipients = [$form->user->email, auth()->user()->email];
|
|
$phoneNumbers = [$form->user->phone, auth()->user()->phone];
|
|
|
|
$cabang = UserHasCabang::where('user_id', $form->user_id)->first();
|
|
$cabang_id = $cabang ? $cabang->cabang_id : null;
|
|
|
|
$cabangData = $cabang_id ? Cabang::where('id', $cabang_id)->first() : null;
|
|
$region_id = $cabangData ? $cabangData->region->id : null;
|
|
|
|
foreach ($roles as $role) {
|
|
$users = Admin::getUserByRoleName($role)->filter(function ($user) use ($role, $cabang_id, $region_id) {
|
|
if ($role === 'Marketing Information System' || $role === 'Head of Sales Marketing') {
|
|
return true; // Tidak ada filter cabang untuk peran ini
|
|
}
|
|
|
|
if (!$user->cabang || !$user->cabang->cabang) {
|
|
return false; // Pastikan user memiliki cabang
|
|
}
|
|
|
|
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
|
return $user->cabang->cabang->region->id === $region_id;
|
|
}
|
|
|
|
return $user->cabang->cabang->id === $cabang_id;
|
|
});
|
|
|
|
foreach ($users as $user) {
|
|
$recipients[] = $user->email;
|
|
$phoneNumbers[] = $user->phone;
|
|
}
|
|
}
|
|
|
|
// Remove duplicate email addresses, if any
|
|
$recipients = array_unique($recipients);
|
|
$phoneNumbers = array_unique($phoneNumbers);
|
|
|
|
// send whatsapp message
|
|
$url = route('forms.up-country.view', $form->id);
|
|
WhatsappHelper::finalApprove($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
|
|
|
// Send bulk email
|
|
$brevoService = app(BrevoService::class);
|
|
foreach ($recipients as $recipient) {
|
|
try {
|
|
$mail = new FinalApprove(
|
|
$name,
|
|
$expense_number,
|
|
$tanggal,
|
|
$total,
|
|
$url
|
|
);
|
|
|
|
$response = $brevoService->expenseFinalApproved($recipient, $name, $mail);
|
|
|
|
if (isset($response['success']) && $response['success'] === false) {
|
|
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
AuditTrailHelper::AddAuditTrail('Final Approve', 'Final Approve Expense at Form Up Country (' . $form->expense_number . ')');
|
|
session()->flash('success', 'Form has been final approved.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function reject(Request $request, $id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
|
|
|
$request->validate([
|
|
'remarks' => 'required|string|max:500',
|
|
]);
|
|
|
|
$form = FormUpCountry::findOrfail($id);
|
|
$form->update([
|
|
'status' => 'Rejected',
|
|
'remarks' => $request->remarks,
|
|
]);
|
|
|
|
$heads = $form->user->getCabangAndRegionHead();
|
|
$name = $form->user->name;
|
|
$expense_number = $form->expense_number;
|
|
$tanggal = $form->tanggal;
|
|
$total = $form->total;
|
|
|
|
// Collect all recipients
|
|
$recipients = [$form->user->email, auth()->user()->email];
|
|
$phoneNumbers = [$form->user->phone, auth()->user()->phone];
|
|
|
|
if ($heads['cabang_head']) {
|
|
$recipients[] = $heads['cabang_head']['email'];
|
|
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
|
}
|
|
|
|
if ($heads['region_head']) {
|
|
$recipients[] = $heads['region_head']['email'];
|
|
$phoneNumbers[] = $heads['region_head']['phone'];
|
|
}
|
|
|
|
// Remove duplicate email addresses, if any
|
|
$recipients = array_unique($recipients);
|
|
$phoneNumbers = array_unique($phoneNumbers);
|
|
|
|
// send whatsapp message
|
|
$url = route('forms.up-country.view', $form->id);
|
|
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
|
|
|
// Send bulk email
|
|
$brevoService = app(BrevoService::class);
|
|
foreach ($recipients as $recipient) {
|
|
try {
|
|
$mail = new ExpenseRejected(
|
|
$name,
|
|
$expense_number,
|
|
$tanggal,
|
|
$total,
|
|
$url
|
|
);
|
|
|
|
$response = $brevoService->expenseRejected($recipient, $name, $mail);
|
|
|
|
if (isset($response['success']) && $response['success'] === false) {
|
|
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
|
continue;
|
|
}
|
|
}
|
|
|
|
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Up Country (' . $form->expense_number . ')');
|
|
session()->flash('success', 'Form has been rejected.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function open($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['final_approval.open']);
|
|
|
|
$form = FormUpCountry::findOrfail($id);
|
|
$form->update([
|
|
'final_approved_at' => null,
|
|
'final_approved_by' => null,
|
|
'status' => 'Approved 2'
|
|
]);
|
|
|
|
AuditTrailHelper::AddAuditTrail('Open', 'Open Expense at Form Up Country (' . $form->expense_number . ')');
|
|
session()->flash('success', 'Form has been opened.');
|
|
return redirect()->back();
|
|
}
|
|
|
|
public function destroy($id)
|
|
{
|
|
$this->checkAuthorization(auth()->user(), ['forms.country.delete']);
|
|
$role = auth()->user()->getRoleNames()[0];
|
|
|
|
$form = FormUpCountry::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();
|
|
}
|
|
|
|
AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Up Country (' . $form->expense_number . ')');
|
|
|
|
$form->delete();
|
|
|
|
session()->flash('success', 'Form has been deleted.');
|
|
return redirect()->back();
|
|
}
|
|
}
|