first init

This commit is contained in:
ISMAIL MASSERAN
2026-06-08 11:37:14 +08:00
commit 94ecbe5887
1058 changed files with 87732 additions and 0 deletions
@@ -0,0 +1,5 @@
<?php
return [
'name' => 'Notification',
];
@@ -0,0 +1,16 @@
<?php
namespace Modules\Notification\Database\Seeders;
use Illuminate\Database\Seeder;
class NotificationDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// $this->call([]);
}
}
@@ -0,0 +1,21 @@
<?php
namespace Modules\Notification\Entities;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Auth\Entities\User;
class Notification extends Model
{
protected $fillable = ['type', 'notifiable_id', 'notifiable_type', 'data', 'read_at'];
protected $casts = [
'read_at' => 'datetime',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
@@ -0,0 +1,469 @@
<?php
namespace Modules\Notification\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Notifications\DatabaseNotification;
class NotificationController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index(Request $request): JsonResponse
{
try {
$user = Auth::user();
$perPage = $request->get('per_page', 10);
$page = $request->get('page', 1);
$filter = $request->get('filter', 'all'); // all, unread, read
$query = $user->notifications();
// Apply filter
switch ($filter) {
case 'unread':
$query->whereNull('read_at');
break;
case 'read':
$query->whereNotNull('read_at');
break;
default:
// Show all notifications
break;
}
$notifications = $query->orderBy('created_at', 'desc')
->paginate($perPage, ['*'], 'page', $page);
// Transform notifications to match frontend format
$transformedNotifications = $notifications->map(function ($notification) {
$data = $notification->data;
// Detect notification category (for internal categorization)
$notificationCategory = $this->detectNotificationCategory($data);
// Get display type (action type for KJC Repair, or original type for others)
$displayType = $this->getDisplayType($data, $notificationCategory);
return [
'id' => $notification->id,
'type' => $displayType,
'title' => $this->getNotificationTitle($data, $notificationCategory),
'message' => $this->getNotificationMessage($data, $notificationCategory),
'is_read' => $notification->read_at !== null,
'created_at' => $notification->created_at->format('Y-m-d H:i:s'),
'time_ago' => $notification->created_at->diffForHumans(),
'icon' => $this->getNotificationIcon($notificationCategory),
'color' => $this->getNotificationColor($notificationCategory),
'navigation' => $this->getNotificationNavigation($data, $notificationCategory),
'data' => $data
];
});
return response()->json([
'success' => true,
'data' => $transformedNotifications,
'pagination' => [
'current_page' => $notifications->currentPage(),
'last_page' => $notifications->lastPage(),
'per_page' => $notifications->perPage(),
'total' => $notifications->total(),
'has_more' => $notifications->hasMorePages()
],
'unread_count' => $user->unreadNotifications()->count()
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Failed to fetch notifications: ' . $e->getMessage()
], 500);
}
}
/**
* Mark notification as read
*/
public function markAsRead($id): JsonResponse
{
try {
$user = Auth::user();
$notification = $user->notifications()->find($id);
if (!$notification) {
return response()->json([
'success' => false,
'message' => 'Notifikasi tidak ditemukan'
], 404);
}
$notification->markAsRead();
return response()->json([
'success' => true,
'message' => 'Notifikasi ditandakan sebagai telah dibaca'
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menandakan notifikasi sebagai telah dibaca: ' . $e->getMessage()
], 500);
}
}
/**
* Mark all notifications as read
*/
public function markAllAsRead(): JsonResponse
{
try {
$user = Auth::user();
$user->unreadNotifications->markAsRead();
return response()->json([
'success' => true,
'message' => 'Semua notifikasi ditandakan sebagai telah dibaca'
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal menandakan semua notifikasi sebagai telah dibaca: ' . $e->getMessage()
], 500);
}
}
/**
* Get notification count
*/
public function getCount(): JsonResponse
{
try {
$user = Auth::user();
$unreadCount = $user->unreadNotifications()->count();
return response()->json([
'success' => true,
'unread_count' => $unreadCount
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => 'Gagal mendapatkan bilangan notifikasi: ' . $e->getMessage()
], 500);
}
}
/**
* Detect notification category from data (for internal categorization)
*/
private function detectNotificationCategory($data): string
{
// Check if it's a KJC Repair notification
if (isset($data['kjc_repair_id'])) {
return 'kjc_repair';
}
// Check if it's a KJC Temporary Loan notification
if (isset($data['kjc_temporary_loan_id'])) {
return 'kjc_temporary_loan';
}
// Check if it's a User Activation notification
if (isset($data['user_id']) && isset($data['type']) && $data['type'] === 'user_activation_required') {
return 'user_activation';
}
// Check if it's a Feedback notification
if (isset($data['feedback_id'])) {
return 'feedback';
}
// Check for other notification types
if (isset($data['type'])) {
return $data['type'];
}
return 'general';
}
/**
* Get display type for frontend (action type for KJC Repair/Temporary Loan, original type for others)
*/
private function getDisplayType($data, $category): string
{
// For KJC Repair and Temporary Loan notifications, return the action type (next_approval, approved, etc.)
if (($category === 'kjc_repair' || $category === 'kjc_temporary_loan') && isset($data['type'])) {
return $data['type'];
}
// For User Activation notifications, return the type
if ($category === 'user_activation' && isset($data['type'])) {
return $data['type'];
}
// For Feedback notifications, return the type
if ($category === 'feedback' && isset($data['type'])) {
return $data['type'];
}
// For other notifications, return the category
return $category;
}
/**
* Get notification title based on category and data
*/
private function getNotificationTitle($data, $notificationCategory): string
{
if ($notificationCategory === 'kjc_repair') {
$repairType = $data['type'] ?? 'general';
switch ($repairType) {
case 'next_approval':
return 'Pembaikan KJC - Permohonan Disemak';
case 'approved':
return 'Pembaikan KJC - Disetujui';
case 'rejected':
return 'Pembaikan KJC - Ditolak';
case 'returned_for_revision':
return 'Pembaikan KJC - Dikembalikan untuk semakan semula';
default:
return 'Notifikasi Pembaikan KJC';
}
}
if ($notificationCategory === 'kjc_temporary_loan') {
$loanType = $data['type'] ?? 'general';
switch ($loanType) {
case 'next_approval':
return 'Pinjaman Sementara KJC - Permohonan Disemak';
case 'approved':
return 'Pinjaman Sementara KJC - Disetujui';
case 'rejected':
return 'Pinjaman Sementara KJC - Ditolak';
case 'returned_for_revision':
return 'Pinjaman Sementara KJC - Dikembalikan untuk semakan semula';
default:
return 'Notifikasi Pinjaman Sementara KJC';
}
}
if ($notificationCategory === 'user_activation') {
return 'Pengaktifan Pengguna Diperlukan';
}
if ($notificationCategory === 'feedback') {
return 'Maklum Balas Baru Diterima';
}
switch ($notificationCategory) {
case 'report_generation':
return 'Penyata Mingguan Dicipta';
case 'system':
return 'Notifikasi Sistem';
default:
return 'Notifikasi';
}
}
/**
* Get notification message based on category and data
*/
private function getNotificationMessage($data, $notificationCategory): string
{
// If message is already set, use it
if (!empty($data['message'])) {
return $data['message'];
}
// Generate message for KJC Repair notifications
if ($notificationCategory === 'kjc_repair') {
$repairType = $data['type'] ?? 'general';
$repairId = $data['kjc_repair_id'] ?? 'N/A';
$assetName = $data['asset_name'] ?? 'Unknown';
$unitName = $data['unit_name'] ?? 'Unknown';
switch ($repairType) {
case 'next_approval':
return "Permohonan pembaikan KJC perlu disemak oleh anda. ID Permohonan: {$repairId}, Asset: {$assetName}, Unit: {$unitName}";
case 'approved':
return "Permohonan pembaikan KJC telah disetujui. ID Permohonan: {$repairId}, Asset: {$assetName}, Unit: {$unitName}";
case 'rejected':
return "Permohonan pembaikan KJC telah ditolak. ID Permohonan: {$repairId}, Asset: {$assetName}, Unit: {$unitName}";
case 'returned_for_revision':
return "Permohonan pembaikan KJC telah dikembalikan untuk semakan semula. ID Permohonan: {$repairId}, Asset: {$assetName}, Unit: {$unitName}";
default:
return "Notifikasi berkaitan permohonan pembaikan KJC. ID Permohonan: {$repairId}";
}
}
// Generate message for KJC Temporary Loan notifications
if ($notificationCategory === 'kjc_temporary_loan') {
$loanType = $data['type'] ?? 'general';
$assetName = $data['asset_name'] ?? 'Unknown';
$originalUnitName = $data['original_unit_name'] ?? 'Unknown';
$borrowerUnitName = $data['borrower_unit_name'] ?? 'Unknown';
switch ($loanType) {
case 'next_approval':
return "Permohonan pinjaman sementara KJC perlu disemak oleh anda, Asset: {$assetName}, Pasukan Asal: {$originalUnitName}, Pasukan Peminjam: {$borrowerUnitName}";
case 'approved':
return "Permohonan pinjaman sementara KJC telah disetujui, Asset: {$assetName}, Pasukan Asal: {$originalUnitName}, Pasukan Peminjam: {$borrowerUnitName}";
case 'rejected':
return "Permohonan pinjaman sementara KJC telah ditolak, Asset: {$assetName}, Pasukan Asal: {$originalUnitName}, Pasukan Peminjam: {$borrowerUnitName}";
case 'returned_for_revision':
return "Permohonan pinjaman sementara KJC telah dikembalikan untuk semakan semula, Asset: {$assetName}, Pasukan Asal: {$originalUnitName}, Pasukan Peminjam: {$borrowerUnitName}";
default:
return "Notifikasi berkaitan permohonan pinjaman sementara KJC, Asset: {$assetName}, Pasukan Asal: {$originalUnitName}, Pasukan Peminjam: {$borrowerUnitName}";
}
}
// Generate message for User Activation notifications
if ($notificationCategory === 'user_activation') {
// If message is already set, use it
if (!empty($data['message'])) {
return $data['message'];
}
$userName = $data['user_name'] ?? 'Unknown';
$userEmail = $data['user_email'] ?? 'Unknown';
$userArmyNumber = $data['user_army_number'] ?? 'Unknown';
$unitName = $data['user_unit_name'] ?? 'Unknown';
return "Pengguna baru memerlukan pengaktifan. Nama: {$userName}, Email: {$userEmail}, No. Tentera: {$userArmyNumber}, Unit: {$unitName}";
}
// Generate message for Feedback notifications
if ($notificationCategory === 'feedback') {
// If message is already set, use it
if (!empty($data['message'])) {
return $data['message'];
}
$feedbackTitle = $data['feedback_title'] ?? 'Unknown';
$feedbackType = $data['feedback_type'] ?? 'Unknown';
$feedbackPriority = $data['feedback_priority'] ?? 'normal';
$userName = $data['user_name'] ?? 'Anonymous';
$feedbackId = $data['feedback_id'] ?? 'N/A';
return "Maklum balas baru telah diterima. ID: {$feedbackId}, Tajuk: {$feedbackTitle}, Jenis: {$feedbackType}, Keutamaan: {$feedbackPriority}, Pengguna: {$userName}";
}
return 'No message available';
}
/**
* Get notification icon based on type
*/
private function getNotificationIcon($type): string
{
switch ($type) {
case 'report_generation':
return 'mdi-file-document';
case 'kjc_repair':
return 'mdi-tools';
case 'kjc_temporary_loan':
return 'mdi-handshake';
case 'user_activation':
case 'user_activation_required':
return 'mdi-account-plus';
case 'feedback':
case 'feedback_submitted':
return 'mdi-message-alert';
case 'system':
return 'mdi-cog';
default:
return 'mdi-bell';
}
}
/**
* Get notification color based on type
*/
private function getNotificationColor($type): string
{
switch ($type) {
case 'report_generation':
return 'success';
case 'kjc_repair':
return 'warning';
case 'kjc_temporary_loan':
return 'info';
case 'user_activation':
case 'user_activation_required':
return 'purple';
case 'feedback':
case 'feedback_submitted':
return 'orange';
case 'system':
return 'info';
default:
return 'primary';
}
}
/**
* Get notification navigation data based on category
*/
private function getNotificationNavigation($data, $notificationCategory): array
{
if ($notificationCategory === 'kjc_repair') {
$repairId = $data['kjc_repair_id'] ?? null;
return [
'route' => '/kjcrepairs',
'params' => [],
'query' => $repairId ? ['id' => $repairId] : []
];
}
if ($notificationCategory === 'kjc_temporary_loan') {
$loanId = $data['kjc_temporary_loan_id'] ?? null;
return [
'route' => '/kjctemporaryloans',
'params' => [],
'query' => $loanId ? ['id' => $loanId] : []
];
}
if ($notificationCategory === 'user_activation') {
$userId = $data['user_id'] ?? null;
return [
'route' => '/users',
'params' => [],
'query' => $userId ? ['id' => $userId] : []
];
}
if ($notificationCategory === 'feedback') {
$feedbackId = $data['feedback_id'] ?? null;
return [
'route' => '/feedback',
'params' => [],
'query' => $feedbackId ? ['id' => $feedbackId] : []
];
}
switch ($notificationCategory) {
case 'report_generation':
return [
'route' => '/kjcreports',
'params' => [],
'query' => []
];
case 'system':
return [
'route' => '/dashboard',
'params' => [],
'query' => []
];
default:
return [
'route' => '/dashboard',
'params' => [],
'query' => []
];
}
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\Notification\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event handler mappings for the application.
*
* @var array<string, array<int, string>>
*/
protected $listen = [];
/**
* Indicates if events should be discovered.
*
* @var bool
*/
protected static $shouldDiscoverEvents = true;
/**
* Configure the proper event listeners for email verification.
*/
protected function configureEmailVerification(): void {}
}
@@ -0,0 +1,154 @@
<?php
namespace Modules\Notification\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class NotificationServiceProvider extends ServiceProvider
{
use PathNamespace;
protected string $name = 'Notification';
protected string $nameLower = 'notification';
/**
* Boot the application events.
*/
public function boot(): void
{
$this->registerCommands();
$this->registerCommandSchedules();
$this->registerTranslations();
$this->registerConfig();
$this->registerViews();
$this->loadMigrationsFrom(module_path($this->name, 'Database/Migrations'));
}
/**
* Register the service provider.
*/
public function register(): void
{
$this->app->register(EventServiceProvider::class);
$this->app->register(RouteServiceProvider::class);
}
/**
* Register commands in the format of Command::class
*/
protected function registerCommands(): void
{
// $this->commands([]);
}
/**
* Register command Schedules.
*/
protected function registerCommandSchedules(): void
{
// $this->app->booted(function () {
// $schedule = $this->app->make(Schedule::class);
// $schedule->command('inspire')->hourly();
// });
}
/**
* Register translations.
*/
public function registerTranslations(): void
{
$langPath = resource_path('lang/modules/'.$this->nameLower);
if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, $this->nameLower);
$this->loadJsonTranslationsFrom($langPath);
} else {
$this->loadTranslationsFrom(module_path($this->name, 'Lang'), $this->nameLower);
$this->loadJsonTranslationsFrom(module_path($this->name, 'Lang'));
}
}
/**
* Register config.
*/
protected function registerConfig(): void
{
$configPath = module_path($this->name, config('modules.paths.generator.config.path'));
if (is_dir($configPath)) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$config = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
$config_key = str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $config);
$segments = explode('.', $this->nameLower.'.'.$config_key);
// Remove duplicated adjacent segments
$normalized = [];
foreach ($segments as $segment) {
if (end($normalized) !== $segment) {
$normalized[] = $segment;
}
}
$key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);
$this->publishes([$file->getPathname() => config_path($config)], 'config');
$this->merge_config_from($file->getPathname(), $key);
}
}
}
}
/**
* Merge config from the given path recursively.
*/
protected function merge_config_from(string $path, string $key): void
{
$existing = config($key, []);
$module_config = require $path;
config([$key => array_replace_recursive($existing, $module_config)]);
}
/**
* Register views.
*/
public function registerViews(): void
{
$viewPath = resource_path('views/modules/'.$this->nameLower);
$sourcePath = module_path($this->name, 'Resources/Views');
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);
Blade::componentNamespace(config('modules.namespace').'\\' . $this->name . '\\View\\Components', $this->nameLower);
}
/**
* Get the services provided by the provider.
*/
public function provides(): array
{
return [];
}
private function getPublishableViewPaths(): array
{
$paths = [];
foreach (config('view.paths') as $path) {
if (is_dir($path.'/modules/'.$this->nameLower)) {
$paths[] = $path.'/modules/'.$this->nameLower;
}
}
return $paths;
}
}
@@ -0,0 +1,50 @@
<?php
namespace Modules\Notification\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
protected string $name = 'Notification';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*/
public function boot(): void
{
parent::boot();
}
/**
* Define the routes for the application.
*/
public function map(): void
{
$this->mapApiRoutes();
$this->mapWebRoutes();
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*/
protected function mapWebRoutes(): void
{
Route::middleware('web')->group(module_path($this->name, '/Routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*/
protected function mapApiRoutes(): void
{
Route::middleware('api')->name('api.')->group(module_path($this->name, '/Routes/api.php'));
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Notification\Http\Controllers\NotificationController;
Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () {
Route::get('notifications', [NotificationController::class, 'index'])->name('notifications.index');
Route::patch('notifications/{id}/read', [NotificationController::class, 'markAsRead'])->name('notifications.markAsRead');
Route::patch('notifications/mark-all-read', [NotificationController::class, 'markAllAsRead'])->name('notifications.markAllAsRead');
Route::get('notifications/count', [NotificationController::class, 'getCount'])->name('notifications.count');
});
+8
View File
@@ -0,0 +1,8 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Notification\Http\Controllers\NotificationController;
Route::middleware(['auth', 'verified'])->group(function () {
Route::resource('notifications', NotificationController::class)->names('notification');
});
+30
View File
@@ -0,0 +1,30 @@
{
"name": "nwidart/notification",
"description": "",
"authors": [
{
"name": "Nicolas Widart",
"email": "n.widart@gmail.com"
}
],
"extra": {
"laravel": {
"providers": [],
"aliases": {
}
}
},
"autoload": {
"psr-4": {
"Modules\\Notification\\": "App",
"Modules\\Notification\\Database\\Factories\\": "database/factories/",
"Modules\\Notification\\Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Modules\\Notification\\Tests\\": "tests/"
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"name": "Notification",
"alias": "notification",
"description": "",
"keywords": [],
"priority": 0,
"providers": [
"Modules\\Notification\\Providers\\NotificationServiceProvider"
],
"files": []
}
+15
View File
@@ -0,0 +1,15 @@
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"axios": "^1.1.2",
"laravel-vite-plugin": "^0.7.5",
"sass": "^1.69.5",
"postcss": "^8.3.7",
"vite": "^4.0.0"
}
}