Files
ilycats/app/Providers/AppServiceProvider.php
T

88 lines
2.7 KiB
PHP
Raw Normal View History

2026-02-08 15:16:35 +07:00
<?php
namespace App\Providers;
use App\Models\Food;
use App\Models\Medicine;
use App\Models\Setting;
use App\Observers\FoodObserver;
use App\Observers\MedicineObserver;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Gate; // Import Gate untuk sistem permission
2026-09-23 12:45:02 +07:00
use Illuminate\Support\Facades\URL;
2026-02-08 15:16:35 +07:00
class AppServiceProvider extends ServiceProvider
{
2026-09-23 12:45:02 +07:00
2026-02-08 15:16:35 +07:00
public function boot(): void
{
2026-09-23 12:45:02 +07:00
if (config('app.env') === 'production') {
URL::forceScheme('https');
}
2026-02-08 15:16:35 +07:00
// 1. DAFTARKAN OBSERVERS (Tetap Utuh & Aman)
if (Schema::hasTable('medicines')) {
Medicine::observe(MedicineObserver::class);
}
if (class_exists(FoodObserver::class) && Schema::hasTable('foods')) {
Food::observe(FoodObserver::class);
}
// 2. GLOBAL SETTINGS (Dinamis)
if (!app()->runningInConsole() && Schema::hasTable('settings')) {
$rawSettings = Setting::pluck('value', 'key')->toArray();
View::share('setting', (object) $rawSettings);
}
// 3. VIEW COMPOSER (Fungsi Notifikasi Stok Tetap Berjalan)
$alertViews = ['layouts.app', 'layouts.navigation-sidebar', 'dashboard', 'pages.*'];
View::composer($alertViews, function ($view) {
$stockData = Cache::remember('low_stock_alerts', 600, function () {
$lowMedicines = Medicine::where('qty', '<', 5)->get(['nama_obat', 'qty', 'unit']);
$lowFoods = Food::where('qty', '<', 5)->get(['nama_makanan', 'qty', 'unit']);
return [
'lowStockMedicines' => $lowMedicines,
'lowStockFoods' => $lowFoods,
'totalAlerts' => $lowMedicines->count() + $lowFoods->count(),
];
});
$view->with($stockData);
});
2026-09-23 12:45:02 +07:00
// 4. SISTEM OTORISASI GLOBAL (Gate Permission)
2026-02-08 15:16:35 +07:00
Gate::define('check-access', function ($user, $module, $permission) {
2026-09-23 12:45:02 +07:00
// Dukungan akun legacy yang masih menyimpan role sebagai string.
if ($user->getRawOriginal('role') === 'admin') {
return true;
}
2026-02-08 15:16:35 +07:00
2026-09-23 12:45:02 +07:00
if (!$user->role_id) {
return false;
}
2026-02-08 15:16:35 +07:00
2026-09-23 12:45:02 +07:00
$role = $user->roleModel;
if ($role?->slug === 'admin') {
2026-02-08 15:16:35 +07:00
return true;
}
$column = str_starts_with($permission, 'can_') ? $permission : 'can_' . $permission;
2026-09-23 12:45:02 +07:00
try {
return \App\Models\RolePermission::where('role_id', $user->role_id)
->where('module_slug', $module)
->where($column, 1)
->exists();
} catch (\Throwable $e) {
return false;
}
2026-02-08 15:16:35 +07:00
});
2026-09-23 12:45:02 +07:00
}
2026-02-08 15:16:35 +07:00
}