This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\Models\FormUpCountry;
|
||||
use App\Models\FormVehicleRunningCost;
|
||||
use App\Models\FormEntertaimentPresentation;
|
||||
use App\Models\FormMeetingSeminar;
|
||||
use App\Models\FormOthers;
|
||||
use App\Helpers\AuditTrailHelper;
|
||||
|
||||
class AutoRejectExpense extends Command
|
||||
{
|
||||
/**
|
||||
* Nama perintah yang akan dijalankan di terminal/cron
|
||||
*/
|
||||
protected $signature = 'expense:auto-reject';
|
||||
|
||||
/**
|
||||
* Deskripsi perintah
|
||||
*/
|
||||
protected $description = 'Otomatis reject expense yang melewati batas waktu final approve (Tgl 13)';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
|
||||
// Hanya jalankan eksekusi reject pada H+1 dari Closing Day (Misal: Tanggal 14 jam 00:01)
|
||||
if ($now->day !== ($closingDay + 1)) {
|
||||
$this->info("Hari ini bukan jadwal auto-reject. Jadwal berikutnya: Tanggal " . ($closingDay + 1));
|
||||
return;
|
||||
}
|
||||
|
||||
// Batas maksimal tanggal expense yang harus direject adalah H-1 dari Start Day (Misal: Tanggal 10 bulan ini)
|
||||
// Karena tanggal 11 sudah masuk ke periode bulan depannya.
|
||||
$batasTanggalPeriodeLalu = Carbon::create($now->year, $now->month, $startDay)->subDay()->endOfDay();
|
||||
|
||||
$models = [
|
||||
FormUpCountry::class,
|
||||
FormVehicleRunningCost::class,
|
||||
FormEntertaimentPresentation::class,
|
||||
FormMeetingSeminar::class,
|
||||
FormOthers::class
|
||||
];
|
||||
|
||||
// Daftar status yang dianggap menggantung / belum selesai
|
||||
$pendingStatuses = ['On Progress', 'Approved 1', 'Approved 2', 'Waiting Approval', 'Validated'];
|
||||
|
||||
$totalRejected = 0;
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
foreach ($models as $model) {
|
||||
// Tentukan kolom tanggal yang digunakan
|
||||
$dateColumn = ($model === FormMeetingSeminar::class) ? 'created_at' : 'tanggal';
|
||||
|
||||
// Ambil semua data yang masih menggantung dari periode lalu
|
||||
$pendingExpenses = $model::whereIn('status', $pendingStatuses)
|
||||
->where($dateColumn, '<=', $batasTanggalPeriodeLalu)
|
||||
->get();
|
||||
|
||||
foreach ($pendingExpenses as $expense) {
|
||||
// Update status dan berikan alasan penolakan sesuai instruksi core business
|
||||
$expense->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => 'auto reject by system - lewat periode cut off',
|
||||
'rejected_at' => Carbon::now(),
|
||||
'rejected_by' => 0 // Diisi 0 sebagai flag penanda sistem otomatis
|
||||
]);
|
||||
|
||||
// Tambahkan ke Audit Trail
|
||||
$noExpense = $expense->expense_number ?? 'Unknown';
|
||||
AuditTrailHelper::AddAuditTrail('System Update', "Auto Reject by System for Expense ({$noExpense})");
|
||||
|
||||
$totalRejected++;
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
|
||||
$msg = "Auto Reject berhasil dijalankan. Total direject: {$totalRejected} dokumen.";
|
||||
$this->info($msg);
|
||||
Log::info($msg);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
$this->error("Gagal menjalankan Auto Reject: " . $e->getMessage());
|
||||
Log::error("Cron Auto Reject Failed: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class MigrateOldExpenseData extends Command
|
||||
{
|
||||
// Perintah yang akan dieksekusi di terminal
|
||||
protected $signature = 'expense:migrate-old';
|
||||
protected $description = 'Migrasi data transaksional paling update dari expense-old ke database expense (v2.0) secara aman';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$this->info('Memulai Proses Sinkronisasi: Memindahkan data update dari [expense-old] ke [expense]...');
|
||||
|
||||
// Daftar tabel yang akan disinkronkan (Nama tabel diasumsikan sama pada kedua versi)
|
||||
$tablesToMigrate = [
|
||||
'form_up_country' => 'form_up_country',
|
||||
'form_vehicle_running_cost' => 'form_vehicle_running_cost',
|
||||
'form_entertainment_presentation' => 'form_entertainment_presentation',
|
||||
'form_meeting_seminar' => 'form_meeting_seminar',
|
||||
'form_others' => 'form_others',
|
||||
];
|
||||
|
||||
foreach ($tablesToMigrate as $oldTable => $newTable) {
|
||||
$this->comment("--------------------------------------------------");
|
||||
$this->comment("Memproses Tabel Target: {$newTable}");
|
||||
|
||||
// 1. Validasi eksistensi tabel di database tujuan (expense)
|
||||
if (!Schema::hasTable($newTable)) {
|
||||
$this->error("Tabel [{$newTable}] tidak ditemukan di database 'expense'. Melewati tabel ini.");
|
||||
continue;
|
||||
}
|
||||
|
||||
// 2. Ambil list kolom lengkap yang ada di database tujuan (expense)
|
||||
$destinationColumns = Schema::getColumnListing($newTable);
|
||||
|
||||
// 3. Ambil data transaksional paling update dari database lama (expense-old)
|
||||
$oldData = DB::connection('mysql_lama')->table($oldTable)->get();
|
||||
|
||||
$insertedCount = 0;
|
||||
$skippedCount = 0;
|
||||
|
||||
foreach ($oldData as $row) {
|
||||
// 4. PROTEKSI ANTI-OVERWRITE: Cek apakah data sudah ada di database 'expense'
|
||||
$isExists = DB::table($newTable)
|
||||
->where('expense_number', $row->expense_number)
|
||||
->exists();
|
||||
|
||||
if (!$isExists) {
|
||||
$insertData = [];
|
||||
|
||||
// 5. MAPPING DATA SECARA DINAMIS
|
||||
foreach ($destinationColumns as $column) {
|
||||
// KUNCI PENYEMPURNAAN: Jangan bawa ID lama agar tidak tabrakan dengan Auto-Increment di DB baru
|
||||
if ($column === 'id') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Jika kolom dari database baru tersedia di data 'expense-old', ambil nilainya
|
||||
if (property_exists($row, $column) && !is_null($row->$column)) {
|
||||
$insertData[$column] = $row->$column;
|
||||
} else {
|
||||
// Jika kolom baru versi 2.0 tidak ada di database lama / bernilai NULL, isi dengan nilai default aman
|
||||
$insertData[$column] = $this->getDefaultValueForColumn($newTable, $column);
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Jalankan amunisi Insert ke database utama (expense)
|
||||
DB::table($newTable)->insert($insertData);
|
||||
$insertedCount++;
|
||||
} else {
|
||||
$skippedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
$this->info("Tabel [{$newTable}] Selesai: Masuk {$insertedCount} data baru. Diabaikan (Sudah ada) {$skippedCount} data.");
|
||||
}
|
||||
|
||||
$this->info('==================================================');
|
||||
$this->info('Sukses! Seluruh data dari [expense-old] telah bermigrasi ke [expense] dengan aman.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fallback Nilai Default untuk Kolom Baru Struktur Aplikasi 2.0
|
||||
*/
|
||||
private function getDefaultValueForColumn($tableName, $columnName)
|
||||
{
|
||||
// POINT 1: Solusi otomatisasi penanganan cabang_id yang NULL pada tabel entertainment
|
||||
if ($tableName === 'form_entertainment_presentation' && $columnName === 'cabang_id') {
|
||||
return 1; // Ganti angka 1 dengan ID Cabang default existing Anda
|
||||
}
|
||||
|
||||
// Pengondisian khusus untuk kolom-kolom baru krusial di versi 2.0 Anda
|
||||
if ($columnName === 'account_number') {
|
||||
return '-';
|
||||
}
|
||||
if ($columnName === 'approved_total') {
|
||||
return 0;
|
||||
}
|
||||
if ($columnName === 'approved_at' || $columnName === 'approved2_at' || $columnName === 'final_approved_at') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Nilai bawaan jika tidak masuk kategori spesifik di atas
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use App\Models\AuditTrail;
|
||||
use Maatwebsite\Excel\Concerns\FromQuery;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithColumnWidths;
|
||||
use Maatwebsite\Excel\Concerns\WithStyles;
|
||||
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
|
||||
|
||||
class AuditTrailExport implements FromQuery, WithMapping, WithHeadings, WithColumnWidths, WithStyles
|
||||
{
|
||||
protected $filters;
|
||||
|
||||
public function __construct($filters)
|
||||
{
|
||||
$this->filters = $filters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Menggunakan FromQuery untuk efisiensi memori pada data besar
|
||||
*/
|
||||
public function query()
|
||||
{
|
||||
$f = $this->filters;
|
||||
$query = AuditTrail::with(['user.cabang.cabang.region']);
|
||||
|
||||
// Filter Region & Cabang
|
||||
if (!empty($f['region']) || !empty($f['cabang'])) {
|
||||
$query->whereHas('user.cabang.cabang', function($q) use ($f) {
|
||||
if (!empty($f['cabang'])) {
|
||||
$q->where('id', $f['cabang']);
|
||||
}
|
||||
if (!empty($f['region'])) {
|
||||
$q->whereHas('region', function($rq) use ($f) {
|
||||
// PERBAIKAN: Gunakan 'code' sesuai image_63aac6.png
|
||||
$rq->where('code', $f['region']);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Filter User & Tanggal...
|
||||
if (!empty($f['admin_id'])) {
|
||||
$query->where('user_id', $f['admin_id']);
|
||||
}
|
||||
|
||||
return $query->latest();
|
||||
}
|
||||
/**
|
||||
* Header Tabel Excel
|
||||
*/
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
'Waktu',
|
||||
'User',
|
||||
'IP Address',
|
||||
'Aksi',
|
||||
'Aktivitas',
|
||||
'Browser'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Transformasi Data per baris
|
||||
*/
|
||||
public function map($audit): array
|
||||
{
|
||||
return [
|
||||
$audit->created_at->format('d-m-Y H:i:s'),
|
||||
$audit->user->name ?? 'System',
|
||||
$audit->ip_address,
|
||||
$audit->action,
|
||||
$audit->activity,
|
||||
$audit->browser,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Atur Lebar Kolom agar rapi secara otomatis
|
||||
*/
|
||||
public function columnWidths(): array
|
||||
{
|
||||
return [
|
||||
'A' => 20,
|
||||
'B' => 20,
|
||||
'C' => 15,
|
||||
'D' => 15,
|
||||
'E' => 50,
|
||||
'F' => 20,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Styling Header agar lebih profesional
|
||||
*/
|
||||
public function styles(Worksheet $sheet)
|
||||
{
|
||||
return [
|
||||
1 => ['font' => ['bold' => true]],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Exports;
|
||||
|
||||
use Maatwebsite\Excel\Concerns\FromCollection;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use Maatwebsite\Excel\Concerns\WithMapping;
|
||||
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
|
||||
|
||||
class PendingDocumentExport implements FromCollection, WithHeadings, WithMapping, ShouldAutoSize
|
||||
{
|
||||
protected $cabangs;
|
||||
|
||||
public function __construct($cabangs)
|
||||
{
|
||||
$this->cabangs = $cabangs;
|
||||
}
|
||||
|
||||
public function collection()
|
||||
{
|
||||
return $this->cabangs;
|
||||
}
|
||||
|
||||
public function headings(): array
|
||||
{
|
||||
return [
|
||||
'Region',
|
||||
'Nama Cabang',
|
||||
'Up Country',
|
||||
'Vehicle',
|
||||
'Entertainment',
|
||||
'Meeting',
|
||||
'Others',
|
||||
'Total Pending',
|
||||
'Budget Aktif'
|
||||
];
|
||||
}
|
||||
|
||||
public function map($cabang): array
|
||||
{
|
||||
return [
|
||||
$cabang->region->name ?? '-',
|
||||
$cabang->name,
|
||||
$cabang->pending_details['up_country'] ?? 0,
|
||||
$cabang->pending_details['vehicle'] ?? 0,
|
||||
$cabang->pending_details['entertainment'] ?? 0,
|
||||
$cabang->pending_details['meeting'] ?? 0,
|
||||
$cabang->pending_details['others'] ?? 0,
|
||||
$cabang->total_pending,
|
||||
$cabang->available_budget
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,29 +4,59 @@ namespace App\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\AuditTrail;
|
||||
use Illuminate\Support\Facades\Request;
|
||||
|
||||
class AuditTrailHelper
|
||||
{
|
||||
public static function AddAuditTrail($action, $activity)
|
||||
{
|
||||
$audit = new AuditTrail();
|
||||
$audit->user_id = Auth::user()->id;
|
||||
$audit->ip_address = request()->ip();
|
||||
$audit->activity = $activity;
|
||||
$audit->action = $action;
|
||||
$audit->user_agent = request()->userAgent();
|
||||
$audit->browser = substr($audit->user_agent, 0, strpos($audit->user_agent, '/'));
|
||||
$audit->save();
|
||||
}
|
||||
/**
|
||||
* Mencatat aktivitas umum (Insert, Update, Delete, Approve, Reject)
|
||||
*/
|
||||
public static function AddAuditTrail($action, $activity)
|
||||
{
|
||||
// Menggunakan guard 'admin' sesuai spesifikasi login aplikasi Anda
|
||||
$user = Auth::guard('admin')->user();
|
||||
|
||||
public static function AuthAttempt($action, $activity)
|
||||
{
|
||||
$audit = new AuditTrail();
|
||||
$audit->ip_address = request()->ip();
|
||||
$audit->activity = $activity;
|
||||
$audit->action = $action;
|
||||
$audit->user_agent = request()->userAgent();
|
||||
$audit->browser = substr($audit->user_agent, 0, strpos($audit->user_agent, '/'));
|
||||
$audit->save();
|
||||
}
|
||||
$audit = new AuditTrail();
|
||||
$audit->user_id = $user ? $user->id : null;
|
||||
$audit->ip_address = Request::ip();
|
||||
$audit->activity = $activity;
|
||||
$audit->action = $action;
|
||||
$audit->user_agent = Request::userAgent();
|
||||
$audit->browser = self::getBrowserName(Request::userAgent());
|
||||
|
||||
$audit->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Mencatat percobaan otentikasi (Login/Logout)
|
||||
*/
|
||||
public static function AuthAttempt($action, $activity)
|
||||
{
|
||||
$audit = new AuditTrail();
|
||||
$audit->user_id = Auth::guard('admin')->id(); // Tetap coba ambil ID jika ada (misal saat logout)
|
||||
$audit->ip_address = Request::ip();
|
||||
$audit->activity = $activity;
|
||||
$audit->action = $action;
|
||||
$audit->user_agent = Request::userAgent();
|
||||
$audit->browser = self::getBrowserName(Request::userAgent());
|
||||
|
||||
$audit->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper internal untuk deteksi browser yang lebih bersih
|
||||
*/
|
||||
private static function getBrowserName($userAgent)
|
||||
{
|
||||
if (!$userAgent) return 'Unknown';
|
||||
|
||||
if (strpos($userAgent, 'Opera') || strpos($userAgent, 'OPR')) return 'Opera';
|
||||
if (strpos($userAgent, 'Edge')) return 'Edge';
|
||||
if (strpos($userAgent, 'Chrome')) return 'Chrome';
|
||||
if (strpos($userAgent, 'Safari')) return 'Safari';
|
||||
if (strpos($userAgent, 'Firefox')) return 'Firefox';
|
||||
if (strpos($userAgent, 'MSIE') || strpos($userAgent, 'Trident/7')) return 'Internet Explorer';
|
||||
|
||||
return explode('/', $userAgent)[0] ?? 'Unknown';
|
||||
}
|
||||
}
|
||||
+317
-70
@@ -2,97 +2,344 @@
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Exception\RequestException;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Models\Kategori;
|
||||
use App\Models\BudgetControl;
|
||||
use App\Models\FormUpCountry;
|
||||
use App\Models\FormMeetingSeminar;
|
||||
use App\Models\FormOthers;
|
||||
use App\Models\FormEntertaimentPresentation;
|
||||
use App\Models\FormVehicleRunningCost;
|
||||
use App\Helpers\FormHelper;
|
||||
use App\Models\UserHasCabang;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class BudgetHelper
|
||||
{
|
||||
/**
|
||||
* Cache memori sementara untuk fungsi jurnal agar loading halaman riwayat tidak berat.
|
||||
*/
|
||||
private static $jurnalCache = [];
|
||||
|
||||
/**
|
||||
* Daftar status yang akan memotong (menge-hold) sisa budget secara real-time.
|
||||
*/
|
||||
const HOLD_STATUSES = [
|
||||
'Approved 1',
|
||||
'Approved 2',
|
||||
'Waiting Approval',
|
||||
'Validated',
|
||||
'Approved',
|
||||
'Closed',
|
||||
'Completed'
|
||||
];
|
||||
|
||||
public static function getBulkAvailableBudget($budgetControls)
|
||||
{
|
||||
if ($budgetControls->isEmpty()) return [];
|
||||
|
||||
$cabangIds = $budgetControls->pluck('cabang_id')->unique()->toArray();
|
||||
|
||||
// 1. Mapping User per Cabang
|
||||
$branchUsers = UserHasCabang::whereIn('cabang_id', $cabangIds)
|
||||
->get()
|
||||
->groupBy('cabang_id')
|
||||
->map(fn($item) => $item->pluck('user_id')->toArray());
|
||||
|
||||
$allUserIds = $branchUsers->flatten()->unique()->toArray();
|
||||
$resultsMap = [];
|
||||
|
||||
if (empty($allUserIds)) return [];
|
||||
|
||||
$formModels = [
|
||||
'tanggal' => [
|
||||
FormUpCountry::class,
|
||||
FormVehicleRunningCost::class,
|
||||
FormEntertaimentPresentation::class,
|
||||
FormOthers::class
|
||||
],
|
||||
'created_at' => [
|
||||
FormMeetingSeminar::class
|
||||
]
|
||||
];
|
||||
|
||||
// 2. Tarik data pengeluaran sekaligus dari semua tabel form
|
||||
foreach ($formModels as $dateColumn => $models) {
|
||||
foreach ($models as $model) {
|
||||
$query = $model::whereIn('user_id', $allUserIds)
|
||||
->whereIn('status', self::HOLD_STATUSES)
|
||||
->select(
|
||||
'user_id',
|
||||
DB::raw("MONTH($dateColumn) as month"),
|
||||
DB::raw("YEAR($dateColumn) as year"),
|
||||
DB::raw("SUM(approved_total) as total")
|
||||
)
|
||||
->groupBy('user_id', 'month', 'year')
|
||||
->get();
|
||||
|
||||
// 3. Masukkan ke Map berdasarkan Cabang_Bulan_Tahun
|
||||
foreach ($query as $row) {
|
||||
foreach ($branchUsers as $cabangId => $userIds) {
|
||||
if (in_array($row->user_id, $userIds)) {
|
||||
$monthName = strtolower(date('F', mktime(0, 0, 0, $row->month, 10)));
|
||||
$key = "{$cabangId}_{$monthName}_{$row->year}";
|
||||
|
||||
$resultsMap[$key] = ($resultsMap[$key] ?? 0) + $row->total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $resultsMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghitung sisa budget (Pagu - Total Hold/Terpakai).
|
||||
* Tetap menggunakan kolom tanggal/created_at karena pengajuan yang baru
|
||||
* dibuat (Approved 1) belum memiliki final_approved_at.
|
||||
*/
|
||||
public static function getAvailableBudget($cabang_id, $periode_month, $periode_year)
|
||||
{
|
||||
// Validasi & normalisasi
|
||||
$periode_month = strtolower($periode_month);
|
||||
$periode_year = (int) $periode_year;
|
||||
{
|
||||
$periode_month = strtolower($periode_month);
|
||||
$periode_year = (int) $periode_year;
|
||||
|
||||
// Ambil budget sesuai cabang dan periode
|
||||
$budget = BudgetControl::where('cabang_id', $cabang_id)
|
||||
->where('periode_month', $periode_month)
|
||||
->where('periode_year', $periode_year)
|
||||
->with(['user.cabang'])
|
||||
->get();
|
||||
$totalPagu = BudgetControl::where('cabang_id', $cabang_id)
|
||||
->where('periode_month', $periode_month)
|
||||
->where('periode_year', $periode_year)
|
||||
->sum('amount');
|
||||
|
||||
$usedBudget = 0;
|
||||
if ($totalPagu <= 0) return 0;
|
||||
|
||||
$users = UserHasCabang::where('cabang_id', $cabang_id)->get();
|
||||
$userIds = $users->pluck('user_id')->toArray();
|
||||
$userIds = UserHasCabang::where('cabang_id', $cabang_id)->pluck('user_id')->toArray();
|
||||
|
||||
$forms = FormHelper::getTotalAmount($userIds, $periode_month, $periode_year)
|
||||
->sortByDesc('tanggal')
|
||||
->sortByDesc('created_at');
|
||||
if (empty($userIds)) return $totalPagu;
|
||||
|
||||
$usedBudget += $forms->sum('approved_total');
|
||||
$usedBudget = 0;
|
||||
$monthNumeric = date('m', strtotime($periode_month));
|
||||
|
||||
$availableBudget = $budget->sum('amount') - $usedBudget;
|
||||
$formModels = [
|
||||
FormUpCountry::class,
|
||||
FormVehicleRunningCost::class,
|
||||
FormEntertaimentPresentation::class,
|
||||
FormMeetingSeminar::class,
|
||||
FormOthers::class
|
||||
];
|
||||
|
||||
return $availableBudget;
|
||||
}
|
||||
foreach ($formModels as $model) {
|
||||
$query = $model::whereIn('user_id', $userIds)
|
||||
->whereIn('status', self::HOLD_STATUSES);
|
||||
|
||||
public static function getNominalByFormType($userIds, $type, $type_id, $month, $year)
|
||||
{
|
||||
if ($type == 'Up Country') {
|
||||
$form = FormUpCountry::select('approved_total')
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', '=', date('m', strtotime($month)))
|
||||
->whereYear('tanggal', '=', $year)
|
||||
->whereIn('status', ['Approved', 'Closed'])
|
||||
->get();
|
||||
} elseif ($type == 'Vehicle Running Cost') {
|
||||
$form = FormVehicleRunningCost::select('approved_total')
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', '=', date('m', strtotime($month)))
|
||||
->whereYear('tanggal', '=', $year)
|
||||
->whereIn('status', ['Approved', 'Closed'])
|
||||
->get();
|
||||
} elseif ($type == 'Entertainment') {
|
||||
$form = FormEntertaimentPresentation::select('approved_total')
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', '=', date('m', strtotime($month)))
|
||||
->whereYear('tanggal', '=', $year)
|
||||
->whereIn('status', ['Approved', 'Closed'])
|
||||
->get();
|
||||
} elseif ($type == 'Meeting / Seminar') {
|
||||
$form = FormMeetingSeminar::select('approved_total')
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereMonth('created_at', '=', date('m', strtotime($month)))
|
||||
->whereYear('created_at', '=', $year)
|
||||
->whereIn('status', ['Approved', 'Closed'])
|
||||
->get();
|
||||
} else {
|
||||
$form = FormOthers::select('approved_total')
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', '=', date('m', strtotime($month)))
|
||||
->whereYear('tanggal', '=', $year)
|
||||
->where('kategori_id', $type_id)
|
||||
->whereIn('status', ['Approved', 'Closed'])
|
||||
->get();
|
||||
}
|
||||
if ($model === FormMeetingSeminar::class) {
|
||||
$query->whereMonth('created_at', $monthNumeric)
|
||||
->whereYear('created_at', $periode_year);
|
||||
} else {
|
||||
$query->whereMonth('tanggal', $monthNumeric)
|
||||
->whereYear('tanggal', $periode_year);
|
||||
}
|
||||
|
||||
return $form->sum('approved_total');
|
||||
}
|
||||
$usedBudget += $query->sum('approved_total');
|
||||
}
|
||||
|
||||
public static function getClosingDate($cabang_id)
|
||||
{
|
||||
$budget = BudgetControl::where('cabang_id', $cabang_id)->orderBy('created_at', 'desc')->first();
|
||||
return $totalPagu - $usedBudget;
|
||||
}
|
||||
|
||||
return $budget->closing_at;
|
||||
}
|
||||
/**
|
||||
* Memvalidasi apakah tanggal expense yang diinput user berada dalam
|
||||
* rentang periode aktif (Tanggal 11 s/d 10).
|
||||
*/
|
||||
public static function checkExpenseInputWindow($tanggal_expense)
|
||||
{
|
||||
$inputDate = \Carbon\Carbon::parse($tanggal_expense)->startOfDay();
|
||||
$today = \Carbon\Carbon::now();
|
||||
|
||||
$startDay = 11;
|
||||
$endDay = 10;
|
||||
|
||||
// Menentukan jendela periode yang sedang aktif hari ini
|
||||
if ($today->day >= $startDay) {
|
||||
// Jika hari ini tgl 11 atau lebih: Jendela aktif adalah Tgl 11 bulan ini s/d Tgl 10 bulan depan
|
||||
$periodStart = \Carbon\Carbon::create($today->year, $today->month, $startDay)->startOfDay();
|
||||
$periodEnd = \Carbon\Carbon::create($today->year, $today->month, $endDay)->addMonth()->endOfDay();
|
||||
} else {
|
||||
// Jika hari ini tgl 1-10: Jendela aktif adalah Tgl 11 bulan lalu s/d Tgl 10 bulan ini
|
||||
$periodStart = \Carbon\Carbon::create($today->year, $today->month, $startDay)->subMonth()->startOfDay();
|
||||
$periodEnd = \Carbon\Carbon::create($today->year, $today->month, $endDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Jika tanggal form yang diinput user berada di luar jendela aktif
|
||||
if ($inputDate->lt($periodStart) || $inputDate->gt($periodEnd)) {
|
||||
return [
|
||||
'is_valid' => false,
|
||||
'message' => "Gagal! Batas input expense untuk periode aktif saat ini adalah {$periodStart->format('d M Y')} s/d {$periodEnd->format('d M Y')}. Tanggal {$inputDate->format('d M Y')} sudah ditutup atau belum dibuka."
|
||||
];
|
||||
}
|
||||
|
||||
return ['is_valid' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengambil nominal per tipe form.
|
||||
*/
|
||||
public static function getNominalByFormType($userIds, $type, $type_id, $month, $year)
|
||||
{
|
||||
$monthNumeric = date('m', strtotime($month));
|
||||
$used = 0;
|
||||
|
||||
if ($type == 'Up Country') {
|
||||
$used = FormUpCountry::whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', $monthNumeric)->whereYear('tanggal', $year)
|
||||
->whereIn('status', self::HOLD_STATUSES)->sum('approved_total');
|
||||
|
||||
} elseif ($type == 'Vehicle Running Cost') {
|
||||
$used = FormVehicleRunningCost::whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', $monthNumeric)->whereYear('tanggal', $year)
|
||||
->whereIn('status', self::HOLD_STATUSES)->sum('approved_total');
|
||||
|
||||
} elseif ($type == 'Entertainment') {
|
||||
$used = FormEntertaimentPresentation::whereIn('user_id', $userIds)
|
||||
->whereMonth('tanggal', $monthNumeric)->whereYear('tanggal', $year)
|
||||
->whereIn('status', self::HOLD_STATUSES)->sum('approved_total');
|
||||
|
||||
} elseif ($type == 'Meeting / Seminar') {
|
||||
$used = FormMeetingSeminar::whereIn('user_id', $userIds)
|
||||
->whereMonth('created_at', $monthNumeric)->whereYear('created_at', $year)
|
||||
->whereIn('status', self::HOLD_STATUSES)->sum('approved_total');
|
||||
|
||||
} else {
|
||||
$used = FormOthers::whereIn('user_id', $userIds)
|
||||
->where('kategori_id', $type_id)
|
||||
->whereMonth('tanggal', $monthNumeric)->whereYear('tanggal', $year)
|
||||
->whereIn('status', self::HOLD_STATUSES)->sum('approved_total');
|
||||
}
|
||||
|
||||
return $used;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengambil tanggal closing.
|
||||
*/
|
||||
public static function getClosingDate($cabang_id)
|
||||
{
|
||||
return BudgetControl::where('cabang_id', $cabang_id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->value('closing_at');
|
||||
}
|
||||
|
||||
/**
|
||||
* KALKULASI JURNAL AKUNTANSI
|
||||
* Berlaku seragam menggunakan kolom final_approved_at untuk semua form
|
||||
* Cut-off Date: Tgl 11 s/d Tgl 13 Bulan Berikutnya
|
||||
*/
|
||||
/**
|
||||
* KALKULASI JURNAL AKUNTANSI (Log & Report)
|
||||
* Sinkron dengan 12 Kategori Utama & Akun 800xxx
|
||||
*/
|
||||
// public static function getKalkulasiJurnal($cabang_id, $periode_month, $periode_year)
|
||||
// {
|
||||
// $periode_month = strtolower($periode_month);
|
||||
// $periode_year = (int) $periode_year;
|
||||
|
||||
// $cacheKey = "{$cabang_id}_{$periode_month}_{$periode_year}";
|
||||
// if (isset(self::$jurnalCache[$cacheKey])) return self::$jurnalCache[$cacheKey];
|
||||
|
||||
// $userIds = UserHasCabang::where('cabang_id', $cabang_id)->pluck('user_id')->toArray();
|
||||
// $totalDebet = 0;
|
||||
|
||||
// if (!empty($userIds)) {
|
||||
// // Ambil Range Tanggal (Contoh: 11 Maret - 13 April)
|
||||
// $startDay = env('STARTING_DATE', 11);
|
||||
// $closeDay = env('CLOSING_DATE', 13);
|
||||
// $monthNumeric = date('m', strtotime($periode_month));
|
||||
|
||||
// $startDate = Carbon::create($periode_year, $monthNumeric, $startDay)->startOfDay();
|
||||
// $endDate = Carbon::create($periode_year, $monthNumeric, $closeDay)->addMonth()->endOfDay();
|
||||
|
||||
// // Mapping Model dengan pengamanan Typo
|
||||
// $formModels = [
|
||||
// 'Up Country' => FormUpCountry::class,
|
||||
// 'Vehicle Running Cost' => FormVehicleRunningCost::class,
|
||||
// 'Entertainment' => FormEntertaimentPresentation::class,
|
||||
// 'Entertaiment' => FormEntertaimentPresentation::class,
|
||||
// 'Presentation' => FormEntertaimentPresentation::class,
|
||||
// 'Meeting / Seminar' => FormMeetingSeminar::class,
|
||||
// ];
|
||||
|
||||
// // Ambil kategori yang punya account_number dan tidak dikecualikan
|
||||
// $kategoris = \App\Models\Kategori::whereNotIn('name', ['Cash in Bank BCA', 'Donasi/Gift', 'PPn Masukan', 'Sponsorship'])
|
||||
// ->whereNotNull('account_number')
|
||||
// ->where('account_number', '!=', '')
|
||||
// ->get();
|
||||
|
||||
// foreach ($kategoris as $kat) {
|
||||
// $katName = trim($kat->name);
|
||||
|
||||
// if (isset($formModels[$katName])) {
|
||||
// $model = $formModels[$katName];
|
||||
// $query = $model::whereIn('user_id', $userIds)
|
||||
// ->whereIn('status', ['Closed', 'Final Approved'])
|
||||
// ->whereBetween('final_approved_at', [$startDate, $endDate]);
|
||||
|
||||
// // PENTING: Filter berdasarkan kategori_id agar data tidak tertukar di tabel yang sama
|
||||
// if (\Illuminate\Support\Facades\Schema::hasColumn((new $model)->getTable(), 'kategori_id')) {
|
||||
// $query->where('kategori_id', $kat->id);
|
||||
// }
|
||||
// $totalDebet += $query->sum('approved_total');
|
||||
// } else {
|
||||
// // Masuk ke Form Others
|
||||
// $totalDebet += FormOthers::whereIn('user_id', $userIds)
|
||||
// ->where('kategori_id', $kat->id)
|
||||
// ->whereIn('status', ['Closed', 'Final Approved'])
|
||||
// ->whereBetween('final_approved_at', [$startDate, $endDate])
|
||||
// ->sum('approved_total');
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// self::$jurnalCache[$cacheKey] = $totalDebet;
|
||||
// return $totalDebet;
|
||||
// }
|
||||
|
||||
public static function getBulkKalkulasiJurnal(array $lookups)
|
||||
{
|
||||
if (empty($lookups)) return [];
|
||||
|
||||
$resultsMap = [];
|
||||
$startDay = 11; // Batas awal periode (Contoh: tgl 11)
|
||||
$closeDay = 13; // Batas akhir approval (Contoh: tgl 13 bulan depan)
|
||||
|
||||
foreach ($lookups as $item) {
|
||||
$cabId = $item['cabang_id'];
|
||||
$monthNumeric = date('m', strtotime($item['month']));
|
||||
$year = (int) $item['year'];
|
||||
$key = $cabId . '_' . strtolower($item['month']) . '_' . $year;
|
||||
|
||||
// Penentuan Rentang Tanggal Cut-off Akuntansi
|
||||
$startDate = \Illuminate\Support\Carbon::create($year, $monthNumeric, $startDay)->startOfDay();
|
||||
$endDate = $startDate->copy()->addMonth()->day($closeDay)->endOfDay();
|
||||
|
||||
$userIds = \App\Models\UserHasCabang::where('cabang_id', $cabId)->pluck('user_id')->toArray();
|
||||
|
||||
if (empty($userIds)) {
|
||||
$resultsMap[$key] = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Menghitung Total Pengeluaran Riil (Status: Closed / Final Approved)
|
||||
$tables = ['form_up_country', 'form_vehicle_running_cost', 'form_entertainment_presentation', 'form_meeting_seminar', 'form_others'];
|
||||
$totalExpense = 0;
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$totalExpense += \Illuminate\Support\Facades\DB::table($table)
|
||||
->whereIn('user_id', $userIds)
|
||||
->whereIn('status', ['Closed', 'Final Approved'])
|
||||
->whereBetween('final_approved_at', [$startDate, $endDate])
|
||||
->sum('approved_total');
|
||||
}
|
||||
|
||||
$resultsMap[$key] = $totalExpense;
|
||||
}
|
||||
|
||||
return $resultsMap;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Models\Admin;
|
||||
use App\Models\FormEntertaimentPresentation;
|
||||
use App\Models\FormMeetingSeminar;
|
||||
use App\Models\FormOthers;
|
||||
use App\Models\FormUpCountry;
|
||||
use App\Models\FormVehicleRunningCost;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\UserHasCabang;
|
||||
|
||||
class FormHelper
|
||||
{
|
||||
public static function getFormsByUserIds($userIds, $month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->whereIn('id', $userIds)
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('created_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Use union to combine queries
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Return forms with eager loaded user details
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms($month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereBetween('created_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Combine queries using union
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Map users to the forms with eager loaded data
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms2() {
|
||||
// Get all users with eager loading for 'region' and 'cabang'
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
);
|
||||
|
||||
// Combine queries using union
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Map users to the forms with eager loaded data
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getNominalByFormType($cabang_id, $type, $type_id, $month, $year) {
|
||||
$users = UserHasCabang::where('cabang_id', $cabang_id)->get();
|
||||
$userIds = $users->pluck('user_id')->toArray();
|
||||
|
||||
if($type == 'Up Country') {
|
||||
$form = FormUpCountry::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Vehicle Running Cost') {
|
||||
$form = FormVehicleRunningCost::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Entertainment') {
|
||||
$form = FormEntertaimentPresentation::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Meeting / Seminar') {
|
||||
$form = FormMeetingSeminar::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('created_at', '=', date('m', strtotime($month)))->whereYear('created_at', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else {
|
||||
$form = FormOthers::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('kategori_id', $type_id)->where('status', ['Approved', 'Closed'])->get();
|
||||
}
|
||||
|
||||
$nominal = $form->sum('approved_total');
|
||||
return $nominal;
|
||||
}
|
||||
|
||||
public static function getTotalAmount($userIds, $month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->whereIn('id', $userIds)
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Use union to combine queries
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Return forms with eager loaded user details
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
}
|
||||
+193
-347
@@ -10,357 +10,203 @@ use App\Models\FormUpCountry;
|
||||
use App\Models\FormVehicleRunningCost;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Models\UserHasCabang;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class FormHelper
|
||||
{
|
||||
public static function getFormsByUserIds($userIds, $month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
/**
|
||||
* Helper internal untuk menghitung rentang siklus tanggal
|
||||
* Menghasilkan: Start (11), Max Input (10 bln depan), Closing (13 bln depan)
|
||||
*/
|
||||
private static function getCycleRange($month, $year)
|
||||
{
|
||||
// Pastikan di-cast ke (int) agar Carbon tidak error
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$maxInputDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
// Mengambil nomor bulan sebagai integer
|
||||
$monthNumber = (int) date('m', strtotime($month . ' 1'));
|
||||
|
||||
// Pastikan $year juga integer
|
||||
$year = (int) $year;
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->whereIn('id', $userIds)
|
||||
->get();
|
||||
// Carbon::createFromDate membutuhkan integer
|
||||
$startDate = \Illuminate\Support\Carbon::createFromDate($year, $monthNumber, $startDay)->startOfDay();
|
||||
|
||||
// Input maksimal dan Closing menggunakan method ->day() yang butuh integer
|
||||
$maxInputDate = $startDate->copy()->addMonth()->day($maxInputDay)->endOfDay();
|
||||
$closingDate = $startDate->copy()->addMonth()->day($closingDay)->endOfDay();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('created_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Use union to combine queries
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Return forms with eager loaded user details
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms($month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereBetween('created_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereBetween('tanggal', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Combine queries using union
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Map users to the forms with eager loaded data
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms2() {
|
||||
// Get all users with eager loading for 'region' and 'cabang'
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
);
|
||||
|
||||
// Combine queries using union
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Map users to the forms with eager loaded data
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getNominalByFormType($cabang_id, $type, $type_id, $month, $year) {
|
||||
$users = UserHasCabang::where('cabang_id', $cabang_id)->get();
|
||||
$userIds = $users->pluck('user_id')->toArray();
|
||||
|
||||
if($type == 'Up Country') {
|
||||
$form = FormUpCountry::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Vehicle Running Cost') {
|
||||
$form = FormVehicleRunningCost::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Entertainment') {
|
||||
$form = FormEntertaimentPresentation::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else if($type == 'Meeting / Seminar') {
|
||||
$form = FormMeetingSeminar::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('created_at', '=', date('m', strtotime($month)))->whereYear('created_at', '=', $year)->where('status', ['Approved', 'Closed'])->get();
|
||||
} else {
|
||||
$form = FormOthers::select('approved_total')->whereIn('user_id', $userIds)->whereMonth('tanggal', '=', date('m', strtotime($month)))->whereYear('tanggal', '=', $year)->where('kategori_id', $type_id)->where('status', ['Approved', 'Closed'])->get();
|
||||
}
|
||||
|
||||
$nominal = $form->sum('approved_total');
|
||||
return $nominal;
|
||||
}
|
||||
|
||||
public static function getTotalAmount($userIds, $month, $year) {
|
||||
$monthNumber = date('m', strtotime($month . ' 1'));
|
||||
$startDate = "$year-$monthNumber-" . env('STARTING_DATE');
|
||||
|
||||
$nextMonthTimestamp = strtotime("first day of next month", strtotime("$year-$monthNumber-01"));
|
||||
$closingDateNextMonth = date('Y-m-', $nextMonthTimestamp) . env('CLOSING_DATE');
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->whereIn('id', $userIds)
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'total',
|
||||
'approved_total',
|
||||
'status',
|
||||
'account_number',
|
||||
'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('final_approved_at', [$startDate, $closingDateNextMonth]);
|
||||
|
||||
// Use union to combine queries
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
// Return forms with eager loaded user details
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
return [
|
||||
'start' => $startDate->toDateTimeString(),
|
||||
'input_max' => $maxInputDate->toDateTimeString(),
|
||||
'closing' => $closingDate->toDateTimeString(),
|
||||
'display_label' => $startDate->format('d M') . ' - ' . $maxInputDate->format('d M Y')
|
||||
];
|
||||
}
|
||||
|
||||
public static function getFormsByUserIds($userIds, $month, $year) {
|
||||
$dates = self::getCycleRange($month, $year);
|
||||
$startDate = $dates['start'];
|
||||
$closingDate = $dates['closing']; // Mengacu ke Closing Date (13)
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])
|
||||
->whereIn('id', $userIds)
|
||||
->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select(
|
||||
'expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at',
|
||||
DB::raw("'Up Country' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select(
|
||||
'expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at',
|
||||
DB::raw("'Vehicle Running Cost' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select(
|
||||
'expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at',
|
||||
DB::raw("'Entertainment Presentation' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select(
|
||||
'expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at',
|
||||
DB::raw("'Meeting Seminar' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('created_at', [$startDate, $closingDate]);
|
||||
|
||||
$formOthersQuery = FormOthers::select(
|
||||
'expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at',
|
||||
DB::raw("'Others' as type")
|
||||
)->whereIn('user_id', $userIds)
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]);
|
||||
|
||||
$forms = $formUpCountryQuery
|
||||
->union($formVehicleRunningCostQuery)
|
||||
->union($formEntertaimentPresentationQuery)
|
||||
->union($formMeetingSeminarQuery)
|
||||
->union($formOthersQuery)
|
||||
->get();
|
||||
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms($month, $year) {
|
||||
$dates = self::getCycleRange($month, $year);
|
||||
$startDate = $dates['start'];
|
||||
$closingDate = $dates['closing'];
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])->get();
|
||||
|
||||
$commonSelect = ['expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at'];
|
||||
|
||||
$queries = [
|
||||
FormUpCountry::select(array_merge($commonSelect, [DB::raw("'Up Country' as type")]))->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
FormVehicleRunningCost::select(array_merge($commonSelect, [DB::raw("'Vehicle Running Cost' as type")]))->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
FormEntertaimentPresentation::select(array_merge($commonSelect, [DB::raw("'Entertainment Presentation' as type")]))->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
FormMeetingSeminar::select(array_merge($commonSelect, [DB::raw("'Meeting Seminar' as type")]))->whereBetween('created_at', [$startDate, $closingDate]),
|
||||
FormOthers::select(array_merge($commonSelect, [DB::raw("'Others' as type")]))->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
];
|
||||
|
||||
$mainQuery = array_shift($queries);
|
||||
foreach ($queries as $q) { $mainQuery->union($q); }
|
||||
|
||||
$forms = $mainQuery->get();
|
||||
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard Info: Menghasilkan label periode input (11-10)
|
||||
*/
|
||||
public static function getDashboardPeriodLabel($month, $year) {
|
||||
return self::getCycleRange($month, $year)['display_label'];
|
||||
}
|
||||
|
||||
public static function getNominalByFormType($cabang_id, $type, $type_id, $month, $year) {
|
||||
$users = UserHasCabang::where('cabang_id', $cabang_id)->get();
|
||||
$userIds = $users->pluck('user_id')->toArray();
|
||||
|
||||
// Menggunakan logika cycle agar nominal yang muncul sinkron dengan cutoff
|
||||
$dates = self::getCycleRange($month, $year);
|
||||
$start = $dates['start'];
|
||||
$end = $dates['closing'];
|
||||
|
||||
$query = null;
|
||||
if($type == 'Up Country') {
|
||||
$query = FormUpCountry::whereIn('user_id', $userIds)->whereBetween('tanggal', [$start, $end]);
|
||||
} else if($type == 'Vehicle Running Cost') {
|
||||
$query = FormVehicleRunningCost::whereIn('user_id', $userIds)->whereBetween('tanggal', [$start, $end]);
|
||||
} else if($type == 'Entertainment') {
|
||||
$query = FormEntertaimentPresentation::whereIn('user_id', $userIds)->whereBetween('tanggal', [$start, $end]);
|
||||
} else if($type == 'Meeting / Seminar') {
|
||||
$query = FormMeetingSeminar::whereIn('user_id', $userIds)->whereBetween('created_at', [$start, $end]);
|
||||
} else {
|
||||
$query = FormOthers::whereIn('user_id', $userIds)->whereBetween('tanggal', [$start, $end])->where('kategori_id', $type_id);
|
||||
}
|
||||
|
||||
return $query->whereIn('status', ['Approved', 'Closed'])->sum('approved_total');
|
||||
}
|
||||
|
||||
public static function getTotalAmount($userIds, $month, $year) {
|
||||
$dates = self::getCycleRange($month, $year);
|
||||
$startDate = $dates['start'];
|
||||
$closingDate = $dates['closing'];
|
||||
|
||||
$users = Admin::with(['region', 'cabang'])->whereIn('id', $userIds)->get();
|
||||
|
||||
$formUpCountryQuery = FormUpCountry::select('expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at', DB::raw("'Up Country' as type"))
|
||||
->whereIn('user_id', $userIds)->whereBetween('final_approved_at', [$startDate, $closingDate]);
|
||||
|
||||
$formVehicleRunningCostQuery = FormVehicleRunningCost::select('expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at', DB::raw("'Vehicle Running Cost' as type"))
|
||||
->whereIn('user_id', $userIds)->whereBetween('final_approved_at', [$startDate, $closingDate]);
|
||||
|
||||
$formEntertaimentPresentationQuery = FormEntertaimentPresentation::select('expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at', DB::raw("'Entertainment Presentation' as type"))
|
||||
->whereIn('user_id', $userIds)->whereBetween('final_approved_at', [$startDate, $closingDate]);
|
||||
|
||||
$formMeetingSeminarQuery = FormMeetingSeminar::select('expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at', DB::raw("'Meeting Seminar' as type"))
|
||||
->whereIn('user_id', $userIds)->whereBetween('final_approved_at', [$startDate, $closingDate]);
|
||||
|
||||
$formOthersQuery = FormOthers::select('expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at', DB::raw("'Others' as type"))
|
||||
->whereIn('user_id', $userIds)->whereBetween('final_approved_at', [$startDate, $closingDate]);
|
||||
|
||||
$forms = $formUpCountryQuery->union($formVehicleRunningCostQuery)->union($formEntertaimentPresentationQuery)->union($formMeetingSeminarQuery)->union($formOthersQuery)->get();
|
||||
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
|
||||
public static function getAllForms2() {
|
||||
// Fungsi ini tetap dipertahankan sesuai request (tanpa filter tanggal)
|
||||
$users = Admin::with(['region', 'cabang'])->get();
|
||||
$commonSelect = ['expense_number', 'user_id', 'total', 'approved_total', 'status', 'account_number', 'created_at'];
|
||||
|
||||
$forms = FormUpCountry::select(array_merge($commonSelect, [DB::raw("'Up Country' as type")]))
|
||||
->union(FormVehicleRunningCost::select(array_merge($commonSelect, [DB::raw("'Vehicle Running Cost' as type")])))
|
||||
->union(FormEntertaimentPresentation::select(array_merge($commonSelect, [DB::raw("'Entertainment Presentation' as type")])))
|
||||
->union(FormMeetingSeminar::select(array_merge($commonSelect, [DB::raw("'Meeting Seminar' as type")])))
|
||||
->union(FormOthers::select(array_merge($commonSelect, [DB::raw("'Others' as type")])))
|
||||
->get();
|
||||
|
||||
return $forms->map(function ($form) use ($users) {
|
||||
$user = $users->firstWhere('id', $form->user_id);
|
||||
$form->user = $user;
|
||||
return $form;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
class PeriodeHelper
|
||||
{
|
||||
public static function getPeriodeRange($month, $year)
|
||||
{
|
||||
$month = (int) date('m', strtotime($month));
|
||||
$year = (int) $year;
|
||||
/**
|
||||
* Mendapatkan rentang tanggal fisik pengakuan untuk sebuah periode akuntansi (Bulan & Tahun)
|
||||
* Contoh: Periode "april 2026" -> Start: 11 April 2026, End: 13 Mei 2026 (Closing Date)
|
||||
*/
|
||||
public static function getPeriodeRange(string $month, int $year): array
|
||||
{
|
||||
// 1. Tentukan tanggal 11 di bulan dan tahun yang dipilih
|
||||
$startDate = Carbon::parse("11 $month $year")->startOfDay()->toDateTimeString();
|
||||
|
||||
// Jika Januari, periode dimulai dari 11 Januari hingga 10 Februari
|
||||
$start = Carbon::create($year, $month, 11)->startOfDay();
|
||||
$end = $start->copy()->addMonth()->subDay()->endOfDay();
|
||||
// 2. Tentukan tanggal 13 di bulan berikutnya (Bulan berjalan + 1)
|
||||
$endDate = Carbon::parse("13 $month $year")->addMonth()->endOfDay()->toDateTimeString();
|
||||
|
||||
return [$start, $end];
|
||||
}
|
||||
}
|
||||
return [$startDate, $endDate];
|
||||
}
|
||||
}
|
||||
@@ -6,26 +6,108 @@ namespace App\Http\Controllers\Backend;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AuditTrail;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use App\Models\Admin; // Pastikan Model Admin diimport
|
||||
use App\Models\Region; // Pastikan Model Region diimport
|
||||
use App\Models\Cabang; // Pastikan Model Cabang diimport
|
||||
use App\Helpers\AuditTrailHelper;
|
||||
use Illuminate\Http\Request; // BARIS INI YANG WAJIB ADA
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use App\Exports\AuditTrailExport;
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
|
||||
class AuditTrailController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$pageInfo = [
|
||||
'title' => 'Audit Trails',
|
||||
'sub_title' => 'List of Audit Trails System',
|
||||
'path' => url()->current()
|
||||
];
|
||||
public function index(Request $request)
|
||||
{
|
||||
$pageInfo = [
|
||||
'title' => 'Audit Trails',
|
||||
'sub_title' => 'List of Audit Trails System',
|
||||
'path' => url()->current()
|
||||
];
|
||||
|
||||
return view(
|
||||
'backend.pages.audit_trail.index',
|
||||
[
|
||||
// sort by newest
|
||||
'data' => AuditTrail::with('user')->orderBy('created_at', 'desc')->get(),
|
||||
'pageInfo' => $pageInfo,
|
||||
]
|
||||
);
|
||||
$query = AuditTrail::with(['user.cabang.cabang.region']);
|
||||
|
||||
// Filter: User
|
||||
if ($request->filled('admin_id')) {
|
||||
$query->where('user_id', $request->admin_id);
|
||||
}
|
||||
|
||||
// Filter: Region & Cabang (Sesuai relasi hasOne UserHasCabang)
|
||||
if ($request->filled('region') || $request->filled('cabang')) {
|
||||
$query->whereHas('user.cabang.cabang', function($q) use ($request) {
|
||||
if ($request->filled('cabang')) {
|
||||
$q->where('id', $request->cabang);
|
||||
}
|
||||
if ($request->filled('region')) {
|
||||
$q->whereHas('region', function($rq) use ($request) {
|
||||
// PERBAIKAN: Gunakan 'code' sesuai image_63aac6.png
|
||||
$rq->where('code', $request->region);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Filter: Rentang Waktu
|
||||
if ($request->filled('start_date') && $request->filled('end_date')) {
|
||||
$query->whereBetween('created_at', [
|
||||
$request->start_date . ' 00:00:00',
|
||||
$request->end_date . ' 23:59:59'
|
||||
]);
|
||||
}
|
||||
|
||||
$data = $query->latest()->paginate(50)->appends($request->all());
|
||||
|
||||
return view('backend.pages.audit_trail.index', [
|
||||
'data' => $data,
|
||||
'pageInfo' => $pageInfo,
|
||||
'admins' => \App\Models\Admin::select('id', 'name')->orderBy('name')->get(),
|
||||
// PERBAIKAN: Select 'code' sesuai image_63aac6.png
|
||||
'regions' => \App\Models\Region::select('code', 'name')->get(),
|
||||
'cabangs' => \App\Models\Cabang::select('id', 'name')->orderBy('name')->get(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function exportExcel(Request $request)
|
||||
{
|
||||
AuditTrailHelper::AddAuditTrail('Export', 'Melakukan export data Audit Trail dengan filter tertentu');
|
||||
|
||||
// Mengirimkan parameter filter ke class Export
|
||||
return Excel::download(new AuditTrailExport($request->all()), 'Audit_Trail_' . date('Y-m-d') . '.xlsx');
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Membersihkan semua data audit trail (Truncate)
|
||||
*/
|
||||
public function clearAll()
|
||||
{
|
||||
try {
|
||||
// Catat siapa yang menghapus log sebelum data dihapus
|
||||
AuditTrailHelper::AddAuditTrail('Delete', 'Membersihkan (Truncate) seluruh data Audit Trail');
|
||||
|
||||
// Menggunakan truncate untuk performa maksimal pada tabel besar
|
||||
DB::table('audit_trail')->truncate();
|
||||
|
||||
return redirect()->back()->with('success', 'All audit logs have been cleared.');
|
||||
} catch (\Exception $e) {
|
||||
return redirect()->back()->with('error', 'Failed to clear logs: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fungsi untuk membersihkan cache sistem
|
||||
*/
|
||||
public function clearCache()
|
||||
{
|
||||
try {
|
||||
Artisan::call('optimize:clear');
|
||||
AuditTrailHelper::AddAuditTrail('System', 'Membersihkan cache sistem (Optimize Clear)');
|
||||
|
||||
return redirect()->back()->with('success', 'System cache cleared successfully!');
|
||||
} catch (\Exception $e) {
|
||||
return redirect()->back()->with('error', 'Failed to clear cache: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,164 +11,617 @@ use App\Models\BudgetControlLog;
|
||||
use App\Models\Admin;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
use Maatwebsite\Excel\Facades\Excel;
|
||||
use Maatwebsite\Excel\Concerns\FromArray;
|
||||
use Maatwebsite\Excel\Concerns\WithHeadings;
|
||||
use App\Helpers\PeriodeHelper;
|
||||
|
||||
class BudgetControlController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.view']);
|
||||
session()->put('redirect_url', route('budget_control'));
|
||||
/**
|
||||
* Halaman Utama Budget Control (Termasuk Data Grafik)
|
||||
*/
|
||||
public function index(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.view']);
|
||||
|
||||
$user = auth()->user();
|
||||
$role = $user->getRoleNames()->first();
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$budget = null;
|
||||
// --- 1. IDENTIFIKASI WILAYAH USER (Sama seperti Dashboard) ---
|
||||
// Mengambil semua cabang yang di-assign ke user ini
|
||||
$userCabangIds = \App\Models\UserHasCabang::where('user_id', $user->id)
|
||||
->pluck('cabang_id')
|
||||
->toArray();
|
||||
|
||||
if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
|
||||
$region_id = auth()->user()->getMyCabangAndRegionId()['region'];
|
||||
// Mengambil semua ID Region dari cabang-cabang tersebut
|
||||
$userRegionIds = \App\Models\Cabang::whereIn('id', $userCabangIds)
|
||||
->pluck('region_id')
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
if ($region_id) {
|
||||
$budget = BudgetControl::whereHas('cabang', function ($query) use ($region_id) {
|
||||
$query->where('region_id', $region_id);
|
||||
})->with(['receiver', 'sender', 'cabang'])->get();
|
||||
}
|
||||
} elseif ($role == 'Area Manager Cabang') {
|
||||
$cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];
|
||||
|
||||
if ($cabang_id) {
|
||||
$budget = BudgetControl::where('cabang_id', $cabang_id)
|
||||
->with(['receiver', 'sender', 'cabang'])
|
||||
->get();
|
||||
}
|
||||
} else {
|
||||
$budget = BudgetControl::with(['receiver', 'sender', 'cabang'])->get();
|
||||
}
|
||||
|
||||
// Tentukan periode berdasarkan start dan closing date
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
}
|
||||
|
||||
// Hitung available budget berdasarkan periode
|
||||
$budget->map(function ($b) {
|
||||
$b->availableBudget = BudgetHelper::getAvailableBudget($b->cabang_id, $b->periode_month, $b->periode_year);
|
||||
return $b;
|
||||
});
|
||||
|
||||
return view('backend.pages.budget_control.index', [
|
||||
'data' => $budget,
|
||||
]);
|
||||
}
|
||||
|
||||
public function log()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.view']);
|
||||
session()->put('redirect_url', route('budget_control'));
|
||||
|
||||
return view(
|
||||
'backend.pages.budget_control.log',
|
||||
[
|
||||
'data' => BudgetControlLog::orderBy('created_at', 'desc')->with(['receiver', 'sender', 'cabang'])->get(),
|
||||
]
|
||||
);
|
||||
// --- 2. KOLEKSI DROPDOWN FILTER BERDASARKAN ROLE ---
|
||||
if (in_array($role, ['Admin Region', 'Marketing Operational Manager Region'])) {
|
||||
// Dropdown Region HANYA muncul region miliknya (Menghilangkan Blank)
|
||||
$regions = \App\Models\Region::whereIn('id', $userRegionIds)->get();
|
||||
// Dropdown Cabang HANYA muncul cabang-cabang di bawah region tersebut
|
||||
$cabangOptions = \App\Models\Cabang::whereIn('region_id', $userRegionIds)->get();
|
||||
|
||||
} elseif (in_array($role, ['Area Manager Cabang', 'Medical Representatif'])) {
|
||||
$regions = \App\Models\Region::whereIn('id', $userRegionIds)->get();
|
||||
$cabangOptions = \App\Models\Cabang::whereIn('id', $userCabangIds)->get();
|
||||
|
||||
} else {
|
||||
// Superadmin & Accounting: Muncul Semua
|
||||
$regions = \App\Models\Region::all();
|
||||
$cabangOptions = \App\Models\Cabang::when($request->region_id, function($q) use ($request) {
|
||||
return $q->where('region_id', $request->region_id);
|
||||
})->get();
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.create']);
|
||||
// --- 3. QUERY UTAMA DENGAN PROTEKSI DATA ---
|
||||
$query = \App\Models\BudgetControl::with(['receiver', 'sender', 'cabang.region']);
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
// Jika bukan Superadmin/Accounting, kunci kueri ke wilayahnya saja
|
||||
if (!in_array($role, ['Superadmin', 'Super Admin', 'Accounting', 'accounting'])) {
|
||||
$query->whereHas('cabang', function($q) use ($userRegionIds) {
|
||||
$q->whereIn('region_id', $userRegionIds);
|
||||
});
|
||||
}
|
||||
|
||||
if ($role == 'Admin Region' || $role == 'Marketing Operational Manager Region') {
|
||||
$region_id = auth()->user()->getMyCabangAndRegionId()['region'];
|
||||
// --- 4. FILTER DARI INPUT USER ---
|
||||
if ($request->filled('region_id')) {
|
||||
$query->whereHas('cabang', fn($q) => $q->where('region_id', $request->region_id));
|
||||
}
|
||||
if ($request->filled('cabang_id')) {
|
||||
$query->where('cabang_id', $request->cabang_id);
|
||||
}
|
||||
if ($request->filled('month')) {
|
||||
$query->where('periode_month', strtolower($request->month));
|
||||
}
|
||||
if ($request->filled('year')) {
|
||||
$query->where('periode_year', $request->year);
|
||||
}
|
||||
|
||||
if ($region_id) {
|
||||
// only show users from the same region
|
||||
$users = Admin::where('id', '!=', auth()->user()->id)
|
||||
->whereHas('cabang', function ($query) use ($region_id) {
|
||||
$query->where('region_id', $region_id);
|
||||
})
|
||||
->get();
|
||||
} else {
|
||||
$users = Admin::getUserByRoleName('Area Manager Cabang');
|
||||
}
|
||||
} elseif ($role == 'Area Manager Cabang') {
|
||||
$cabang_id = auth()->user()->getMyCabangAndRegionId()['cabang'];
|
||||
$data = $query->latest()->paginate(50)->withQueryString();
|
||||
|
||||
if ($cabang_id) {
|
||||
// only show users from the same cabang
|
||||
$users = Admin::where('id', '!=', auth()->user()->id)
|
||||
->whereHas('cabang', function ($query) use ($cabang_id) {
|
||||
$query->where('id', $cabang_id);
|
||||
})
|
||||
->get();
|
||||
}
|
||||
} else {
|
||||
$users = Admin::getUserByRoleName('Area Manager Cabang');
|
||||
}
|
||||
// --- 5. OPTIMASI PERHITUNGAN REALISASI ---
|
||||
$expenseMap = \App\Helpers\BudgetHelper::getBulkAvailableBudget($data);
|
||||
|
||||
return view('backend.pages.budget_control.create', [
|
||||
'users' => $users,
|
||||
]);
|
||||
}
|
||||
$data->getCollection()->transform(function ($b) use ($expenseMap) {
|
||||
$key = $b->cabang_id . '_' . strtolower($b->periode_month) . '_' . $b->periode_year;
|
||||
$b->availableBudget = isset($expenseMap[$key]) ? ($b->amount - $expenseMap[$key]) : $b->amount;
|
||||
return $b;
|
||||
});
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.create']);
|
||||
|
||||
$validated = $request->validate([
|
||||
'receiver_id' => 'required|exists:admins,id',
|
||||
'periode_month' => 'required|string|in:january,february,march,april,may,june,july,august,september,october,november,december',
|
||||
'periode_year' => 'required|numeric',
|
||||
'amount' => 'required|numeric',
|
||||
'remarks' => 'nullable|string',
|
||||
]);
|
||||
|
||||
$cabang_id = Admin::find($validated['receiver_id'])->getMyCabangAndRegionId()['cabang'];
|
||||
$periode = [
|
||||
'periode_month' => $validated['periode_month'],
|
||||
'periode_year' => $validated['periode_year'],
|
||||
];
|
||||
|
||||
BudgetControl::updateOrCreate(
|
||||
array_merge(['cabang_id' => $cabang_id], $periode),
|
||||
array_merge($periode, [
|
||||
'sender_id' => auth()->user()->id,
|
||||
'receiver_id' => $validated['receiver_id'],
|
||||
'amount' => $validated['amount'],
|
||||
'remarks' => $validated['remarks'],
|
||||
'closing_at' => null,
|
||||
'status' => 'Assigned',
|
||||
])
|
||||
);
|
||||
|
||||
BudgetControlLog::create([
|
||||
'cabang_id' => $cabang_id,
|
||||
'sender_id' => auth()->user()->id,
|
||||
'receiver_id' => $validated['receiver_id'],
|
||||
'periode_month' => $validated['periode_month'],
|
||||
'periode_year' => $validated['periode_year'],
|
||||
'amount' => $validated['amount'],
|
||||
'remarks' => $validated['remarks'],
|
||||
'closing_at' => null,
|
||||
'status' => 'Assigned',
|
||||
]);
|
||||
|
||||
session()->flash('success', 'Budget has been added or updated successfully');
|
||||
return redirect()->route('budget_control');
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.delete']);
|
||||
|
||||
$budgetRequest = BudgetControl::findOrfail($id);
|
||||
$budgetRequest->delete();
|
||||
|
||||
return redirect()->route('budget_control');
|
||||
}
|
||||
return view('backend.pages.budget_control.index', compact('data', 'regions', 'cabangOptions'));
|
||||
}
|
||||
/**
|
||||
* Menampilkan Log Riwayat Budget (Disempurnakan dengan Total, Realisasi, DR, CR)
|
||||
*/
|
||||
/**
|
||||
* Menampilkan Log Riwayat Budget (Menampilkan Budget & Realisasi Cash BCA)
|
||||
*/
|
||||
/**
|
||||
* Menampilkan Log Riwayat Budget dengan Integrasi Tabel Transaksi
|
||||
*/
|
||||
public function log(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.view']);
|
||||
|
||||
// Data untuk Dropdown Filter
|
||||
$regions = \App\Models\Region::all();
|
||||
$cabangOptions = \App\Models\Cabang::when($request->region_id, function($q) use ($request) {
|
||||
return $q->where('region_id', $request->region_id);
|
||||
})->get();
|
||||
|
||||
// Query Utama dengan Filter Dinamis
|
||||
$query = \App\Models\BudgetControlLog::with(['receiver', 'sender', 'cabang.region']);
|
||||
|
||||
if ($request->filled('region_id')) {
|
||||
$query->whereHas('cabang', fn($q) => $q->where('region_id', $request->region_id));
|
||||
}
|
||||
if ($request->filled('cabang_id')) {
|
||||
$query->where('cabang_id', $request->cabang_id);
|
||||
}
|
||||
if ($request->filled('month')) {
|
||||
$query->where('periode_month', strtolower($request->month));
|
||||
}
|
||||
if ($request->filled('year')) {
|
||||
$query->where('periode_year', $request->year);
|
||||
}
|
||||
|
||||
$data = $query->orderBy('created_at', 'desc')->paginate(50)->withQueryString();
|
||||
|
||||
// Sinkronisasi Kalkulasi Realisasi
|
||||
$lookups = $data->map(fn($l) => [
|
||||
'cabang_id' => $l->cabang_id,
|
||||
'month' => $l->periode_month,
|
||||
'year' => $l->periode_year
|
||||
])->unique()->toArray();
|
||||
|
||||
$debetMap = \App\Helpers\BudgetHelper::getBulkKalkulasiJurnal($lookups);
|
||||
|
||||
$data->getCollection()->transform(function ($log) use ($debetMap) {
|
||||
$key = $log->cabang_id . '_' . strtolower($log->periode_month) . '_' . $log->periode_year;
|
||||
|
||||
$log->total_budget = (float) $log->amount;
|
||||
$log->total_credit = (float) $log->amount; // Pagu/Transfer
|
||||
$log->total_debet = (float) ($debetMap[$key] ?? 0); // Pengeluaran riil
|
||||
$log->realisasi = $log->total_credit - $log->total_debet; // Sisa Saldo
|
||||
|
||||
return $log;
|
||||
});
|
||||
|
||||
// Menyiapkan Data Grafik (Top 10 hasil filter)
|
||||
$chartData = [
|
||||
'labels' => $data->getCollection()->take(10)->map(fn($l) => $l->cabang->name)->toArray(),
|
||||
'budget' => $data->getCollection()->take(10)->pluck('total_budget')->toArray(),
|
||||
'realisasi' => $data->getCollection()->take(10)->pluck('realisasi')->toArray(),
|
||||
];
|
||||
|
||||
return view('backend.pages.budget_control.log', compact('data', 'regions', 'cabangOptions', 'chartData'));
|
||||
}
|
||||
|
||||
private function prepareLogChartData($collection)
|
||||
{
|
||||
// Mengelompokkan data berdasarkan periode untuk grafik
|
||||
$grouped = $collection->groupBy(function($item) {
|
||||
return strtoupper($item->periode_month) . ' ' . $item->periode_year;
|
||||
})->take(6); // Ambil 6 periode terbaru yang ada di list
|
||||
|
||||
return [
|
||||
'labels' => $grouped->keys()->toArray(),
|
||||
'budget' => $grouped->map(fn($group) => $group->sum('total_budget'))->values()->toArray(),
|
||||
'realisasi' => $grouped->map(fn($group) => $group->sum('realisasi'))->values()->toArray(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Download Template untuk Bulk Upload
|
||||
*/
|
||||
public function downloadTemplate()
|
||||
{
|
||||
$fileName = 'Template_Bulk_Upload_Budget.csv';
|
||||
|
||||
$headers = [
|
||||
"Content-type" => "text/csv",
|
||||
"Content-Disposition" => "attachment; filename=$fileName",
|
||||
"Pragma" => "no-cache",
|
||||
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
|
||||
"Expires" => "0"
|
||||
];
|
||||
|
||||
$columns = ['Kode Cabang', 'Bulan', 'Nominal Budget', 'Keterangan'];
|
||||
|
||||
$callback = function() use($columns) {
|
||||
$file = fopen('php://output', 'w');
|
||||
|
||||
// Baris 1: Header
|
||||
fputcsv($file, $columns);
|
||||
|
||||
// Baris 2 & 3: Contoh data agar user paham
|
||||
fputcsv($file, ['JKT-01', 'January', '15000000', 'Budget Ops JKT-01']);
|
||||
fputcsv($file, ['BDG-01', 'January', '12500000', 'Budget Ops BDG-01']);
|
||||
|
||||
fclose($file);
|
||||
};
|
||||
|
||||
return response()->stream($callback, 200, $headers);
|
||||
}
|
||||
|
||||
public static function generateRefNumber($cabang)
|
||||
{
|
||||
// Mengambil 3 huruf kode cabang (Pastikan Anda menggunakan kolom yang tepat, misalnya $cabang->code atau $cabang->name)
|
||||
$kodeCabang = strtoupper(substr($cabang->code ?? $cabang->name, 0, 3));
|
||||
|
||||
// Format ym (Contoh: 2605 untuk Mei 2026)
|
||||
$ym = date('ym');
|
||||
|
||||
$prefix = "JRN-{$kodeCabang}-{$ym}";
|
||||
|
||||
// Menghitung urutan transaksi untuk cabang dan bulan ini
|
||||
$count = \Illuminate\Support\Facades\DB::table('transactions')
|
||||
->where('cabang_id', $cabang->id)
|
||||
->whereRaw("DATE_FORMAT(created_at, '%y%m') = ?", [$ym])
|
||||
->count();
|
||||
|
||||
$sequence = str_pad((string)($count + 1), 3, '0', STR_PAD_LEFT);
|
||||
|
||||
// Hasil akhir: JRN-PDG-2605-001
|
||||
return "{$prefix}-{$sequence}";
|
||||
}
|
||||
/**
|
||||
* Form Create Budget
|
||||
*/
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.create']);
|
||||
|
||||
$user = auth()->user();
|
||||
$role = $user->getRoleNames()[0];
|
||||
|
||||
if (in_array($role, ['Admin Region', 'Marketing Operational Manager Region'])) {
|
||||
$region_id = $user->getMyCabangAndRegionId()['region'];
|
||||
$users = $region_id
|
||||
? Admin::where('id', '!=', $user->id)->whereHas('cabang', fn($q) => $q->where('region_id', $region_id))->get()
|
||||
: Admin::getUserByRoleName('Area Manager Cabang');
|
||||
} elseif ($role == 'Area Manager Cabang') {
|
||||
$cabang_id = $user->getMyCabangAndRegionId()['cabang'];
|
||||
$users = $cabang_id
|
||||
? Admin::where('id', '!=', $user->id)->whereHas('cabang', fn($q) => $q->where('id', $cabang_id))->get()
|
||||
: collect();
|
||||
} else {
|
||||
$users = Admin::getUserByRoleName('Area Manager Cabang');
|
||||
}
|
||||
|
||||
return view('backend.pages.budget_control.create', ['users' => $users]);
|
||||
}
|
||||
/**
|
||||
* Menampilkan Halaman Filter Generate Report Jurnal
|
||||
*/
|
||||
public function jurnal()
|
||||
{
|
||||
$user = auth()->user();
|
||||
$role = $user->getRoleNames()[0] ?? null;
|
||||
$userData = $user->getMyCabangAndRegionId();
|
||||
|
||||
$regions = Region::all();
|
||||
$cabangs = Cabang::all();
|
||||
|
||||
// Filter data berdasarkan hak akses (Role)
|
||||
if (in_array($role, ['Admin Region', 'Marketing Operational Manager Region'])) {
|
||||
$regions = Region::where('id', $userData['region'])->get();
|
||||
$cabangs = Cabang::where('region_id', $userData['region'])->get();
|
||||
} elseif ($role == 'Area Manager Cabang') {
|
||||
$cabangs = Cabang::where('id', $userData['cabang'])->get();
|
||||
$regions = Region::where('id', $cabangs->first()->region_id ?? 0)->get();
|
||||
}
|
||||
|
||||
return view('backend.pages.report.jurnal', [
|
||||
'pageInfo' => ['title' => 'Generate Reports For Jurnal'],
|
||||
'cabang' => $cabangs,
|
||||
'regions' => $regions
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Proses Menghitung Data Jurnal (Debet, Kredit, & Realisasi)
|
||||
*/
|
||||
public function generateJurnal()
|
||||
{
|
||||
$params = request()->all();
|
||||
$accounting_period = $params['accounting_period'] ?? '-';
|
||||
|
||||
// 1. Ambil kategori yang valid (Wajib punya Account Number & tidak di-exclude)
|
||||
$excluded = ['Cash in Bank BCA', 'Donasi/Gift', 'PPn Masukan', 'Vehicle Maintenance', 'Bahan Promosi', 'Sponsorship'];
|
||||
$kategoris = Kategori::whereNotIn('name', $excluded)
|
||||
->whereNotNull('account_number')
|
||||
->where('account_number', '!=', '')
|
||||
->where('account_number', '!=', '0')
|
||||
->get();
|
||||
|
||||
$kategori_bca = Kategori::where('name', 'Cash in Bank BCA')->first();
|
||||
$cabang = Cabang::where('code', $params['cabang'])->firstOrFail();
|
||||
$year = $params['year'];
|
||||
$month = $params['month'];
|
||||
|
||||
// 2. Ambil Range Tanggal Cut-off (Misal: 11 Maret - 13 April)
|
||||
[$startDate, $endDate] = PeriodeHelper::getPeriodeRange($month, $year);
|
||||
|
||||
// 3. KREDIT: Total Petty Cash yang diterima cabang (Pagu)
|
||||
$pettyCashAmount = BudgetControl::where('cabang_id', $cabang->id)
|
||||
->where('periode_year', $year)
|
||||
->where('periode_month', $month)
|
||||
->sum('amount');
|
||||
|
||||
// Log budget untuk display di view
|
||||
$budget = BudgetControlLog::where('cabang_id', $cabang->id)
|
||||
->where('periode_year', $year)
|
||||
->where('periode_month', $month)
|
||||
->orderByDesc('created_at')->first();
|
||||
|
||||
$userIds = UserHasCabang::where('cabang_id', $cabang->id)->pluck('user_id');
|
||||
|
||||
// Mapping Model & Alias
|
||||
$formModels = [
|
||||
'Up Country' => FormUpCountry::class,
|
||||
'Vehicle Running Cost' => FormVehicleRunningCost::class,
|
||||
'Entertainment' => FormEntertaimentPresentation::class,
|
||||
'Entertaiment' => FormEntertaimentPresentation::class,
|
||||
'Presentation' => FormEntertaimentPresentation::class,
|
||||
'Meeting / Seminar' => FormMeetingSeminar::class,
|
||||
];
|
||||
|
||||
$nominals = [];
|
||||
foreach ($kategoris as $kategori) {
|
||||
$sum = 0;
|
||||
$katName = trim($kategori->name);
|
||||
|
||||
if (isset($formModels[$katName])) {
|
||||
$model = $formModels[$katName];
|
||||
$sum = $model::whereIn('user_id', $userIds)
|
||||
->where('expense_number', 'LIKE', "%-{$cabang->code}-%") // Filter Cabang
|
||||
->where('kategori_id', $kategori->id) // Filter Kategori WAJIB
|
||||
->whereIn('status', ['Closed', 'Final Approved'])
|
||||
->whereBetween('final_approved_at', [$startDate, $endDate])
|
||||
->sum('approved_total');
|
||||
} else {
|
||||
$sum = FormOthers::whereIn('user_id', $userIds)
|
||||
->where('expense_number', 'LIKE', "%-{$cabang->code}-%") // Filter Cabang
|
||||
->where('kategori_id', $kategori->id) // Filter Kategori WAJIB
|
||||
->whereIn('status', ['Closed', 'Final Approved'])
|
||||
->whereBetween('final_approved_at', [$startDate, $endDate])
|
||||
->sum('approved_total');
|
||||
}
|
||||
$nominals[$kategori->id] = $sum;
|
||||
}
|
||||
$totalDebet = array_sum($nominals); // Total Pengeluaran riil
|
||||
|
||||
return view('backend.pages.report.generate_jurnal', [
|
||||
'pageInfo' => ['title' => 'Generate Reports For Jurnal'],
|
||||
'kategori' => $kategoris,
|
||||
'cabang' => $cabang,
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
'kategori_bca' => $kategori_bca,
|
||||
'nominals' => $nominals,
|
||||
'budget' => $budget,
|
||||
'totalKategori' => $totalDebet, // Total Debet Jurnal
|
||||
'pettyCashAmount' => $pettyCashAmount, // Total Kredit Jurnal
|
||||
'cashInBca' => $pettyCashAmount - $totalDebet, // Sisa Uang BCA
|
||||
'accounting_period' => $accounting_period,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan Budget Baru & Log
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.create']);
|
||||
$validated = $request->validate([
|
||||
'receiver_id' => 'required|exists:admins,id',
|
||||
'periode_month' => 'required|string',
|
||||
'periode_year' => 'required|numeric',
|
||||
'amount' => 'required|numeric',
|
||||
'remarks' => 'nullable|string',
|
||||
]);
|
||||
|
||||
return DB::transaction(function () use ($validated) {
|
||||
$receiver = Admin::find($validated['receiver_id']);
|
||||
$cabang_id = $receiver->getMyCabangAndRegionId()['cabang'];
|
||||
|
||||
$existing = BudgetControl::where('cabang_id', $cabang_id)
|
||||
->where('periode_month', $validated['periode_month'])
|
||||
->where('periode_year', $validated['periode_year'])
|
||||
->first();
|
||||
|
||||
if ($existing && strtolower($existing->status) == 'assigned') {
|
||||
return back()->with('error', 'Gagal: Budget periode ini sudah Assigned.');
|
||||
}
|
||||
|
||||
$budgetData = [
|
||||
'sender_id' => auth()->user()->id,
|
||||
'receiver_id' => $validated['receiver_id'],
|
||||
'amount' => $validated['amount'],
|
||||
'remarks' => $validated['remarks'],
|
||||
'status' => 'Assigned',
|
||||
];
|
||||
|
||||
BudgetControl::updateOrCreate(
|
||||
['cabang_id' => $cabang_id, 'periode_month' => $validated['periode_month'], 'periode_year' => $validated['periode_year']],
|
||||
$budgetData
|
||||
);
|
||||
|
||||
BudgetControlLog::create(array_merge(['cabang_id' => $cabang_id], $validated, $budgetData));
|
||||
|
||||
return redirect()->route('budget_control')->with('success', 'Budget Assigned successfully');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Proses Upload Bukti Transfer (Disempurnakan untuk dukung PDF & Gambar)
|
||||
*/
|
||||
public function uploadProof(Request $request)
|
||||
{
|
||||
// PERBAIKAN: Ganti 'image' menjadi 'file', karena aturan 'image' akan menolak PDF
|
||||
$request->validate([
|
||||
'budget_id' => 'required|exists:budget_control,id',
|
||||
'transfer_proof' => 'required|file|mimes:jpeg,png,jpg,pdf|max:5120', // Maks 5MB
|
||||
], [
|
||||
'transfer_proof.mimes' => 'Format file harus berupa JPG, JPEG, PNG, atau PDF.',
|
||||
'transfer_proof.max' => 'Ukuran file maksimal 5MB.'
|
||||
]);
|
||||
|
||||
$budget = BudgetControl::find($request->budget_id);
|
||||
|
||||
if ($request->hasFile('transfer_proof')) {
|
||||
$file = $request->file('transfer_proof');
|
||||
$filename = time() . '_' . str_replace(' ', '_', $file->getClientOriginalName());
|
||||
|
||||
// Simpan file
|
||||
$file->move(public_path('uploads/transfer_proofs'), $filename);
|
||||
|
||||
$budget->update([
|
||||
'transfer_proof' => 'uploads/transfer_proofs/' . $filename,
|
||||
'transfer_status' => 'Waiting Approval'
|
||||
]);
|
||||
|
||||
return back()->with('success', 'Bukti transfer berhasil diunggah.');
|
||||
}
|
||||
|
||||
return back()->with('error', 'File gagal diunggah.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Konfirmasi Accounting (Validated)
|
||||
*/
|
||||
public function approveTransfer($id)
|
||||
{
|
||||
BudgetControl::where('id', $id)->update([
|
||||
'transfer_status' => 'Validated',
|
||||
'updated_at' => now()
|
||||
]);
|
||||
return back()->with('success', 'Transfer divalidasi.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Penolakan Accounting (Rejected)
|
||||
*/
|
||||
public function rejectTransfer($id)
|
||||
{
|
||||
BudgetControl::where('id', $id)->update([
|
||||
'transfer_status' => 'Rejected',
|
||||
'updated_at' => now()
|
||||
]);
|
||||
return back()->with('error', 'Transfer ditolak.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Proses Bulk Upload Budget via Excel/CSV
|
||||
*/
|
||||
public function bulkUpload(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.create']);
|
||||
|
||||
// Tambahkan 'csv' pada mimes
|
||||
$request->validate([
|
||||
'upload_type' => 'required|in:region,cabang',
|
||||
'periode_year' => 'required|numeric',
|
||||
'file_excel' => 'required|file|mimes:xlsx,xls,csv|max:5120',
|
||||
], [
|
||||
'file_excel.mimes' => 'Format file wajib berupa Microsoft Excel (.xls / .xlsx) atau CSV.'
|
||||
]);
|
||||
|
||||
// 1. Tentukan Cabang ID mana saja yang diizinkan untuk di-upload pada proses ini
|
||||
$cabangIds = [];
|
||||
if ($request->upload_type === 'region') {
|
||||
$request->validate(['region_id' => 'required|exists:region,id']);
|
||||
$cabangIds = \App\Models\Cabang::where('region_id', $request->region_id)->pluck('id')->toArray();
|
||||
} else {
|
||||
$request->validate(['cabang_id' => 'required|array', 'cabang_id.*' => 'exists:cabang,id']);
|
||||
$cabangIds = $request->cabang_id;
|
||||
}
|
||||
|
||||
try {
|
||||
// 2. Baca file Excel menggunakan Maatwebsite (otomatis jadi Array)
|
||||
// Parameter pertama new \stdClass() digunakan sebagai dummy import class
|
||||
$data = Excel::toArray(new \stdClass(), $request->file('file_excel'));
|
||||
$rows = $data[0] ?? [];
|
||||
|
||||
DB::beginTransaction();
|
||||
$count = 0;
|
||||
|
||||
// 3. Looping data Excel
|
||||
foreach ($rows as $index => $row) {
|
||||
// Skip baris pertama (Asumsi baris 1 adalah Header)
|
||||
if ($index === 0) continue;
|
||||
|
||||
$cabangCode = $row[0] ?? null;
|
||||
$month = $row[1] ?? null;
|
||||
$amount = (float) ($row[2] ?? 0);
|
||||
$remarks = $row[3] ?? null;
|
||||
|
||||
if (!$cabangCode || !$month || $amount <= 0) continue;
|
||||
|
||||
// Cari cabang berdasarkan Kode Cabang di Excel
|
||||
$cabang = \App\Models\Cabang::where('code', $cabangCode)->first();
|
||||
|
||||
// Validasi Keamanan: Pastikan cabang ditemukan DAN termasuk dalam scope filter modal
|
||||
if (!$cabang || !in_array($cabang->id, $cabangIds)) continue;
|
||||
|
||||
$budgetData = [
|
||||
'sender_id' => auth()->user()->id,
|
||||
'receiver_id' => $cabang->head_id ?? auth()->user()->id, // Assign ke Head Cabang
|
||||
'amount' => $amount,
|
||||
'remarks' => $remarks,
|
||||
'status' => 'Assigned',
|
||||
];
|
||||
|
||||
// Simpan atau Update Budget
|
||||
BudgetControl::updateOrCreate(
|
||||
[
|
||||
'cabang_id' => $cabang->id,
|
||||
'periode_month' => $month,
|
||||
'periode_year' => $request->periode_year
|
||||
],
|
||||
$budgetData
|
||||
);
|
||||
|
||||
// Catat di Log
|
||||
BudgetControlLog::create(array_merge([
|
||||
'cabang_id' => $cabang->id,
|
||||
'periode_month' => $month,
|
||||
'periode_year' => $request->periode_year
|
||||
], $budgetData));
|
||||
|
||||
$count++;
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
return back()->with('success', "Bulk upload berhasil! Sebanyak {$count} data budget telah diproses.");
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
\Illuminate\Support\Facades\Log::error("Bulk Upload Error: " . $e->getMessage());
|
||||
return back()->with('error', 'Gagal memproses file Excel. Pastikan format tabel sudah sesuai.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus Data Budget
|
||||
*/
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['budget_control.delete']);
|
||||
BudgetControl::findOrFail($id)->delete();
|
||||
return redirect()->route('budget_control')->with('success', 'Deleted successfully');
|
||||
}
|
||||
|
||||
/**
|
||||
* PRIVATE METHOD: Logika Grafik Trend Petty Cash vs Realisasi
|
||||
*/
|
||||
private function getTrendChartData(array $cabangIds): array
|
||||
{
|
||||
$currentYear = \Carbon\Carbon::now()->year;
|
||||
$months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
|
||||
|
||||
$pettyCashData = [];
|
||||
$realisasiData = [];
|
||||
|
||||
foreach ($months as $month) {
|
||||
$pettyCash = \App\Models\BudgetControl::whereIn('cabang_id', $cabangIds)
|
||||
->where('periode_month', strtolower($month))
|
||||
->where('periode_year', $currentYear)
|
||||
->sum('amount');
|
||||
|
||||
// Realisasi Sementara Di-set 0
|
||||
$realisasi = 0;
|
||||
|
||||
$pettyCashData[] = (float) $pettyCash;
|
||||
$realisasiData[] = (float) $realisasi;
|
||||
}
|
||||
|
||||
return [
|
||||
'labels' => $months,
|
||||
'datasets' => [
|
||||
[
|
||||
'label' => 'Petty Cash (Budget)',
|
||||
'data' => $pettyCashData,
|
||||
'backgroundColor' => 'rgba(54, 162, 235, 0.6)',
|
||||
'borderColor' => 'rgba(54, 162, 235, 1)',
|
||||
],
|
||||
[
|
||||
'label' => 'Realisasi',
|
||||
'data' => $realisasiData,
|
||||
'backgroundColor' => 'rgba(255, 99, 132, 0.6)',
|
||||
'borderColor' => 'rgba(255, 99, 132, 1)',
|
||||
]
|
||||
]
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -5,120 +5,243 @@ declare(strict_types=1);
|
||||
namespace App\Http\Controllers\Backend;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Admin;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use App\Models\FormUpCountry;
|
||||
use App\Models\FormEntertaimentPresentation;
|
||||
use App\Models\FormVehicleRunningCost;
|
||||
use App\Models\FormMeetingSeminar;
|
||||
use App\Models\FormOthers;
|
||||
use App\Models\UserHasCabang;
|
||||
use App\Models\Notifications;
|
||||
use App\Models\Region;
|
||||
use App\Models\Cabang;
|
||||
use App\Models\Kategori;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
private array $tables = [
|
||||
'up_country' => 'form_up_country',
|
||||
'vehicle' => 'form_vehicle_running_cost',
|
||||
'entertainment' => 'form_entertainment_presentation',
|
||||
'meeting' => 'form_meeting_seminar',
|
||||
'others' => 'form_others'
|
||||
];
|
||||
|
||||
// Referensi waktu sekarang
|
||||
public function index(Request $request)
|
||||
{
|
||||
$user = auth()->user();
|
||||
$roleName = trim($user->getRoleNames()->first() ?? '');
|
||||
$now = Carbon::now();
|
||||
|
||||
// Tentukan periode
|
||||
if ($now->day >= $startDay) {
|
||||
// Mulai dari tanggal START bulan ini
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
// Sampai tanggal CLOSING bulan depan
|
||||
$closingDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $closingDay)->endOfDay();
|
||||
} else {
|
||||
// Mulai dari tanggal START bulan lalu
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
// Sampai tanggal CLOSING bulan ini
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay)->endOfDay();
|
||||
// 1. FILTER WAKTU (Default ke bulan berjalan)
|
||||
$chartMonth = $request->chart_month ?? $now->format('m');
|
||||
$chartYear = $request->chart_year ?? $now->format('Y');
|
||||
$monthName = Carbon::createFromFormat('m', $chartMonth)->translatedFormat('F');
|
||||
|
||||
// --- KALKULASI PERIODE PENILAIAN (11 di bulan terpilih s/d 13 di bulan berikutnya) ---
|
||||
$displayStart = Carbon::create((int)$chartYear, (int)$chartMonth, 11)->startOfDay();
|
||||
$displayEnd = $displayStart->copy()->addMonth()->day(13)->endOfDay(); // Dikunci aman ke tanggal 13 penutupan closing laporan
|
||||
|
||||
$periodeLabelFormatted = $displayStart->translatedFormat('d F') . ' - ' . $displayEnd->translatedFormat('d F Y');
|
||||
|
||||
// 2. FILTER OTORISASI & DATA
|
||||
$allowedCabangIds = $this->getScopedCabangIds($user, $roleName);
|
||||
if (empty($allowedCabangIds)) {
|
||||
return view('backend.pages.dashboard.index', $this->emptyData());
|
||||
}
|
||||
|
||||
$formQueries = [
|
||||
'vehicle' => FormVehicleRunningCost::query()
|
||||
->whereMonth('tanggal', date('m'))
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
'upcountry' => FormUpCountry::query()
|
||||
->whereMonth('tanggal', date('m'))
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
'entertainment' => FormEntertaimentPresentation::query()
|
||||
->whereMonth('tanggal', date('m'))
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
'meeting' => FormMeetingSeminar::query()
|
||||
->whereMonth('created_at', date('m'))
|
||||
->whereBetween('created_at', [$startDate, $closingDate]),
|
||||
'others' => FormOthers::query()
|
||||
->whereMonth('tanggal', date('m'))
|
||||
->whereBetween('tanggal', [$startDate, $closingDate]),
|
||||
$availableRegions = $this->getAvailableRegions($user, $roleName, $allowedCabangIds);
|
||||
$cabangOptions = Cabang::whereIn('id', $allowedCabangIds)
|
||||
->when($request->region_id, fn($q) => $q->where('region_id', $request->region_id))
|
||||
->get();
|
||||
|
||||
// 3. AMBIL DATA PENDING & PERFORMA (Passing Variable Waktu Siklus ke Chart Method)
|
||||
$cabangDetails = $this->getPendingExpenseTable($allowedCabangIds, $request);
|
||||
$performance = $this->getPerformanceCharts($allowedCabangIds, $displayStart, $displayEnd);
|
||||
$totalKategori = Kategori::whereNotNull('account_number')->where('account_number', '!=', '')->count();
|
||||
|
||||
$data = [
|
||||
'periodeLabel' => $periodeLabelFormatted,
|
||||
'totalRegions' => Region::count(),
|
||||
'totalCabangs' => count($allowedCabangIds),
|
||||
'totalKategori' => $totalKategori,
|
||||
'regions' => $availableRegions,
|
||||
'cabangOptions' => $cabangOptions,
|
||||
'cabangDetails' => $cabangDetails,
|
||||
'pendingCount' => $this->getTotalPendingGlobal($allowedCabangIds),
|
||||
];
|
||||
|
||||
$approvedStatuses = [
|
||||
// 'Approved',
|
||||
// 'Approved 1',
|
||||
// 'Approved 2',
|
||||
// 'Final Approved',
|
||||
// 'Final Approve',
|
||||
'Closed',
|
||||
];
|
||||
return view('backend.pages.dashboard.index', array_merge($data, $performance));
|
||||
}
|
||||
|
||||
$forms = [];
|
||||
// ========================================================================
|
||||
// PRIVATE METHODS - SEPARATION OF CONCERNS
|
||||
// ========================================================================
|
||||
|
||||
foreach ($formQueries as $key => $query) {
|
||||
$forms[$key] = $query
|
||||
->whereIn('status', $approvedStatuses)
|
||||
->whereNotNull('final_approved_at')
|
||||
->sum('approved_total');
|
||||
/**
|
||||
* MENGAMBIL DATA UNTUK TABEL MONITORING PENDING
|
||||
*/
|
||||
private function getPendingExpenseTable($allowedCabangIds, Request $request)
|
||||
{
|
||||
$query = Cabang::whereIn('id', $allowedCabangIds)->with('region');
|
||||
|
||||
if ($request->region_id) $query->where('region_id', $request->region_id);
|
||||
if ($request->cabang_id) $query->where('id', $request->cabang_id);
|
||||
if ($request->filled('search')) $query->where('name', 'like', "%{$request->search}%");
|
||||
|
||||
$sortField = $request->get('sort', 'name');
|
||||
$sortOrder = $request->get('direction', 'asc');
|
||||
|
||||
if ($sortField == 'region') {
|
||||
$query->leftJoin('region', 'cabang.region_id', '=', 'region.id')
|
||||
->select('cabang.*')->orderBy('region.name', $sortOrder);
|
||||
} else {
|
||||
$query->orderBy('cabang.' . ($sortField == 'total_pending' ? 'name' : $sortField), $sortOrder);
|
||||
}
|
||||
|
||||
return view(
|
||||
'backend.pages.dashboard.index',
|
||||
[
|
||||
'forms' => $forms,
|
||||
]
|
||||
);
|
||||
$cabangDetails = $query->paginate(100)->withQueryString()->through(function($cabang) {
|
||||
$statuses = ['Pending', 'On Progress', 'Approved 1', 'Approved 2', 'Waiting Approval'];
|
||||
$details = []; $total = 0;
|
||||
|
||||
foreach ($this->tables as $key => $table) {
|
||||
$count = DB::table($table)->where('cabang_id', $cabang->id)->whereIn('status', $statuses)->count();
|
||||
$details[$key] = $count;
|
||||
$total += $count;
|
||||
}
|
||||
|
||||
$cabang->pending_details = $details;
|
||||
$cabang->total_pending = $total;
|
||||
return $cabang;
|
||||
});
|
||||
|
||||
if ($sortField == 'total_pending') {
|
||||
$sortedCollection = $cabangDetails->getCollection()->sortBy('total_pending', SORT_REGULAR, $sortOrder == 'desc')->values();
|
||||
$cabangDetails->setCollection($sortedCollection);
|
||||
}
|
||||
|
||||
return $cabangDetails;
|
||||
}
|
||||
|
||||
public function notifications()
|
||||
/**
|
||||
* MENGHITUNG PERFORMA KECEPATAN APPROVE CABANG (Fokus Akurat Jendela Siklus Transaksi Tanggal 11 - 13)
|
||||
*/
|
||||
private function getPerformanceCharts($cabangIds, Carbon $startDate, Carbon $endDate): array
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['notification.view']);
|
||||
$queryUnion = null;
|
||||
|
||||
foreach ($this->tables as $table) {
|
||||
$q = DB::table($table)
|
||||
->select('cabang_id', 'created_at', 'final_approved_at', 'updated_at')
|
||||
->where('status', 'Closed')
|
||||
->whereIn('cabang_id', $cabangIds)
|
||||
// KUNCI UTAMA: Hanya membaca pengajuan yang dibuat murni di dalam rentang tanggal siklus 11 s/d 13 berjalan
|
||||
->whereBetween('tanggal', [$startDate->format('Y-m-d H:i:s'), $endDate->format('Y-m-d H:i:s')]);
|
||||
|
||||
$queryUnion = is_null($queryUnion) ? $q : $queryUnion->unionAll($q);
|
||||
}
|
||||
|
||||
// Mulai dengan query dasar
|
||||
$notifications = Notifications::orderBy('created_at', 'desc')
|
||||
->where('receiver_id', auth()->user()->id)
|
||||
->where('is_read', 0);
|
||||
if ($queryUnion && DB::table(DB::raw("({$queryUnion->toSql()}) as t"))->mergeBindings($queryUnion)->exists()) {
|
||||
// Kalkulasi selisih waktu rata-rata penyelesaian berkas menggunakan fondasi TIMESTAMPDIFF detik secara objektif
|
||||
$res = DB::table(DB::raw("({$queryUnion->toSql()}) as combined"))
|
||||
->mergeBindings($queryUnion)
|
||||
->select('cabang_id', DB::raw('AVG(TIMESTAMPDIFF(SECOND, created_at, COALESCE(final_approved_at, updated_at))) as avg_sec'))
|
||||
->groupBy('cabang_id')
|
||||
->get();
|
||||
|
||||
// Ambil data dan kembalikan sebagai JSON
|
||||
return response()->json([
|
||||
'count' => $notifications->count(),
|
||||
'data' => $notifications->take(7)->get(),
|
||||
]);
|
||||
$cabangNames = Cabang::whereIn('id', $res->pluck('cabang_id'))->pluck('name', 'id');
|
||||
$fastest = $res->sortBy('avg_sec')->take(5);
|
||||
$slowest = $res->sortByDesc('avg_sec')->take(5);
|
||||
|
||||
return [
|
||||
'chartFastest' => [
|
||||
'labels' => $fastest->map(fn($i) => $cabangNames[$i->cabang_id] ?? 'N/A')->values(),
|
||||
'data' => $fastest->map(fn($i) => round($i->avg_sec / 3600, 2))->values(),
|
||||
'raw' => $fastest->map(fn($i) => $this->formatDuration((int)$i->avg_sec))->values()
|
||||
],
|
||||
'chartSlowest' => [
|
||||
'labels' => $slowest->map(fn($i) => $cabangNames[$i->cabang_id] ?? 'N/A')->values(),
|
||||
'data' => $slowest->map(fn($i) => round($i->avg_sec / 3600, 2))->values(),
|
||||
'raw' => $slowest->map(fn($i) => $this->formatDuration((int)$i->avg_sec))->values()
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'chartFastest' => ['labels'=>[], 'data'=>[], 'raw'=>[]],
|
||||
'chartSlowest' => ['labels'=>[], 'data'=>[], 'raw'=>[]]
|
||||
];
|
||||
}
|
||||
|
||||
public function mark_read($id)
|
||||
/**
|
||||
* GET AVAILABLE REGIONS BERDASARKAN ROLE
|
||||
*/
|
||||
private function getAvailableRegions($user, $roleName, $allowedCabangIds)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['notification.delete']);
|
||||
$receiver_id = auth()->user()->id;
|
||||
|
||||
Notifications::where('receiver_id', $receiver_id)->where('id', $id)->update(['is_read' => 1]);
|
||||
|
||||
return response()->json(['message' => 'Notification marked as read.']);
|
||||
$regionsQuery = Region::query();
|
||||
if (in_array($roleName, ['Admin Region', 'Marketing Operational Manager Region'])) {
|
||||
$regionsQuery->where('id', $user->region_id);
|
||||
} elseif (in_array($roleName, ['Area Manager Cabang', 'Medical Representatif'])) {
|
||||
$myRegionIds = Cabang::whereIn('id', $allowedCabangIds)->pluck('region_id')->unique();
|
||||
$regionsQuery->whereIn('id', $myRegionIds);
|
||||
}
|
||||
return $regionsQuery->get();
|
||||
}
|
||||
|
||||
public function mark_all_read()
|
||||
private function getScopedCabangIds($user, $roleName): array
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['notification.delete']);
|
||||
$receiver_id = auth()->user()->id;
|
||||
$central = ['Superadmin', 'Head of Sales Marketing', 'Marketing Information System', 'Accounting'];
|
||||
if (in_array($roleName, $central)) return Cabang::pluck('id')->toArray();
|
||||
|
||||
Notifications::where('receiver_id', $receiver_id)->update(['is_read' => 1]);
|
||||
if (in_array($roleName, ['Admin Region', 'Marketing Operational Manager Region'])) {
|
||||
return $user->region_id ? Cabang::where('region_id', $user->region_id)->pluck('id')->toArray() : [];
|
||||
}
|
||||
|
||||
session()->flash('success', 'All notifications marked as read.');
|
||||
return redirect()->back();
|
||||
if (in_array($roleName, ['Area Manager Cabang', 'Medical Representatif'])) {
|
||||
$cabangId = $user->cabang->cabang_id ?? \App\Models\Rayon::where('id', $user->rayon_id)->value('cabang_id');
|
||||
return $cabangId ? [(int)$cabangId] : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
private function getTotalPendingGlobal($cabangIds): int
|
||||
{
|
||||
$total = 0;
|
||||
foreach ($this->tables as $table) {
|
||||
$total += DB::table($table)->whereIn('cabang_id', $cabangIds)->whereIn('status', ['Pending', 'On Progress', 'Approved 1', 'Approved 2', 'Waiting Approval'])->count();
|
||||
}
|
||||
return $total;
|
||||
}
|
||||
|
||||
private function formatDuration(int $sec): string
|
||||
{
|
||||
if ($sec <= 0) return "0 Jam";
|
||||
$d = floor($sec / 86400); $h = floor(($sec % 86400) / 3600);
|
||||
return $d > 0 ? "{$d} Hari {$h} Jam" : "{$h} Jam";
|
||||
}
|
||||
|
||||
private function emptyData(): array
|
||||
{
|
||||
return [
|
||||
'periodeLabel' => '-', 'totalRegions' => 0, 'totalCabangs' => 0, 'totalKategori' => 0, 'pendingCount' => 0,
|
||||
'cabangDetails' => collect(), 'chartFastest' => ['labels'=>[], 'data'=>[], 'raw'=>[]],
|
||||
'chartSlowest' => ['labels'=>[], 'data'=>[], 'raw'=>[]], 'regions' => collect(), 'cabangOptions' => collect()
|
||||
];
|
||||
}
|
||||
|
||||
public function notifications() { return response()->json(['status' => 'success', 'data' => []]); }
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
try {
|
||||
$user = auth()->user();
|
||||
$allowedIds = $this->getScopedCabangIds($user, $user->getRoleNames()->first());
|
||||
if (!in_array((int)$id, $allowedIds)) abort(403);
|
||||
|
||||
$cabang = Cabang::with('region')->findOrFail($id);
|
||||
$statuses = ['Pending', 'On Progress', 'Approved 1', 'Approved 2', 'Waiting Approval'];
|
||||
|
||||
$data = [];
|
||||
foreach (['Up Country' => 'form_up_country', 'Vehicle' => 'form_vehicle_running_cost', 'Entertainment' => 'form_entertainment_presentation', 'Meeting' => 'form_meeting_seminar', 'Others' => 'form_others'] as $label => $table) {
|
||||
$data[$label] = DB::table($table)->where('cabang_id', $id)->whereIn('status', $statuses)->get();
|
||||
}
|
||||
return view('backend.pages.dashboard.show', compact('cabang', 'data'));
|
||||
} catch (\Exception $e) {
|
||||
return redirect()->route('admin.dashboard')->with('error', 'Cabang tidak ditemukan.');
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -76,7 +76,7 @@ class FormEntertainmentPresentationController extends Controller
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
$userRegionData = auth()->user()->getMyCabangAndRegionId();
|
||||
$regionContextId = $userRegionData['region'] !== '-' ? $userRegionData['region'] : null;
|
||||
$cabangContextId = $userRegionData['cabang'] !== '-' ? $userRegionData['cabang'] : null;
|
||||
@@ -182,15 +182,15 @@ class FormEntertainmentPresentationController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.entertainment.create']);
|
||||
|
||||
return view('backend.pages.forms.entertainment.create');
|
||||
}
|
||||
return view('backend.pages.forms.entertainment.create');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.entertainment.create']);
|
||||
|
||||
$validator = Validator::make($request->all(), [
|
||||
@@ -201,6 +201,9 @@ class FormEntertainmentPresentationController extends Controller
|
||||
'name' => 'required|string',
|
||||
'alamat' => 'required|string',
|
||||
'nik_or_npwp' => 'required|string',
|
||||
'jabatan' => 'required|string',
|
||||
'nama_perusahaan' => 'required|string',
|
||||
'jenis_usaha' => 'required|string',
|
||||
'attachments' => 'nullable|array',
|
||||
'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
|
||||
'attachments.*.file_path' => 'nullable|file|max:10240',
|
||||
@@ -209,24 +212,26 @@ class FormEntertainmentPresentationController extends Controller
|
||||
$validator->validate();
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
|
||||
// Ambil tanggal sekarang untuk tentukan periode berjalan
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
// Periode berjalan dari bulan ini sampai bulan depan
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay);
|
||||
$closingDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $closingDay);
|
||||
// Jendela Aktif: Tgl 11 Bulan Ini s/d Tgl 10 Bulan Depan
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
// Periode berjalan dari bulan lalu sampai bulan ini
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
||||
// Jendela Aktif: Tgl 11 Bulan Lalu s/d Tgl 10 Bulan Ini
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
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')}");
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
@@ -244,19 +249,19 @@ class FormEntertainmentPresentationController extends Controller
|
||||
|
||||
$region = Region::where('id', $cabang->region_id)->first();
|
||||
|
||||
$kategori = "";
|
||||
$kategori = null;
|
||||
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
|
||||
$kategori = Kategori::where('name', 'Entertainment')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Entertainment%')->first();
|
||||
} elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') {
|
||||
$kategori = Kategori::where('name', 'Presentation')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Presentation%')->first();
|
||||
} elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
|
||||
$kategori = Kategori::where('name', 'Sponsorship')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Sponsorship%')->first();
|
||||
}
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment';
|
||||
|
||||
// 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);
|
||||
$expense_number = $region->code . '-' . $cabang->code . '-ETY-' . date('ym') . $formatted_sequence_number;
|
||||
|
||||
@@ -275,6 +280,7 @@ class FormEntertainmentPresentationController extends Controller
|
||||
$form = FormEntertaimentPresentation::create([
|
||||
'expense_number' => $expense_number,
|
||||
'user_id' => auth()->user()->id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID BARU
|
||||
'tanggal' => $request->tanggal,
|
||||
'jenis' => $request->jenis,
|
||||
'keterangan' => $request->keterangan,
|
||||
@@ -282,8 +288,12 @@ class FormEntertainmentPresentationController extends Controller
|
||||
'name' => $request->name,
|
||||
'alamat' => $request->alamat,
|
||||
'nik_or_npwp' => $request->nik_or_npwp,
|
||||
'jabatan' => $request->jabatan,
|
||||
'nama_perusahaan' => $request->nama_perusahaan,
|
||||
'jenis_usaha' => $request->jenis_usaha,
|
||||
'bukti_total' => $primaryAttachmentPath,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? null,
|
||||
'kategori_id' => $kategori->id ?? null,
|
||||
'status' => 'On Progress',
|
||||
]);
|
||||
|
||||
@@ -388,10 +398,10 @@ class FormEntertainmentPresentationController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Entertainment Presentation (' . $expense_number . ')');
|
||||
session()->flash('success', 'Form has been created.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
public function edit($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -403,39 +413,49 @@ class FormEntertainmentPresentationController extends Controller
|
||||
|
||||
$attachments = $this->formatAttachmentCollection($form);
|
||||
|
||||
return view('backend.pages.forms.entertainment.edit', [
|
||||
return view('backend.pages.forms.entertainment.edit', [
|
||||
'form' => $form,
|
||||
'attachments' => $attachments,
|
||||
]);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.entertainment.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$form = FormEntertaimentPresentation::with('attachments')->findOrFail($id);
|
||||
$cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()?->cabang_id;
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()?->cabang;
|
||||
|
||||
if (!$cabang_id) {
|
||||
if (!$cabang) {
|
||||
return redirect()->back()->with('error', 'Cabang tidak ditemukan.');
|
||||
}
|
||||
|
||||
// Hitung periode berdasarkan tanggal form
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE (Konsisten dengan fungsi Store)
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
|
||||
$now = Carbon::now();
|
||||
|
||||
// Periode aktif berdasarkan tanggal input
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$periodeDate = Carbon::create($tanggal->copy()->subMonth()->year, $tanggal->copy()->subMonth()->month, $startDay);
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
// Hitung periode berdasarkan tanggal form untuk validasi budget
|
||||
$periodeMonth = strtolower($startDate->format('F'));
|
||||
$periodeYear = (int) $startDate->format('Y');
|
||||
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
||||
|
||||
$validator = Validator::make($request->all(), [
|
||||
'tanggal' => 'required|date',
|
||||
@@ -445,6 +465,9 @@ class FormEntertainmentPresentationController extends Controller
|
||||
'name' => 'required|string',
|
||||
'alamat' => 'required|string',
|
||||
'nik_or_npwp' => 'required|string',
|
||||
'jabatan' => 'required|string',
|
||||
'nama_perusahaan' => 'required|string',
|
||||
'jenis_usaha' => 'required|string',
|
||||
'attachments' => 'nullable|array',
|
||||
'attachments.*.file_category' => 'nullable|string|in:' . implode(',', array_keys($this->attachmentCategories)),
|
||||
'attachments.*.file_path' => 'nullable|file|max:10240',
|
||||
@@ -457,16 +480,15 @@ class FormEntertainmentPresentationController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()->cabang;
|
||||
$region = Region::where('id', $cabang->region_id)->first();
|
||||
|
||||
$kategori = "";
|
||||
$kategori = null;
|
||||
if (strtolower($request->jenis) == 'entertainment' || $request->jenis == 'entertainment') {
|
||||
$kategori = Kategori::where('name', 'Entertainment')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Entertainment%')->first();
|
||||
} elseif (strtolower($request->jenis) == 'presentation' || $request->jenis == 'presentation') {
|
||||
$kategori = Kategori::where('name', 'Presentation')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Presentation%')->first();
|
||||
} elseif (strtolower($request->jenis) == 'sponsorship' || $request->jenis == 'sponsorship') {
|
||||
$kategori = Kategori::where('name', 'Sponsorship')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Sponsorship%')->first();
|
||||
}
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/entertainment';
|
||||
@@ -479,6 +501,7 @@ class FormEntertainmentPresentationController extends Controller
|
||||
: $form->bukti_total;
|
||||
|
||||
$form->update([
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID TERBARU
|
||||
'tanggal' => $request->tanggal,
|
||||
'jenis' => $request->jenis,
|
||||
'keterangan' => $request->keterangan,
|
||||
@@ -486,8 +509,12 @@ class FormEntertainmentPresentationController extends Controller
|
||||
'name' => $request->name,
|
||||
'alamat' => $request->alamat,
|
||||
'nik_or_npwp' => $request->nik_or_npwp,
|
||||
'jabatan' => $request->jabatan,
|
||||
'nama_perusahaan' => $request->nama_perusahaan,
|
||||
'jenis_usaha' => $request->jenis_usaha,
|
||||
'bukti_total' => $primaryAttachmentPath,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? $form->account_number,
|
||||
'kategori_id' => $kategori->id ?? null,
|
||||
]);
|
||||
|
||||
if (!empty($attachmentsPayload)) {
|
||||
@@ -518,7 +545,7 @@ class FormEntertainmentPresentationController extends Controller
|
||||
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)
|
||||
{
|
||||
@@ -731,7 +758,8 @@ class FormEntertainmentPresentationController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function finalApprove($id)
|
||||
// <--- REPARASI SUNTIKAN REQUEST DARI JAVASCRIPT MODAL AGAR DATA BISA DIAMBIL
|
||||
public function finalApprove(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
||||
$form = FormEntertaimentPresentation::findOrFail($id);
|
||||
@@ -748,11 +776,10 @@ class FormEntertainmentPresentationController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Hitung periode dari tanggal form
|
||||
// Hitung periode berdasarkan tanggal form
|
||||
$tanggal = Carbon::parse($form->tanggal);
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
|
||||
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -762,13 +789,17 @@ class FormEntertainmentPresentationController extends Controller
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// <--- REPARASI: Penangkapan nilai payload dari checkbox JavaScript
|
||||
$approvedTotal = $request->input('approved_total', $form->total);
|
||||
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
if($form->approved_total > $availableBudget) {
|
||||
if($approvedTotal > $availableBudget) { // <--- DISINKRONKAN DENGAN NILAI BARU HASIL CHECKLIST
|
||||
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$form->update([
|
||||
'approved_total' => $approvedTotal, // <--- SUNTIK DATA UPDATE HASIL CHECKLIST KE DATABASE
|
||||
'final_approved_at' => now(),
|
||||
'final_approved_by' => auth()->user()->id,
|
||||
'status' => 'Closed',
|
||||
@@ -777,7 +808,7 @@ class FormEntertainmentPresentationController extends Controller
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$total = $form->approved_total;
|
||||
$total = $form->approved_total; // <--- TOTAL BARU YANG DIKIRIMKAN KE EMAIL / WHATSAPP
|
||||
|
||||
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
||||
$recipients = [$form->user->email, auth()->user()->email];
|
||||
@@ -850,75 +881,77 @@ class FormEntertainmentPresentationController extends Controller
|
||||
|
||||
public function reject(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
||||
// Otorisasi khusus MOM Region dan Atasan
|
||||
if (!auth()->user()->hasAnyPermission(['approval.reject', 'approval2.reject', 'final_approval.approve'])) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki izin untuk melakukan Reject.');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'remarks' => 'required|string|max:500',
|
||||
'remarks' => 'required|string|max:500',
|
||||
]);
|
||||
|
||||
// Menggunakan Model Entertainment & Presentation
|
||||
$form = FormEntertaimentPresentation::findOrfail($id);
|
||||
|
||||
$form->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'rejected_by' => auth()->id(), // Kolom baru
|
||||
'rejected_at' => now(), // Kolom baru
|
||||
]);
|
||||
|
||||
$heads = $form->user->getCabangAndRegionHead();
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$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'];
|
||||
$recipients[] = $heads['cabang_head']['email'];
|
||||
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
||||
}
|
||||
|
||||
if ($heads['region_head']) {
|
||||
$recipients[] = $heads['region_head']['email'];
|
||||
$phoneNumbers[] = $heads['region_head']['phone'];
|
||||
$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
|
||||
// Route khusus Entertainment
|
||||
$url = route('forms.entertainment.view', $form->id);
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks);
|
||||
|
||||
// Notifikasi WhatsApp
|
||||
$this->rejectExpenseWithNotification($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks, $recipients);
|
||||
|
||||
// Send bulk email
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url,
|
||||
$request->remarks
|
||||
);
|
||||
|
||||
$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 Entertainment (' . $form->expense_number . ')');
|
||||
// Audit Trail Khusus Form Entertainment
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Entertainment Presentation (' . $form->expense_number . ') oleh ' . auth()->user()->name);
|
||||
|
||||
session()->flash('success', 'Form has been rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
private function rejectExpenseWithNotification($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $remarks, $recipients)
|
||||
{
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $remarks);
|
||||
|
||||
// Notifikasi Email (Brevo)
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected($name, $expense_number, $tanggal, $total, $url, $remarks);
|
||||
$brevoService->expenseRejected($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function open($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.open']);
|
||||
@@ -935,23 +968,23 @@ class FormEntertainmentPresentationController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.entertainment.delete']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
$form = FormEntertaimentPresentation::findOrfail($id);
|
||||
$form = FormEntertaimentPresentation::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 Entertainment Presentation (' . $form->expense_number . ')');
|
||||
$form->delete();
|
||||
$form->delete();
|
||||
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
protected function addAttachmentValidationRules(\Illuminate\Validation\Validator $validator, Request $request): void
|
||||
{
|
||||
@@ -1138,4 +1171,4 @@ class FormEntertainmentPresentationController extends Controller
|
||||
|
||||
return ucwords(str_replace('_', ' ', $category));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ class FormMeetingSeminarController extends Controller
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
$userRegionData = auth()->user()->getMyCabangAndRegionId();
|
||||
$regionContextId = $userRegionData['region'] !== '-' ? $userRegionData['region'] : null;
|
||||
$cabangContextId = $userRegionData['cabang'] !== '-' ? $userRegionData['cabang'] : null;
|
||||
@@ -180,14 +180,14 @@ class FormMeetingSeminarController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.meeting.create']);
|
||||
|
||||
return view('backend.pages.forms.meeting.create');
|
||||
}
|
||||
return view('backend.pages.forms.meeting.create');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.meeting.create']);
|
||||
|
||||
@@ -204,23 +204,28 @@ class FormMeetingSeminarController extends Controller
|
||||
$validator->validate();
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
|
||||
$now = Carbon::now();
|
||||
|
||||
// Tentukan periode aktif berdasarkan tanggal 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);
|
||||
// Jendela Aktif: Tgl 11 Bulan Ini s/d Tgl 10 Bulan Depan
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
||||
// Jendela Aktif: Tgl 11 Bulan Lalu s/d Tgl 10 Bulan Ini
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode saat ini
|
||||
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();
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()?->cabang;
|
||||
@@ -230,7 +235,9 @@ class FormMeetingSeminarController extends Controller
|
||||
}
|
||||
|
||||
$region = Region::find($cabang->region_id);
|
||||
$kategori = Kategori::where('name', 'Meeting / Seminar')->first();
|
||||
|
||||
// Optimasi pencarian kategori menggunakan LIKE fleksibel untuk menjamin ID ditemukan
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Meeting / Seminar%')->first();
|
||||
|
||||
// Hitung periode dari tanggal input (bukan dari today)
|
||||
if ($tanggal->day >= $startDay) {
|
||||
@@ -266,7 +273,7 @@ class FormMeetingSeminarController extends Controller
|
||||
// Check if the total nominal exceeds the available budget
|
||||
if ($totalNominal > $availableBudget) {
|
||||
session()->flash('error', 'Alokasi budget bulanan cabang tidak mencukupi,silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
DB::beginTransaction();
|
||||
@@ -276,6 +283,7 @@ class FormMeetingSeminarController extends Controller
|
||||
$form = FormMeetingSeminar::create([
|
||||
'expense_number' => $expense_number,
|
||||
'user_id' => auth()->user()->id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID BARU
|
||||
'tanggal' => $request->tanggal,
|
||||
'allowance' => $data_nominal['allowance'],
|
||||
'transport_ankot' => $data_nominal['transport_ankot'],
|
||||
@@ -285,6 +293,7 @@ class FormMeetingSeminarController extends Controller
|
||||
'bukti_transport_ankot' => null,
|
||||
'bukti_hotel' => null,
|
||||
'account_number' => $kategori?->account_number,
|
||||
'kategori_id' => $kategori->id ?? null,
|
||||
'status' => 'On Progress',
|
||||
]);
|
||||
|
||||
@@ -391,10 +400,10 @@ class FormMeetingSeminarController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Meeting Seminar (' . $expense_number . ')');
|
||||
session()->flash('success', 'Form has been created.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
public function edit($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.meeting.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -406,14 +415,14 @@ class FormMeetingSeminarController extends Controller
|
||||
|
||||
$attachments = $this->formatAttachmentCollection($form);
|
||||
|
||||
return view('backend.pages.forms.meeting.edit', [
|
||||
return view('backend.pages.forms.meeting.edit', [
|
||||
'form' => $form,
|
||||
'attachments' => $attachments,
|
||||
]);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.meeting.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$form = FormMeetingSeminar::with('attachments')->findOrFail($id);
|
||||
@@ -434,6 +443,28 @@ class FormMeetingSeminarController extends Controller
|
||||
session()->flash('error', 'You cannot edit this form because it has been approved or rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()?->cabang;
|
||||
if (!$cabang) {
|
||||
@@ -442,7 +473,7 @@ class FormMeetingSeminarController extends Controller
|
||||
}
|
||||
|
||||
$region = Region::find($cabang->region_id);
|
||||
$kategori = Kategori::where('name', 'Meeting / Seminar')->first();
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Meeting / Seminar%')->first();
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/meeting';
|
||||
|
||||
@@ -458,8 +489,6 @@ class FormMeetingSeminarController extends Controller
|
||||
$totalNominal = array_sum($data_nominal);
|
||||
|
||||
// Hitung periode dari tanggal form yang diinput
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -473,18 +502,20 @@ class FormMeetingSeminarController extends Controller
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
||||
if ($totalNominal > $availableBudget) {
|
||||
session()->flash('error', 'The total nominal exceeds the available budget.');
|
||||
return redirect()->back();
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$form->update([
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID TERBARU SAAT PROSES UPDATE
|
||||
'tanggal' => $request->tanggal,
|
||||
'allowance' => $data_nominal['allowance'],
|
||||
'transport_ankot' => $data_nominal['transport_ankot'],
|
||||
'hotel' => $data_nominal['hotel'],
|
||||
'total' => $totalNominal,
|
||||
'account_number' => $kategori?->account_number,
|
||||
'kategori_id' => $kategori->id ?? null,
|
||||
]);
|
||||
|
||||
if (!empty($attachmentsPayload)) {
|
||||
@@ -512,7 +543,7 @@ class FormMeetingSeminarController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Update', 'Update Expense at Form Meeting Seminar (' . $form->expense_number . ')');
|
||||
session()->flash('success', 'Form has been updated.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteAttachment(Request $request, $formId, $attachmentId)
|
||||
{
|
||||
@@ -735,7 +766,8 @@ class FormMeetingSeminarController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function finalApprove($id)
|
||||
// <--- REPARASI SUNTIKAN OBJECT REQUEST HASIL CHECKLIST JAVASCRIPT MODAL DILUAR
|
||||
public function finalApprove(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
||||
$form = FormMeetingSeminar::findOrFail($id);
|
||||
@@ -764,22 +796,27 @@ class FormMeetingSeminarController extends Controller
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// <--- REPARASI: Penangkapan nilai payload dari checkbox JavaScript
|
||||
$approvedTotal = $request->input('approved_total', $form->total);
|
||||
|
||||
// Ambil sisa budget bulanan dan sinkronkan dengan nominal dinamis terbaru
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
if($form->approved_total > $availableBudget) {
|
||||
if($approvedTotal > $availableBudget) {
|
||||
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$form->update([
|
||||
'approved_total' => $approvedTotal, // <--- SUNTIK NOMINAL BARU HASIL CHECKLIST DARI JAVASCRIPT KE DB
|
||||
'final_approved_at' => now(),
|
||||
'final_approved_by' => auth()->user()->id,
|
||||
'status' => 'Closed',
|
||||
'status' => 'Closed',
|
||||
]);
|
||||
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->tanggal;
|
||||
$total = $form->approved_total;
|
||||
$total = $form->approved_total; // <--- TOTAL BARU YANG DIKIRIMKAN KE EMAIL / WHATSAPP
|
||||
|
||||
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
||||
$recipients = [$form->user->email, auth()->user()->email];
|
||||
@@ -822,16 +859,18 @@ class FormMeetingSeminarController extends Controller
|
||||
$url = route('forms.meeting.view', $form->id);
|
||||
WhatsappHelper::finalApprove($phoneNumbers, $expense_number, $url, $tanggal, $total, $name);
|
||||
|
||||
// Send bulk email
|
||||
// Send bulk email (Optimasi menggunakan BrevoService)
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
Mail::to($recipient)->send(new FinalApprove(
|
||||
$mail = new FinalApprove(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url
|
||||
));
|
||||
);
|
||||
$brevoService->expenseFinalApproved($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
@@ -845,16 +884,22 @@ class FormMeetingSeminarController extends Controller
|
||||
|
||||
public function reject(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
||||
if (!auth()->user()->hasAnyPermission(['approval.reject', 'approval2.reject', 'final_approval.approve'])) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki izin untuk melakukan Reject.');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'remarks' => 'required|string|max:500',
|
||||
'remarks' => 'required|string|max:500',
|
||||
]);
|
||||
|
||||
$form = FormMeetingSeminar::findOrfail($id);
|
||||
|
||||
// Update Metadata Rejeksi
|
||||
$form->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'rejected_by' => auth()->id(), // Kolom baru
|
||||
'rejected_at' => now(), // Kolom baru
|
||||
]);
|
||||
|
||||
$heads = $form->user->getCabangAndRegionHead();
|
||||
@@ -863,53 +908,37 @@ class FormMeetingSeminarController extends Controller
|
||||
$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'];
|
||||
$recipients[] = $heads['cabang_head']['email'];
|
||||
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
||||
}
|
||||
|
||||
if ($heads['region_head']) {
|
||||
$recipients[] = $heads['region_head']['email'];
|
||||
$phoneNumbers[] = $heads['region_head']['phone'];
|
||||
$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.meeting.view', $form->id);
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks);
|
||||
|
||||
// Send bulk email
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url,
|
||||
$request->remarks
|
||||
);
|
||||
|
||||
$response = $brevoService->expenseRejected($recipient, $name, $mail);
|
||||
|
||||
if (isset($response['success']) && $response['success'] === false) {
|
||||
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
||||
try {
|
||||
$mail = new ExpenseRejected($name, $expense_number, $tanggal, $total, $url, $request->remarks);
|
||||
$brevoService->expenseRejected($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Meeting Seminar (' . $form->expense_number . ')');
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Meeting Seminar (' . $form->expense_number . ') oleh ' . auth()->user()->name);
|
||||
session()->flash('success', 'Form has been rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
@@ -930,12 +959,12 @@ class FormMeetingSeminarController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.meeting.delete']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
$form = FormMeetingSeminar::findOrfail($id);
|
||||
$form = FormMeetingSeminar::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();
|
||||
@@ -943,11 +972,11 @@ class FormMeetingSeminarController extends Controller
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Meeting Seminar (' . $form->expense_number . ')');
|
||||
|
||||
$form->delete();
|
||||
$form->delete();
|
||||
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
protected function addAttachmentValidationRules(\Illuminate\Validation\Validator $validator, Request $request): void
|
||||
{
|
||||
@@ -1138,4 +1167,4 @@ class FormMeetingSeminarController extends Controller
|
||||
|
||||
return ucwords(str_replace('_', ' ', $category));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -74,7 +74,7 @@ class FormOtherController extends Controller
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
$userRegionData = auth()->user()->getMyCabangAndRegionId();
|
||||
$regionContextId = $userRegionData['region'] !== '-' ? $userRegionData['region'] : null;
|
||||
$cabangContextId = $userRegionData['cabang'] !== '-' ? $userRegionData['cabang'] : null;
|
||||
@@ -179,18 +179,18 @@ class FormOtherController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.other.create']);
|
||||
|
||||
return view('backend.pages.forms.other.create', [
|
||||
return view('backend.pages.forms.other.create', [
|
||||
'kategori' => Kategori::whereNotIn('name', $this->excludedKategoriNames)->get(),
|
||||
'attachmentCategories' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.other.create']);
|
||||
$validator = Validator::make($request->all(), [
|
||||
'kategori_id' => 'required',
|
||||
@@ -203,7 +203,7 @@ class FormOtherController extends Controller
|
||||
'nullable',
|
||||
'file',
|
||||
'max:10240',
|
||||
'mimetypes:image/jpeg,image/png,image/webp,application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain,text/csv,application/zip,application/x-zip-compressed,application/x-7z-compressed,application/vnd.rar,application/octet-stream'
|
||||
'mimetypes:image/jpeg,image/png,image/webp,application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain,text/csv,application/zip,application/x-zip-compressed,application/x-7z-compressed,application/vnd.rar,application/octet-stream'
|
||||
],
|
||||
]);
|
||||
|
||||
@@ -229,23 +229,27 @@ class FormOtherController extends Controller
|
||||
$validator->validate();
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
// Tentukan periode input berdasarkan waktu saat ini
|
||||
// Tentukan periode aktif berdasarkan tanggal 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);
|
||||
// Jendela Aktif: Tgl 11 Bulan Ini s/d Tgl 10 Bulan Depan
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
||||
// Jendela Aktif: Tgl 11 Bulan Lalu s/d Tgl 10 Bulan Ini
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal berada dalam periode aktif input
|
||||
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();
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
// Ambil cabang user
|
||||
@@ -256,7 +260,7 @@ class FormOtherController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Tentukan periode budget berdasarkan tanggal input (bukan now)
|
||||
// Tentukan periode budget berdasarkan tanggal input
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -270,7 +274,7 @@ class FormOtherController extends Controller
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
||||
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();
|
||||
@@ -279,10 +283,9 @@ class FormOtherController extends Controller
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/other';
|
||||
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
|
||||
$primaryAttachmentPath = $attachmentsPayload[0]['file_path'] ?? null;
|
||||
$primaryAttachmentPath = $attachmentsPayload[0]['file_path'] ?? null;
|
||||
|
||||
// Generate sequence number and expense number
|
||||
$sequence_number = FormOthers::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-OTH-' . date('ym') . '%')->count() + 1;
|
||||
$sequence_number = FormOthers::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-OTH-' . date('ym') . '%')->count() + 1;
|
||||
$formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT);
|
||||
$expense_number = $region->code . '-' . $cabang->code . '-OTH-' . date('ym') . $formatted_sequence_number;
|
||||
|
||||
@@ -291,6 +294,7 @@ class FormOtherController extends Controller
|
||||
$form = FormOthers::create([
|
||||
'expense_number' => $expense_number,
|
||||
'user_id' => auth()->user()->id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID BARU
|
||||
'kategori_id' => $request->kategori_id,
|
||||
'tanggal' => $request->tanggal,
|
||||
'keterangan' => $request->keterangan,
|
||||
@@ -400,10 +404,10 @@ class FormOtherController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Other (' . $expense_number . ')');
|
||||
session()->flash('success', 'Form has been created.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
public function edit($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.other.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -413,15 +417,15 @@ class FormOtherController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
return view('backend.pages.forms.other.edit', [
|
||||
return view('backend.pages.forms.other.edit', [
|
||||
'form' => $form,
|
||||
'kategori' => Kategori::whereNotIn('name', $this->excludedKategoriNames)->get(),
|
||||
'attachments' => $this->formatAttachmentCollection($form),
|
||||
'attachmentCategories' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.other.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
@@ -438,10 +442,28 @@ class FormOtherController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Hitung periode dari tanggal input
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
// Hitung periode budget dari tanggal input
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -465,7 +487,7 @@ class FormOtherController extends Controller
|
||||
'nullable',
|
||||
'file',
|
||||
'max:10240',
|
||||
'mimetypes:image/jpeg,image/png,image/webp,application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain,text/csv,application/zip,application/x-zip-compressed,application/x-7z-compressed,application/vnd.rar,application/octet-stream'
|
||||
'mimetypes:image/jpeg,image/png,image/webp,application/pdf,application/msword,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,text/plain,text/csv,application/zip,application/x-zip-compressed,application/x-7z-compressed,application/vnd.rar,application/octet-stream'
|
||||
],
|
||||
]);
|
||||
|
||||
@@ -495,10 +517,12 @@ class FormOtherController extends Controller
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/other';
|
||||
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
|
||||
$primaryAttachmentPath = !empty($attachmentsPayload) ? $attachmentsPayload[0]['file_path'] : null;
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$form->update([
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID TERBARU
|
||||
'kategori_id' => $request->kategori_id,
|
||||
'tanggal' => $request->tanggal,
|
||||
'keterangan' => $request->keterangan,
|
||||
@@ -752,7 +776,8 @@ class FormOtherController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function finalApprove($id)
|
||||
// <--- REPARASI SUNTIKAN OBJECT REQUEST HASIL CHECKLIST JAVASCRIPT MODAL DILUAR
|
||||
public function finalApprove(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
||||
$form = FormOthers::findOrFail($id);
|
||||
@@ -781,14 +806,18 @@ class FormOtherController extends Controller
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// Ambil sisa budget
|
||||
// <--- REPARASI: Penangkapan nilai payload dari checkbox JavaScript
|
||||
$approvedTotal = $request->input('approved_total', $form->total);
|
||||
|
||||
// Ambil sisa budget dan sinkronkan validasinya dengan nominal dinamis terbaru
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
if($form->approved_total > $availableBudget) {
|
||||
if($approvedTotal > $availableBudget) {
|
||||
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$form->update([
|
||||
'approved_total' => $approvedTotal, // <--- SUNTIK NOMINAL BARU HASIL CHECKLIST DARI JAVASCRIPT KE DB
|
||||
'final_approved_at' => now(),
|
||||
'final_approved_by' => auth()->user()->id,
|
||||
'status' => 'Closed',
|
||||
@@ -797,7 +826,7 @@ class FormOtherController extends Controller
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$total = $form->approved_total;
|
||||
$total = $form->approved_total; // <--- SEKARANG MENGGUNAKAN DATA UPDATE TERBARU
|
||||
|
||||
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
||||
$recipients = [$form->user->email, auth()->user()->email];
|
||||
@@ -870,71 +899,60 @@ class FormOtherController extends Controller
|
||||
|
||||
public function reject(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
||||
if (!auth()->user()->hasAnyPermission(['approval.reject', 'approval2.reject', 'final_approval.approve'])) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki izin untuk melakukan Reject.');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'remarks' => 'required|string|max:500',
|
||||
'remarks' => 'required|string|max:500',
|
||||
]);
|
||||
|
||||
$form = FormOthers::findOrfail($id);
|
||||
|
||||
$form->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'rejected_by' => auth()->id(), // Kolom baru
|
||||
'rejected_at' => now(), // Kolom baru
|
||||
]);
|
||||
|
||||
$heads = $form->user->getCabangAndRegionHead();
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$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'];
|
||||
$recipients[] = $heads['cabang_head']['email'];
|
||||
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
||||
}
|
||||
|
||||
if ($heads['region_head']) {
|
||||
$recipients[] = $heads['region_head']['email'];
|
||||
$phoneNumbers[] = $heads['region_head']['phone'];
|
||||
$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.other.view', $form->id);
|
||||
$url = route('forms.others.view', $form->id);
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks);
|
||||
|
||||
// Send bulk email
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url,
|
||||
$request->remarks
|
||||
);
|
||||
|
||||
$response = $brevoService->expenseRejected($recipient, $name, $mail);
|
||||
|
||||
if (isset($response['success']) && $response['success'] === false) {
|
||||
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
||||
try {
|
||||
$mail = new ExpenseRejected($name, $expense_number, $tanggal, $total, $url, $request->remarks);
|
||||
$brevoService->expenseRejected($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Other (' . $form->expense_number . ')');
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Others (' . $form->expense_number . ') oleh ' . auth()->user()->name);
|
||||
session()->flash('success', 'Form has been rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
@@ -955,12 +973,12 @@ class FormOtherController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.other.delete']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
$form = FormOthers::findOrfail($id);
|
||||
$form = FormOthers::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();
|
||||
@@ -968,11 +986,11 @@ class FormOtherController extends Controller
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Other (' . $form->expense_number . ')');
|
||||
|
||||
$form->delete();
|
||||
$form->delete();
|
||||
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
protected function formatAttachmentCollection(FormOthers $form): array
|
||||
{
|
||||
@@ -1075,4 +1093,4 @@ class FormOtherController extends Controller
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,7 @@ class FormUpCountryController extends Controller
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
|
||||
// Current time reference
|
||||
$now = Carbon::now();
|
||||
@@ -190,20 +190,20 @@ class FormUpCountryController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.country.create']);
|
||||
$rayons = $this->getAccessibleRayonsForCurrentUser();
|
||||
|
||||
return view('backend.pages.forms.upcountry.create', [
|
||||
'rayons' => $rayons,
|
||||
return view('backend.pages.forms.upcountry.create', [
|
||||
'rayons' => $rayons,
|
||||
'attachmentCategories' => array_keys($this->attachmentCategories),
|
||||
'attachmentCategoryLabels' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.country.create']);
|
||||
$request->validate([
|
||||
'rayon_id' => 'required|exists:rayon,id',
|
||||
@@ -221,23 +221,24 @@ class FormUpCountryController extends Controller
|
||||
]);
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// SINKRONISASI JENDELA INPUT ATURAN BISNIS: 11 s/d 10 Bulan Berikutnya
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_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);
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// 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();
|
||||
// Blokade Sistem: Tolak input jika berada di luar siklus pengisian aktif
|
||||
if ($now->lt($startDate) || $now->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, pengajuan saat ini sudah ditutup. Periode pengisian aktif hanya diizinkan dari tanggal {$startDay} sampai tanggal {$inputMaxDay} berikutnya.");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', auth()->user()->id)->first()?->cabang;
|
||||
@@ -247,7 +248,9 @@ class FormUpCountryController extends Controller
|
||||
}
|
||||
|
||||
$region = Region::find($cabang->region_id);
|
||||
$kategori = Kategori::where('name', 'Up Country')->first();
|
||||
|
||||
// Optimasi pencarian kategori menggunakan LIKE fleksibel untuk menjamin ID ditemukan
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Up Country%')->first();
|
||||
|
||||
// Hitung periode budget dari tanggal input
|
||||
if ($tanggal->day >= $startDay) {
|
||||
@@ -301,6 +304,8 @@ class FormUpCountryController extends Controller
|
||||
$form = FormUpCountry::create([
|
||||
'expense_number' => $expense_number,
|
||||
'user_id' => auth()->user()->id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI: Memasukkan Cabang ID milik user pengaju secara instan
|
||||
'kategori_id' => $kategori->id ?? null, // SUNTIK KATEGORI_ID OTOMATIS BERHASIL
|
||||
'rayon_id' => $request->rayon_id,
|
||||
'tanggal' => $request->tanggal,
|
||||
'tujuan' => $request->tujuan,
|
||||
@@ -315,14 +320,14 @@ class FormUpCountryController extends Controller
|
||||
'bukti_transport_ankot' => null,
|
||||
'bukti_hotel' => null,
|
||||
'uc_plan' => $ucPlanPath,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? null,
|
||||
'status' => 'On Progress',
|
||||
]);
|
||||
|
||||
if (!empty($attachmentsPayload)) {
|
||||
$this->attachmentService->addMultipleAttachments(
|
||||
$form->id,
|
||||
AttachmentTableName::FORM_UP_COUNTRY,
|
||||
$dynamicTable = AttachmentTableName::FORM_UP_COUNTRY,
|
||||
$attachmentsPayload
|
||||
);
|
||||
}
|
||||
@@ -359,11 +364,11 @@ class FormUpCountryController extends Controller
|
||||
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
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$user->cabang || !$user->cabang->cabang) {
|
||||
return false; // Pastikan user memiliki cabang
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
||||
@@ -417,10 +422,10 @@ class FormUpCountryController extends Controller
|
||||
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)
|
||||
{
|
||||
public function edit($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.country.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -453,14 +458,14 @@ class FormUpCountryController extends Controller
|
||||
];
|
||||
})->values();
|
||||
|
||||
return view('backend.pages.forms.upcountry.edit', [
|
||||
'rayons' => $rayonData,
|
||||
return view('backend.pages.forms.upcountry.edit', [
|
||||
'rayons' => $rayonData,
|
||||
'form' => $form,
|
||||
'attachments' => $existingAttachments,
|
||||
'attachmentCategories' => array_keys($this->attachmentCategories),
|
||||
'attachmentCategoryLabels' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
protected function getAccessibleRayonsForCurrentUser()
|
||||
{
|
||||
@@ -494,7 +499,7 @@ class FormUpCountryController extends Controller
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.country.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -525,12 +530,31 @@ class FormUpCountryController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
if ($now->lt($startDate) || $now->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, pengajuan saat ini sudah ditutup. Periode pengisian aktif hanya diizinkan dari tanggal {$startDay} sampai tanggal {$inputMaxDay} berikutnya.");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
$region = Region::find($cabang->region_id);
|
||||
$kategori = Kategori::where('name', 'Up Country')->first();
|
||||
|
||||
// Optimasi pencarian kategori menggunakan LIKE fleksibel untuk menjamin ID ditemukan
|
||||
$kategori = Kategori::where('name', 'LIKE', '%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 {
|
||||
@@ -564,7 +588,7 @@ class FormUpCountryController extends Controller
|
||||
|
||||
// Validasi budget dengan periode
|
||||
$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.');
|
||||
return redirect()->back();
|
||||
}
|
||||
@@ -574,6 +598,8 @@ class FormUpCountryController extends Controller
|
||||
try {
|
||||
$form->update([
|
||||
'rayon_id' => $request->rayon_id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI: Memastikan Cabang ID tersimpan akurat saat update data
|
||||
'kategori_id' => $kategori->id ?? null, // RE-SUNTIK KATEGORI_ID SAAT UPDATE
|
||||
'tanggal' => $request->tanggal,
|
||||
'tujuan' => $request->tujuan,
|
||||
'jarak' => $request->jarak,
|
||||
@@ -583,7 +609,7 @@ class FormUpCountryController extends Controller
|
||||
'hotel' => $data_nominal['hotel'],
|
||||
'total' => $totalNominal,
|
||||
'uc_plan' => $ucPlanPath ?? $form->uc_plan,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? $form->account_number,
|
||||
]);
|
||||
|
||||
if (!empty($attachmentsPayload)) {
|
||||
@@ -609,7 +635,7 @@ class FormUpCountryController extends Controller
|
||||
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)
|
||||
{
|
||||
@@ -717,11 +743,11 @@ class FormUpCountryController extends Controller
|
||||
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
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$user->cabang || !$user->cabang->cabang) {
|
||||
return false; // Pastikan user memiliki cabang
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
||||
@@ -808,11 +834,11 @@ class FormUpCountryController extends Controller
|
||||
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
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$user->cabang || !$user->cabang->cabang) {
|
||||
return false; // Pastikan user memiliki cabang
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
||||
@@ -867,7 +893,7 @@ class FormUpCountryController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function finalApprove($id)
|
||||
public function finalApprove(Request $request, $id) // <--- MENAMBAHKAN OBJECT REQUEST
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
||||
$form = FormUpCountry::findOrFail($id);
|
||||
@@ -877,42 +903,61 @@ class FormUpCountryController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Ambil cabang_id dari user yang mengisi form
|
||||
// ATURAN BISNIS: Batas Akhir Approval adalah tanggal CLOSING_DATE (Bulan Depan tgl 13)
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$now = Carbon::now();
|
||||
$tanggalForm = Carbon::parse($form->tanggal);
|
||||
|
||||
// Hitung batas maksimal closing sesuai siklus transaksi form tersebut
|
||||
if ($tanggalForm->day >= $startDay) {
|
||||
$maxClosingDate = Carbon::create($tanggalForm->year, $tanggalForm->month, $closingDay)->addMonth()->endOfDay();
|
||||
} else {
|
||||
$maxClosingDate = Carbon::create($tanggalForm->year, $tanggalForm->month, $closingDay)->endOfDay();
|
||||
}
|
||||
|
||||
if ($now->gt($maxClosingDate)) {
|
||||
session()->flash('error', "Gagal, Batas waktu maksimal approval (Closing Date) untuk pengajuan ini telah berakhir pada {$maxClosingDate->format('d M Y H:i')} WIB.");
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$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);
|
||||
if ($tanggalForm->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggalForm->year, $tanggalForm->month, $startDay);
|
||||
} else {
|
||||
$periodeDate = Carbon::create($tanggal->copy()->subMonth()->year, $tanggal->copy()->subMonth()->month, $startDay);
|
||||
$periodeDate = Carbon::create($tanggalForm->copy()->subMonth()->year, $tanggalForm->copy()->subMonth()->month, $startDay);
|
||||
}
|
||||
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// MENGAMBIL NILAI AKUMULASI CHECKLIST DARI JAVASCRIPT JS (Fallback ke total awal jika kosong)
|
||||
$approvedTotal = $request->input('approved_total', $form->total);
|
||||
|
||||
// Ambil sisa budget sesuai periode
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
if($form->approved_total > $availableBudget) {
|
||||
if($approvedTotal > $availableBudget) { // <--- DISINKRONKAN DENGAN NILAI BARU HASIL CHECKLIST
|
||||
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// UPDATE DATABASE SECARA AKURAT BERDASARKAN HASIL PILIHAN CHECKLIST FINANCE
|
||||
$form->update([
|
||||
'approved_total' => $approvedTotal, // <--- SUNTIK NOMINAL BARU HASIL CHECKLIST KE DATABASE
|
||||
'final_approved_at' => now(),
|
||||
'final_approved_by' => auth()->user()->id,
|
||||
'status' => 'Closed',
|
||||
'status' => 'Closed',
|
||||
]);
|
||||
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->tanggal;
|
||||
$total = $form->approved_total;
|
||||
$total = $form->approved_total; // <--- OTOMATIS MEMAKAI DATA UPDATE TERBARU
|
||||
|
||||
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
||||
$recipients = [$form->user->email, auth()->user()->email];
|
||||
@@ -927,11 +972,11 @@ class FormUpCountryController extends Controller
|
||||
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
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$user->cabang || !$user->cabang->cabang) {
|
||||
return false; // Pastikan user memiliki cabang
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($role === 'Admin Region' || $role === 'Marketing Operational Manager Region') {
|
||||
@@ -985,16 +1030,21 @@ class FormUpCountryController extends Controller
|
||||
|
||||
public function reject(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
||||
if (!auth()->user()->hasAnyPermission(['approval.reject', 'approval2.reject', 'final_approval.approve'])) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki izin untuk melakukan Reject.');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'remarks' => 'required|string|max:500',
|
||||
'remarks' => 'required|string|max:500',
|
||||
]);
|
||||
|
||||
$form = FormUpCountry::findOrfail($id);
|
||||
|
||||
$form->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'rejected_by' => auth()->id(), // SUNTIK DATA AUDIT TRAIL
|
||||
'rejected_at' => now(), // SUNTIK DATA AUDIT TRAIL
|
||||
]);
|
||||
|
||||
$heads = $form->user->getCabangAndRegionHead();
|
||||
@@ -1003,53 +1053,37 @@ class FormUpCountryController extends Controller
|
||||
$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'];
|
||||
$recipients[] = $heads['cabang_head']['email'];
|
||||
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
||||
}
|
||||
|
||||
if ($heads['region_head']) {
|
||||
$recipients[] = $heads['region_head']['email'];
|
||||
$phoneNumbers[] = $heads['region_head']['phone'];
|
||||
$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);
|
||||
$url = route('forms.up-country.view', $form->id);
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks);
|
||||
|
||||
// Send bulk email
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url,
|
||||
$request->remarks
|
||||
);
|
||||
|
||||
$response = $brevoService->expenseRejected($recipient, $name, $mail);
|
||||
|
||||
if (isset($response['success']) && $response['success'] === false) {
|
||||
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
||||
try {
|
||||
$mail = new ExpenseRejected($name, $expense_number, $tanggal, $total, $url, $request->remarks);
|
||||
$brevoService->expenseRejected($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
} 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 . ')');
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Up Country (' . $form->expense_number . ') oleh ' . auth()->user()->name);
|
||||
session()->flash('success', 'Form has been rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
@@ -1070,12 +1104,12 @@ class FormUpCountryController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.country.delete']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
$form = FormUpCountry::findOrfail($id);
|
||||
$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();
|
||||
@@ -1083,9 +1117,9 @@ class FormUpCountryController extends Controller
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Up Country (' . $form->expense_number . ')');
|
||||
|
||||
$form->delete();
|
||||
$form->delete();
|
||||
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ class FormVehicleController extends Controller
|
||||
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$closingDay = (int) env('CLOSING_DATE', 13);
|
||||
|
||||
// Referensi waktu sekarang
|
||||
$now = Carbon::now();
|
||||
@@ -173,17 +173,17 @@ class FormVehicleController extends Controller
|
||||
]);
|
||||
}
|
||||
|
||||
public function create()
|
||||
{
|
||||
public function create()
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.vehicle.create']);
|
||||
|
||||
return view('backend.pages.forms.vehicle.create', [
|
||||
return view('backend.pages.forms.vehicle.create', [
|
||||
'attachmentCategories' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
public function store(Request $request)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.vehicle.create']);
|
||||
$validator = Validator::make($request->all(), [
|
||||
'tanggal' => 'required',
|
||||
@@ -226,23 +226,27 @@ class FormVehicleController extends Controller
|
||||
$validator->validate();
|
||||
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
// Tentukan periode input berdasarkan waktu saat ini
|
||||
// Tentukan periode aktif berdasarkan tanggal 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);
|
||||
// Jendela Aktif: Tgl 11 Bulan Ini s/d Tgl 10 Bulan Depan
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay);
|
||||
$closingDate = Carbon::create($now->year, $now->month, $closingDay);
|
||||
// Jendela Aktif: Tgl 11 Bulan Lalu s/d Tgl 10 Bulan Ini
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal form berada dalam periode input
|
||||
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();
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
// Ambil cabang user
|
||||
@@ -252,7 +256,7 @@ class FormVehicleController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Tentukan periode budget berdasarkan tanggal input (bukan now)
|
||||
// Tentukan periode budget dari tanggal input
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -266,18 +270,19 @@ class FormVehicleController extends Controller
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
||||
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();
|
||||
$kategori = Kategori::where('name', 'Vehicle Running Cost')->first();
|
||||
// REPARASI SUNTIK KATEGORI: Penggunaan LIKE untuk toleransi kecocokan spasi
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Vehicle Running Cost%')->first();
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/vehicle';
|
||||
|
||||
$attachmentsPayload = $this->buildAttachmentPayload($request, $folderPath);
|
||||
|
||||
// Generate sequence number and expense number
|
||||
$sequence_number = FormVehicleRunningCost::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-VHC-' . date('ym') . '%')->count() + 1;
|
||||
$sequence_number = FormVehicleRunningCost::withTrashed()->where('expense_number', 'like', $region->code . '-' . $cabang->code . '-VHC-' . date('ym') . '%')->count() + 1;
|
||||
$formatted_sequence_number = str_pad($sequence_number, 4, '0', STR_PAD_LEFT);
|
||||
$expense_number = $region->code . '-' . $cabang->code . '-VHC-' . date('ym') . $formatted_sequence_number;
|
||||
|
||||
@@ -286,6 +291,8 @@ class FormVehicleController extends Controller
|
||||
$form = FormVehicleRunningCost::create([
|
||||
'expense_number' => $expense_number,
|
||||
'user_id' => auth()->user()->id,
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG ID
|
||||
'kategori_id' => $kategori->id ?? null, // <--- REPARASI SUNTIK KATEGORI ID
|
||||
'tanggal' => $request->tanggal,
|
||||
'type' => $request->type,
|
||||
'liter' => $request->liter ?? 0,
|
||||
@@ -295,7 +302,7 @@ class FormVehicleController extends Controller
|
||||
'nopol' => $request->nopol ?? '-',
|
||||
'keterangan' => $request->keterangan,
|
||||
'bukti_total' => null,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? null,
|
||||
'status' => 'On Progress',
|
||||
]);
|
||||
|
||||
@@ -399,10 +406,10 @@ class FormVehicleController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Insert', 'Insert New Expense at Form Vehicle Running Cost (' . $expense_number . ')');
|
||||
session()->flash('success', 'Form has been created.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function edit($id)
|
||||
{
|
||||
public function edit($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.vehicle.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
@@ -412,30 +419,48 @@ class FormVehicleController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
return view('backend.pages.forms.vehicle.edit', [
|
||||
return view('backend.pages.forms.vehicle.edit', [
|
||||
'form' => $form,
|
||||
'attachments' => $this->formatAttachmentCollection($form),
|
||||
'attachmentCategories' => $this->attachmentCategories,
|
||||
]);
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
public function update(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.vehicle.edit']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
$form = FormVehicleRunningCost::with('attachments')->findOrFail($id);
|
||||
|
||||
// Ambil cabang ID dari user yang mengisi form
|
||||
$cabang_id = UserHasCabang::where('user_id', $form->user_id)->first()?->cabang_id;
|
||||
if (!$cabang_id) {
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()?->cabang;
|
||||
if (!$cabang) {
|
||||
session()->flash('error', 'Data cabang tidak ditemukan.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
// Hitung periode berdasarkan tanggal input
|
||||
$tanggal = Carbon::parse($request->tanggal);
|
||||
|
||||
// PEMBATASAN INPUT MENGGUNAKAN STARTING_DATE & INPUT_MAX_DATE
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$inputMaxDay = (int) env('INPUT_MAX_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$startDate = Carbon::create($now->year, $now->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->copy()->addMonth()->year, $now->copy()->addMonth()->month, $inputMaxDay)->endOfDay();
|
||||
} else {
|
||||
$startDate = Carbon::create($now->copy()->subMonth()->year, $now->copy()->subMonth()->month, $startDay)->startOfDay();
|
||||
$maxInputDate = Carbon::create($now->year, $now->month, $inputMaxDay)->endOfDay();
|
||||
}
|
||||
|
||||
// Validasi apakah tanggal pengajuan masuk ke periode input saat ini
|
||||
if ($tanggal->lt($startDate) || $tanggal->gt($maxInputDate)) {
|
||||
session()->flash('error', "Gagal, tanggal expense tidak berada dalam batas waktu input yang diizinkan: {$startDate->format('d M Y')} - {$maxInputDate->format('d M Y')}");
|
||||
return redirect()->back()->withInput();
|
||||
}
|
||||
|
||||
// Hitung periode dari tanggal form yang diinput
|
||||
if ($tanggal->day >= $startDay) {
|
||||
$periodeDate = Carbon::create($tanggal->year, $tanggal->month, $startDay);
|
||||
} else {
|
||||
@@ -446,7 +471,7 @@ class FormVehicleController extends Controller
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// Hitung sisa budget
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang->id, $periodeMonth, $periodeYear);
|
||||
|
||||
// Validasi input
|
||||
$validator = Validator::make($request->all(), [
|
||||
@@ -494,9 +519,9 @@ class FormVehicleController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$cabang = UserHasCabang::with('cabang')->where('user_id', $form->user_id)->first()->cabang;
|
||||
$region = Region::where('id', $cabang->region_id)->first();
|
||||
$kategori = Kategori::where('name', 'Vehicle Running Cost')->first();
|
||||
// REPARASI SUNTIK KATEGORI_ID SAAT UPDATE
|
||||
$kategori = Kategori::where('name', 'LIKE', '%Vehicle Running Cost%')->first();
|
||||
|
||||
$folderPath = '/expense/' . $region->code . '/' . $cabang->code . '/vehicle';
|
||||
|
||||
@@ -505,6 +530,8 @@ class FormVehicleController extends Controller
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$form->update([
|
||||
'cabang_id' => $cabang->id, // <--- REPARASI SUNTIK CABANG_ID
|
||||
'kategori_id' => $kategori->id ?? null, // <--- REPARASI SUNTIK KATEGORI_ID
|
||||
'tanggal' => $request->tanggal,
|
||||
'type' => $request->type,
|
||||
'liter' => $request->liter ?? 0,
|
||||
@@ -514,7 +541,7 @@ class FormVehicleController extends Controller
|
||||
'nopol' => $request->nopol ?? '-',
|
||||
'keterangan' => $request->keterangan,
|
||||
'bukti_total' => $form->bukti_total,
|
||||
'account_number' => $kategori->account_number,
|
||||
'account_number' => $kategori->account_number ?? $form->account_number,
|
||||
'status' => 'On Progress',
|
||||
]);
|
||||
|
||||
@@ -542,7 +569,7 @@ class FormVehicleController extends Controller
|
||||
AuditTrailHelper::AddAuditTrail('Update', 'Update Record at Form Vehicle Running Cost (' . $form->expense_number . ')');
|
||||
session()->flash('success', 'Form has been updated.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteAttachment(Request $request, $formId, $attachmentId)
|
||||
{
|
||||
@@ -755,7 +782,8 @@ class FormVehicleController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function finalApprove($id)
|
||||
// <--- REPARASI SUNTIKAN REQUEST DARI JAVASCRIPT MODAL AGAR DATA BISA DIAMBIL
|
||||
public function finalApprove(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['final_approval.approve']);
|
||||
$form = FormVehicleRunningCost::findOrFail($id);
|
||||
@@ -785,23 +813,27 @@ class FormVehicleController extends Controller
|
||||
$periodeMonth = strtolower($periodeDate->format('F'));
|
||||
$periodeYear = (int) $periodeDate->format('Y');
|
||||
|
||||
// Hitung sisa budget cabang di periode tersebut
|
||||
// <--- REPARASI: Penangkapan nilai payload dari checkbox JavaScript
|
||||
$approvedTotal = $request->input('approved_total', $form->total);
|
||||
|
||||
// Hitung sisa budget cabang di periode tersebut disinkronisasi dengan variabel kalkulasi terbaru
|
||||
$availableBudget = BudgetHelper::getAvailableBudget($cabang_id, $periodeMonth, $periodeYear);
|
||||
if($form->approved_total > $availableBudget) {
|
||||
if($approvedTotal > $availableBudget) {
|
||||
session()->flash('error', 'Budget cabang untuk periode ini tidak mencukupi, silahkan ajukan pada periode expense berikutnya');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
$form->update([
|
||||
'approved_total' => $approvedTotal, // <--- SUNTIK DATA UPDATE HASIL CHECKLIST
|
||||
'final_approved_at' => now(),
|
||||
'final_approved_by' => auth()->user()->id,
|
||||
'status' => 'Closed',
|
||||
'status' => 'Closed',
|
||||
]);
|
||||
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$total = $form->approved_total;
|
||||
$total = $form->approved_total; // <--- TOTAL BARU YANG DIKIRIMKAN KE EMAIL / WHATSAPP
|
||||
|
||||
$roles = ['Head of Sales Marketing', 'Marketing Operational Manager Region'];
|
||||
$recipients = [$form->user->email, auth()->user()->email];
|
||||
@@ -874,75 +906,64 @@ class FormVehicleController extends Controller
|
||||
}
|
||||
|
||||
public function reject(Request $request, $id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['approval.reject']);
|
||||
{
|
||||
if (!auth()->user()->hasAnyPermission(['approval.reject', 'approval2.reject', 'final_approval.approve'])) {
|
||||
abort(403, 'Akses Ditolak: Anda tidak memiliki izin untuk melakukan Reject.');
|
||||
}
|
||||
|
||||
$request->validate([
|
||||
'remarks' => 'required|string|max:500',
|
||||
'remarks' => 'required|string|max:500',
|
||||
]);
|
||||
|
||||
$form = FormVehicleRunningCost::findOrfail($id);
|
||||
|
||||
$form->update([
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
]);
|
||||
'status' => 'Rejected',
|
||||
'remarks' => $request->remarks,
|
||||
'rejected_by' => auth()->id(), // Kolom baru
|
||||
'rejected_at' => now(), // Kolom baru
|
||||
]);
|
||||
|
||||
$heads = $form->user->getCabangAndRegionHead();
|
||||
$name = $form->user->name;
|
||||
$expense_number = $form->expense_number;
|
||||
$tanggal = $form->created_at;
|
||||
$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'];
|
||||
$recipients[] = $heads['cabang_head']['email'];
|
||||
$phoneNumbers[] = $heads['cabang_head']['phone'];
|
||||
}
|
||||
|
||||
if ($heads['region_head']) {
|
||||
$recipients[] = $heads['region_head']['email'];
|
||||
$phoneNumbers[] = $heads['region_head']['phone'];
|
||||
$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.vehicle.view', $form->id);
|
||||
WhatsappHelper::rejectExpense($phoneNumbers, $expense_number, $url, $tanggal, $total, $name, $request->remarks);
|
||||
|
||||
// Send bulk email
|
||||
$brevoService = app(BrevoService::class);
|
||||
foreach ($recipients as $recipient) {
|
||||
try {
|
||||
$mail = new ExpenseRejected(
|
||||
$name,
|
||||
$expense_number,
|
||||
$tanggal,
|
||||
$total,
|
||||
$url,
|
||||
$request->remarks
|
||||
);
|
||||
|
||||
$response = $brevoService->expenseRejected($recipient, $name, $mail);
|
||||
|
||||
if (isset($response['success']) && $response['success'] === false) {
|
||||
Log::warning("Email to {$recipient} failed: " . ($response['message'] ?? 'Unknown error'));
|
||||
try {
|
||||
$mail = new ExpenseRejected($name, $expense_number, $tanggal, $total, $url, $request->remarks);
|
||||
$brevoService->expenseRejected($recipient, $name, $mail);
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
Log::error("Failed to send email to {$recipient}: " . $e->getMessage());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Vehicle Running Cost (' . $form->expense_number . ')');
|
||||
AuditTrailHelper::AddAuditTrail('Reject', 'Reject Expense at Form Vehicle Running Cost (' . $form->expense_number . ') oleh ' . auth()->user()->name);
|
||||
session()->flash('success', 'Form has been rejected.');
|
||||
return redirect()->back();
|
||||
}
|
||||
}
|
||||
|
||||
public function open($id)
|
||||
{
|
||||
@@ -960,12 +981,12 @@ class FormVehicleController extends Controller
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
public function destroy($id)
|
||||
{
|
||||
$this->checkAuthorization(auth()->user(), ['forms.vehicle.delete']);
|
||||
$role = auth()->user()->getRoleNames()[0];
|
||||
|
||||
$form = FormVehicleRunningCost::findOrfail($id);
|
||||
$form = FormVehicleRunningCost::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();
|
||||
@@ -973,11 +994,11 @@ class FormVehicleController extends Controller
|
||||
|
||||
AuditTrailHelper::AddAuditTrail('Delete', 'Delete Record at Form Vehicle Running Cost (' . $form->expense_number . ')');
|
||||
|
||||
$form->delete();
|
||||
$form->delete();
|
||||
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
session()->flash('success', 'Form has been deleted.');
|
||||
return redirect()->back();
|
||||
}
|
||||
|
||||
protected function formatAttachmentCollection(FormVehicleRunningCost $form): array
|
||||
{
|
||||
@@ -1080,4 +1101,4 @@ class FormVehicleController extends Controller
|
||||
|
||||
return $payload;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,8 @@ class BudgetControl extends Model
|
||||
'transferred_at',
|
||||
'closing_at',
|
||||
'status',
|
||||
'transfer_proof',
|
||||
'transfer_status',
|
||||
];
|
||||
|
||||
public function user()
|
||||
|
||||
@@ -7,7 +7,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class FormEntertaimentPresentation extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
use SoftDeletes, \App\Traits\HasAttachments;
|
||||
|
||||
protected $table = 'form_entertainment_presentation';
|
||||
protected $fillable = [
|
||||
@@ -31,17 +31,40 @@ class FormEntertaimentPresentation extends Model
|
||||
'approved2_by',
|
||||
'final_approved_at',
|
||||
'final_approved_by',
|
||||
// Kolom baru
|
||||
'jabatan',
|
||||
'nama_perusahaan',
|
||||
'jenis_usaha',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'created_at' => 'datetime',
|
||||
'approved_at' => 'datetime',
|
||||
'approved2_at' => 'datetime',
|
||||
'final_approved_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo('App\Models\Admin');
|
||||
}
|
||||
|
||||
public function attachments()
|
||||
{
|
||||
return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
->where('table_name', \App\Enums\AttachmentTableName::FORM_ENTERTAINMENT_PRESENTATION);
|
||||
}
|
||||
// Relasi ke kategori untuk mengambil account_number
|
||||
public function kategori()
|
||||
{
|
||||
return $this->belongsTo(Kategori::class, 'kategori_id');
|
||||
}
|
||||
|
||||
public function rejector() {
|
||||
return $this->belongsTo(User::class, 'rejected_by');
|
||||
}
|
||||
|
||||
// public function attachments()
|
||||
// {
|
||||
// // form_id adalah kolom di tabel attachment_forms
|
||||
// // table_name digunakan jika satu tabel attachment dipakai banyak form
|
||||
// return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
// ->where('table_name', 'form_entertainment_presentation');
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
@@ -4,46 +4,53 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class FormMeetingSeminar extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'form_meeting_seminar';
|
||||
|
||||
protected $fillable = [
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'tanggal',
|
||||
'allowance',
|
||||
'transport_ankot',
|
||||
'hotel',
|
||||
'total',
|
||||
'approved_allowance',
|
||||
'approved_transport_ankot',
|
||||
'approved_hotel',
|
||||
'approved_total',
|
||||
'bukti_allowance',
|
||||
'bukti_transport_ankot',
|
||||
'bukti_hotel',
|
||||
'account_number',
|
||||
'status',
|
||||
'remarks',
|
||||
'approved_at',
|
||||
'approved2_at',
|
||||
'approved_by',
|
||||
'approved2_by',
|
||||
'final_approved_at',
|
||||
'expense_number', 'user_id', 'tanggal', 'allowance', 'transport_ankot',
|
||||
'hotel', 'total', 'approved_allowance', 'approved_transport_ankot',
|
||||
'approved_hotel', 'approved_total', 'bukti_allowance', 'bukti_transport_ankot',
|
||||
'bukti_hotel', 'account_number', 'status', 'remarks', 'approved_at',
|
||||
'approved2_at', 'approved_by', 'approved2_by', 'final_approved_at',
|
||||
'final_approved_by',
|
||||
];
|
||||
|
||||
public function user()
|
||||
/**
|
||||
* Casts untuk otomatisasi format Carbon pada tanggal agar konsisten di Blade.
|
||||
*/
|
||||
protected $casts = [
|
||||
'tanggal' => 'date',
|
||||
'final_approved_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Relasi ke Admin (Pengaju).
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Admin::class, 'user_id');
|
||||
}
|
||||
|
||||
public function attachments()
|
||||
/**
|
||||
* Relasi ke Attachments (Dokumen Digital) sesuai pola Entertainment.
|
||||
*/
|
||||
public function attachments(): HasMany
|
||||
{
|
||||
return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
return $this->hasMany(AttachmentForm::class, 'form_id')
|
||||
->where('table_name', \App\Enums\AttachmentTableName::FORM_MEETING_SEMINAR);
|
||||
}
|
||||
|
||||
public function rejector() {
|
||||
return $this->belongsTo(User::class, 'rejected_by');
|
||||
}
|
||||
|
||||
}
|
||||
+35
-22
@@ -4,6 +4,8 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class FormOthers extends Model
|
||||
{
|
||||
@@ -11,38 +13,49 @@ class FormOthers extends Model
|
||||
|
||||
protected $table = 'form_others';
|
||||
protected $fillable = [
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'kategori_id',
|
||||
'tanggal',
|
||||
'keterangan',
|
||||
'total',
|
||||
'approved_total',
|
||||
'bukti_total',
|
||||
'account_number',
|
||||
'status',
|
||||
'remarks',
|
||||
'approved_at',
|
||||
'approved2_at',
|
||||
'approved_by',
|
||||
'approved2_by',
|
||||
'final_approved_at',
|
||||
'final_approved_by',
|
||||
'expense_number', 'user_id', 'kategori_id', 'tanggal', 'keterangan',
|
||||
'total', 'approved_total', 'bukti_total', 'account_number', 'status',
|
||||
'remarks', 'approved_at', 'approved2_at', 'approved_by', 'approved2_by',
|
||||
'final_approved_at', 'final_approved_by',
|
||||
];
|
||||
|
||||
public function user()
|
||||
/**
|
||||
* Casts untuk otomatisasi format Carbon pada tanggal agar konsisten di Blade.
|
||||
*/
|
||||
protected $casts = [
|
||||
'tanggal' => 'date',
|
||||
'final_approved_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Relasi ke Admin (Pengaju).
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Admin::class);
|
||||
return $this->belongsTo(Admin::class, 'user_id');
|
||||
}
|
||||
|
||||
public function kategori()
|
||||
/**
|
||||
* Relasi ke Kategori.
|
||||
*/
|
||||
public function kategori(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Kategori::class);
|
||||
return $this->belongsTo(Kategori::class, 'kategori_id');
|
||||
}
|
||||
|
||||
public function attachments()
|
||||
/**
|
||||
* Relasi ke Attachments (Dokumen Digital) sesuai pola Entertainment.
|
||||
*/
|
||||
public function attachments(): HasMany
|
||||
{
|
||||
return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
->where('table_name', \App\Enums\AttachmentTableName::FORM_OTHERS);
|
||||
}
|
||||
|
||||
public function rejector() {
|
||||
return $this->belongsTo(User::class, 'rejected_by');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -4,58 +4,61 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class FormUpCountry extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'form_up_country';
|
||||
|
||||
protected $fillable = [
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'rayon_id',
|
||||
'tanggal',
|
||||
'tujuan',
|
||||
'jarak',
|
||||
'allowance',
|
||||
'transport_dalkot',
|
||||
'transport_ankot',
|
||||
'hotel',
|
||||
'total',
|
||||
'approved_allowance',
|
||||
'approved_transport_dalkot',
|
||||
'approved_transport_ankot',
|
||||
'approved_hotel',
|
||||
'approved_total',
|
||||
'bukti_allowance',
|
||||
'bukti_transport_dalkot',
|
||||
'bukti_transport_ankot',
|
||||
'bukti_hotel',
|
||||
'uc_plan',
|
||||
'account_number',
|
||||
'status',
|
||||
'remarks',
|
||||
'approved_at',
|
||||
'approved2_at',
|
||||
'approved_by',
|
||||
'approved2_by',
|
||||
'final_approved_at',
|
||||
'final_approved_by',
|
||||
'expense_number', 'user_id', 'rayon_id', 'tanggal', 'tujuan', 'jarak',
|
||||
'allowance', 'transport_dalkot', 'transport_ankot', 'hotel', 'total',
|
||||
'approved_allowance', 'approved_transport_dalkot', 'approved_transport_ankot',
|
||||
'approved_hotel', 'approved_total', 'bukti_allowance', 'bukti_transport_dalkot',
|
||||
'bukti_transport_ankot', 'bukti_hotel', 'uc_plan', 'account_number', 'status',
|
||||
'remarks', 'approved_at', 'approved2_at', 'approved_by', 'approved2_by',
|
||||
'final_approved_at', 'final_approved_by','cabang_id','kategori_id',
|
||||
];
|
||||
|
||||
public function user()
|
||||
/**
|
||||
* Casts untuk otomatisasi format Carbon pada tanggal.
|
||||
*/
|
||||
protected $casts = [
|
||||
'tanggal' => 'date',
|
||||
'final_approved_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Relasi ke Admin (Pengaju).
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo('App\Models\Admin');
|
||||
return $this->belongsTo(Admin::class, 'user_id');
|
||||
}
|
||||
|
||||
public function rayon()
|
||||
/**
|
||||
* Relasi ke Rayon.
|
||||
*/
|
||||
public function rayon(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo('App\Models\Rayon');
|
||||
return $this->belongsTo(Rayon::class, 'rayon_id');
|
||||
}
|
||||
|
||||
public function attachments()
|
||||
/**
|
||||
* Relasi ke Attachments (Dokumen Digital) sesuai pola Entertainment.
|
||||
*/
|
||||
public function attachments(): HasMany
|
||||
{
|
||||
return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
return $this->hasMany(AttachmentForm::class, 'form_id')
|
||||
->where('table_name', \App\Enums\AttachmentTableName::FORM_UP_COUNTRY);
|
||||
}
|
||||
|
||||
public function rejector() {
|
||||
return $this->belongsTo(User::class, 'rejected_by');
|
||||
}
|
||||
}
|
||||
@@ -4,44 +4,51 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
class FormVehicleRunningCost extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $table = 'form_vehicle_running_cost';
|
||||
|
||||
protected $fillable = [
|
||||
'expense_number',
|
||||
'user_id',
|
||||
'tanggal',
|
||||
'liter',
|
||||
'total',
|
||||
'approved_total',
|
||||
'jarak',
|
||||
'tipe_bensin',
|
||||
'nopol',
|
||||
'keterangan',
|
||||
'bukti_total',
|
||||
'account_number',
|
||||
'type',
|
||||
'status',
|
||||
'remarks',
|
||||
'approved_at',
|
||||
'approved2_at',
|
||||
'approved_by',
|
||||
'approved2_by',
|
||||
'final_approved_at',
|
||||
'final_approved_by',
|
||||
'expense_number', 'user_id', 'tanggal', 'liter', 'total', 'approved_total',
|
||||
'jarak', 'tipe_bensin', 'nopol', 'keterangan', 'bukti_total', 'account_number',
|
||||
'type', 'status', 'remarks', 'approved_at', 'approved2_at', 'approved_by',
|
||||
'approved2_by', 'final_approved_at', 'final_approved_by',
|
||||
];
|
||||
|
||||
public function user()
|
||||
/**
|
||||
* Casts untuk otomatisasi format Carbon pada tanggal.
|
||||
*/
|
||||
protected $casts = [
|
||||
'tanggal' => 'date',
|
||||
'final_approved_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
'updated_at' => 'datetime',
|
||||
];
|
||||
|
||||
/**
|
||||
* Relasi ke Admin (Pengaju)
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo('App\Models\Admin', 'user_id');
|
||||
return $this->belongsTo(Admin::class, 'user_id');
|
||||
}
|
||||
|
||||
public function attachments()
|
||||
/**
|
||||
* Relasi ke Attachments (Dokumen Digital)
|
||||
*/
|
||||
public function attachments(): HasMany
|
||||
{
|
||||
return $this->hasMany(\App\Models\AttachmentForm::class, 'form_id')
|
||||
return $this->hasMany(AttachmentForm::class, 'form_id')
|
||||
->where('table_name', \App\Enums\AttachmentTableName::FORM_VEHICLE_RUNNING_COST);
|
||||
}
|
||||
|
||||
public function rejector() {
|
||||
return $this->belongsTo(User::class, 'rejected_by');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class Transaction extends Model
|
||||
{
|
||||
use SoftDeletes;
|
||||
|
||||
protected $fillable = [
|
||||
'cabang_id', 'budget_control_id', 'transaction_date', 'reference_number',
|
||||
'description', 'amount', 'type', 'category', 'periode_month',
|
||||
'periode_year', 'created_by'
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'transaction_date' => 'date',
|
||||
'amount' => 'decimal:2',
|
||||
];
|
||||
|
||||
public function cabang() {
|
||||
return $this->belongsTo(Cabang::class);
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ class User extends Authenticatable
|
||||
'username',
|
||||
'password',
|
||||
'phone',
|
||||
'region_id',
|
||||
'cabang_id'
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -49,4 +51,42 @@ class User extends Authenticatable
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper untuk mendapatkan ID Cabang & Region milik user
|
||||
*/
|
||||
public function getMyCabangAndRegionId(): array
|
||||
{
|
||||
// Jika User punya cabang_id (Level AM / MR)
|
||||
if ($this->cabang_id) {
|
||||
$cabang = \DB::table('cabang')->where('id', $this->cabang_id)->first();
|
||||
return [
|
||||
'cabang' => (int) $this->cabang_id,
|
||||
'region' => $cabang ? (int) $cabang->region_id : null
|
||||
];
|
||||
}
|
||||
|
||||
// Jika User level Region (Admin Region / MOM Region)
|
||||
// Pastikan kolom 'region_id' ada di tabel users Anda
|
||||
return [
|
||||
'cabang' => null,
|
||||
'region' => $this->region_id ? (int) $this->region_id : null
|
||||
];
|
||||
}
|
||||
|
||||
public function cabangs()
|
||||
{
|
||||
// Relasi Many-to-Many melalui tabel pivot user_has_cabang
|
||||
return $this->belongsToMany(Cabang::class, 'user_has_cabang', 'user_id', 'cabang_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Mendapatkan ID Region berdasarkan penugasan cabang pertama
|
||||
*/
|
||||
public function getAssignedRegionId()
|
||||
{
|
||||
$firstAssignment = $this->cabangs()->first();
|
||||
return $firstAssignment ? $firstAssignment->region_id : null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Pagination\Paginator;
|
||||
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
@@ -29,6 +30,8 @@ class AppServiceProvider extends ServiceProvider
|
||||
URL::forceScheme('https');
|
||||
}
|
||||
|
||||
Paginator::useBootstrap();
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class DashboardService
|
||||
{
|
||||
protected $startDate;
|
||||
protected $endDate;
|
||||
protected $allowedCabangIds = [];
|
||||
protected $user;
|
||||
|
||||
public function __construct($user)
|
||||
{
|
||||
$this->user = $user;
|
||||
$this->setPeriode();
|
||||
$this->setUserVisibility();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set Periode Cut-off (11 - 10)
|
||||
*/
|
||||
protected function setPeriode(): void
|
||||
{
|
||||
$startDay = (int) env('STARTING_DATE', 11);
|
||||
$closingDay = (int) env('CLOSING_DATE', 10);
|
||||
$now = Carbon::now();
|
||||
|
||||
if ($now->day >= $startDay) {
|
||||
$this->startDate = $now->copy()->day($startDay)->startOfDay();
|
||||
$this->endDate = $now->copy()->addMonth()->day($closingDay)->endOfDay();
|
||||
} else {
|
||||
$this->startDate = $now->copy()->subMonth()->day($startDay)->startOfDay();
|
||||
$this->endDate = $now->copy()->day($closingDay)->endOfDay();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atur Visibilitas Berdasarkan Hierarki Role
|
||||
*/
|
||||
protected function setUserVisibility(): void
|
||||
{
|
||||
// 1. MIS / HEAD / SUPERADMIN: Akses Nasional
|
||||
if ($this->user->hasRole(['Marketing Information System', 'Head of Sales Management', 'Super Admin'])) {
|
||||
$this->allowedCabangIds = [];
|
||||
return;
|
||||
}
|
||||
|
||||
$myCabangs = DB::table('user_has_cabang')
|
||||
->where('user_id', $this->user->id)
|
||||
->whereNull('deleted_at')
|
||||
->pluck('cabang_id')
|
||||
->toArray();
|
||||
|
||||
// 2. MOM / ADMIN REGION: Akses Regional (Semua cabang di dalam regionnya)
|
||||
if ($this->user->hasRole(['Marketing Operational Manager Region', 'Admin Region'])) {
|
||||
$regionIds = DB::table('cabang')
|
||||
->whereIn('id', $myCabangs)
|
||||
->pluck('region_id')
|
||||
->toArray();
|
||||
|
||||
$this->allowedCabangIds = DB::table('cabang')
|
||||
->whereIn('region_id', $regionIds)
|
||||
->pluck('id')
|
||||
->toArray();
|
||||
}
|
||||
// 3. AM / MR: Akses Cabang Spesifik
|
||||
else {
|
||||
$this->allowedCabangIds = $myCabangs;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper Filter: Digunakan di semua query analitik
|
||||
*/
|
||||
protected function applyFilters($query)
|
||||
{
|
||||
if (!empty($this->allowedCabangIds)) {
|
||||
$query->whereIn('combined_forms.cabang_id', $this->allowedCabangIds);
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query Utama: Menggabungkan 5 tabel kategori expense
|
||||
*/
|
||||
protected function getCombinedFormsQuery()
|
||||
{
|
||||
$tables = [
|
||||
'form_up_country',
|
||||
'form_vehicle_running_cost',
|
||||
'form_entertainment_presentation',
|
||||
'form_meeting_seminar',
|
||||
'form_others'
|
||||
];
|
||||
|
||||
$query = null;
|
||||
foreach ($tables as $table) {
|
||||
$sub = DB::table($table)
|
||||
->select(
|
||||
'id',
|
||||
'cabang_id',
|
||||
'total',
|
||||
'status',
|
||||
'created_at',
|
||||
'final_approved_at',
|
||||
DB::raw("'$table' as source_table")
|
||||
)
|
||||
->whereNull('deleted_at');
|
||||
$query = ($query === null) ? $sub : $query->unionAll($sub);
|
||||
}
|
||||
|
||||
return DB::table(DB::raw("({$query->toSql()}) as combined_forms"))
|
||||
->mergeBindings($query)
|
||||
->join('cabang', 'combined_forms.cabang_id', '=', 'cabang.id')
|
||||
->join('region', 'cabang.region_id', '=', 'region.id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Data untuk 4 Kartu Statistik Utama
|
||||
*/
|
||||
public function getApprovalStats(): array
|
||||
{
|
||||
// Ambil semua data tanpa filter tanggal dulu untuk kartu "Waiting"
|
||||
$allData = $this->getCombinedFormsQuery()
|
||||
->select('combined_forms.status', 'combined_forms.total', 'combined_forms.created_at')
|
||||
->get();
|
||||
|
||||
$map = [
|
||||
// 1. TOTAL PENDING: Khusus periode aktif (11 Maret - 10 April) & Status On Progress
|
||||
'total_pending' => [
|
||||
'label' => 'Total Pending',
|
||||
'keys' => ['on progress'],
|
||||
'color' => 'warning',
|
||||
'icon' => 'fas fa-hourglass-half',
|
||||
'use_period' => true
|
||||
],
|
||||
// 2. WAITING APPR 1: Semua yang statusnya On Progress
|
||||
'appr1' => [
|
||||
'label' => 'Waiting Appr 1',
|
||||
'keys' => ['on progress'],
|
||||
'color' => 'info',
|
||||
'icon' => 'fas fa-user-check',
|
||||
'use_period' => false
|
||||
],
|
||||
// 3. WAITING APPR 2: Semua yang statusnya Approved 1
|
||||
'appr2' => [
|
||||
'label' => 'Waiting Appr 2',
|
||||
'keys' => ['approved 1'],
|
||||
'color' => 'primary',
|
||||
'icon' => 'fas fa-file-invoice-dollar',
|
||||
'use_period' => false
|
||||
],
|
||||
// 4. WAITING FINAL APPROVED: Semua yang statusnya Approved 2
|
||||
'waiting_final' => [
|
||||
'label' => 'Waiting Final Approved',
|
||||
'keys' => ['approved 2'],
|
||||
'color' => 'secondary',
|
||||
'icon' => 'fas fa-tasks',
|
||||
'use_period' => false
|
||||
],
|
||||
// 5. FINAL APPROVED (CLOSED): Semua yang sudah Closed
|
||||
'closed' => [
|
||||
'label' => 'Final Approved',
|
||||
'keys' => ['closed', 'approved'],
|
||||
'color' => 'success',
|
||||
'icon' => 'fas fa-check-double',
|
||||
'use_period' => false
|
||||
],
|
||||
];
|
||||
|
||||
$results = [];
|
||||
foreach ($map as $config) {
|
||||
$filtered = $allData->filter(function ($item) use ($config) {
|
||||
$statusMatch = in_array(strtolower(trim((string)$item->status)), $config['keys']);
|
||||
|
||||
// Jika kartu membutuhkan filter periode (Maret 11 - April 10)
|
||||
if ($config['use_period']) {
|
||||
$dateMatch = Carbon::parse($item->created_at)->between($this->startDate, $this->endDate);
|
||||
return $statusMatch && $dateMatch;
|
||||
}
|
||||
|
||||
return $statusMatch;
|
||||
});
|
||||
|
||||
$results[] = [
|
||||
'label' => $config['label'],
|
||||
'count' => $filtered->count(),
|
||||
'amount' => (float) $filtered->sum('total'),
|
||||
'color' => $config['color'],
|
||||
'icon' => $config['icon']
|
||||
];
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mengambil daftar pengajuan dengan status 'Approved 2'
|
||||
* Untuk antrian persetujuan akhir (HOSM/MIS)
|
||||
*/
|
||||
public function getPendingFinalApproval()
|
||||
{
|
||||
$query = $this->getCombinedFormsQuery()
|
||||
->select(
|
||||
'combined_forms.*',
|
||||
'cabang.name as cabang_name',
|
||||
'region.name as region_name'
|
||||
)
|
||||
->where('combined_forms.status', 'Approved 2');
|
||||
|
||||
$this->applyFilters($query);
|
||||
|
||||
return $query->orderBy('combined_forms.created_at', 'desc')->paginate(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Summary per Kategori untuk Chart
|
||||
*/
|
||||
public function getTotals(): array
|
||||
{
|
||||
$query = $this->getCombinedFormsQuery()
|
||||
->whereBetween('combined_forms.created_at', [$this->startDate, $this->endDate])
|
||||
->whereIn('combined_forms.status', ['Approved', 'Closed']);
|
||||
|
||||
$this->applyFilters($query);
|
||||
|
||||
$results = $query->select('combined_forms.source_table', DB::raw('SUM(combined_forms.total) as total_per_table'))
|
||||
->groupBy('combined_forms.source_table')
|
||||
->get();
|
||||
|
||||
return [
|
||||
'forms' => [
|
||||
'upcountry' => $results->where('source_table', 'form_up_country')->first()->total_per_table ?? 0,
|
||||
'vehicle' => $results->where('source_table', 'form_vehicle_running_cost')->first()->total_per_table ?? 0,
|
||||
'entertainment' => $results->where('source_table', 'form_entertainment_presentation')->first()->total_per_table ?? 0,
|
||||
'meeting' => $results->where('source_table', 'form_meeting_seminar')->first()->total_per_table ?? 0,
|
||||
'others' => $results->where('source_table', 'form_others')->first()->total_per_table ?? 0,
|
||||
],
|
||||
'grand_total' => $results->sum('total_per_table')
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Top 5 Pengeluaran Terbanyak per Cabang
|
||||
*/
|
||||
/**
|
||||
* Top 10 Pengeluaran Terbanyak (Volume Giants)
|
||||
*/
|
||||
public function getTopExpenses()
|
||||
{
|
||||
$query = $this->getCombinedFormsQuery()
|
||||
->whereBetween('combined_forms.created_at', [$this->startDate, $this->endDate]);
|
||||
|
||||
$this->applyFilters($query);
|
||||
|
||||
return $query->select('cabang.name', 'region.name as region_name', DB::raw('SUM(combined_forms.total) as total_amount'))
|
||||
->groupBy('cabang.id', 'cabang.name', 'region.name')
|
||||
->orderBy('total_amount', 'desc')
|
||||
->take(10) // Update ke 10
|
||||
->get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Top 10 Efisiensi Approval (Speed Kings)
|
||||
*/
|
||||
public function getFastestClosing()
|
||||
{
|
||||
$query = $this->getCombinedFormsQuery()
|
||||
->select('cabang.name', DB::raw('AVG(TIMESTAMPDIFF(HOUR, combined_forms.created_at, combined_forms.final_approved_at)) as avg_hours'))
|
||||
->whereIn('combined_forms.status', ['Approved', 'Closed'])
|
||||
->whereNotNull('combined_forms.final_approved_at')
|
||||
->whereBetween('combined_forms.final_approved_at', [$this->startDate, $this->endDate]);
|
||||
|
||||
$this->applyFilters($query);
|
||||
|
||||
return $query->groupBy('cabang.id', 'cabang.name')
|
||||
->orderBy('avg_hours', 'asc')
|
||||
->take(10) // Update ke 10
|
||||
->get();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Traits;
|
||||
|
||||
use App\Models\AttachmentForm;
|
||||
|
||||
trait HasAttachments
|
||||
{
|
||||
public function attachments()
|
||||
{
|
||||
// Relasi ini akan otomatis menyesuaikan table_name berdasarkan property $table di model
|
||||
return $this->hasMany(AttachmentForm::class, 'form_id')
|
||||
->where('table_name', $this->table);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user