commit b2e1785ad1cfca9339b2a71d14e486541f497061 Author: HOMSIN_01 <158242366+Homsin1@users.noreply.github.com> Date: Fri Apr 3 10:45:19 2026 +0700 init commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a186cd2 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,18 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 + +[compose.yaml] +indent_size = 4 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c0660ea --- /dev/null +++ b/.env.example @@ -0,0 +1,65 @@ +APP_NAME=Laravel +APP_ENV=local +APP_KEY= +APP_DEBUG=true +APP_URL=http://localhost + +APP_LOCALE=en +APP_FALLBACK_LOCALE=en +APP_FAKER_LOCALE=en_US + +APP_MAINTENANCE_DRIVER=file +# APP_MAINTENANCE_STORE=database + +# PHP_CLI_SERVER_WORKERS=4 + +BCRYPT_ROUNDS=12 + +LOG_CHANNEL=stack +LOG_STACK=single +LOG_DEPRECATIONS_CHANNEL=null +LOG_LEVEL=debug + +DB_CONNECTION=sqlite +# DB_HOST=127.0.0.1 +# DB_PORT=3306 +# DB_DATABASE=laravel +# DB_USERNAME=root +# DB_PASSWORD= + +SESSION_DRIVER=database +SESSION_LIFETIME=120 +SESSION_ENCRYPT=false +SESSION_PATH=/ +SESSION_DOMAIN=null + +BROADCAST_CONNECTION=log +FILESYSTEM_DISK=local +QUEUE_CONNECTION=database + +CACHE_STORE=database +# CACHE_PREFIX= + +MEMCACHED_HOST=127.0.0.1 + +REDIS_CLIENT=phpredis +REDIS_HOST=127.0.0.1 +REDIS_PASSWORD=null +REDIS_PORT=6379 + +MAIL_MAILER=log +MAIL_SCHEME=null +MAIL_HOST=127.0.0.1 +MAIL_PORT=2525 +MAIL_USERNAME=null +MAIL_PASSWORD=null +MAIL_FROM_ADDRESS="hello@example.com" +MAIL_FROM_NAME="${APP_NAME}" + +AWS_ACCESS_KEY_ID= +AWS_SECRET_ACCESS_KEY= +AWS_DEFAULT_REGION=us-east-1 +AWS_BUCKET= +AWS_USE_PATH_STYLE_ENDPOINT=false + +VITE_APP_NAME="${APP_NAME}" diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fcb21d3 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +* text=auto eol=lf + +*.blade.php diff=html +*.css diff=css +*.html diff=html +*.md diff=markdown +*.php diff=php + +/.github export-ignore +CHANGELOG.md export-ignore +.styleci.yml export-ignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b71b1ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +*.log +.DS_Store +.env +.env.backup +.env.production +.phpactor.json +.phpunit.result.cache +/.fleet +/.idea +/.nova +/.phpunit.cache +/.vscode +/.zed +/auth.json +/node_modules +/public/build +/public/hot +/public/storage +/storage/*.key +/storage/pail +/vendor +Homestead.json +Homestead.yaml +Thumbs.db diff --git a/README.md b/README.md new file mode 100644 index 0000000..0165a77 --- /dev/null +++ b/README.md @@ -0,0 +1,59 @@ +
+ + + +## About Laravel + +Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as: + +- [Simple, fast routing engine](https://laravel.com/docs/routing). +- [Powerful dependency injection container](https://laravel.com/docs/container). +- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage. +- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent). +- Database agnostic [schema migrations](https://laravel.com/docs/migrations). +- [Robust background job processing](https://laravel.com/docs/queues). +- [Real-time event broadcasting](https://laravel.com/docs/broadcasting). + +Laravel is accessible, powerful, and provides tools required for large, robust applications. + +## Learning Laravel + +Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework. You can also check out [Laravel Learn](https://laravel.com/learn), where you will be guided through building a modern Laravel application. + +If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library. + +## Laravel Sponsors + +We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com). + +### Premium Partners + +- **[Vehikl](https://vehikl.com)** +- **[Tighten Co.](https://tighten.co)** +- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)** +- **[64 Robots](https://64robots.com)** +- **[Curotec](https://www.curotec.com/services/technologies/laravel)** +- **[DevSquad](https://devsquad.com/hire-laravel-developers)** +- **[Redberry](https://redberry.international/laravel-development)** +- **[Active Logic](https://activelogic.com)** + +## Contributing + +Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions). + +## Code of Conduct + +In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct). + +## Security Vulnerabilities + +If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed. + +## License + +The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT). diff --git a/app/Http/Controllers/Auth/AuthenticatedSessionController.php b/app/Http/Controllers/Auth/AuthenticatedSessionController.php new file mode 100644 index 0000000..613bcd9 --- /dev/null +++ b/app/Http/Controllers/Auth/AuthenticatedSessionController.php @@ -0,0 +1,47 @@ +authenticate(); + + $request->session()->regenerate(); + + return redirect()->intended(route('dashboard', absolute: false)); + } + + /** + * Destroy an authenticated session. + */ + public function destroy(Request $request): RedirectResponse + { + Auth::guard('web')->logout(); + + $request->session()->invalidate(); + + $request->session()->regenerateToken(); + + return redirect('/'); + } +} diff --git a/app/Http/Controllers/Auth/ConfirmablePasswordController.php b/app/Http/Controllers/Auth/ConfirmablePasswordController.php new file mode 100644 index 0000000..712394a --- /dev/null +++ b/app/Http/Controllers/Auth/ConfirmablePasswordController.php @@ -0,0 +1,40 @@ +validate([ + 'email' => $request->user()->email, + 'password' => $request->password, + ])) { + throw ValidationException::withMessages([ + 'password' => __('auth.password'), + ]); + } + + $request->session()->put('auth.password_confirmed_at', time()); + + return redirect()->intended(route('dashboard', absolute: false)); + } +} diff --git a/app/Http/Controllers/Auth/EmailVerificationNotificationController.php b/app/Http/Controllers/Auth/EmailVerificationNotificationController.php new file mode 100644 index 0000000..f64fa9b --- /dev/null +++ b/app/Http/Controllers/Auth/EmailVerificationNotificationController.php @@ -0,0 +1,24 @@ +user()->hasVerifiedEmail()) { + return redirect()->intended(route('dashboard', absolute: false)); + } + + $request->user()->sendEmailVerificationNotification(); + + return back()->with('status', 'verification-link-sent'); + } +} diff --git a/app/Http/Controllers/Auth/EmailVerificationPromptController.php b/app/Http/Controllers/Auth/EmailVerificationPromptController.php new file mode 100644 index 0000000..ee3cb6f --- /dev/null +++ b/app/Http/Controllers/Auth/EmailVerificationPromptController.php @@ -0,0 +1,21 @@ +user()->hasVerifiedEmail() + ? redirect()->intended(route('dashboard', absolute: false)) + : view('auth.verify-email'); + } +} diff --git a/app/Http/Controllers/Auth/NewPasswordController.php b/app/Http/Controllers/Auth/NewPasswordController.php new file mode 100644 index 0000000..e8368bd --- /dev/null +++ b/app/Http/Controllers/Auth/NewPasswordController.php @@ -0,0 +1,62 @@ + $request]); + } + + /** + * Handle an incoming new password request. + * + * @throws \Illuminate\Validation\ValidationException + */ + public function store(Request $request): RedirectResponse + { + $request->validate([ + 'token' => ['required'], + 'email' => ['required', 'email'], + 'password' => ['required', 'confirmed', Rules\Password::defaults()], + ]); + + // Here we will attempt to reset the user's password. If it is successful we + // will update the password on an actual user model and persist it to the + // database. Otherwise we will parse the error and return the response. + $status = Password::reset( + $request->only('email', 'password', 'password_confirmation', 'token'), + function (User $user) use ($request) { + $user->forceFill([ + 'password' => Hash::make($request->password), + 'remember_token' => Str::random(60), + ])->save(); + + event(new PasswordReset($user)); + } + ); + + // If the password was successfully reset, we will redirect the user back to + // the application's home authenticated view. If there is an error we can + // redirect them back to where they came from with their error message. + return $status == Password::PASSWORD_RESET + ? redirect()->route('login')->with('status', __($status)) + : back()->withInput($request->only('email')) + ->withErrors(['email' => __($status)]); + } +} diff --git a/app/Http/Controllers/Auth/PasswordController.php b/app/Http/Controllers/Auth/PasswordController.php new file mode 100644 index 0000000..6916409 --- /dev/null +++ b/app/Http/Controllers/Auth/PasswordController.php @@ -0,0 +1,29 @@ +validateWithBag('updatePassword', [ + 'current_password' => ['required', 'current_password'], + 'password' => ['required', Password::defaults(), 'confirmed'], + ]); + + $request->user()->update([ + 'password' => Hash::make($validated['password']), + ]); + + return back()->with('status', 'password-updated'); + } +} diff --git a/app/Http/Controllers/Auth/PasswordResetLinkController.php b/app/Http/Controllers/Auth/PasswordResetLinkController.php new file mode 100644 index 0000000..bf1ebfa --- /dev/null +++ b/app/Http/Controllers/Auth/PasswordResetLinkController.php @@ -0,0 +1,44 @@ +validate([ + 'email' => ['required', 'email'], + ]); + + // We will send the password reset link to this user. Once we have attempted + // to send the link, we will examine the response then see the message we + // need to show to the user. Finally, we'll send out a proper response. + $status = Password::sendResetLink( + $request->only('email') + ); + + return $status == Password::RESET_LINK_SENT + ? back()->with('status', __($status)) + : back()->withInput($request->only('email')) + ->withErrors(['email' => __($status)]); + } +} diff --git a/app/Http/Controllers/Auth/RegisteredUserController.php b/app/Http/Controllers/Auth/RegisteredUserController.php new file mode 100644 index 0000000..0739e2e --- /dev/null +++ b/app/Http/Controllers/Auth/RegisteredUserController.php @@ -0,0 +1,50 @@ +validate([ + 'name' => ['required', 'string', 'max:255'], + 'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class], + 'password' => ['required', 'confirmed', Rules\Password::defaults()], + ]); + + $user = User::create([ + 'name' => $request->name, + 'email' => $request->email, + 'password' => Hash::make($request->password), + ]); + + event(new Registered($user)); + + Auth::login($user); + + return redirect(route('dashboard', absolute: false)); + } +} diff --git a/app/Http/Controllers/Auth/VerifyEmailController.php b/app/Http/Controllers/Auth/VerifyEmailController.php new file mode 100644 index 0000000..784765e --- /dev/null +++ b/app/Http/Controllers/Auth/VerifyEmailController.php @@ -0,0 +1,27 @@ +user()->hasVerifiedEmail()) { + return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); + } + + if ($request->user()->markEmailAsVerified()) { + event(new Verified($request->user())); + } + + return redirect()->intended(route('dashboard', absolute: false).'?verified=1'); + } +} diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php new file mode 100644 index 0000000..8677cd5 --- /dev/null +++ b/app/Http/Controllers/Controller.php @@ -0,0 +1,8 @@ +getCommonData($request); + return view('dashboard', $data); + } + + /** + * =============================== + * HALAMAN DATA MANAGEMENT + * =============================== + */ + public function dataManagement(Request $request) + { + $data = $this->getCommonData($request); + + // Tambahkan pagination untuk data management + $perPage = $request->get('per_page', 10); + $search = $request->get('search', ''); + + $query = Review::query(); + + if ($search) { + $query->where(function($q) use ($search) { + $q->where('review', 'like', "%{$search}%") + ->orWhere('text_final', 'like', "%{$search}%"); + }); + } + + // Filter berdasarkan sentimen + if ($request->has('filter_sentiment') && $request->filter_sentiment != '') { + $query->where('sentiment', $request->filter_sentiment); + } + + $data['reviews'] = $query->latest()->paginate($perPage); + $data['search'] = $search; + $data['filter_sentiment'] = $request->filter_sentiment; + $data['per_page'] = $perPage; + + return view('data-management', $data); + } + + /** + * =============================== + * FUNGSI AMBIL DATA UMUM + * =============================== + */ + private function getCommonData($request = null) + { + // Cek apakah tabel reviews ada + if (!Schema::hasTable('reviews')) { + return $this->getEmptyData(); + } + + // Filter berdasarkan tanggal jika ada + $query = Review::query(); + + if ($request && $request->has('start_date') && $request->has('end_date') && $request->start_date && $request->end_date) { + $query->whereBetween('created_at', [ + $request->start_date . ' 00:00:00', + $request->end_date . ' 23:59:59' + ]); + } + + // Filter berdasarkan sentimen + if ($request && $request->has('sentiment') && $request->sentiment != '') { + $query->where('sentiment', $request->sentiment); + } + + $dataset = $query->latest()->get(); + + // Hitung sentimen + $positif = (clone $query)->where('sentiment', 'positif')->count(); + $negatif = (clone $query)->where('sentiment', 'negatif')->count(); + + $totalData = $positif + $negatif; + $totalSafe = $totalData > 0 ? $totalData : 1; + + /** + * =============================== + * SCORE DISTRIBUTION UNTUK CHART (5 Range) + * =============================== + */ + $scoreDistribution = [ + 'Very Negative (-5 to -9)' => 0, + 'Negative (-1 to -4)' => 0, + 'Positive (1 to 4)' => 0, + 'Very Positive (5 to 9)' => 0, + ]; + + // Untuk chart line distribusi (0-100) + $scoreChartDistribution = [ + '0-20' => 0, + '21-40' => 0, + '41-60' => 0, + '61-80' => 0, + '81-100' => 0, + ]; + + /** + * =============================== + * MAINTENANCE CATEGORY + * =============================== + */ + $maintenance = [ + 'Login / Akses' => 0, + 'Performa Sistem (Server/Lambat)' => 0, + 'Fitur Pembelajaran' => 0, + 'UI / Tampilan' => 0, + 'Bug / Error' => 0, + 'Aplikasi Mobile' => 0, + 'Ujian / Exam' => 0, + ]; + + $maintenanceDetails = [ + 'Login / Akses' => [], + 'Performa Sistem (Server/Lambat)' => [], + 'Fitur Pembelajaran' => [], + 'UI / Tampilan' => [], + 'Bug / Error' => [], + 'Aplikasi Mobile' => [], + 'Ujian / Exam' => [], + ]; + + foreach ($dataset as $row) { + $review = strtolower($row->review ?? ''); + $text = strtolower($row->steming_data ?? ''); + $score = (int)($row->score ?? 0); + + /** + * SCORE DISTRIBUTION + */ + if ($score <= -5) { + $scoreDistribution['Very Negative (-5 to -9)']++; + } elseif ($score <= -1) { + $scoreDistribution['Negative (-1 to -4)']++; + } elseif ($score >= 5) { + $scoreDistribution['Very Positive (5 to 9)']++; + } elseif ($score >= 1) { + $scoreDistribution['Positive (1 to 4)']++; + } + + /** + * SCORE DISTRIBUTION UNTUK CHART LINE (0-100) + * Konversi score dari range -9..9 ke 0..100 + */ + $normalizedScore = (($score + 9) / 18) * 100; + + if ($normalizedScore <= 20) { + $scoreChartDistribution['0-20']++; + } elseif ($normalizedScore <= 40) { + $scoreChartDistribution['21-40']++; + } elseif ($normalizedScore <= 60) { + $scoreChartDistribution['41-60']++; + } elseif ($normalizedScore <= 80) { + $scoreChartDistribution['61-80']++; + } else { + $scoreChartDistribution['81-100']++; + } + + /** + * MAINTENANCE DETECTION + */ + $combinedText = $text . ' ' . $review; + + $keywords = [ + 'Login / Akses' => ['login', 'akses', 'masuk', 'akun', 'log in', 'sign in'], + 'Performa Sistem (Server/Lambat)' => ['lambat', 'server', 'loading', 'lemot', 'slow', 'cepat', 'lancar', 'responsif'], + 'Fitur Pembelajaran' => ['materi', 'tugas', 'belajar', 'pembelajaran', 'course', 'modul', 'video', 'konten'], + 'UI / Tampilan' => ['tampilan', 'ui', 'desain', 'interface', 'ux', 'user interface', 'user experience'], + 'Bug / Error' => ['error', 'bug', 'crash', 'force close', 'warning', 'galat', 'masalah'], + 'Aplikasi Mobile' => ['mobile', 'android', 'ios', 'hp', 'handphone', 'app', 'aplikasi'], + 'Ujian / Exam' => ['ujian', 'exam', 'test', 'quiz', 'nilai', 'skor', 'ujian online'] + ]; + + foreach ($keywords as $category => $words) { + foreach ($words as $word) { + if (str_contains($combinedText, $word)) { + $maintenance[$category]++; + if (count($maintenanceDetails[$category]) < 10) { + $maintenanceDetails[$category][] = $row->review; + } + break; + } + } + } + } + + /** + * CONFUSION MATRIX + */ + $cmPath = storage_path('app/public/confusion_matrix.csv'); + $cm = file_exists($cmPath) ? $this->readCSV($cmPath) : [ + ['', 'Pred Negatif', 'Pred Positif'], + ['Actual Negatif', 0, 0], + ['Actual Positif', 0, 0] + ]; + + /** + * METRICS - Disesuaikan dengan format dari Colab + */ + $metricsPath = storage_path('app/public/evaluation_metrics.csv'); + $metrics = file_exists($metricsPath) ? $this->readMetrics($metricsPath) : $this->getDefaultMetrics(); + + /** + * FORMAT METRICS UNTUK CHART + */ + $formattedMetrics = $this->formatMetricsForChart($metrics); + + return [ + 'dataset' => $dataset, + 'positif' => $positif, + 'negatif' => $negatif, + 'totalData' => $totalData, + 'totalSafe' => $totalSafe, + 'maintenance' => $maintenance, + 'maintenanceDetails' => $maintenanceDetails, + 'scoreDistribution' => $scoreDistribution, + 'scoreChartDistribution' => $scoreChartDistribution, + 'score_0_20' => $scoreChartDistribution['0-20'], + 'score_21_40' => $scoreChartDistribution['21-40'], + 'score_41_60' => $scoreChartDistribution['41-60'], + 'score_61_80' => $scoreChartDistribution['61-80'], + 'score_81_100' => $scoreChartDistribution['81-100'], + 'cm' => $cm, + 'metrics' => $metrics, + 'formattedMetrics' => $formattedMetrics + ]; + } + + /** + * Format metrics untuk chart + */ + private function formatMetricsForChart($metrics) + { + return [ + 'accuracy' => $metrics['accuracy'] ?? 0, + 'negatif' => [ + 'precision' => $metrics['precision_negatif'] ?? 0, + 'recall' => $metrics['recall_negatif'] ?? 0, + 'f1' => $metrics['f1_negatif'] ?? 0 + ], + 'positif' => [ + 'precision' => $metrics['precision_positif'] ?? 0, + 'recall' => $metrics['recall_positif'] ?? 0, + 'f1' => $metrics['f1_positif'] ?? 0 + ] + ]; + } + + /** + * Get default metrics structure + */ + private function getDefaultMetrics() + { + return [ + 'accuracy' => 0, + 'precision_negatif' => 0, + 'precision_positif' => 0, + 'recall_negatif' => 0, + 'recall_positif' => 0, + 'f1_negatif' => 0, + 'f1_positif' => 0, + 'macro_avg_precision' => 0, + 'macro_avg_recall' => 0, + 'macro_avg_f1' => 0, + 'weighted_avg_precision' => 0, + 'weighted_avg_recall' => 0, + 'weighted_avg_f1' => 0 + ]; + } + + /** + * Get empty data structure + */ + private function getEmptyData() + { + $maintenance = [ + 'Login / Akses' => 0, + 'Performa Sistem (Server/Lambat)' => 0, + 'Fitur Pembelajaran' => 0, + 'UI / Tampilan' => 0, + 'Bug / Error' => 0, + 'Aplikasi Mobile' => 0, + 'Ujian / Exam' => 0, + ]; + + $maintenanceDetails = [ + 'Login / Akses' => [], + 'Performa Sistem (Server/Lambat)' => [], + 'Fitur Pembelajaran' => [], + 'UI / Tampilan' => [], + 'Bug / Error' => [], + 'Aplikasi Mobile' => [], + 'Ujian / Exam' => [], + ]; + + $scoreDistribution = [ + 'Very Negative (-5 to -9)' => 0, + 'Negative (-1 to -4)' => 0, + 'Positive (1 to 4)' => 0, + 'Very Positive (5 to 9)' => 0, + ]; + + $scoreChartDistribution = [ + '0-20' => 0, + '21-40' => 0, + '41-60' => 0, + '61-80' => 0, + '81-100' => 0, + ]; + + return [ + 'dataset' => collect([]), + 'positif' => 0, + 'negatif' => 0, + 'totalData' => 0, + 'totalSafe' => 1, + 'maintenance' => $maintenance, + 'maintenanceDetails' => $maintenanceDetails, + 'scoreDistribution' => $scoreDistribution, + 'scoreChartDistribution' => $scoreChartDistribution, + 'score_0_20' => 0, + 'score_21_40' => 0, + 'score_41_60' => 0, + 'score_61_80' => 0, + 'score_81_100' => 0, + 'cm' => [ + ['', 'Pred Negatif', 'Pred Positif'], + ['Actual Negatif', 0, 0], + ['Actual Positif', 0, 0] + ], + 'metrics' => $this->getDefaultMetrics(), + 'formattedMetrics' => $this->formatMetricsForChart($this->getDefaultMetrics()) + ]; + } + + /** + * READ METRICS DARI CSV (disesuaikan dengan format dari Colab) + */ + private function readMetrics($path) + { + $default = $this->getDefaultMetrics(); + + if (!file_exists($path)) { + return $default; + } + + $data = $this->readCSV($path); + $metrics = $default; + + foreach ($data as $row) { + if (isset($row[0]) && isset($row[1])) { + $key = strtolower(trim($row[0])); + $value = (float) trim($row[1]); + + // Mapping key dari CSV ke array metrics + if (str_contains($key, 'accuracy')) { + $metrics['accuracy'] = $value; + } elseif (str_contains($key, 'precision_negatif') || str_contains($key, 'precision negatif')) { + $metrics['precision_negatif'] = $value; + } elseif (str_contains($key, 'precision_positif') || str_contains($key, 'precision positif')) { + $metrics['precision_positif'] = $value; + } elseif (str_contains($key, 'recall_negatif') || str_contains($key, 'recall negatif')) { + $metrics['recall_negatif'] = $value; + } elseif (str_contains($key, 'recall_positif') || str_contains($key, 'recall positif')) { + $metrics['recall_positif'] = $value; + } elseif (str_contains($key, 'f1_negatif') || str_contains($key, 'f1 negatif') || str_contains($key, 'f1-score negatif')) { + $metrics['f1_negatif'] = $value; + } elseif (str_contains($key, 'f1_positif') || str_contains($key, 'f1 positif') || str_contains($key, 'f1-score positif')) { + $metrics['f1_positif'] = $value; + } elseif (str_contains($key, 'macro_avg_precision') || str_contains($key, 'macro avg precision')) { + $metrics['macro_avg_precision'] = $value; + } elseif (str_contains($key, 'macro_avg_recall') || str_contains($key, 'macro avg recall')) { + $metrics['macro_avg_recall'] = $value; + } elseif (str_contains($key, 'macro_avg_f1') || str_contains($key, 'macro avg f1')) { + $metrics['macro_avg_f1'] = $value; + } elseif (str_contains($key, 'weighted_avg_precision') || str_contains($key, 'weighted avg precision')) { + $metrics['weighted_avg_precision'] = $value; + } elseif (str_contains($key, 'weighted_avg_recall') || str_contains($key, 'weighted avg recall')) { + $metrics['weighted_avg_recall'] = $value; + } elseif (str_contains($key, 'weighted_avg_f1') || str_contains($key, 'weighted avg f1')) { + $metrics['weighted_avg_f1'] = $value; + } + } + } + + return $metrics; + } + + /** + * =============================== + * UPLOAD CSV → INSERT DATABASE + * =============================== + */ + public function upload(Request $request) + { + $validator = Validator::make($request->all(), [ + 'dataset' => 'required|mimes:csv,txt|max:10240', + ]); + + if ($validator->fails()) { + return back()->withErrors($validator)->withInput(); + } + + $file = $request->file('dataset'); + $path = $file->getRealPath(); + + try { + $rows = $this->readCSV($path); + + if (count($rows) <= 1) { + return back()->with('error', 'File CSV tidak memiliki data!'); + } + + $header = array_shift($rows); // Hapus header + + DB::beginTransaction(); + + if ($request->has('replace_data') && $request->replace_data == '1') { + Review::truncate(); + } + + $inserted = 0; + $failed = 0; + + foreach ($rows as $row) { + try { + // Validasi minimal memiliki 4 kolom + if (count($row) >= 4) { + + // Parse sentiment + $sentiment = strtolower(trim($row[3] ?? '')); + // Pastikan sentiment hanya positif atau negatif + if (!in_array($sentiment, ['positif', 'negatif'])) { + $sentiment = $sentiment == 'positive' ? 'positif' : ($sentiment == 'negative' ? 'negatif' : 'netral'); + } + + // Parse score + $score = is_numeric($row[2] ?? '') ? (int)$row[2] : 0; + + Review::create([ + 'review' => $row[0] ?? '', + 'steming_data' => $row[1] ?? '', + 'score' => $score, + 'sentiment' => $sentiment, + 'created_at' => $row[4] ?? now(), + 'updated_at' => now(), + ]); + $inserted++; + } else { + $failed++; + } + } catch (\Exception $e) { + $failed++; + // \Log::warning('Gagal insert row: ' . json_encode($row) . ' Error: ' . $e->getMessage()); + } + } + + DB::commit(); + + $message = "Berhasil mengupload {$inserted} data"; + if ($failed > 0) { + $message .= ", {$failed} data gagal diproses"; + } + + return back()->with('success', $message); + + } catch (\Exception $e) { + DB::rollBack(); + return back()->with('error', 'Gagal upload: ' . $e->getMessage()); + } + } + + /** + * =============================== + * HAPUS SEMUA DATA + * =============================== + */ + public function truncate() + { + try { + Review::truncate(); + return back()->with('success', 'Semua data berhasil dihapus!'); + } catch (\Exception $e) { + return back()->with('error', 'Gagal menghapus data: ' . $e->getMessage()); + } + } + + /** + * =============================== + * EXPORT PDF + * =============================== + */ + public function exportPDF(Request $request) + { + $data = $this->getCommonData($request); + $data['title'] = 'Laporan Analisis Sentimen'; + $data['date'] = now()->format('d F Y'); + // $data['user'] = auth()->user(); + + $pdf = Pdf::loadView('pdf.report', $data); + $pdf->setPaper('A4', 'landscape'); + + return $pdf->download('laporan_sentimen_' . date('Y-m-d') . '.pdf'); + } + + /** + * =============================== + * EXPORT EXCEL (CSV) + * =============================== + */ + public function exportExcel(Request $request) + { + $data = $this->getCommonData($request); + + $filename = 'data_sentimen_' . date('Y-m-d') . '.csv'; + + $headers = [ + 'Content-Type' => 'text/csv', + 'Content-Disposition' => "attachment; filename=\"$filename\"", + ]; + + $callback = function() use ($data) { + $file = fopen('php://output', 'w'); + + // Header CSV + fputcsv($file, ['ID', 'Review', 'Steming Data', 'Score', 'Sentimen', 'Tanggal']); + + // Data + foreach ($data['dataset'] as $review) { + fputcsv($file, [ + $review->id, + $review->review, + $review->steming_data, + $review->score, + $review->sentiment, + $review->created_at->format('Y-m-d H:i:s') + ]); + } + + fclose($file); + }; + + return response()->stream($callback, 200, $headers); + } + + /** + * =============================== + * API ENDPOINT (Untuk AJAX) + * =============================== + */ + public function getStats(Request $request) + { + $data = $this->getCommonData($request); + + return response()->json([ + 'success' => true, + 'data' => [ + 'positif' => $data['positif'], + 'negatif' => $data['negatif'], + 'total' => $data['totalData'], + 'positif_percentage' => $data['totalData'] > 0 ? round(($data['positif'] / $data['totalData']) * 100, 1) : 0, + 'negatif_percentage' => $data['totalData'] > 0 ? round(($data['negatif'] / $data['totalData']) * 100, 1) : 0, + 'score_distribution' => [ + '0-20' => $data['score_0_20'] ?? 0, + '21-40' => $data['score_21_40'] ?? 0, + '41-60' => $data['score_41_60'] ?? 0, + '61-80' => $data['score_61_80'] ?? 0, + '81-100' => $data['score_81_100'] ?? 0, + ], + 'metrics' => [ + 'accuracy' => $data['metrics']['accuracy'] ?? 0, + 'negatif' => [ + 'precision' => $data['metrics']['precision_negatif'] ?? 0, + 'recall' => $data['metrics']['recall_negatif'] ?? 0, + 'f1' => $data['metrics']['f1_negatif'] ?? 0 + ], + 'positif' => [ + 'precision' => $data['metrics']['precision_positif'] ?? 0, + 'recall' => $data['metrics']['recall_positif'] ?? 0, + 'f1' => $data['metrics']['f1_positif'] ?? 0 + ] + ], + 'maintenance' => $data['maintenance'], + 'cm' => $data['cm'] + ] + ]); + } + + /** + * =============================== + * HELPER READ CSV + * =============================== + */ + private function readCSV($path) + { + $data = []; + + if (!file_exists($path) || !is_readable($path)) { + return $data; + } + + $file = fopen($path, 'r'); + + if (!$file) { + return $data; + } + + // Deteksi delimiter + $firstLine = fgets($file); + rewind($file); + + $delimiters = [',', ';', "\t", '|']; + $delimiter = ','; + $maxCount = 0; + + foreach ($delimiters as $d) { + $count = count(str_getcsv($firstLine, $d)); + if ($count > $maxCount) { + $maxCount = $count; + $delimiter = $d; + } + } + + // Baca CSV + while (($row = fgetcsv($file, 0, $delimiter)) !== FALSE) { + $row = array_map('trim', $row); + $data[] = $row; + } + + fclose($file); + + return $data; + } + + /** + * =============================== + * UPDATE SINGLE REVIEW + * =============================== + */ + public function updateReview(Request $request, $id) + { + $request->validate([ + 'review' => 'required|string', + 'sentiment' => 'required|in:positif,negatif', + 'score' => 'required|integer|min:-9|max:9' + ]); + + try { + $review = Review::findOrFail($id); + $review->update([ + 'review' => $request->review, + 'steming_data' => $request->steming_data ?? $request->review, + 'score' => $request->score, + 'sentiment' => $request->sentiment + ]); + + return response()->json([ + 'success' => true, + 'message' => 'Review berhasil diupdate' + ]); + } catch (\Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Gagal update: ' . $e->getMessage() + ], 500); + } + } + + /** + * =============================== + * DELETE SINGLE REVIEW + * =============================== + */ + public function deleteReview($id) + { + try { + $review = Review::findOrFail($id); + $review->delete(); + + return response()->json([ + 'success' => true, + 'message' => 'Review berhasil dihapus' + ]); + } catch (\Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Gagal hapus: ' . $e->getMessage() + ], 500); + } + } + + /** + * =============================== + * HALAMAN ANALYTICS KHUSUS (Optional) + * =============================== + */ + public function showAnalytics(Request $request) + { + $data = $this->getCommonData($request); + + // Data tambahan untuk analytics + $data['page_title'] = 'Analytics Dashboard'; + $data['date_range'] = [ + 'start' => $request->start_date ?? now()->subDays(30)->format('Y-m-d'), + 'end' => $request->end_date ?? now()->format('Y-m-d') + ]; + + return view('analytics', $data); + } + + +} \ No newline at end of file diff --git a/app/Http/Controllers/ProfileController.php b/app/Http/Controllers/ProfileController.php new file mode 100644 index 0000000..a48eb8d --- /dev/null +++ b/app/Http/Controllers/ProfileController.php @@ -0,0 +1,60 @@ + $request->user(), + ]); + } + + /** + * Update the user's profile information. + */ + public function update(ProfileUpdateRequest $request): RedirectResponse + { + $request->user()->fill($request->validated()); + + if ($request->user()->isDirty('email')) { + $request->user()->email_verified_at = null; + } + + $request->user()->save(); + + return Redirect::route('profile.edit')->with('status', 'profile-updated'); + } + + /** + * Delete the user's account. + */ + public function destroy(Request $request): RedirectResponse + { + $request->validateWithBag('userDeletion', [ + 'password' => ['required', 'current_password'], + ]); + + $user = $request->user(); + + Auth::logout(); + + $user->delete(); + + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return Redirect::to('/'); + } +} diff --git a/app/Http/Middleware/CheckRole.php b/app/Http/Middleware/CheckRole.php new file mode 100644 index 0000000..0daa2c9 --- /dev/null +++ b/app/Http/Middleware/CheckRole.php @@ -0,0 +1,20 @@ +user() || $request->user()->role !== $role) { + return redirect()->route('dashboard')->with('error', 'Akses ditolak! Halaman ini hanya untuk Administrator.'); + } + + return $next($request); + } +} \ No newline at end of file diff --git a/app/Http/Requests/Auth/LoginRequest.php b/app/Http/Requests/Auth/LoginRequest.php new file mode 100644 index 0000000..2574642 --- /dev/null +++ b/app/Http/Requests/Auth/LoginRequest.php @@ -0,0 +1,85 @@ +|string> + */ + public function rules(): array + { + return [ + 'email' => ['required', 'string', 'email'], + 'password' => ['required', 'string'], + ]; + } + + /** + * Attempt to authenticate the request's credentials. + * + * @throws \Illuminate\Validation\ValidationException + */ + public function authenticate(): void + { + $this->ensureIsNotRateLimited(); + + if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) { + RateLimiter::hit($this->throttleKey()); + + throw ValidationException::withMessages([ + 'email' => trans('auth.failed'), + ]); + } + + RateLimiter::clear($this->throttleKey()); + } + + /** + * Ensure the login request is not rate limited. + * + * @throws \Illuminate\Validation\ValidationException + */ + public function ensureIsNotRateLimited(): void + { + if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) { + return; + } + + event(new Lockout($this)); + + $seconds = RateLimiter::availableIn($this->throttleKey()); + + throw ValidationException::withMessages([ + 'email' => trans('auth.throttle', [ + 'seconds' => $seconds, + 'minutes' => ceil($seconds / 60), + ]), + ]); + } + + /** + * Get the rate limiting throttle key for the request. + */ + public function throttleKey(): string + { + return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip()); + } +} diff --git a/app/Http/Requests/ProfileUpdateRequest.php b/app/Http/Requests/ProfileUpdateRequest.php new file mode 100644 index 0000000..3622a8f --- /dev/null +++ b/app/Http/Requests/ProfileUpdateRequest.php @@ -0,0 +1,30 @@ +|string> + */ + public function rules(): array + { + return [ + 'name' => ['required', 'string', 'max:255'], + 'email' => [ + 'required', + 'string', + 'lowercase', + 'email', + 'max:255', + Rule::unique(User::class)->ignore($this->user()->id), + ], + ]; + } +} diff --git a/app/Models/Review.php b/app/Models/Review.php new file mode 100644 index 0000000..426747e --- /dev/null +++ b/app/Models/Review.php @@ -0,0 +1,69 @@ + 'integer', + 'created_at' => 'datetime', + 'updated_at' => 'datetime' + ]; + + /** + * Scope untuk filter sentimen positif + */ + public function scopePositif($query) + { + return $query->where('sentiment', 'positif'); + } + + /** + * Scope untuk filter sentimen negatif + */ + public function scopeNegatif($query) + { + return $query->where('sentiment', 'negatif'); + } + + /** + * Scope untuk filter berdasarkan score + */ + public function scopeScoreRange($query, $min, $max) + { + return $query->whereBetween('score', [$min, $max]); + } + + /** + * Get sentiment badge class untuk styling + */ + public function getSentimentBadgeClassAttribute() + { + return $this->sentiment === 'positif' + ? 'bg-green-100 text-green-800' + : 'bg-red-100 text-red-800'; + } + + /** + * Get sentiment in uppercase + */ + public function getSentimentUppercaseAttribute() + { + return strtoupper($this->sentiment); + } +} \ No newline at end of file diff --git a/app/Models/Sentiment.php b/app/Models/Sentiment.php new file mode 100644 index 0000000..48d43e4 --- /dev/null +++ b/app/Models/Sentiment.php @@ -0,0 +1,16 @@ + */ + use HasFactory, Notifiable; + + /** + * The attributes that are mass assignable. + * + * @var listTenang, kami akan bantu reset password Anda
+Masukkan email Anda dan kami akan mengirimkan link reset password.
+Silakan login ke akun S-Learn Anda
+Daftar untuk menggunakan S-Learn
+Memantau kepuasan dan masukan pengguna platform S-Learn
+Total Ulasan
+{{ number_format($totalData) }}
+Semua ulasan yang masuk
+Ulasan Positif
+{{ number_format($positif) }}
+{{ $persentasePositif }}% dari total
+Ulasan Negatif
+{{ number_format($negatif) }}
+{{ $persentaseNegatif }}% dari total
+Tingkat Kepuasan
+{{ $persentasePositif }}%
+Pengguna puas
+Membandingkan jumlah ulasan positif dan negatif
+Persentase perbandingan ulasan
++ {{ $persentasePositif }}% Puas + | + {{ $persentaseNegatif }}% Tidak Puas +
+Skor 0-100 (Semakin tinggi angkanya, semakin puas pengguna)
+ + ++ 📊 Analisis: + Grafik menunjukkan sebaran tingkat kepuasan. + @if($score_81_100 > $score_0_20) + Mayoritas pengguna merasa puas dengan layanan S-Learn (skor 81-100). + @else + Perlu perhatian pada area dengan skor rendah (0-40) untuk meningkatkan kepuasan. + @endif +
+Seberapa akurat sistem dalam memprediksi sentimen
+ +Precision (Ketepatan)
+{{ number_format($metricsPositif['precision'] * 100, 1) }}%
+Seberapa tepat sistem memprediksi sentimen positif
+Recall (Kelengkapan)
+{{ number_format($metricsPositif['recall'] * 100, 1) }}%
+Seberapa lengkap sistem menangkap sentimen positif
+F1-Score (Keseimbangan)
+{{ number_format($metricsPositif['f1'] * 100, 1) }}%
+Keseimbangan antara ketepatan dan kelengkapan
+Tabel ini menunjukkan detail hasil prediksi sistem
+ + @if(isset($cm) && count($cm) > 1) +| + | HASIL PREDIKSI SISTEM | +|
| + | Diprediksi NEGATIF | +Diprediksi POSITIF | +
| + {{ $i == 1 ? 'AKTUAL NEGATIF' : 'AKTUAL POSITIF' }} + (Kenyataan sebenarnya) + | ++ {{ number_format($row[1]) }} + + @if($i==1) + ✓ Benar Negatif + (Sistem benar memprediksi NEGATIF) + @else + ✗ Salah Negatif + (Sistem salah memprediksi NEGATIF, padahal POSITIF) + @endif + + | ++ {{ number_format($row[2]) }} + + @if($i==2) + ✓ Benar Positif + (Sistem benar memprediksi POSITIF) + @else + ✗ Salah Positif + (Sistem salah memprediksi POSITIF, padahal NEGATIF) + @endif + + | +
✓ Prediksi Benar
+✗ Prediksi Salah
+
+ 📈 Ringkasan:
+ Dari total {{ number_format($totalData) }} ulasan, sistem berhasil memprediksi dengan benar
+ {{ number_format(($cm[1][1] ?? 0) + ($cm[2][2] ?? 0)) }} data
+ ({{ $totalData > 0 ? round((($cm[1][1] ?? 0) + ($cm[2][2] ?? 0)) / $totalData * 100, 1) : 0 }}%)
+ dan salah memprediksi
+ {{ number_format(($cm[1][2] ?? 0) + ($cm[2][1] ?? 0)) }} data.
+
Data confusion matrix belum tersedia
+Keluhan pengguna yang perlu mendapatkan perhatian
+ ++ {{ $jumlah }} pengguna melaporkan masalah ini +
+ + @if(!empty($maintenanceDetails[$kategori])) + + @endif +Tidak ada masalah yang dilaporkan
+Semua sistem berjalan dengan baik
+Kelola, upload, dan export dataset analisis sentimen
+{{ session('success') }}
+{{ session('error') }}
+Terjadi kesalahan:
+Total Dataset
+{{ number_format($totalData) }}
+Data Positif
+{{ number_format($positif) }}
+Data Negatif
+{{ number_format($negatif) }}
+Akurasi Model
+{{ number_format(($metrics['accuracy'] ?? 0) * 100, 1) }}%
+| ID | +Review | +Text Final | +Score | +Sentimen | +Tanggal | +Aksi | +
|---|---|---|---|---|---|---|
| #{{ $review->id ?? '-' }} | + +
+
+
+
+ {{ Str::limit($review->review ?? '-', 50) }}
+
+
+ |
+
+ + + {{ Str::limit($review->text_final ?? $review->review ?? '-', 40) }} + + | + ++ @php $score = $review->score ?? 0; @endphp + + {{ $score }} + + | + ++ @php $sentiment = $review->sentiment ?? 'netral'; @endphp + + + {{ ucfirst($sentiment) }} + + | + ++ + {{ $review->created_at ? $review->created_at->format('d/m/Y H:i') : date('d/m/Y H:i') }} + | + +
+
+
+
+
+ |
+
|
+
+ Belum ada data tersedia +Silakan upload file CSV untuk memulai + |
+ ||||||
Informasi Dataset
++ Dataset terdiri dari {{ number_format($totalData) }} review dengan {{ number_format($positif) }} data positif ({{ number_format(($positif/$totalSafe)*100, 1) }}%) dan {{ number_format($negatif) }} data negatif ({{ number_format(($negatif/$totalSafe)*100, 1) }}%). + Format file CSV yang diterima: review, steming_data, score (integer -9 s/d 9), sentiment (positif/negatif). +
+Tanggal: {{ $date }}
+Diekspor oleh: {{ auth()->user()->name ?? 'Admin' }}
+| Total Data | +{{ $totalData }} | +
|---|---|
| Positif | +{{ $positif }} ({{ number_format(($positif / $totalSafe) * 100, 1) }}%) | +
| Negatif | +{{ $negatif }} ({{ number_format(($negatif / $totalSafe) * 100, 1) }}%) | +
| No | +Review | +Score | +Sentimen | +Tanggal | +
|---|---|---|---|---|
| {{ $index + 1 }} | +{{ $review->review }} | +{{ $review->score }} | +{{ ucfirst($review->sentiment) }} | +{{ $review->created_at->format('d/m/Y') }} | +
+ {{ __('Once your account is deleted, all of its resources and data will be permanently deleted. Before deleting your account, please download any data or information that you wish to retain.') }} +
++ {{ __('Ensure your account is using a long, random password to stay secure.') }} +
++ {{ __("Update your account's profile information and email address.") }} +
+Laravel has an incredibly rich ecosystem.
We suggest starting with the following.
Memantau kepuasan dan masukan pengguna platform S-Learn
+Total Ulasan
+ +Semua ulasan yang masuk
+Ulasan Positif
+ +% dari total
+Ulasan Negatif
+ +% dari total
+Tingkat Kepuasan
+%
+Pengguna puas
+Membandingkan jumlah ulasan positif dan negatif
+Persentase perbandingan ulasan
++ % Puas + | + % Tidak Puas +
+Skor 0-100 (Semakin tinggi angkanya, semakin puas pengguna)
+ + ++ 📊 Analisis: + Grafik menunjukkan sebaran tingkat kepuasan. + $score_0_20): ?> + Mayoritas pengguna merasa puas dengan layanan S-Learn (skor 81-100). + + Perlu perhatian pada area dengan skor rendah (0-40) untuk meningkatkan kepuasan. + +
+Seberapa akurat sistem dalam memprediksi sentimen
+ +Precision (Ketepatan)
+%
+Seberapa tepat sistem memprediksi sentimen positif
+Recall (Kelengkapan)
+%
+Seberapa lengkap sistem menangkap sentimen positif
+F1-Score (Keseimbangan)
+%
+Keseimbangan antara ketepatan dan kelengkapan
+Tabel ini menunjukkan detail hasil prediksi sistem
+ + 1): ?> +| + | HASIL PREDIKSI SISTEM | +|
| + | Diprediksi NEGATIF | +Diprediksi POSITIF | +
| + + + (Kenyataan sebenarnya) + | ++ + + + ✓ Benar Negatif + (Sistem benar memprediksi NEGATIF) + + ✗ Salah Negatif + (Sistem salah memprediksi NEGATIF, padahal POSITIF) + + + | ++ + + + ✓ Benar Positif + (Sistem benar memprediksi POSITIF) + + ✗ Salah Positif + (Sistem salah memprediksi POSITIF, padahal NEGATIF) + + + | +
✓ Prediksi Benar
+✗ Prediksi Salah
+
+ 📈 Ringkasan:
+ Dari total ulasan, sistem berhasil memprediksi dengan benar
+ data
+ ( 0 ? round((($cm[1][1] ?? 0) + ($cm[2][2] ?? 0)) / $totalData * 100, 1) : 0); ?>%)
+ dan salah memprediksi
+ data.
+
Data confusion matrix belum tersedia
+Keluhan pengguna yang perlu mendapatkan perhatian
+ ++ pengguna melaporkan masalah ini +
+ + + + +Tidak ada masalah yang dilaporkan
+Semua sistem berjalan dengan baik
+Silakan login ke akun S-Learn Anda
+