first commit
This commit is contained in:
commit
d74f2d442c
|
|
@ -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
|
||||
|
||||
[docker-compose.yml]
|
||||
indent_size = 4
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
APP_NAME=Laravel
|
||||
APP_ENV=local
|
||||
APP_KEY=
|
||||
APP_DEBUG=true
|
||||
APP_URL=http://localhost
|
||||
|
||||
LOG_CHANNEL=stack
|
||||
LOG_DEPRECATIONS_CHANNEL=null
|
||||
LOG_LEVEL=debug
|
||||
|
||||
DB_CONNECTION=mysql
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=laravel
|
||||
DB_USERNAME=root
|
||||
DB_PASSWORD=
|
||||
|
||||
BROADCAST_DRIVER=log
|
||||
CACHE_DRIVER=file
|
||||
FILESYSTEM_DISK=local
|
||||
QUEUE_CONNECTION=sync
|
||||
SESSION_DRIVER=file
|
||||
SESSION_LIFETIME=120
|
||||
|
||||
MEMCACHED_HOST=127.0.0.1
|
||||
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=mailpit
|
||||
MAIL_PORT=1025
|
||||
MAIL_USERNAME=null
|
||||
MAIL_PASSWORD=null
|
||||
MAIL_ENCRYPTION=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
|
||||
|
||||
PUSHER_APP_ID=
|
||||
PUSHER_APP_KEY=
|
||||
PUSHER_APP_SECRET=
|
||||
PUSHER_HOST=
|
||||
PUSHER_PORT=443
|
||||
PUSHER_SCHEME=https
|
||||
PUSHER_APP_CLUSTER=mt1
|
||||
|
||||
VITE_APP_NAME="${APP_NAME}"
|
||||
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
|
||||
VITE_PUSHER_HOST="${PUSHER_HOST}"
|
||||
VITE_PUSHER_PORT="${PUSHER_PORT}"
|
||||
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
|
||||
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
|
||||
|
|
@ -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
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
/.phpunit.cache
|
||||
/node_modules
|
||||
/public/build
|
||||
/public/hot
|
||||
/public/storage
|
||||
/storage/*.key
|
||||
/vendor
|
||||
.env
|
||||
.env.backup
|
||||
.env.production
|
||||
.phpunit.result.cache
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
auth.json
|
||||
npm-debug.log
|
||||
yarn-error.log
|
||||
/.fleet
|
||||
/.idea
|
||||
/.vscode
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
|
||||
</p>
|
||||
|
||||
## 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 may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
|
||||
|
||||
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)**
|
||||
- **[WebReinvent](https://webreinvent.com/)**
|
||||
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
|
||||
- **[64 Robots](https://64robots.com)**
|
||||
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
|
||||
- **[Cyber-Duck](https://cyber-duck.co.uk)**
|
||||
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
|
||||
- **[Jump24](https://jump24.co.uk)**
|
||||
- **[Redberry](https://redberry.international/laravel/)**
|
||||
- **[Active Logic](https://activelogic.com)**
|
||||
- **[byte5](https://byte5.de)**
|
||||
- **[OP.GG](https://op.gg)**
|
||||
|
||||
## 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).
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule;
|
||||
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
|
||||
|
||||
class Kernel extends ConsoleKernel
|
||||
{
|
||||
/**
|
||||
* Define the application's command schedule.
|
||||
*/
|
||||
protected function schedule(Schedule $schedule): void
|
||||
{
|
||||
// $schedule->command('inspire')->hourly();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the commands for the application.
|
||||
*/
|
||||
protected function commands(): void
|
||||
{
|
||||
$this->load(__DIR__.'/Commands');
|
||||
|
||||
require base_path('routes/console.php');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
|
||||
namespace App\Exceptions;
|
||||
|
||||
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
|
||||
use Throwable;
|
||||
|
||||
class Handler extends ExceptionHandler
|
||||
{
|
||||
/**
|
||||
* The list of the inputs that are never flashed to the session on validation exceptions.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $dontFlash = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
|
||||
/**
|
||||
* Register the exception handling callbacks for the application.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
$this->reportable(function (Throwable $e) {
|
||||
//
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Auth\LoginRequest;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AuthenticatedSessionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the login view.
|
||||
*/
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle an incoming authentication request.
|
||||
*/
|
||||
public function store(LoginRequest $request): RedirectResponse
|
||||
{
|
||||
$request->authenticate();
|
||||
|
||||
$request->session()->regenerate();
|
||||
|
||||
return redirect()->intended(RouteServiceProvider::HOME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy an authenticated session.
|
||||
*/
|
||||
public function destroy(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
|
||||
$request->session()->invalidate();
|
||||
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect('/login');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ConfirmablePasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Show the confirm password view.
|
||||
*/
|
||||
public function show(): View
|
||||
{
|
||||
return view('auth.confirm-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm the user's password.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if (! Auth::guard('web')->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(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class EmailVerificationNotificationController extends Controller
|
||||
{
|
||||
/**
|
||||
* Send a new email verification notification.
|
||||
*/
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(RouteServiceProvider::HOME);
|
||||
}
|
||||
|
||||
$request->user()->sendEmailVerificationNotification();
|
||||
|
||||
return back()->with('status', 'verification-link-sent');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class EmailVerificationPromptController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the email verification prompt.
|
||||
*/
|
||||
public function __invoke(Request $request): RedirectResponse|View
|
||||
{
|
||||
return $request->user()->hasVerifiedEmail()
|
||||
? redirect()->intended(RouteServiceProvider::HOME)
|
||||
: view('auth.verify-email');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\User;
|
||||
use App\Models\PasswordReset;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class ForgotPasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan form request OTP
|
||||
*/
|
||||
public function showForgotForm()
|
||||
{
|
||||
return view('auth.forgot-password');
|
||||
}
|
||||
|
||||
/**
|
||||
* Kirim OTP ke email menggunakan Laravel Mail
|
||||
*/
|
||||
public function sendOtp(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email|exists:users,email',
|
||||
], [
|
||||
'email.exists' => 'Email tidak terdaftar dalam sistem.'
|
||||
]);
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
// Generate OTP 6 digit
|
||||
$otp = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||
|
||||
// Simpan OTP ke database (expired 5 menit)
|
||||
PasswordReset::updateOrCreate(
|
||||
['email' => $request->email],
|
||||
[
|
||||
'token' => $otp,
|
||||
'created_at' => Carbon::now(),
|
||||
]
|
||||
);
|
||||
|
||||
// Kirim email menggunakan Laravel Mail
|
||||
try {
|
||||
Mail::send([], [], function ($message) use ($user, $otp) {
|
||||
$message->to($user->email, $user->name)
|
||||
->subject('Kode OTP Reset Password - LearnMood')
|
||||
->html($this->getEmailTemplate($user->name, $otp, $user->email));
|
||||
});
|
||||
|
||||
return redirect()->route('password.verify.form', ['email' => $request->email])
|
||||
->with('success', 'Kode OTP telah dikirim ke email Anda. Cek inbox/spam folder.');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
// Log error
|
||||
\Log::error('Email error: ' . $e->getMessage());
|
||||
|
||||
// Untuk development, tampilkan OTP di session
|
||||
return redirect()->route('password.verify.form', ['email' => $request->email])
|
||||
->with('dev_otp', $otp)
|
||||
->with('success', '🔧 Mode Development - Gagal kirim email. Gunakan kode OTP berikut:');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form verifikasi OTP
|
||||
*/
|
||||
public function showVerifyForm(Request $request)
|
||||
{
|
||||
return view('auth.verify-code', ['email' => $request->email]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifikasi OTP
|
||||
*/
|
||||
public function verifyOtp(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'otp' => 'required|string|size:6',
|
||||
]);
|
||||
|
||||
$reset = PasswordReset::where('email', $request->email)
|
||||
->where('token', $request->otp)
|
||||
->first();
|
||||
|
||||
if (!$reset) {
|
||||
return back()->with('error', 'Kode OTP tidak valid.');
|
||||
}
|
||||
|
||||
// Cek apakah OTP sudah expired (lebih dari 5 menit)
|
||||
if (Carbon::parse($reset->created_at)->addMinutes(5)->isPast()) {
|
||||
$reset->delete();
|
||||
return back()->with('error', 'Kode OTP sudah kadaluarsa. Silakan minta kode baru.');
|
||||
}
|
||||
|
||||
// OTP valid, arahkan ke form reset password
|
||||
return redirect()->route('password.reset.form', [
|
||||
'email' => $request->email,
|
||||
'token' => $request->otp
|
||||
])->with('success', 'Kode valid. Silakan buat password baru.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form reset password
|
||||
*/
|
||||
public function showResetForm(Request $request)
|
||||
{
|
||||
return view('auth.reset-password', [
|
||||
'email' => $request->email,
|
||||
'token' => $request->token
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset password dengan OTP
|
||||
*/
|
||||
public function resetPassword(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'token' => 'required|string|size:6',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
]);
|
||||
|
||||
// Verifikasi OTP sekali lagi
|
||||
$reset = PasswordReset::where('email', $request->email)
|
||||
->where('token', $request->token)
|
||||
->first();
|
||||
|
||||
if (!$reset || Carbon::parse($reset->created_at)->addMinutes(5)->isPast()) {
|
||||
return back()->with('error', 'Kode OTP tidak valid atau sudah kadaluarsa.');
|
||||
}
|
||||
|
||||
// Update password user
|
||||
$user = User::where('email', $request->email)->first();
|
||||
$user->password = Hash::make($request->password);
|
||||
$user->save();
|
||||
|
||||
// Hapus data reset
|
||||
$reset->delete();
|
||||
|
||||
return redirect()->route('login')
|
||||
->with('success', 'Password berhasil direset. Silakan login dengan password baru.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Template email HTML
|
||||
*/
|
||||
private function getEmailTemplate($toName, $otp, $toEmail)
|
||||
{
|
||||
return "
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Kode OTP Reset Password</title>
|
||||
</head>
|
||||
<body style='font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px;'>
|
||||
<div style='max-width: 500px; margin: 0 auto; background-color: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>
|
||||
<div style='text-align: center; margin-bottom: 25px;'>
|
||||
<h1 style='color: #4A90E2; margin: 0;'>Learn<span style='color: #333;'>Mood</span></h1>
|
||||
</div>
|
||||
|
||||
<p style='font-size: 16px; color: #333;'>Halo <strong>{$toName}</strong>,</p>
|
||||
|
||||
<p style='font-size: 14px; color: #666;'>Kami menerima permintaan reset password untuk akun Anda. Gunakan kode OTP berikut untuk melanjutkan:</p>
|
||||
|
||||
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; text-align: center; border-radius: 8px; margin: 25px 0;'>
|
||||
<p style='margin: 0; font-size: 14px; color: rgba(255,255,255,0.9);'>Kode Verifikasi</p>
|
||||
<h1 style='font-size: 48px; letter-spacing: 8px; color: white; margin: 10px 0; font-family: monospace;'>{$otp}</h1>
|
||||
</div>
|
||||
|
||||
<div style='background-color: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;'>
|
||||
<p style='margin: 0; font-size: 13px; color: #666;'>
|
||||
<strong>⏰ Berlaku selama:</strong> 5 menit<br>
|
||||
<strong>📧 Email:</strong> {$toEmail}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p style='font-size: 13px; color: #999; border-top: 1px solid #eee; padding-top: 20px; margin-top: 20px;'>
|
||||
Jika Anda tidak meminta reset password, abaikan email ini.
|
||||
</p>
|
||||
|
||||
<p style='font-size: 12px; color: #999; text-align: center; margin-top: 20px;'>
|
||||
© " . date('Y') . " LearnMood. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
";
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class LoginController extends Controller
|
||||
{
|
||||
public function showLoginForm()
|
||||
{
|
||||
return view('auth.login');
|
||||
}
|
||||
|
||||
public function login(Request $request)
|
||||
{
|
||||
$credentials = $request->validate([
|
||||
'email' => ['required', 'email'],
|
||||
'password' => ['required'],
|
||||
]);
|
||||
|
||||
if (Auth::attempt($credentials, $request->boolean('remember'))) {
|
||||
$request->session()->regenerate();
|
||||
return redirect()->intended('dashboard');
|
||||
}
|
||||
|
||||
return back()->withErrors([
|
||||
'email' => 'Email atau password salah.',
|
||||
])->onlyInput('email');
|
||||
}
|
||||
|
||||
public function logout(Request $request)
|
||||
{
|
||||
Auth::logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
return redirect()->route('login');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,205 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use App\Models\User;
|
||||
use App\Models\PasswordOtp;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
|
||||
class OtpPasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Tampilkan form request OTP
|
||||
*/
|
||||
public function showRequestForm()
|
||||
{
|
||||
return view('auth.forgot-password-otp');
|
||||
}
|
||||
|
||||
/**
|
||||
* Kirim OTP ke email
|
||||
*/
|
||||
public function sendOtp(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email|exists:users,email',
|
||||
], [
|
||||
'email.exists' => 'Email tidak terdaftar dalam sistem.'
|
||||
]);
|
||||
|
||||
$user = User::where('email', $request->email)->first();
|
||||
|
||||
// Generate OTP 6 digit
|
||||
$otp = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
|
||||
|
||||
// Simpan OTP ke database (expired 5 menit)
|
||||
PasswordOtp::updateOrCreate(
|
||||
['email' => $request->email],
|
||||
[
|
||||
'otp' => $otp,
|
||||
'expires_at' => Carbon::now()->addMinutes(5),
|
||||
]
|
||||
);
|
||||
|
||||
// Kirim email OTP
|
||||
try {
|
||||
$this->sendOtpEmail($user->email, $user->name, $otp);
|
||||
|
||||
return redirect()->route('password.otp.verify.form', ['email' => $request->email])
|
||||
->with('success', 'Kode OTP telah dikirim ke email Anda. Cek inbox/spam folder.');
|
||||
} catch (\Exception $e) {
|
||||
// Log error
|
||||
\Log::error('OTP Email error: ' . $e->getMessage());
|
||||
|
||||
// Untuk development, tampilkan OTP di session
|
||||
if (app()->environment('local')) {
|
||||
return redirect()->route('password.otp.verify.form', ['email' => $request->email])
|
||||
->with('dev_otp', $otp)
|
||||
->with('success', '🔧 Mode Development - Kode OTP Anda:');
|
||||
}
|
||||
|
||||
return back()->with('error', 'Gagal mengirim email. Silakan coba lagi.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form verifikasi OTP
|
||||
*/
|
||||
public function showVerifyForm(Request $request)
|
||||
{
|
||||
return view('auth.verify-otp', ['email' => $request->email]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifikasi OTP
|
||||
*/
|
||||
public function verifyOtp(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'otp' => 'required|string|size:6',
|
||||
]);
|
||||
|
||||
$otpRecord = PasswordOtp::where('email', $request->email)
|
||||
->where('otp', $request->otp)
|
||||
->first();
|
||||
|
||||
if (!$otpRecord) {
|
||||
return back()->with('error', 'Kode OTP tidak valid.');
|
||||
}
|
||||
|
||||
// Cek apakah OTP sudah expired
|
||||
if (Carbon::now()->gt($otpRecord->expires_at)) {
|
||||
$otpRecord->delete();
|
||||
return back()->with('error', 'Kode OTP sudah kadaluarsa. Silakan minta kode baru.');
|
||||
}
|
||||
|
||||
// OTP valid, arahkan ke form reset password
|
||||
return redirect()->route('password.otp.reset.form', [
|
||||
'email' => $request->email,
|
||||
'otp' => $request->otp
|
||||
])->with('success', 'Kode valid. Silakan buat password baru.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form reset password
|
||||
*/
|
||||
public function showResetForm(Request $request)
|
||||
{
|
||||
return view('auth.reset-password-otp', [
|
||||
'email' => $request->email,
|
||||
'otp' => $request->otp
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset password dengan OTP
|
||||
*/
|
||||
public function resetPassword(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'email' => 'required|email',
|
||||
'otp' => 'required|string|size:6',
|
||||
'password' => 'required|string|min:8|confirmed',
|
||||
]);
|
||||
|
||||
// Verifikasi OTP sekali lagi
|
||||
$otpRecord = PasswordOtp::where('email', $request->email)
|
||||
->where('otp', $request->otp)
|
||||
->first();
|
||||
|
||||
if (!$otpRecord || Carbon::now()->gt($otpRecord->expires_at)) {
|
||||
return back()->with('error', 'Kode OTP tidak valid atau sudah kadaluarsa.');
|
||||
}
|
||||
|
||||
// Update password user
|
||||
$user = User::where('email', $request->email)->first();
|
||||
$user->password = Hash::make($request->password);
|
||||
$user->save();
|
||||
|
||||
// Hapus data OTP
|
||||
$otpRecord->delete();
|
||||
|
||||
return redirect()->route('login')
|
||||
->with('success', 'Password berhasil direset. Silakan login dengan password baru.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Kirim email OTP
|
||||
*/
|
||||
private function sendOtpEmail($toEmail, $toName, $otp)
|
||||
{
|
||||
$subject = "Kode OTP Reset Password - LearnMood";
|
||||
|
||||
$message = "
|
||||
<html>
|
||||
<head>
|
||||
<title>Kode OTP Reset Password</title>
|
||||
</head>
|
||||
<body style='font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;'>
|
||||
<div style='max-width: 500px; margin: 0 auto; background-color: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);'>
|
||||
<div style='text-align: center; margin-bottom: 25px;'>
|
||||
<h1 style='color: #4A90E2; margin: 0;'>Learn<span style='color: #333;'>Mood</span></h1>
|
||||
</div>
|
||||
|
||||
<p style='font-size: 16px; color: #333;'>Halo <strong>{$toName}</strong>,</p>
|
||||
|
||||
<p style='font-size: 14px; color: #666;'>Kami menerima permintaan reset password untuk akun Anda. Gunakan kode OTP berikut untuk melanjutkan:</p>
|
||||
|
||||
<div style='background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 20px; text-align: center; border-radius: 8px; margin: 25px 0;'>
|
||||
<p style='margin: 0; font-size: 14px; color: rgba(255,255,255,0.9);'>Kode Verifikasi OTP</p>
|
||||
<h1 style='font-size: 48px; letter-spacing: 8px; color: white; margin: 10px 0; font-family: monospace;'>{$otp}</h1>
|
||||
</div>
|
||||
|
||||
<div style='background-color: #f8f9fa; padding: 15px; border-radius: 8px; margin: 20px 0;'>
|
||||
<p style='margin: 0; font-size: 13px; color: #666;'>
|
||||
<strong>⏰ Berlaku selama:</strong> 5 menit<br>
|
||||
<strong>📧 Email:</strong> {$toEmail}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p style='font-size: 13px; color: #999; border-top: 1px solid #eee; padding-top: 20px; margin-top: 20px;'>
|
||||
Jika Anda tidak meminta reset password, abaikan email ini.
|
||||
</p>
|
||||
|
||||
<p style='font-size: 12px; color: #999; text-align: center; margin-top: 20px;'>
|
||||
© " . date('Y') . " LearnMood. All rights reserved.
|
||||
</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
";
|
||||
|
||||
$headers = "MIME-Version: 1.0" . "\r\n";
|
||||
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
|
||||
$headers .= 'From: LearnMood <' . env('MAIL_FROM_ADDRESS') . '>' . "\r\n";
|
||||
$headers .= 'Reply-To: ' . env('MAIL_FROM_ADDRESS') . "\r\n";
|
||||
$headers .= 'X-Mailer: PHP/' . phpversion();
|
||||
|
||||
mail($toEmail, $subject, $message, $headers);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
class PasswordController extends Controller
|
||||
{
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function update(Request $request): RedirectResponse
|
||||
{
|
||||
$validated = $request->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');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class RegisterController extends Controller
|
||||
{
|
||||
public function showRegistrationForm()
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
public function register(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
|
||||
'password' => ['required', 'string', 'min:8', 'confirmed'],
|
||||
'role' => ['required', 'in:siswa,orang_tua'],
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
'role' => $request->role,
|
||||
]);
|
||||
|
||||
Auth::login($user);
|
||||
|
||||
return redirect('dashboard');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,46 @@
|
|||
<?php
|
||||
// app/Http/Controllers/Auth/RegisteredUserController.php (Modifikasi)
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\User;
|
||||
use App\Models\ParentConnection;
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Validation\Rules;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class RegisteredUserController extends Controller
|
||||
{
|
||||
public function create(): View
|
||||
{
|
||||
return view('auth.register');
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
|
||||
'password' => ['required', 'confirmed', Rules\Password::defaults()],
|
||||
'role' => ['required', 'in:siswa,orang_tua'],
|
||||
]);
|
||||
|
||||
$user = User::create([
|
||||
'name' => $request->name,
|
||||
'email' => $request->email,
|
||||
'password' => Hash::make($request->password),
|
||||
'role' => $request->role,
|
||||
]);
|
||||
|
||||
event(new Registered($user));
|
||||
|
||||
Auth::login($user);
|
||||
|
||||
return redirect(route('dashboard', absolute: false));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Illuminate\Auth\Events\Verified;
|
||||
use Illuminate\Foundation\Auth\EmailVerificationRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
|
||||
class VerifyEmailController extends Controller
|
||||
{
|
||||
/**
|
||||
* Mark the authenticated user's email address as verified.
|
||||
*/
|
||||
public function __invoke(EmailVerificationRequest $request): RedirectResponse
|
||||
{
|
||||
if ($request->user()->hasVerifiedEmail()) {
|
||||
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
|
||||
}
|
||||
|
||||
if ($request->user()->markEmailAsVerified()) {
|
||||
event(new Verified($request->user()));
|
||||
}
|
||||
|
||||
return redirect()->intended(RouteServiceProvider::HOME.'?verified=1');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
||||
use Illuminate\Foundation\Validation\ValidatesRequests;
|
||||
use Illuminate\Routing\Controller as BaseController;
|
||||
|
||||
class Controller extends BaseController
|
||||
{
|
||||
use AuthorizesRequests, ValidatesRequests;
|
||||
}
|
||||
|
|
@ -0,0 +1,295 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
/**
|
||||
* Dashboard utama berdasarkan role pengguna
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
if ($user->isSiswa()) {
|
||||
return $this->siswaDashboard();
|
||||
} else {
|
||||
return $this->orangTuaDashboard();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard untuk role Siswa
|
||||
*/
|
||||
private function siswaDashboard()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// SET TIMEZONE - Pastikan konsisten di seluruh aplikasi
|
||||
Carbon::setLocale('id');
|
||||
$now = Carbon::now('Asia/Jakarta');
|
||||
$todayDate = $now->toDateString(); // Format Y-m-d
|
||||
|
||||
// DEBUG: Log untuk memantau
|
||||
Log::info('Siswa Dashboard - Pengecekan', [
|
||||
'user_id' => $user->id,
|
||||
'waktu_server' => now()->toDateTimeString(),
|
||||
'waktu_wib' => $now->toDateTimeString(),
|
||||
'today_date' => $todayDate
|
||||
]);
|
||||
|
||||
// DATA HARI INI - Gunakan query dengan whereDate untuk konsistensi
|
||||
$todayActivity = ActivityLog::where('user_id', $user->id)
|
||||
->whereDate('activity_date', $todayDate)
|
||||
->first();
|
||||
|
||||
// DEBUG: Cek apakah ada data
|
||||
if ($todayActivity) {
|
||||
Log::info('Siswa - Aktivitas hari ini ditemukan', [
|
||||
'activity_id' => $todayActivity->id,
|
||||
'activity_date' => $todayActivity->activity_date,
|
||||
'duration' => $todayActivity->duration_minutes
|
||||
]);
|
||||
} else {
|
||||
Log::info('Siswa - Tidak ada aktivitas hari ini', [
|
||||
'tanggal_yang_dicek' => $todayDate
|
||||
]);
|
||||
|
||||
// CEK MANUAL: Apakah ada data dengan tanggal yang sama tapi format berbeda?
|
||||
$alternativeCheck = ActivityLog::where('user_id', $user->id)
|
||||
->whereRaw("DATE(activity_date) = ?", [$todayDate])
|
||||
->first();
|
||||
|
||||
if ($alternativeCheck) {
|
||||
Log::warning('Siswa - Data ditemukan dengan RAW query tapi tidak dengan whereDate!', [
|
||||
'id' => $alternativeCheck->id,
|
||||
'date' => $alternativeCheck->activity_date
|
||||
]);
|
||||
$todayActivity = $alternativeCheck; // Gunakan yang ditemukan
|
||||
}
|
||||
}
|
||||
|
||||
// STATISTIK 7 HARI TERAKHIR
|
||||
$weekStartDate = $now->copy()->subDays(7)->toDateString();
|
||||
$weekActivities = ActivityLog::where('user_id', $user->id)
|
||||
->whereDate('activity_date', '>=', $weekStartDate)
|
||||
->orderBy('activity_date', 'desc')
|
||||
->get();
|
||||
|
||||
// TOTAL HARI INPUT (semua waktu)
|
||||
$totalDays = ActivityLog::where('user_id', $user->id)->count();
|
||||
|
||||
// RATA-RATA DURASI BELAJAR
|
||||
$avgDuration = ActivityLog::where('user_id', $user->id)
|
||||
->avg('duration_minutes') ?? 0;
|
||||
|
||||
// REKOMENDASI TERAKHIR
|
||||
$latestRecommendation = Recommendation::where('user_id', $user->id)
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
// GREETING BERDASARKAN WAKTU
|
||||
$greeting = $this->getGreeting($now);
|
||||
|
||||
return view('dashboard.siswa', compact(
|
||||
'todayActivity',
|
||||
'weekActivities',
|
||||
'totalDays',
|
||||
'avgDuration',
|
||||
'latestRecommendation',
|
||||
'greeting'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Dashboard untuk role Orang Tua
|
||||
*/
|
||||
private function orangTuaDashboard()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// SET TIMEZONE
|
||||
Carbon::setLocale('id');
|
||||
$now = Carbon::now('Asia/Jakarta');
|
||||
$todayDate = $now->toDateString();
|
||||
$weekStartDate = $now->copy()->subDays(7)->toDateString();
|
||||
|
||||
// DEBUG
|
||||
Log::info('Orang Tua Dashboard - Pengecekan', [
|
||||
'parent_id' => $user->id,
|
||||
'waktu_wib' => $now->toDateTimeString(),
|
||||
'today_date' => $todayDate
|
||||
]);
|
||||
|
||||
// AMBIL SEMUA ANAK YANG TERKONEKSI
|
||||
$children = User::where('parent_id', $user->id)->get();
|
||||
|
||||
$childrenData = [];
|
||||
$totalTodayInput = 0;
|
||||
$totalWeekActivities = 0;
|
||||
$totalMoodScore = 0;
|
||||
$moodCount = 0;
|
||||
|
||||
// SKOR MOOD
|
||||
$moodScores = [
|
||||
'Bagus' => 5,
|
||||
'Lumayan' => 4,
|
||||
'Biasa Saja' => 3,
|
||||
'Cukup Jenuh' => 2,
|
||||
'Jenuh' => 1
|
||||
];
|
||||
|
||||
foreach ($children as $child) {
|
||||
// AKTIVITAS HARI INI
|
||||
$todayActivity = ActivityLog::where('user_id', $child->id)
|
||||
->whereDate('activity_date', $todayDate)
|
||||
->first();
|
||||
|
||||
// DEBUG per anak
|
||||
Log::info('Orang Tua - Cek anak', [
|
||||
'child_id' => $child->id,
|
||||
'child_name' => $child->name,
|
||||
'today_activity' => $todayActivity ? 'ADA' : 'TIDAK ADA',
|
||||
'tanggal_dicek' => $todayDate
|
||||
]);
|
||||
|
||||
if ($todayActivity) {
|
||||
$totalTodayInput++;
|
||||
}
|
||||
|
||||
// AKTIVITAS 7 HARI TERAKHIR
|
||||
$weekActivities = ActivityLog::where('user_id', $child->id)
|
||||
->whereDate('activity_date', '>=', $weekStartDate)
|
||||
->orderBy('activity_date', 'desc')
|
||||
->get();
|
||||
|
||||
$weekActivitiesCount = $weekActivities->count();
|
||||
$totalWeekActivities += $weekActivitiesCount;
|
||||
|
||||
// TOTAL DURASI 7 HARI
|
||||
$weekTotalDuration = $weekActivities->sum('duration_minutes');
|
||||
|
||||
// REKOMENDASI TERAKHIR
|
||||
$latestRecommendation = Recommendation::where('user_id', $child->id)
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
// RATA-RATA MOOD SCORE
|
||||
$averageMoodScore = 0;
|
||||
if ($weekActivitiesCount > 0) {
|
||||
$totalChildMood = 0;
|
||||
foreach ($weekActivities as $activity) {
|
||||
$moodScore = $moodScores[$activity->mood] ?? 3;
|
||||
$totalChildMood += $moodScore;
|
||||
$totalMoodScore += $moodScore;
|
||||
$moodCount++;
|
||||
}
|
||||
$averageMoodScore = round($totalChildMood / $weekActivitiesCount, 1);
|
||||
}
|
||||
|
||||
// 5 AKTIVITAS TERAKHIR
|
||||
$recentActivities = ActivityLog::where('user_id', $child->id)
|
||||
->orderBy('activity_date', 'desc')
|
||||
->limit(5)
|
||||
->get();
|
||||
|
||||
$childrenData[] = [
|
||||
'child' => $child,
|
||||
'today_activity' => $todayActivity,
|
||||
'week_activities_count' => $weekActivitiesCount,
|
||||
'week_total_duration' => $weekTotalDuration,
|
||||
'average_mood_score' => $averageMoodScore,
|
||||
'latest_recommendation' => $latestRecommendation,
|
||||
'recent_activities' => $recentActivities,
|
||||
];
|
||||
}
|
||||
|
||||
// RATA-RATA MOOD GABUNGAN
|
||||
$averageMoodAll = $moodCount > 0 ? round($totalMoodScore / $moodCount, 1) : 0;
|
||||
|
||||
// GREETING
|
||||
$greeting = $this->getGreeting($now);
|
||||
|
||||
return view('dashboard.orangtua', compact(
|
||||
'childrenData',
|
||||
'totalTodayInput',
|
||||
'totalWeekActivities',
|
||||
'averageMoodAll',
|
||||
'greeting'
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Mendapatkan greeting berdasarkan waktu
|
||||
*/
|
||||
private function getGreeting(Carbon $time)
|
||||
{
|
||||
$hour = (int) $time->format('H');
|
||||
|
||||
if ($hour < 12) {
|
||||
return 'Selamat Pagi';
|
||||
} elseif ($hour < 15) {
|
||||
return 'Selamat Siang';
|
||||
} elseif ($hour < 18) {
|
||||
return 'Selamat Sore';
|
||||
} else {
|
||||
return 'Selamat Malam';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Method untuk debugging (opsional)
|
||||
*/
|
||||
public function debugToday($userId = null)
|
||||
{
|
||||
$userId = $userId ?? Auth::id();
|
||||
|
||||
$now = Carbon::now('Asia/Jakarta');
|
||||
$todayDate = $now->toDateString();
|
||||
|
||||
$activities = ActivityLog::where('user_id', $userId)
|
||||
->orderBy('activity_date', 'desc')
|
||||
->limit(20)
|
||||
->get();
|
||||
|
||||
$todayActivity = ActivityLog::where('user_id', $userId)
|
||||
->whereDate('activity_date', $todayDate)
|
||||
->first();
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'debug_info' => [
|
||||
'server_time' => now()->toDateTimeString(),
|
||||
'wib_time' => $now->toDateTimeString(),
|
||||
'timezone' => date_default_timezone_get(),
|
||||
'today_date' => $todayDate,
|
||||
'user_id' => $userId,
|
||||
'has_today_activity' => $todayActivity ? true : false,
|
||||
'today_activity' => $todayActivity ? [
|
||||
'id' => $todayActivity->id,
|
||||
'date' => $todayActivity->activity_date,
|
||||
'duration' => $todayActivity->duration_minutes,
|
||||
'created_at' => $todayActivity->created_at,
|
||||
] : null,
|
||||
'recent_activities' => $activities->map(function($a) {
|
||||
return [
|
||||
'id' => $a->id,
|
||||
'date' => $a->activity_date,
|
||||
'duration' => $a->duration_minutes,
|
||||
'created_at' => $a->created_at,
|
||||
];
|
||||
}),
|
||||
'raw_query' => "SELECT * FROM activity_logs WHERE user_id = $userId AND DATE(activity_date) = '$todayDate'"
|
||||
]
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\OrangTua;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\User;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ChildVisualizationController extends Controller
|
||||
{
|
||||
public function index(Request $request, $childId)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Pastikan anak terhubung dengan orang tua ini
|
||||
$child = User::where('parent_id', $user->id)
|
||||
->findOrFail($childId);
|
||||
|
||||
$period = $request->get('period', 7);
|
||||
if (!in_array($period, [7, 30, 90])) {
|
||||
$period = 7;
|
||||
}
|
||||
|
||||
$startDate = Carbon::today()->subDays($period);
|
||||
|
||||
// Ambil data aktivitas - INI YANG DIBUTUHKAN
|
||||
$activities = ActivityLog::where('user_id', $child->id)
|
||||
->whereDate('activity_date', '>=', $startDate)
|
||||
->orderBy('activity_date', 'asc')
|
||||
->get();
|
||||
|
||||
// Ambil data rekomendasi untuk periode yang sama
|
||||
$recommendations = Recommendation::where('user_id', $child->id)
|
||||
->whereDate('recommendation_date', '>=', $startDate)
|
||||
->get()
|
||||
->keyBy(function($item) {
|
||||
return $item->recommendation_date instanceof Carbon
|
||||
? $item->recommendation_date->format('Y-m-d')
|
||||
: Carbon::parse($item->recommendation_date)->format('Y-m-d');
|
||||
});
|
||||
|
||||
// Siapkan data untuk chart
|
||||
$dates = [];
|
||||
$durations = [];
|
||||
$moods = [];
|
||||
$sleep_hours = [];
|
||||
$categories = [];
|
||||
|
||||
// Statistik mood counter
|
||||
$moodCount = [
|
||||
'Bagus' => 0,
|
||||
'Lumayan' => 0,
|
||||
'Biasa Saja' => 0,
|
||||
'Cukup Jenuh' => 0,
|
||||
'Jenuh' => 0
|
||||
];
|
||||
|
||||
foreach ($activities as $activity) {
|
||||
$dateKey = $activity->activity_date instanceof Carbon
|
||||
? $activity->activity_date->format('Y-m-d')
|
||||
: Carbon::parse($activity->activity_date)->format('Y-m-d');
|
||||
|
||||
$dates[] = $dateKey;
|
||||
$durations[] = $activity->duration_minutes;
|
||||
$moods[] = $activity->mood;
|
||||
|
||||
// Increment mood counter
|
||||
if (isset($moodCount[$activity->mood])) {
|
||||
$moodCount[$activity->mood]++;
|
||||
}
|
||||
|
||||
// Sleep hours - handle both column names
|
||||
$sleep_hours[] = $activity->sleep_duration ?? $activity->sleep_hours ?? 7;
|
||||
|
||||
// Cari rekomendasi berdasarkan tanggal
|
||||
if (isset($recommendations[$dateKey])) {
|
||||
$categories[] = $recommendations[$dateKey]->category;
|
||||
} else {
|
||||
$categories[] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Hitung statistik
|
||||
$stats = [
|
||||
'total_hari' => $activities->count(),
|
||||
'rata_durasi' => $activities->count() > 0 ? round($activities->avg('duration_minutes')) : 0,
|
||||
'mood_terbanyak' => $this->getMostFrequentMood($moodCount),
|
||||
'konsistensi' => $period > 0 ? round(($activities->count() / $period) * 100) : 0,
|
||||
'total_durasi' => array_sum($durations),
|
||||
'rata_tidur' => count($sleep_hours) > 0 ? round(array_sum($sleep_hours) / count($sleep_hours), 1) : 0,
|
||||
];
|
||||
|
||||
// Hitung distribusi mood untuk chart
|
||||
$moodDistribution = array_filter($moodCount, function($count) {
|
||||
return $count > 0;
|
||||
});
|
||||
|
||||
return view('orangtua.child-visualization', compact(
|
||||
'child',
|
||||
'period',
|
||||
'dates',
|
||||
'durations',
|
||||
'moods',
|
||||
'sleep_hours',
|
||||
'categories',
|
||||
'stats',
|
||||
'moodDistribution',
|
||||
'activities' // TAMBAHKAN INI!
|
||||
));
|
||||
}
|
||||
|
||||
private function getMostFrequentMood($moodCount)
|
||||
{
|
||||
if (empty($moodCount) || max($moodCount) == 0) {
|
||||
return '-';
|
||||
}
|
||||
|
||||
arsort($moodCount);
|
||||
return array_key_first($moodCount);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\OrangTua;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\User;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ChildrenController extends Controller
|
||||
{
|
||||
/**
|
||||
* Menampilkan halaman daftar anak (koneksi anak)
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Ambil semua anak yang terkoneksi
|
||||
$children = User::where('parent_id', $user->id)->get();
|
||||
|
||||
$childrenData = [];
|
||||
$stats = [
|
||||
'total_anak' => $children->count(),
|
||||
'today_input' => 0,
|
||||
'total_activities' => 0,
|
||||
'avg_mood' => 0,
|
||||
];
|
||||
|
||||
$totalMoodScore = 0;
|
||||
$moodCount = 0;
|
||||
|
||||
// Skor mood untuk perhitungan
|
||||
$moodScores = [
|
||||
'Bagus' => 5,
|
||||
'Lumayan' => 4,
|
||||
'Biasa Saja' => 3,
|
||||
'Cukup Jenuh' => 2,
|
||||
'Jenuh' => 1
|
||||
];
|
||||
|
||||
foreach ($children as $child) {
|
||||
// Aktivitas hari ini
|
||||
$todayActivity = ActivityLog::where('user_id', $child->id)
|
||||
->whereDate('activity_date', Carbon::today())
|
||||
->orderBy('id', 'desc')
|
||||
->first();
|
||||
|
||||
if ($todayActivity) {
|
||||
$stats['today_input']++;
|
||||
}
|
||||
|
||||
// Aktivitas 7 hari terakhir
|
||||
$weekActivities = ActivityLog::where('user_id', $child->id)
|
||||
->whereDate('activity_date', '>=', Carbon::today()->subDays(7))
|
||||
->get();
|
||||
|
||||
$weekCount = $weekActivities->count();
|
||||
$stats['total_activities'] += $weekCount;
|
||||
|
||||
// Rata-rata durasi 7 hari
|
||||
$avgDuration = $weekCount > 0 ? round($weekActivities->avg('duration_minutes')) : 0;
|
||||
|
||||
// Mood terbanyak
|
||||
$moodCounts = [];
|
||||
foreach ($weekActivities as $activity) {
|
||||
$moodCounts[$activity->mood] = ($moodCounts[$activity->mood] ?? 0) + 1;
|
||||
|
||||
// Hitung total mood score untuk statistik global
|
||||
$totalMoodScore += $moodScores[$activity->mood] ?? 3;
|
||||
$moodCount++;
|
||||
}
|
||||
|
||||
$topMood = !empty($moodCounts) ? array_keys($moodCounts, max($moodCounts))[0] : null;
|
||||
|
||||
// Rekomendasi terakhir
|
||||
$latestRecommendation = Recommendation::where('user_id', $child->id)
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
$childrenData[] = [
|
||||
'id' => $child->id,
|
||||
'name' => $child->name,
|
||||
'email' => $child->email,
|
||||
'today_activity' => $todayActivity,
|
||||
'week_count' => $weekCount,
|
||||
'avg_duration' => $avgDuration,
|
||||
'top_mood' => $topMood,
|
||||
'latest_recommendation' => $latestRecommendation,
|
||||
];
|
||||
}
|
||||
|
||||
// Hitung rata-rata mood global
|
||||
if ($moodCount > 0) {
|
||||
$stats['avg_mood'] = round($totalMoodScore / $moodCount, 1);
|
||||
}
|
||||
|
||||
return view('orangtua.children', compact('childrenData', 'stats'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Menampilkan detail anak
|
||||
*/
|
||||
public function detail($id)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Pastikan anak terhubung dengan orang tua ini
|
||||
$child = User::where('parent_id', $user->id)->findOrFail($id);
|
||||
|
||||
// Ambil aktivitas terbaru
|
||||
$activities = ActivityLog::where('user_id', $child->id)
|
||||
->with('recommendation')
|
||||
->orderBy('activity_date', 'desc')
|
||||
->paginate(15);
|
||||
|
||||
// Statistik
|
||||
$totalActivities = ActivityLog::where('user_id', $child->id)->count();
|
||||
$totalDuration = ActivityLog::where('user_id', $child->id)->sum('duration_minutes');
|
||||
$avgDaily = $totalActivities > 0 ? round($totalDuration / $totalActivities) : 0;
|
||||
|
||||
// Hitung konsistensi
|
||||
$firstDate = ActivityLog::where('user_id', $child->id)->min('activity_date');
|
||||
$consistency = 0;
|
||||
if ($firstDate) {
|
||||
$daysDiff = Carbon::parse($firstDate)->diffInDays(Carbon::today()) + 1;
|
||||
$consistency = round(($totalActivities / $daysDiff) * 100);
|
||||
}
|
||||
|
||||
$stats = [
|
||||
'total_activities' => $totalActivities,
|
||||
'total_duration' => $totalDuration,
|
||||
'avg_daily' => $avgDaily,
|
||||
'consistency' => $consistency,
|
||||
];
|
||||
|
||||
return view('orangtua.child-detail', compact('child', 'activities', 'stats'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghubungkan anak dengan kode
|
||||
*/
|
||||
public function connect(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'connection_code' => 'required|string|size:8'
|
||||
]);
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
// Cari anak berdasarkan kode koneksi - PERBAIKAN: gunakan whereNotNull untuk memastikan kode tidak null
|
||||
$child = User::where('role', 'siswa')
|
||||
->where('parent_code', strtoupper($request->connection_code))
|
||||
->whereNotNull('parent_code')
|
||||
->first();
|
||||
|
||||
if (!$child) {
|
||||
return back()->with('error', 'Kode koneksi tidak valid atau sudah kadaluarsa.');
|
||||
}
|
||||
|
||||
// Cek apakah anak sudah terhubung dengan orang tua lain
|
||||
if ($child->parent_id && $child->parent_id != $user->id) {
|
||||
return back()->with('error', 'Anak ini sudah terhubung dengan orang tua lain.');
|
||||
}
|
||||
|
||||
// Cek apakah anak sudah terhubung dengan orang tua ini
|
||||
if ($child->parent_id == $user->id) {
|
||||
return back()->with('error', 'Anak ini sudah terhubung dengan akun Anda.');
|
||||
}
|
||||
|
||||
// Hubungkan anak dengan orang tua
|
||||
$child->parent_id = $user->id;
|
||||
$child->save();
|
||||
|
||||
return redirect()->route('orangtua.children')->with('success', 'Berhasil terhubung dengan ' . $child->name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Memutuskan koneksi dengan anak
|
||||
*/
|
||||
public function disconnect($id)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Cari anak yang terhubung dengan orang tua ini
|
||||
$child = User::where('parent_id', $user->id)->findOrFail($id);
|
||||
|
||||
// Simpan nama anak untuk pesan sukses
|
||||
$childName = $child->name;
|
||||
|
||||
// Putuskan koneksi dengan mengosongkan parent_id
|
||||
$child->parent_id = null;
|
||||
$child->save();
|
||||
|
||||
return redirect()->route('orangtua.children')->with('success', 'Koneksi dengan ' . $childName . ' berhasil diputuskan.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,160 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Http\Requests\ProfileUpdateRequest;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Redirect;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\View\View;
|
||||
use App\Models\User;
|
||||
|
||||
class ProfileController extends Controller
|
||||
{
|
||||
/**
|
||||
* Display the user's profile form.
|
||||
*/
|
||||
public function edit(Request $request): View
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Statistik tambahan untuk siswa
|
||||
$stats = [];
|
||||
if ($user->isSiswa()) {
|
||||
$stats = [
|
||||
'total_aktivitas' => \App\Models\ActivityLog::where('user_id', $user->id)->count(),
|
||||
'total_durasi' => \App\Models\ActivityLog::where('user_id', $user->id)->sum('duration_minutes'),
|
||||
'joined_since' => $user->created_at->format('d M Y'),
|
||||
'konsistensi' => $this->calculateConsistency($user->id),
|
||||
];
|
||||
} else {
|
||||
// Statistik untuk orang tua
|
||||
$stats = [
|
||||
'total_anak' => \App\Models\User::where('parent_id', $user->id)->count(),
|
||||
'joined_since' => $user->created_at->format('d M Y'),
|
||||
];
|
||||
}
|
||||
|
||||
return view('profile.edit', [
|
||||
'user' => $user,
|
||||
'stats' => $stats
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's profile information.
|
||||
*/
|
||||
public function update(ProfileUpdateRequest $request): RedirectResponse
|
||||
{
|
||||
$user = $request->user();
|
||||
$user->fill($request->validated());
|
||||
|
||||
if ($user->isDirty('email')) {
|
||||
$user->email_verified_at = null;
|
||||
}
|
||||
|
||||
$user->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('success', 'Profile berhasil diperbarui.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's password.
|
||||
*/
|
||||
public function updatePassword(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'current_password' => ['required', 'current_password'],
|
||||
'new_password' => ['required', 'string', 'min:8', 'confirmed'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
$user->password = Hash::make($request->new_password);
|
||||
$user->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('success', 'Password berhasil diubah.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the user's avatar.
|
||||
*/
|
||||
/**
|
||||
* Update the user's avatar.
|
||||
*/
|
||||
public function updateAvatar(Request $request): RedirectResponse
|
||||
{
|
||||
$request->validate([
|
||||
'avatar' => ['required', 'image', 'mimes:jpeg,png,jpg,gif', 'max:2048'],
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
if ($request->hasFile('avatar')) {
|
||||
$avatar = $request->file('avatar');
|
||||
|
||||
// Generate nama file unik
|
||||
$filename = time() . '_' . $user->id . '_' . uniqid() . '.' . $avatar->getClientOriginalExtension();
|
||||
|
||||
// Pastikan folder avatars ada
|
||||
$avatarPath = public_path('avatars');
|
||||
if (!file_exists($avatarPath)) {
|
||||
mkdir($avatarPath, 0755, true);
|
||||
}
|
||||
|
||||
// Simpan ke folder public/avatars
|
||||
$avatar->move($avatarPath, $filename);
|
||||
|
||||
// Hapus avatar lama jika bukan default dan file exists
|
||||
if ($user->avatar && $user->avatar != 'default.png' && file_exists($avatarPath . '/' . $user->avatar)) {
|
||||
unlink($avatarPath . '/' . $user->avatar);
|
||||
}
|
||||
|
||||
// Update database
|
||||
$user->avatar = $filename;
|
||||
$user->save();
|
||||
|
||||
return Redirect::route('profile.edit')->with('success', 'Avatar berhasil diperbarui.');
|
||||
}
|
||||
|
||||
return Redirect::route('profile.edit')->with('error', 'Gagal mengupload avatar.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Menghitung konsistensi untuk siswa
|
||||
*/
|
||||
private function calculateConsistency($userId)
|
||||
{
|
||||
$total = \App\Models\ActivityLog::where('user_id', $userId)->count();
|
||||
if ($total == 0) return 0;
|
||||
|
||||
$firstDate = \App\Models\ActivityLog::where('user_id', $userId)->min('activity_date');
|
||||
if (!$firstDate) return 0;
|
||||
|
||||
$daysDiff = \Carbon\Carbon::parse($firstDate)->diffInDays(\Carbon\Carbon::today()) + 1;
|
||||
|
||||
return round(($total / $daysDiff) * 100);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,594 @@
|
|||
<?php
|
||||
// app/Http/Controllers/Siswa/ActivityController.php
|
||||
|
||||
namespace App\Http\Controllers\Siswa;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use App\Services\FlaskModelService;
|
||||
use App\Services\RecommendationCalculator;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ActivityController extends Controller
|
||||
{
|
||||
protected $flaskService;
|
||||
protected $calculator;
|
||||
|
||||
public function __construct(FlaskModelService $flaskService, RecommendationCalculator $calculator)
|
||||
{
|
||||
$this->flaskService = $flaskService;
|
||||
$this->calculator = $calculator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form input aktivitas
|
||||
*/
|
||||
public function create()
|
||||
{
|
||||
// Cek apakah sudah input hari ini
|
||||
$todayActivity = ActivityLog::where('user_id', Auth::id())
|
||||
->whereDate('activity_date', Carbon::today())
|
||||
->first();
|
||||
|
||||
if ($todayActivity) {
|
||||
return redirect()->route('siswa.input.edit-today')
|
||||
->with('info', 'Kamu sudah menginput aktivitas hari ini. Silakan edit jika ada perubahan.');
|
||||
}
|
||||
|
||||
return view('siswa.input');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan form edit aktivitas hari ini
|
||||
*/
|
||||
public function editToday()
|
||||
{
|
||||
$activity = ActivityLog::where('user_id', Auth::id())
|
||||
->whereDate('activity_date', Carbon::today())
|
||||
->first();
|
||||
|
||||
if (!$activity) {
|
||||
return redirect()->route('siswa.input')
|
||||
->with('info', 'Belum ada aktivitas hari ini. Silakan input aktivitas dulu.');
|
||||
}
|
||||
|
||||
return view('siswa.input', [
|
||||
'activity' => $activity,
|
||||
'isEdit' => true,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan aktivitas dan generate rekomendasi
|
||||
*/
|
||||
public function store(Request $request)
|
||||
{
|
||||
// Log request data
|
||||
Log::info('=== MEMULAI PROSES INPUT ===');
|
||||
Log::info('User ID: ' . Auth::id());
|
||||
Log::info('Request data: ', $request->all());
|
||||
|
||||
// Validasi input
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'start_time' => 'required',
|
||||
'end_time' => 'required|after:start_time',
|
||||
'mood' => 'required|in:Bagus,Lumayan,Biasa Saja,Cukup Jenuh,Jenuh',
|
||||
'sleep_hours' => 'required|numeric|min:1|max:10',
|
||||
]);
|
||||
Log::info('Validasi berhasil');
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Validasi gagal: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->withErrors(['error' => 'Validasi gagal: ' . $e->getMessage()])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$user = Auth::user();
|
||||
|
||||
$todayActivity = ActivityLog::where('user_id', $user->id)
|
||||
->whereDate('activity_date', Carbon::today())
|
||||
->first();
|
||||
|
||||
if ($todayActivity) {
|
||||
DB::rollBack();
|
||||
|
||||
return redirect()->route('siswa.input.edit-today')
|
||||
->with('info', 'Aktivitas hari ini sudah ada. Gunakan form edit untuk memperbarui data.');
|
||||
}
|
||||
|
||||
// Hitung durasi belajar dalam menit
|
||||
$start = Carbon::parse($request->start_time);
|
||||
$end = Carbon::parse($request->end_time);
|
||||
$durationMinutes = $end->diffInMinutes($start);
|
||||
Log::info("Durasi belajar: {$durationMinutes} menit");
|
||||
|
||||
// Ambil nilai sleep hours
|
||||
$sleepHours = floatval($request->sleep_hours);
|
||||
Log::info("Durasi tidur: {$sleepHours} jam");
|
||||
|
||||
// Simpan activity
|
||||
$activity = ActivityLog::create([
|
||||
'user_id' => $user->id,
|
||||
'start_time' => $request->start_time,
|
||||
'end_time' => $request->end_time,
|
||||
'duration_minutes' => $durationMinutes,
|
||||
'mood' => $request->mood,
|
||||
'sleep_hours' => $sleepHours,
|
||||
'activity_date' => Carbon::today(),
|
||||
]);
|
||||
|
||||
Log::info('Activity berhasil disimpan dengan ID: ' . $activity->id);
|
||||
|
||||
// Hitung total hari user sudah input
|
||||
$totalDays = ActivityLog::where('user_id', $user->id)->count();
|
||||
Log::info("Total hari input: {$totalDays}");
|
||||
|
||||
|
||||
|
||||
// Generate rekomendasi hybrid
|
||||
Log::info('Mulai generate rekomendasi...');
|
||||
$recommendation = $this->generateHybridRecommendation($user->id, $activity, $totalDays);
|
||||
Log::info('Rekomendasi berhasil digenerate dengan ID: ' . $recommendation->id);
|
||||
|
||||
DB::commit();
|
||||
|
||||
$message = $totalDays <= 7
|
||||
? "Aktivitas berhasil disimpan! (Mode: Model Harian - Hari ke-{$totalDays}/7)"
|
||||
: "Aktivitas berhasil disimpan! (Mode: Pola Siswa - Hari ke-{$totalDays})";
|
||||
|
||||
Log::info('=== PROSES SELESAI ===');
|
||||
|
||||
// Redirect ke halaman rekomendasi
|
||||
return redirect()->route('siswa.recommendations')
|
||||
->with('success', $message);
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('ERROR di store: ' . $e->getMessage());
|
||||
Log::error('Stack trace: ' . $e->getTraceAsString());
|
||||
|
||||
return redirect()->back()
|
||||
->with('error', 'Gagal menyimpan aktivitas: ' . $e->getMessage())
|
||||
->withInput();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update aktivitas hari ini dan hitung ulang rekomendasi
|
||||
*/
|
||||
public function updateToday(Request $request)
|
||||
{
|
||||
Log::info('=== MEMULAI PROSES UPDATE AKTIVITAS HARI INI ===');
|
||||
Log::info('User ID: ' . Auth::id());
|
||||
Log::info('Request data: ', $request->all());
|
||||
|
||||
try {
|
||||
$validated = $request->validate([
|
||||
'start_time' => 'required',
|
||||
'end_time' => 'required|after:start_time',
|
||||
'mood' => 'required|in:Bagus,Lumayan,Biasa Saja,Cukup Jenuh,Jenuh',
|
||||
'sleep_hours' => 'required|numeric|min:1|max:10',
|
||||
]);
|
||||
Log::info('Validasi update berhasil');
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Validasi update gagal: ' . $e->getMessage());
|
||||
return redirect()->back()
|
||||
->withErrors(['error' => 'Validasi gagal: ' . $e->getMessage()])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$user = Auth::user();
|
||||
$activity = ActivityLog::where('user_id', $user->id)
|
||||
->whereDate('activity_date', Carbon::today())
|
||||
->firstOrFail();
|
||||
|
||||
$start = Carbon::parse($request->start_time);
|
||||
$end = Carbon::parse($request->end_time);
|
||||
$lastEnd = Carbon::parse($activity->end_time);
|
||||
|
||||
if ($start->lt($lastEnd)) {
|
||||
DB::rollBack();
|
||||
|
||||
return redirect()->back()
|
||||
->withErrors(['start_time' => 'Jam mulai tambahan tidak boleh sebelum jam selesai aktivitas sebelumnya.'])
|
||||
->withInput();
|
||||
}
|
||||
|
||||
$additionalMinutes = $end->diffInMinutes($start);
|
||||
$durationMinutes = $activity->duration_minutes + $additionalMinutes;
|
||||
$sleepHours = floatval($request->sleep_hours);
|
||||
|
||||
$activity->update([
|
||||
'start_time' => $activity->start_time,
|
||||
'end_time' => $request->end_time,
|
||||
'duration_minutes' => $durationMinutes,
|
||||
'mood' => $request->mood,
|
||||
'sleep_hours' => $sleepHours,
|
||||
'activity_date' => Carbon::today(),
|
||||
]);
|
||||
|
||||
$totalDays = ActivityLog::where('user_id', $user->id)->count();
|
||||
Log::info("Total hari input setelah update: {$totalDays}");
|
||||
|
||||
$recommendation = $this->generateHybridRecommendation($user->id, $activity, $totalDays);
|
||||
Log::info('Rekomendasi berhasil diperbarui dengan ID: ' . $recommendation->id);
|
||||
|
||||
DB::commit();
|
||||
|
||||
return redirect()->route('siswa.recommendations')
|
||||
->with('success', 'Aktivitas hari ini berhasil diperbarui dan rekomendasi sudah dihitung ulang.');
|
||||
|
||||
} catch (\Exception $e) {
|
||||
DB::rollBack();
|
||||
Log::error('ERROR di updateToday: ' . $e->getMessage());
|
||||
Log::error('Stack trace: ' . $e->getTraceAsString());
|
||||
|
||||
return redirect()->back()
|
||||
->with('error', 'Gagal memperbarui aktivitas: ' . $e->getMessage())
|
||||
->withInput();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate rekomendasi hybrid berdasarkan jumlah hari
|
||||
*/
|
||||
private function generateHybridRecommendation($userId, $activity, $totalDays)
|
||||
{
|
||||
$recommendation = [];
|
||||
$message = '';
|
||||
|
||||
if ($totalDays <= 7) {
|
||||
// 7 HARI PERTAMA: Gunakan model harian (Flask)
|
||||
Log::info("Hari ke-{$totalDays}: Menggunakan model harian");
|
||||
|
||||
$result = $this->flaskService->predictDaily(
|
||||
$activity->mood,
|
||||
$activity->duration_minutes,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
if ($result['success']) {
|
||||
// ✅ FLASK SUKSES - dapat kategori dari ML
|
||||
$category = $result['category'];
|
||||
|
||||
// Hitung durasi personal dengan calculator
|
||||
$durationResult = $this->calculator->calculateDuration(
|
||||
$userId,
|
||||
$category,
|
||||
$activity->mood,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
$recommendation = [
|
||||
'category' => $category,
|
||||
'recommended_minutes' => $durationResult['minutes'],
|
||||
'notes' => $durationResult['notes'],
|
||||
'based_on' => 'daily_model',
|
||||
'confidence' => $result['confidence'] ?? null,
|
||||
'factors' => $durationResult['factors'] ?? [],
|
||||
'adjustment' => $durationResult['adjustment'] ?? 0
|
||||
];
|
||||
$message = 'Rekomendasi berdasarkan model harian dengan penyesuaian personal.';
|
||||
|
||||
Log::info("ML Prediction: {$category}, Durasi personal: {$durationResult['minutes']} menit");
|
||||
|
||||
} else {
|
||||
// ❌ FLASK GAGAL - fallback ke aturan manual
|
||||
Log::warning('Flask API gagal, menggunakan aturan manual');
|
||||
|
||||
$manualResult = $this->generateManualRecommendation($activity);
|
||||
|
||||
// Hitung durasi personal untuk manual result
|
||||
$durationResult = $this->calculator->calculateDuration(
|
||||
$userId,
|
||||
$manualResult['category'],
|
||||
$activity->mood,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
$recommendation = [
|
||||
'category' => $manualResult['category'],
|
||||
'recommended_minutes' => $durationResult['minutes'],
|
||||
'notes' => $durationResult['notes'] . ' (Fallback manual)',
|
||||
'based_on' => 'manual_rules',
|
||||
'confidence' => null,
|
||||
'factors' => $durationResult['factors'] ?? [],
|
||||
'adjustment' => $durationResult['adjustment'] ?? 0
|
||||
];
|
||||
$message = 'Rekomendasi berdasarkan aturan manual (model server sedang maintenance).';
|
||||
}
|
||||
|
||||
} else {
|
||||
// HARI KE-8 dst: Gunakan pola siswa
|
||||
Log::info("Hari ke-{$totalDays}: Menggunakan pola siswa");
|
||||
|
||||
$result = $this->flaskService->predictBasedOnPattern($userId);
|
||||
|
||||
if ($result['success']) {
|
||||
// ✅ ANALISIS POLA SUKSES
|
||||
$category = $result['category'];
|
||||
|
||||
// Hitung durasi personal dengan calculator (dengan data pola)
|
||||
$durationResult = $this->calculator->calculateDuration(
|
||||
$userId,
|
||||
$category,
|
||||
$activity->mood,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
$recommendation = [
|
||||
'category' => $category,
|
||||
'recommended_minutes' => $durationResult['minutes'],
|
||||
'notes' => $durationResult['notes'],
|
||||
'based_on' => 'student_pattern',
|
||||
'pattern_analysis' => $result['pattern_analysis'] ?? null,
|
||||
'factors' => $durationResult['factors'] ?? [],
|
||||
'adjustment' => $durationResult['adjustment'] ?? 0
|
||||
];
|
||||
$message = 'Rekomendasi berdasarkan pola belajarmu selama 7 hari terakhir.';
|
||||
|
||||
} else {
|
||||
// ❌ ANALISIS POLA GAGAL - fallback ke model harian
|
||||
Log::warning('Pattern analysis gagal, fallback ke model harian');
|
||||
|
||||
$dailyResult = $this->flaskService->predictDaily(
|
||||
$activity->mood,
|
||||
$activity->duration_minutes,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
if ($dailyResult['success']) {
|
||||
$category = $dailyResult['category'];
|
||||
|
||||
$durationResult = $this->calculator->calculateDuration(
|
||||
$userId,
|
||||
$category,
|
||||
$activity->mood,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
$recommendation = [
|
||||
'category' => $category,
|
||||
'recommended_minutes' => $durationResult['minutes'],
|
||||
'notes' => $durationResult['notes'] . ' (Fallback dari pola)',
|
||||
'based_on' => 'daily_model_fallback',
|
||||
'confidence' => $dailyResult['confidence'] ?? null,
|
||||
'factors' => $durationResult['factors'] ?? [],
|
||||
'adjustment' => $durationResult['adjustment'] ?? 0
|
||||
];
|
||||
$message = 'Rekomendasi berdasarkan model harian (analisis pola belum tersedia).';
|
||||
|
||||
} else {
|
||||
// 🚨 FALLBACK TERAKHIR - aturan manual
|
||||
Log::warning('Semua fallback gagal, menggunakan aturan manual');
|
||||
|
||||
$manualResult = $this->generateManualRecommendation($activity);
|
||||
|
||||
$durationResult = $this->calculator->calculateDuration(
|
||||
$userId,
|
||||
$manualResult['category'],
|
||||
$activity->mood,
|
||||
$activity->sleep_hours
|
||||
);
|
||||
|
||||
$recommendation = [
|
||||
'category' => $manualResult['category'],
|
||||
'recommended_minutes' => $durationResult['minutes'],
|
||||
'notes' => $durationResult['notes'] . ' (Fallback darurat)',
|
||||
'based_on' => 'emergency_fallback',
|
||||
'confidence' => null,
|
||||
'factors' => $durationResult['factors'] ?? [],
|
||||
'adjustment' => $durationResult['adjustment'] ?? 0
|
||||
];
|
||||
$message = 'Rekomendasi berdasarkan aturan dasar.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PASTIKAN ARRAY $recommendation PUNYA SEMUA KEY YANG DIPERLUKAN
|
||||
if (!isset($recommendation['based_on'])) {
|
||||
$recommendation['based_on'] = 'unknown';
|
||||
Log::warning('based_on tidak diset, menggunakan default unknown');
|
||||
}
|
||||
|
||||
// Simpan atau perbarui rekomendasi untuk aktivitas ini
|
||||
$savedRec = Recommendation::updateOrCreate([
|
||||
'activity_log_id' => $activity->id,
|
||||
], [
|
||||
'user_id' => $userId,
|
||||
'category' => $recommendation['category'],
|
||||
'recommended_minutes' => $recommendation['recommended_minutes'],
|
||||
'notes' => $recommendation['notes'],
|
||||
'based_on' => $recommendation['based_on'],
|
||||
'confidence' => $recommendation['confidence'] ?? null,
|
||||
'model_input' => json_encode([
|
||||
'mood' => $activity->mood,
|
||||
'duration_minutes' => $activity->duration_minutes,
|
||||
'sleep_hours' => $activity->sleep_hours,
|
||||
'total_days' => $totalDays,
|
||||
'factors' => $recommendation['factors'] ?? [],
|
||||
'adjustment' => $recommendation['adjustment'] ?? 0,
|
||||
'pattern_analysis' => $recommendation['pattern_analysis'] ?? null
|
||||
]),
|
||||
'recommendation_date' => Carbon::today(),
|
||||
]);
|
||||
|
||||
Log::info('Rekomendasi tersimpan:', [
|
||||
'id' => $savedRec->id,
|
||||
'category' => $savedRec->category,
|
||||
'minutes' => $savedRec->recommended_minutes,
|
||||
'based_on' => $savedRec->based_on
|
||||
]);
|
||||
|
||||
return $savedRec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate rekomendasi manual (fallback)
|
||||
*/
|
||||
private function generateManualRecommendation($activity)
|
||||
{
|
||||
// Hitung skor manual berdasarkan proposal
|
||||
$moodScore = match($activity->mood) {
|
||||
'Bagus' => 2.0,
|
||||
'Lumayan' => 1.5,
|
||||
'Biasa Saja' => 1.0,
|
||||
'Cukup Jenuh' => 0.5,
|
||||
'Jenuh' => 0.0,
|
||||
default => 1.0
|
||||
};
|
||||
|
||||
$durationScore = $activity->duration_minutes > 60 ? 2.0 : ($activity->duration_minutes >= 31 ? 1.0 : 0.0);
|
||||
$sleepScore = $activity->sleep_hours >= 7 ? 2.0 : ($activity->sleep_hours >= 4 ? 1.0 : 0.0);
|
||||
|
||||
$totalScore = $moodScore + $durationScore + $sleepScore;
|
||||
|
||||
// Tentukan kategori berdasarkan total skor
|
||||
if ($totalScore > 4.5) {
|
||||
$category = 'Intensif';
|
||||
} elseif ($totalScore > 3) {
|
||||
$category = 'Sedang';
|
||||
} else {
|
||||
$category = 'Ringan';
|
||||
}
|
||||
|
||||
Log::info('Manual recommendation:', [
|
||||
'scores' => [$moodScore, $durationScore, $sleepScore],
|
||||
'total' => $totalScore,
|
||||
'category' => $category
|
||||
]);
|
||||
|
||||
return [
|
||||
'category' => $category,
|
||||
'based_on' => 'manual_rules'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper untuk mendapatkan durasi base dari kategori
|
||||
*/
|
||||
private function getMinutesFromCategory($category)
|
||||
{
|
||||
return match($category) {
|
||||
'Ringan' => 30,
|
||||
'Sedang' => 45,
|
||||
'Intensif' => 90,
|
||||
default => 30
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate notes untuk daily model (tidak dipakai langsung karena calculator sudah generate notes)
|
||||
*/
|
||||
private function generateDailyNotes($result, $day, $activity)
|
||||
{
|
||||
$category = $result['category'];
|
||||
$confidence = $result['confidence'] ?? 0;
|
||||
|
||||
$notes = "Hari ke-{$day} belajar. ";
|
||||
|
||||
$sleepQuality = $this->getSleepQuality($activity->sleep_hours);
|
||||
|
||||
$notes .= match($category) {
|
||||
'Ringan' => "Kondisi kamu kurang fit (tidur {$activity->sleep_hours} jam - {$sleepQuality}).",
|
||||
'Sedang' => "Kamu dalam kondisi cukup baik (tidur {$activity->sleep_hours} jam - {$sleepQuality}).",
|
||||
'Intensif' => "Kondisi kamu sangat baik (tidur {$activity->sleep_hours} jam - {$sleepQuality})!",
|
||||
default => 'Tetap semangat belajar!'
|
||||
};
|
||||
|
||||
if ($confidence > 0.9) {
|
||||
$notes .= ' Prediksi dengan keyakinan tinggi.';
|
||||
}
|
||||
|
||||
return $notes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper untuk kualitas tidur
|
||||
*/
|
||||
private function getSleepQuality($hours)
|
||||
{
|
||||
if ($hours < 5) return 'kurang tidur';
|
||||
if ($hours < 7) return 'kurang ideal';
|
||||
if ($hours <= 9) return 'ideal';
|
||||
return 'berlebih';
|
||||
}
|
||||
|
||||
/**
|
||||
* Tampilkan history aktivitas
|
||||
*/
|
||||
public function history(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Ambil parameter filter
|
||||
$period = $request->get('period', 'all'); // all, 7, 30, 90
|
||||
$mood = $request->get('mood', 'all');
|
||||
$search = $request->get('search', '');
|
||||
|
||||
// Query dasar
|
||||
$query = ActivityLog::where('user_id', $user->id)
|
||||
->with('recommendation')
|
||||
->orderBy('activity_date', 'desc');
|
||||
|
||||
// Filter periode
|
||||
if ($period == '7') {
|
||||
$query->whereDate('activity_date', '>=', Carbon::today()->subDays(7));
|
||||
} elseif ($period == '30') {
|
||||
$query->whereDate('activity_date', '>=', Carbon::today()->subDays(30));
|
||||
} elseif ($period == '90') {
|
||||
$query->whereDate('activity_date', '>=', Carbon::today()->subDays(90));
|
||||
}
|
||||
|
||||
// Filter mood
|
||||
if ($mood != 'all') {
|
||||
$query->where('mood', $mood);
|
||||
}
|
||||
|
||||
// Pencarian (di notes)
|
||||
if (!empty($search)) {
|
||||
$query->where('notes', 'like', '%' . $search . '%');
|
||||
}
|
||||
|
||||
// Ambil data dengan pagination
|
||||
$activities = $query->paginate(15)->withQueryString();
|
||||
|
||||
// Statistik untuk header
|
||||
$stats = [
|
||||
'total' => ActivityLog::where('user_id', $user->id)->count(),
|
||||
'total_duration' => ActivityLog::where('user_id', $user->id)->sum('duration_minutes'),
|
||||
'avg_duration' => round(ActivityLog::where('user_id', $user->id)->avg('duration_minutes') ?? 0),
|
||||
'consistency' => $this->calculateConsistency($user->id),
|
||||
];
|
||||
|
||||
// Daftar mood untuk filter dropdown
|
||||
$moodList = ['Bagus', 'Lumayan', 'Biasa Saja', 'Cukup Jenuh', 'Jenuh'];
|
||||
|
||||
return view('siswa.history', compact('activities', 'stats', 'period', 'mood', 'search', 'moodList'));
|
||||
}
|
||||
|
||||
private function calculateConsistency($userId)
|
||||
{
|
||||
$total = ActivityLog::where('user_id', $userId)->count();
|
||||
if ($total == 0) return 0;
|
||||
|
||||
$firstDate = ActivityLog::where('user_id', $userId)->min('activity_date');
|
||||
if (!$firstDate) return 0;
|
||||
|
||||
$daysDiff = Carbon::parse($firstDate)->diffInDays(Carbon::today()) + 1;
|
||||
|
||||
return round(($total / $daysDiff) * 100);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Siswa;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class ParentConnectionController extends Controller
|
||||
{
|
||||
/**
|
||||
* Menampilkan halaman koneksi orang tua
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Cek apakah sudah terhubung dengan orang tua
|
||||
$connection = null;
|
||||
if ($user->parent_id) {
|
||||
// Ambil data orang tua
|
||||
$parent = User::find($user->parent_id);
|
||||
if ($parent) {
|
||||
$connection = $parent;
|
||||
}
|
||||
}
|
||||
|
||||
// Cek apakah ada kode pending
|
||||
$pendingConnection = null;
|
||||
if ($user->parent_code) {
|
||||
$pendingConnection = (object)[
|
||||
'connection_code' => $user->parent_code
|
||||
];
|
||||
}
|
||||
|
||||
return view('siswa.parent-connection', compact('connection', 'pendingConnection'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate kode koneksi baru
|
||||
*/
|
||||
public function generateCode(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Generate kode 8 digit (huruf dan angka) - PASTIKAN UNIK
|
||||
do {
|
||||
$code = strtoupper(substr(md5(uniqid() . $user->id . time()), 0, 8));
|
||||
// Cek apakah kode sudah ada
|
||||
$existing = User::where('parent_code', $code)->first();
|
||||
} while ($existing);
|
||||
|
||||
// Simpan kode ke database
|
||||
$user->parent_code = $code;
|
||||
$user->save();
|
||||
|
||||
return redirect()->route('siswa.parent-connection')
|
||||
->with('success', 'Kode koneksi berhasil digenerate. Berikan kode ini kepada orang tua Anda.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Hapus kode koneksi (jika ingin membatalkan)
|
||||
*/
|
||||
public function clearCode(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
$user->parent_code = null;
|
||||
$user->save();
|
||||
|
||||
return redirect()->route('siswa.parent-connection')
|
||||
->with('success', 'Kode koneksi berhasil dihapus.');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
// app/Http/Controllers/Siswa/RecommendationController.php
|
||||
|
||||
namespace App\Http\Controllers\Siswa;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class RecommendationController extends Controller
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Rekomendasi hari ini
|
||||
$todayRecommendation = Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', Carbon::today())
|
||||
->with('activityLog')
|
||||
->first();
|
||||
|
||||
// Riwayat rekomendasi 7 hari terakhir
|
||||
$weekRecommendations = Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', '>=', Carbon::today()->subDays(7))
|
||||
->with('activityLog')
|
||||
->orderBy('recommendation_date', 'desc')
|
||||
->get();
|
||||
|
||||
// Statistik 7 hari
|
||||
$stats = [
|
||||
'ringan' => Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', '>=', Carbon::today()->subDays(7))
|
||||
->where('category', 'Ringan')
|
||||
->count(),
|
||||
'sedang' => Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', '>=', Carbon::today()->subDays(7))
|
||||
->where('category', 'Sedang')
|
||||
->count(),
|
||||
'intensif' => Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', '>=', Carbon::today()->subDays(7))
|
||||
->where('category', 'Intensif')
|
||||
->count(),
|
||||
];
|
||||
|
||||
return view('siswa.recommendations', compact(
|
||||
'todayRecommendation',
|
||||
'weekRecommendations',
|
||||
'stats'
|
||||
));
|
||||
}
|
||||
|
||||
public function show($id)
|
||||
{
|
||||
$recommendation = Recommendation::where('user_id', Auth::id())
|
||||
->with('activityLog')
|
||||
->findOrFail($id);
|
||||
|
||||
return view('siswa.recommendation-detail', compact('recommendation'));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Siswa;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class VisualizationController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
{
|
||||
$user = Auth::user();
|
||||
|
||||
// Filter periode (default 30 hari)
|
||||
$period = $request->get('period', 30);
|
||||
$startDate = Carbon::today()->subDays($period);
|
||||
|
||||
// Ambil data aktivitas
|
||||
$activities = ActivityLog::where('user_id', $user->id)
|
||||
->whereDate('activity_date', '>=', $startDate)
|
||||
->orderBy('activity_date', 'asc')
|
||||
->get();
|
||||
|
||||
// Ambil data rekomendasi untuk periode yang sama
|
||||
$recommendations = Recommendation::where('user_id', $user->id)
|
||||
->whereDate('recommendation_date', '>=', $startDate)
|
||||
->get()
|
||||
->keyBy(function($item) {
|
||||
return $item->recommendation_date instanceof Carbon
|
||||
? $item->recommendation_date->format('Y-m-d')
|
||||
: Carbon::parse($item->recommendation_date)->format('Y-m-d');
|
||||
});
|
||||
|
||||
// Siapkan data untuk chart
|
||||
$dates = [];
|
||||
$durations = [];
|
||||
$moods = [];
|
||||
$sleep_hours = [];
|
||||
|
||||
// PISAHKAN DUA ARRAY
|
||||
$categoriesRaw = []; // untuk grafik & warna ('Ringan', 'Sedang', 'Intensif')
|
||||
$categoriesDisplay = []; // untuk tampilan teks di tabel
|
||||
|
||||
// Statistik mood counter
|
||||
$moodCount = [
|
||||
'Bagus' => 0,
|
||||
'Lumayan' => 0,
|
||||
'Biasa Saja' => 0,
|
||||
'Cukup Jenuh' => 0,
|
||||
'Jenuh' => 0
|
||||
];
|
||||
|
||||
foreach ($activities as $activity) {
|
||||
$dateKey = $activity->activity_date instanceof Carbon
|
||||
? $activity->activity_date->format('Y-m-d')
|
||||
: Carbon::parse($activity->activity_date)->format('Y-m-d');
|
||||
|
||||
$dates[] = $dateKey;
|
||||
$durations[] = $activity->duration_minutes;
|
||||
$moods[] = $activity->mood;
|
||||
|
||||
if (isset($moodCount[$activity->mood])) {
|
||||
$moodCount[$activity->mood]++;
|
||||
}
|
||||
|
||||
$sleep_hours[] = $activity->sleep_duration ?? $activity->sleep_hours ?? 7;
|
||||
|
||||
// REKOMENDASI: simpan dua array
|
||||
if (isset($recommendations[$dateKey])) {
|
||||
$rec = $recommendations[$dateKey];
|
||||
$categoriesRaw[] = $rec->category; // 'Ringan', 'Sedang', 'Intensif'
|
||||
$categoriesDisplay[] = $rec->display_category; // '📚 Konsisten', dll
|
||||
} else {
|
||||
$categoriesRaw[] = null;
|
||||
$categoriesDisplay[] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Hitung statistik untuk grafik sebaran rekomendasi (pakai $categoriesRaw)
|
||||
$stats = [
|
||||
'total_hari' => $activities->count(),
|
||||
'rata_durasi' => $activities->count() > 0 ? round($activities->avg('duration_minutes'), 1) : 0,
|
||||
'mood_terbanyak' => $this->getMostFrequent($moodCount, '-'),
|
||||
'rekom_terbanyak' => $this->getMostFrequentCategory($categoriesRaw, '-'),
|
||||
];
|
||||
|
||||
$moodDistribution = array_filter($moodCount, function($count) {
|
||||
return $count > 0;
|
||||
});
|
||||
|
||||
return view('siswa.visualization', compact(
|
||||
'dates',
|
||||
'durations',
|
||||
'moods',
|
||||
'sleep_hours',
|
||||
'categoriesRaw', // untuk grafik & warna
|
||||
'categoriesDisplay', // untuk tampilan teks di tabel
|
||||
'stats',
|
||||
'moodDistribution',
|
||||
'period'
|
||||
));
|
||||
}
|
||||
|
||||
private function getMostFrequent($array, $default = '-')
|
||||
{
|
||||
if (empty($array)) return $default;
|
||||
|
||||
arsort($array);
|
||||
$keys = array_keys($array);
|
||||
|
||||
return !empty($keys) && $array[$keys[0]] > 0 ? $keys[0] : $default;
|
||||
}
|
||||
|
||||
private function getMostFrequentCategory($categories, $default = '-')
|
||||
{
|
||||
$filtered = array_filter($categories);
|
||||
if (empty($filtered)) return $default;
|
||||
|
||||
$counts = array_count_values($filtered);
|
||||
arsort($counts);
|
||||
|
||||
return array_key_first($counts) ?? $default;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http;
|
||||
|
||||
use Illuminate\Foundation\Http\Kernel as HttpKernel;
|
||||
|
||||
class Kernel extends HttpKernel
|
||||
{
|
||||
/**
|
||||
* The application's global HTTP middleware stack.
|
||||
*
|
||||
* These middleware are run during every request to your application.
|
||||
*
|
||||
* @var array<int, class-string|string>
|
||||
*/
|
||||
protected $middleware = [
|
||||
// \App\Http\Middleware\TrustHosts::class,
|
||||
\App\Http\Middleware\TrustProxies::class,
|
||||
\Illuminate\Http\Middleware\HandleCors::class,
|
||||
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
|
||||
\App\Http\Middleware\TrimStrings::class,
|
||||
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
|
||||
\App\Http\Middleware\SetTimezone::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's route middleware groups.
|
||||
*
|
||||
* @var array<string, array<int, class-string|string>>
|
||||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
\App\Http\Middleware\EncryptCookies::class,
|
||||
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
|
||||
\Illuminate\Session\Middleware\StartSession::class,
|
||||
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
|
||||
\App\Http\Middleware\VerifyCsrfToken::class,
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
|
||||
'api' => [
|
||||
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
|
||||
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
|
||||
\Illuminate\Routing\Middleware\SubstituteBindings::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* The application's middleware aliases.
|
||||
*
|
||||
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
|
||||
*
|
||||
* @var array<string, class-string|string>
|
||||
*/
|
||||
protected $middlewareAliases = [
|
||||
'auth' => \App\Http\Middleware\Authenticate::class,
|
||||
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
|
||||
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
|
||||
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
|
||||
'can' => \Illuminate\Auth\Middleware\Authorize::class,
|
||||
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
|
||||
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
|
||||
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
|
||||
'signed' => \App\Http\Middleware\ValidateSignature::class,
|
||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||
'role' => \App\Http\Middleware\CheckRole::class,
|
||||
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Auth\Middleware\Authenticate as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class Authenticate extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the path the user should be redirected to when they are not authenticated.
|
||||
*/
|
||||
protected function redirectTo(Request $request): ?string
|
||||
{
|
||||
return $request->expectsJson() ? null : route('login');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
// app/Http/Middleware/CheckRole.php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class CheckRole
|
||||
{
|
||||
public function handle(Request $request, Closure $next, ...$roles)
|
||||
{
|
||||
if (!Auth::check()) {
|
||||
return redirect('login');
|
||||
}
|
||||
|
||||
if (!in_array(Auth::user()->role, $roles)) {
|
||||
abort(403, 'Unauthorized access.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
|
||||
|
||||
class EncryptCookies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the cookies that should not be encrypted.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
|
||||
|
||||
class PreventRequestsDuringMaintenance extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be reachable while maintenance mode is enabled.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Providers\RouteServiceProvider;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class RedirectIfAuthenticated
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next, string ...$guards): Response
|
||||
{
|
||||
$guards = empty($guards) ? [null] : $guards;
|
||||
|
||||
foreach ($guards as $guard) {
|
||||
if (Auth::guard($guard)->check()) {
|
||||
return redirect(RouteServiceProvider::HOME);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class SetTimezone
|
||||
{
|
||||
public function handle($request, Closure $next)
|
||||
{
|
||||
// Set timezone untuk seluruh aplikasi
|
||||
Carbon::setLocale('id');
|
||||
date_default_timezone_set('Asia/Jakarta');
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
|
||||
|
||||
class TrimStrings extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the attributes that should not be trimmed.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
'current_password',
|
||||
'password',
|
||||
'password_confirmation',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustHosts as Middleware;
|
||||
|
||||
class TrustHosts extends Middleware
|
||||
{
|
||||
/**
|
||||
* Get the host patterns that should be trusted.
|
||||
*
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
public function hosts(): array
|
||||
{
|
||||
return [
|
||||
$this->allSubdomainsOfApplicationUrl(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Http\Middleware\TrustProxies as Middleware;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class TrustProxies extends Middleware
|
||||
{
|
||||
/**
|
||||
* The trusted proxies for this application.
|
||||
*
|
||||
* @var array<int, string>|string|null
|
||||
*/
|
||||
protected $proxies;
|
||||
|
||||
/**
|
||||
* The headers that should be used to detect proxies.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $headers =
|
||||
Request::HEADER_X_FORWARDED_FOR |
|
||||
Request::HEADER_X_FORWARDED_HOST |
|
||||
Request::HEADER_X_FORWARDED_PORT |
|
||||
Request::HEADER_X_FORWARDED_PROTO |
|
||||
Request::HEADER_X_FORWARDED_AWS_ELB;
|
||||
}
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
|
||||
|
||||
class ValidateSignature extends Middleware
|
||||
{
|
||||
/**
|
||||
* The names of the query string parameters that should be ignored.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
// 'fbclid',
|
||||
// 'utm_campaign',
|
||||
// 'utm_content',
|
||||
// 'utm_medium',
|
||||
// 'utm_source',
|
||||
// 'utm_term',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
|
||||
|
||||
class VerifyCsrfToken extends Middleware
|
||||
{
|
||||
/**
|
||||
* The URIs that should be excluded from CSRF verification.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
protected $except = [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests\Auth;
|
||||
|
||||
use Illuminate\Auth\Events\Lockout;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class LoginRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Determine if the user is authorized to make this request.
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|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());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class ProfileUpdateRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* Get the validation rules that apply to the request.
|
||||
*
|
||||
* @return array<string, \Illuminate\Contracts\Validation\Rule|array|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)],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
// app/Models/ActivityLog.php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ActivityLog extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'start_time',
|
||||
'end_time',
|
||||
'duration_minutes',
|
||||
'mood',
|
||||
'sleep_hours', // Nilai numerik 1-10 jam
|
||||
'activity_date',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'activity_date' => 'date',
|
||||
'start_time' => 'string',
|
||||
'end_time' => 'string',
|
||||
'sleep_hours' => 'float',
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function recommendation()
|
||||
{
|
||||
return $this->hasOne(Recommendation::class, 'activity_log_id');
|
||||
}
|
||||
|
||||
// Hitung durasi otomatis
|
||||
public function calculateDuration()
|
||||
{
|
||||
if ($this->start_time && $this->end_time) {
|
||||
$start = \Carbon\Carbon::parse($this->start_time);
|
||||
$end = \Carbon\Carbon::parse($this->end_time);
|
||||
$this->duration_minutes = $end->diffInMinutes($start);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper untuk mendapatkan kualitas tidur
|
||||
public function getSleepQualityAttribute()
|
||||
{
|
||||
if ($this->sleep_hours < 5) return 'Kurang Tidur';
|
||||
if ($this->sleep_hours < 7) return 'Kurang Ideal';
|
||||
if ($this->sleep_hours <= 9) return 'Ideal';
|
||||
return 'Berlebih';
|
||||
}
|
||||
|
||||
public function getMoodColorAttribute()
|
||||
{
|
||||
return match($this->mood) {
|
||||
'Bagus' => 'green',
|
||||
'Lumayan' => 'blue',
|
||||
'Biasa Saja' => 'gray',
|
||||
'Cukup Jenuh' => 'yellow',
|
||||
'Jenuh' => 'red',
|
||||
default => 'gray'
|
||||
};
|
||||
}
|
||||
public function scopeToday($query)
|
||||
{
|
||||
return $query->whereDate('activity_date', Carbon::now('Asia/Jakarta')->toDateString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope untuk 7 hari terakhir
|
||||
*/
|
||||
public function scopeLastWeek($query)
|
||||
{
|
||||
return $query->whereDate('activity_date', '>=', Carbon::now('Asia/Jakarta')->subDays(7)->toDateString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope untuk rentang tanggal tertentu
|
||||
*/
|
||||
public function scopeDateRange($query, $startDate, $endDate)
|
||||
{
|
||||
return $query->whereBetween('activity_date', [$startDate, $endDate]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope untuk filter mood
|
||||
*/
|
||||
public function scopeByMood($query, $mood)
|
||||
{
|
||||
return $query->where('mood', $mood);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cek apakah aktivitas untuk hari ini
|
||||
*/
|
||||
public function isToday()
|
||||
{
|
||||
return Carbon::parse($this->activity_date)->isToday();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format tanggal untuk tampilan
|
||||
*/
|
||||
public function getFormattedDateAttribute()
|
||||
{
|
||||
return Carbon::parse($this->activity_date)->format('d M Y');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format hari untuk tampilan
|
||||
*/
|
||||
public function getFormattedDayAttribute()
|
||||
{
|
||||
return Carbon::parse($this->activity_date)->isoFormat('dddd');
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor untuk sleep hours dengan default 7
|
||||
*/
|
||||
public function getSleepHoursAttribute($value)
|
||||
{
|
||||
return $value ?? 7;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get durasi dalam format jam dan menit
|
||||
*/
|
||||
public function getDurationFormattedAttribute()
|
||||
{
|
||||
$hours = floor($this->duration_minutes / 60);
|
||||
$minutes = $this->duration_minutes % 60;
|
||||
|
||||
if ($hours > 0) {
|
||||
return $hours . ' jam ' . $minutes . ' menit';
|
||||
}
|
||||
return $minutes . ' menit';
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
// app/Models/ParentConnection.php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class ParentConnection extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'parent_id',
|
||||
'student_id',
|
||||
'connection_code',
|
||||
'status',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'status' => 'string',
|
||||
];
|
||||
|
||||
public function parent()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function student()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'student_id');
|
||||
}
|
||||
|
||||
// Generate kode koneksi unik
|
||||
public static function generateCode()
|
||||
{
|
||||
do {
|
||||
$code = strtoupper(substr(md5(uniqid() . microtime()), 0, 8));
|
||||
} while (self::where('connection_code', $code)->exists());
|
||||
|
||||
return $code;
|
||||
}
|
||||
|
||||
// Scope untuk koneksi pending
|
||||
public function scopePending($query)
|
||||
{
|
||||
return $query->where('status', 'pending');
|
||||
}
|
||||
|
||||
// Scope untuk koneksi connected
|
||||
public function scopeConnected($query)
|
||||
{
|
||||
return $query->where('status', 'connected');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class PasswordOtp extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'password_otps';
|
||||
|
||||
protected $fillable = [
|
||||
'email',
|
||||
'otp',
|
||||
'expires_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class PasswordReset extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'password_resets';
|
||||
|
||||
protected $fillable = [
|
||||
'email',
|
||||
'token',
|
||||
'expires_at',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'expires_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
|
@ -0,0 +1,193 @@
|
|||
<?php
|
||||
// app/Models/Recommendation.php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Recommendation extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'user_id',
|
||||
'activity_log_id',
|
||||
'category',
|
||||
'recommended_minutes',
|
||||
'notes',
|
||||
'based_on',
|
||||
'confidence',
|
||||
'model_input',
|
||||
'recommendation_date',
|
||||
];
|
||||
|
||||
protected $casts = [
|
||||
'model_input' => 'array',
|
||||
'recommendation_date' => 'date',
|
||||
'confidence' => 'float',
|
||||
];
|
||||
|
||||
public function user()
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
|
||||
public function activityLog()
|
||||
{
|
||||
return $this->belongsTo(ActivityLog::class);
|
||||
}
|
||||
|
||||
public function getDisplayCategoryAttribute()
|
||||
{
|
||||
// Gunakan ID rekomendasi + tanggal sebagai seed untuk variasi
|
||||
// Agar variasi tetap konsisten untuk rekomendasi yang sama
|
||||
$seed = $this->id . $this->recommendation_date->format('Ymd');
|
||||
|
||||
return match($this->category) {
|
||||
'Ringan' => $this->getRandomRingan($seed),
|
||||
'Sedang' => $this->getRandomSedang($seed),
|
||||
'Intensif' => $this->getRandomIntensif($seed),
|
||||
default => $this->category
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Variasi untuk kategori RINGAN
|
||||
*/
|
||||
private function getRandomRingan($seed)
|
||||
{
|
||||
$variations = [
|
||||
'🌱 Pemanasan aja dulu',
|
||||
'😌 Santai aja',
|
||||
'🦥 Selow bro',
|
||||
'🌸 Mulai pelan-pelan',
|
||||
'☕ Rehat bentar, belajar dikit'
|
||||
];
|
||||
|
||||
return $variations[$seed % count($variations)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Variasi untuk kategori SEDANG
|
||||
*/
|
||||
private function getRandomSedang($seed)
|
||||
{
|
||||
$variations = [
|
||||
'📚 Konsisten',
|
||||
'⭐ Ideal banget',
|
||||
'👍 Belajar cukup',
|
||||
'🎯 Tepat sasaran',
|
||||
'⚖️ Seimbang'
|
||||
];
|
||||
|
||||
return $variations[$seed % count($variations)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Variasi untuk kategori INTENSIF
|
||||
*/
|
||||
private function getRandomIntensif($seed)
|
||||
{
|
||||
$variations = [
|
||||
'🚀 Gas terus!',
|
||||
'💪 Semangat 45',
|
||||
'🔥 Maksimal',
|
||||
'🏆 Juara hari ini',
|
||||
'⚡ Fokus penuh'
|
||||
];
|
||||
|
||||
return $variations[$seed % count($variations)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Accessor untuk mendapatkan emoji berdasarkan kategori
|
||||
*/
|
||||
public function getCategoryEmojiAttribute()
|
||||
{
|
||||
return match($this->category) {
|
||||
'Ringan' => '🌱',
|
||||
'Sedang' => '📚',
|
||||
'Intensif' => '🚀',
|
||||
default => '📖'
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* ACCESSOR: Untuk tampilan Orang Tua (formal & mudah dipahami)
|
||||
*/
|
||||
public function getParentDisplayCategoryAttribute()
|
||||
{
|
||||
return match($this->category) {
|
||||
'Ringan' => 'Belajar Ringan',
|
||||
'Sedang' => 'Belajar Cukup',
|
||||
'Intensif' => 'Belajar Lama',
|
||||
default => $this->category
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Accessor untuk warna badge (tetap berdasarkan kategori asli)
|
||||
*/
|
||||
public function getCategoryColorAttribute()
|
||||
{
|
||||
return match($this->category) {
|
||||
'Ringan' => 'yellow',
|
||||
'Sedang' => 'green',
|
||||
'Intensif' => 'blue',
|
||||
default => 'gray'
|
||||
};
|
||||
}
|
||||
|
||||
// Mapping kategori ke durasi
|
||||
public static function getDurationByCategory($category)
|
||||
{
|
||||
return match($category) {
|
||||
'Ringan' => 30,
|
||||
'Sedang' => 45,
|
||||
'Intensif' => 90,
|
||||
default => 30,
|
||||
};
|
||||
}
|
||||
|
||||
// Mapping mood ke skor (sesuai proposal)
|
||||
public static function getMoodScore($mood)
|
||||
{
|
||||
return match($mood) {
|
||||
'Bagus' => 2.0,
|
||||
'Lumayan' => 1.5,
|
||||
'Biasa Saja' => 1.0,
|
||||
'Cukup Jenuh' => 0.5,
|
||||
'Jenuh' => 0.0,
|
||||
default => 1.0,
|
||||
};
|
||||
}
|
||||
|
||||
// Mapping durasi ke skor
|
||||
public static function getDurationScore($durationMinutes)
|
||||
{
|
||||
if ($durationMinutes > 60) return 2.0;
|
||||
if ($durationMinutes >= 31) return 1.0;
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
// Mapping tidur ke skor
|
||||
public static function getSleepScore($sleepDuration)
|
||||
{
|
||||
return match($sleepDuration) {
|
||||
'>7' => 2.0,
|
||||
'4-7' => 1.0,
|
||||
'<4' => 0.0,
|
||||
default => 1.0,
|
||||
};
|
||||
}
|
||||
|
||||
// Hitung rekomendasi berdasarkan skor total
|
||||
public static function calculateCategory($totalScore)
|
||||
{
|
||||
if ($totalScore > 4.5) return 'Intensif';
|
||||
if ($totalScore > 3) return 'Sedang';
|
||||
return 'Ringan';
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
<?php
|
||||
// app/Models/User.php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Support\Facades\Log; // Tambahkan ini
|
||||
|
||||
class User extends Authenticatable
|
||||
{
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'email',
|
||||
'password',
|
||||
'avatar',
|
||||
'role',
|
||||
'ortu_code',
|
||||
'parent_id',
|
||||
'parent_code',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'password',
|
||||
'remember_token',
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
|
||||
// Relasi untuk siswa ke orang tua
|
||||
public function parent()
|
||||
{
|
||||
return $this->belongsTo(User::class, 'parent_id');
|
||||
}
|
||||
|
||||
// Relasi untuk orang tua ke anak-anak
|
||||
public function children()
|
||||
{
|
||||
return $this->hasMany(User::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function activityLogs()
|
||||
{
|
||||
return $this->hasMany(ActivityLog::class);
|
||||
}
|
||||
|
||||
public function recommendations()
|
||||
{
|
||||
return $this->hasMany(Recommendation::class);
|
||||
}
|
||||
|
||||
public function parentConnections()
|
||||
{
|
||||
return $this->hasMany(ParentConnection::class, 'parent_id');
|
||||
}
|
||||
|
||||
public function studentConnections()
|
||||
{
|
||||
return $this->hasMany(ParentConnection::class, 'student_id');
|
||||
}
|
||||
|
||||
public function isSiswa()
|
||||
{
|
||||
return $this->role === 'siswa';
|
||||
}
|
||||
|
||||
public function isOrangTua()
|
||||
{
|
||||
return $this->role === 'orang_tua';
|
||||
}
|
||||
|
||||
// Method untuk generate kode - TIDAK DIGUNAKAN, lebih baik gunakan yang di controller
|
||||
public function generateConnectionCode()
|
||||
{
|
||||
Log::info('generateConnectionCode dipanggil untuk user: ' . $this->id);
|
||||
|
||||
do {
|
||||
$code = strtoupper(substr(md5(uniqid()), 0, 8));
|
||||
} while (self::where('ortu_code', $code)->exists());
|
||||
|
||||
$this->ortu_code = $code;
|
||||
$this->save(); // Ini yang menyebabkan error karena parent_id tidak diisi
|
||||
|
||||
Log::info('Kode berhasil digenerate: ' . $code);
|
||||
|
||||
return $code;
|
||||
}
|
||||
/**
|
||||
* Cek apakah sudah input hari ini
|
||||
*/
|
||||
public function hasTodayActivity()
|
||||
{
|
||||
return $this->activityLogs()
|
||||
->whereDate('activity_date', \Carbon\Carbon::now('Asia/Jakarta')->toDateString())
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ambil aktivitas hari ini
|
||||
*/
|
||||
public function getTodayActivity()
|
||||
{
|
||||
return $this->activityLogs()
|
||||
->whereDate('activity_date', \Carbon\Carbon::now('Asia/Jakarta')->toDateString())
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Register any application services.
|
||||
*/
|
||||
public function register(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
// use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
|
||||
|
||||
class AuthServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The model to policy mappings for the application.
|
||||
*
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
protected $policies = [
|
||||
//
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any authentication / authorization services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Support\Facades\Broadcast;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
class BroadcastServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* Bootstrap any application services.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
Broadcast::routes();
|
||||
|
||||
require base_path('routes/channels.php');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Auth\Events\Registered;
|
||||
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
|
||||
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
|
||||
class EventServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The event to listener mappings for the application.
|
||||
*
|
||||
* @var array<class-string, array<int, class-string>>
|
||||
*/
|
||||
protected $listen = [
|
||||
Registered::class => [
|
||||
SendEmailVerificationNotification::class,
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Register any events for your application.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if events and listeners should be automatically discovered.
|
||||
*/
|
||||
public function shouldDiscoverEvents(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
<?php
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use Illuminate\Cache\RateLimiting\Limit;
|
||||
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
class RouteServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* The path to your application's "home" route.
|
||||
*
|
||||
* Typically, users are redirected here after authentication.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public const HOME = '/dashboard';
|
||||
|
||||
/**
|
||||
* Define your route model bindings, pattern filters, and other route configuration.
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
RateLimiter::for('api', function (Request $request) {
|
||||
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
|
||||
});
|
||||
|
||||
$this->routes(function () {
|
||||
Route::middleware('api')
|
||||
->prefix('api')
|
||||
->group(base_path('routes/api.php'));
|
||||
|
||||
Route::middleware('web')
|
||||
->group(base_path('routes/web.php'));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,152 @@
|
|||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class FlaskModelService
|
||||
{
|
||||
protected $apiUrl;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->apiUrl = env('FLASK_API_URL', 'http://127.0.0.1:5000');
|
||||
Log::info('Flask API URL: ' . $this->apiUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* TEST KONEKSI KE FLASK API
|
||||
*/
|
||||
public function testConnection()
|
||||
{
|
||||
try {
|
||||
$response = Http::timeout(5)->get($this->apiUrl . '/health');
|
||||
return $response->successful();
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Test connection failed: ' . $e->getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PREDIKSI HARIAN (HARI 1-7)
|
||||
* Method ini dipanggil dari ActivityController
|
||||
*/
|
||||
public function predictDaily($mood, $durasiBelajar, $durasiTidur)
|
||||
{
|
||||
try {
|
||||
Log::info('Mengirim request ke Flask API (predictDaily):', [
|
||||
'mood' => $mood,
|
||||
'durasi_belajar' => $durasiBelajar,
|
||||
'durasi_tidur' => $durasiTidur
|
||||
]);
|
||||
|
||||
$response = Http::timeout(10)->post($this->apiUrl . '/predict', [
|
||||
'mood' => $mood,
|
||||
'durasi_belajar' => (int)$durasiBelajar,
|
||||
'durasi_tidur' => (float)$durasiTidur
|
||||
]);
|
||||
|
||||
if ($response->successful()) {
|
||||
$result = $response->json();
|
||||
Log::info('Response dari Flask API (predictDaily):', $result);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'category' => $result['prediction'] ?? $result['category'] ?? 'Sedang',
|
||||
'confidence' => $result['confidence'] ?? 0.85
|
||||
];
|
||||
}
|
||||
|
||||
Log::error('Flask API error (predictDaily): ' . $response->body());
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Gagal memanggil model prediksi'
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Exception saat panggil Flask API (predictDaily): ' . $e->getMessage());
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Koneksi ke model server gagal: ' . $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PREDIKSI BERDASARKAN POLA SISWA (HARI 8+)
|
||||
*/
|
||||
public function predictBasedOnPattern($userId)
|
||||
{
|
||||
try {
|
||||
// Ambil data 7 hari terakhir
|
||||
$activities = ActivityLog::where('user_id', $userId)
|
||||
->orderBy('activity_date', 'desc')
|
||||
->take(7)
|
||||
->get();
|
||||
|
||||
if ($activities->count() < 5) {
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Data belum cukup untuk analisis pola (minimal 5 hari)',
|
||||
'use_daily' => true
|
||||
];
|
||||
}
|
||||
|
||||
// Hitung fitur agregat
|
||||
$avgDuration = $activities->avg('duration_minutes');
|
||||
$mostFrequentMood = $activities->groupBy('mood')
|
||||
->map->count()
|
||||
->sortDesc()
|
||||
->keys()
|
||||
->first();
|
||||
$avgSleep = $activities->avg('sleep_hours');
|
||||
|
||||
Log::info('Mengirim request ke Flask API (predictBasedOnPattern):', [
|
||||
'user_id' => $userId,
|
||||
'avg_duration' => $avgDuration,
|
||||
'most_frequent_mood' => $mostFrequentMood,
|
||||
'avg_sleep' => $avgSleep,
|
||||
'consistency' => $activities->count()
|
||||
]);
|
||||
|
||||
// Kirim ke Flask API endpoint /predict/pattern
|
||||
$response = Http::timeout(10)->post($this->apiUrl . '/predict/pattern', [
|
||||
'avg_duration' => (float)$avgDuration,
|
||||
'most_frequent_mood' => $mostFrequentMood,
|
||||
'avg_sleep' => (float)$avgSleep,
|
||||
'trend' => 'stabil',
|
||||
'consistency' => $activities->count()
|
||||
]);
|
||||
|
||||
if ($response->successful()) {
|
||||
$result = $response->json();
|
||||
Log::info('Response dari Flask API (predictBasedOnPattern):', $result);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'category' => $result['prediction'] ?? $result['category'] ?? 'Sedang',
|
||||
'confidence' => $result['confidence'] ?? 0.85,
|
||||
'pattern_analysis' => $result['pattern_analysis'] ?? null
|
||||
];
|
||||
}
|
||||
|
||||
Log::error('Flask API error (predictBasedOnPattern): ' . $response->body());
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => 'Gagal memanggil model prediksi pola'
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
Log::error('Error dalam pattern analysis: ' . $e->getMessage());
|
||||
return [
|
||||
'success' => false,
|
||||
'message' => $e->getMessage()
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,458 @@
|
|||
<?php
|
||||
// app/Services/RecommendationCalculator.php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\Recommendation;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class RecommendationCalculator
|
||||
{
|
||||
/**
|
||||
* Hitung durasi rekomendasi berdasarkan kategori dan data historis
|
||||
*/
|
||||
public function calculateDuration($userId, $category, $currentMood, $currentSleep)
|
||||
{
|
||||
// Base duration per kategori (dibuat variatif)
|
||||
$baseDurations = [
|
||||
'Ringan' => 30,
|
||||
'Sedang' => 45,
|
||||
'Intensif' => 80 // Base 80, bukan 90, agar lebih bervariasi
|
||||
];
|
||||
|
||||
$baseDuration = $baseDurations[$category];
|
||||
|
||||
// Ambil data 7 hari terakhir untuk analisis
|
||||
$recentActivities = ActivityLog::where('user_id', $userId)
|
||||
->with('recommendation')
|
||||
->orderBy('activity_date', 'desc')
|
||||
->take(7)
|
||||
->get();
|
||||
|
||||
// Jika belum punya history, return base duration dengan variasi ringan
|
||||
if ($recentActivities->isEmpty()) {
|
||||
$initialVariation = $this->getInitialVariation($category);
|
||||
$finalDuration = $baseDuration + $initialVariation;
|
||||
$finalDuration = $this->ensureInRange($finalDuration, $category);
|
||||
|
||||
return [
|
||||
'minutes' => $finalDuration,
|
||||
'notes' => $this->generateSimpleNotes($category, $finalDuration),
|
||||
'factors' => ['new_user'],
|
||||
'adjustment' => $initialVariation,
|
||||
'base_duration' => $baseDuration
|
||||
];
|
||||
}
|
||||
|
||||
// ===========================================
|
||||
// FAKTOR-FAKTOR PENYESUAIAN
|
||||
// ===========================================
|
||||
|
||||
$adjustment = 0;
|
||||
$factors = [];
|
||||
|
||||
// 1. FAKTOR KONSISTENSI
|
||||
$consistencyScore = $this->calculateConsistency($recentActivities);
|
||||
if ($consistencyScore > 0.7) {
|
||||
$adjustment += 5;
|
||||
$factors[] = 'konsisten';
|
||||
} elseif ($consistencyScore < 0.3) {
|
||||
$adjustment -= 5;
|
||||
$factors[] = 'tidak konsisten';
|
||||
}
|
||||
|
||||
// 2. FAKTOR TREND
|
||||
$trend = $this->calculateTrend($recentActivities);
|
||||
if ($trend == 'meningkat') {
|
||||
$adjustment += 4;
|
||||
$factors[] = 'trend meningkat';
|
||||
} elseif ($trend == 'menurun') {
|
||||
$adjustment -= 4;
|
||||
$factors[] = 'trend menurun';
|
||||
}
|
||||
|
||||
// 3. FAKTOR MOOD
|
||||
$moodScore = $this->getMoodWeight($currentMood);
|
||||
if ($moodScore >= 1.5) {
|
||||
$adjustment += 3;
|
||||
$factors[] = 'mood positif';
|
||||
} elseif ($moodScore <= 0.5) {
|
||||
$adjustment -= 5;
|
||||
$factors[] = 'mood negatif';
|
||||
}
|
||||
|
||||
// 4. FAKTOR TIDUR
|
||||
if ($currentSleep >= 7 && $currentSleep <= 9) {
|
||||
$adjustment += 3;
|
||||
$factors[] = 'tidur ideal';
|
||||
} elseif ($currentSleep < 5) {
|
||||
$adjustment -= 5;
|
||||
$factors[] = 'kurang tidur';
|
||||
} elseif ($currentSleep > 9) {
|
||||
$adjustment += 1;
|
||||
$factors[] = 'tidur panjang';
|
||||
}
|
||||
|
||||
// 5. FAKTOR BEBAN KOGNITIF
|
||||
$intensiveDays = $recentActivities->take(3)
|
||||
->filter(function($activity) {
|
||||
return $activity->recommendation && $activity->recommendation->category == 'Intensif';
|
||||
})->count();
|
||||
|
||||
if ($intensiveDays >= 2) {
|
||||
$adjustment -= 5;
|
||||
$factors[] = 'perlu recovery';
|
||||
}
|
||||
|
||||
// 6. FAKTOR ADAPTASI (Individual Differences)
|
||||
$avgActual = $recentActivities->avg('duration_minutes');
|
||||
$avgRecommended = $recentActivities->filter(function($a) {
|
||||
return $a->recommendation;
|
||||
})->avg(function($a) {
|
||||
return $a->recommendation->recommended_minutes ?? 0;
|
||||
});
|
||||
|
||||
if ($avgActual > $avgRecommended * 1.2) {
|
||||
$adjustment += 5;
|
||||
$factors[] = 'kapasitas tinggi';
|
||||
} elseif ($avgActual < $avgRecommended * 0.7) {
|
||||
$adjustment -= 5;
|
||||
$factors[] = 'target terlalu tinggi';
|
||||
}
|
||||
|
||||
// 7. FAKTOR STREAK (Hari beruntun)
|
||||
$streak = $this->calculateStreak($recentActivities);
|
||||
if ($streak >= 5) {
|
||||
$adjustment += 5;
|
||||
$factors[] = 'streak 5+ hari';
|
||||
} elseif ($streak >= 3) {
|
||||
$adjustment += 3;
|
||||
$factors[] = 'streak 3+ hari';
|
||||
}
|
||||
|
||||
// 8. FAKTOR KESESUAIAN KATEGORI
|
||||
$sameCategory = $recentActivities->take(5)
|
||||
->filter(function($a) use ($category) {
|
||||
return $a->recommendation && $a->recommendation->category == $category;
|
||||
})->count();
|
||||
|
||||
if ($sameCategory >= 4) {
|
||||
$adjustment += 3;
|
||||
$factors[] = 'konsisten di kategori';
|
||||
}
|
||||
|
||||
// ===========================================
|
||||
// VARIASI KHUSUS PER KATEGORI
|
||||
// ===========================================
|
||||
|
||||
if ($category == 'Intensif') {
|
||||
// Variasi untuk Intensif (75-115)
|
||||
|
||||
// Berdasarkan durasi aktual
|
||||
if ($avgActual > 100) {
|
||||
$adjustment += rand(5, 10);
|
||||
$factors[] = 'biasa belajar panjang';
|
||||
} elseif ($avgActual > 80) {
|
||||
$adjustment += rand(0, 5);
|
||||
$factors[] = 'cukup terbiasa';
|
||||
} else {
|
||||
$adjustment -= rand(0, 5);
|
||||
$factors[] = 'baru masuk intensif';
|
||||
}
|
||||
|
||||
// Variasi berdasarkan mood
|
||||
if ($currentMood == 'Bagus') {
|
||||
$adjustment += rand(2, 5);
|
||||
} elseif ($currentMood == 'Lumayan') {
|
||||
$adjustment += rand(0, 3);
|
||||
}
|
||||
|
||||
// Random factor untuk variasi alami (±5)
|
||||
$adjustment += rand(-5, 5);
|
||||
|
||||
} elseif ($category == 'Sedang') {
|
||||
// Variasi untuk Sedang (35-65)
|
||||
|
||||
// Berdasarkan trend
|
||||
if ($trend == 'meningkat') {
|
||||
$adjustment += rand(3, 7);
|
||||
$factors[] = 'menuju intensif';
|
||||
} elseif ($trend == 'menurun') {
|
||||
$adjustment -= rand(3, 7);
|
||||
$factors[] = 'menuju ringan';
|
||||
}
|
||||
|
||||
// Random factor kecil
|
||||
$adjustment += rand(-3, 3);
|
||||
|
||||
} elseif ($category == 'Ringan') {
|
||||
// Variasi untuk Ringan (20-40)
|
||||
|
||||
// Jika mood jelek, kurangi
|
||||
if ($currentMood == 'Jenuh' || $currentMood == 'Cukup Jenuh') {
|
||||
$adjustment -= rand(0, 5);
|
||||
$factors[] = 'butuh istirahat';
|
||||
}
|
||||
|
||||
// Random factor kecil
|
||||
$adjustment += rand(-2, 2);
|
||||
}
|
||||
|
||||
// ===========================================
|
||||
// HITUNG DURASI FINAL
|
||||
// ===========================================
|
||||
|
||||
// Batasi adjustment agar tidak terlalu ekstrim
|
||||
$maxAdjustment = $this->getMaxAdjustment($category);
|
||||
$adjustment = max(min($adjustment, $maxAdjustment), -$maxAdjustment);
|
||||
|
||||
$finalDuration = $baseDuration + $adjustment;
|
||||
|
||||
// Bulatkan ke 5 menit terdekat
|
||||
$finalDuration = round($finalDuration / 5) * 5;
|
||||
|
||||
// Pastikan dalam range yang wajar per kategori
|
||||
$finalDuration = $this->ensureInRange($finalDuration, $category);
|
||||
|
||||
// Generate notes yang personal
|
||||
$notes = $this->generatePersonalNotes($category, $factors, $adjustment, $finalDuration, $streak);
|
||||
|
||||
Log::info('Recommendation calculated:', [
|
||||
'user_id' => $userId,
|
||||
'category' => $category,
|
||||
'base' => $baseDuration,
|
||||
'adjustment' => $adjustment,
|
||||
'final' => $finalDuration,
|
||||
'factors' => $factors
|
||||
]);
|
||||
|
||||
return [
|
||||
'minutes' => $finalDuration,
|
||||
'notes' => $notes,
|
||||
'factors' => $factors,
|
||||
'adjustment' => $adjustment,
|
||||
'base_duration' => $baseDuration
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Variasi awal untuk user baru
|
||||
*/
|
||||
private function getInitialVariation($category)
|
||||
{
|
||||
$variations = [
|
||||
'Ringan' => rand(-2, 5),
|
||||
'Sedang' => rand(-3, 8),
|
||||
'Intensif' => rand(-5, 15)
|
||||
];
|
||||
|
||||
return $variations[$category];
|
||||
}
|
||||
|
||||
/**
|
||||
* Hitung skor konsistensi (0-1)
|
||||
*/
|
||||
private function calculateConsistency($activities)
|
||||
{
|
||||
if ($activities->count() < 3) return 0.5;
|
||||
|
||||
$durations = $activities->pluck('duration_minutes')->toArray();
|
||||
$avg = array_sum($durations) / count($durations);
|
||||
|
||||
// Hitung standar deviasi
|
||||
$variance = 0;
|
||||
foreach ($durations as $dur) {
|
||||
$variance += pow($dur - $avg, 2);
|
||||
}
|
||||
$stdDev = sqrt($variance / count($durations));
|
||||
|
||||
// Konsistensi = kebalikan dari koefisien variasi
|
||||
$cv = $stdDev / $avg;
|
||||
$consistency = max(0, min(1, 1 - $cv));
|
||||
|
||||
return $consistency;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hitung trend (meningkat/menurun/stabil)
|
||||
*/
|
||||
private function calculateTrend($activities)
|
||||
{
|
||||
if ($activities->count() < 4) return 'stabil';
|
||||
|
||||
$recent = $activities->take(3)->avg('duration_minutes');
|
||||
$older = $activities->slice(3, 3)->avg('duration_minutes');
|
||||
|
||||
$diff = $recent - $older;
|
||||
|
||||
if ($diff > 10) return 'meningkat';
|
||||
if ($diff < -10) return 'menurun';
|
||||
return 'stabil';
|
||||
}
|
||||
|
||||
/**
|
||||
* Hitung streak hari beruntun
|
||||
*/
|
||||
private function calculateStreak($activities)
|
||||
{
|
||||
if ($activities->isEmpty()) return 0;
|
||||
|
||||
$streak = 1;
|
||||
$prevDate = null;
|
||||
|
||||
foreach ($activities as $activity) {
|
||||
if ($prevDate) {
|
||||
$diff = $prevDate->diffInDays($activity->activity_date);
|
||||
if ($diff == 1) {
|
||||
$streak++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$prevDate = $activity->activity_date;
|
||||
}
|
||||
|
||||
return $streak;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bobot mood (sesuai skema proposal)
|
||||
*/
|
||||
private function getMoodWeight($mood)
|
||||
{
|
||||
return match($mood) {
|
||||
'Bagus' => 2.0,
|
||||
'Lumayan' => 1.5,
|
||||
'Biasa Saja' => 1.0,
|
||||
'Cukup Jenuh' => 0.5,
|
||||
'Jenuh' => 0.0,
|
||||
default => 1.0
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Maksimum adjustment per kategori
|
||||
*/
|
||||
private function getMaxAdjustment($category)
|
||||
{
|
||||
return match($category) {
|
||||
'Ringan' => 10, // 20-40
|
||||
'Sedang' => 20, // 25-65 (lebih lebar)
|
||||
'Intensif' => 35, // 45-115 (sangat lebar)
|
||||
default => 15
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pastikan durasi dalam range wajar
|
||||
*/
|
||||
private function ensureInRange($duration, $category)
|
||||
{
|
||||
$ranges = [
|
||||
'Ringan' => ['min' => 20, 'max' => 40],
|
||||
'Sedang' => ['min' => 30, 'max' => 70], // Diperlebar
|
||||
'Intensif' => ['min' => 60, 'max' => 120] // 60-120
|
||||
];
|
||||
|
||||
$range = $ranges[$category];
|
||||
|
||||
return max($range['min'], min($duration, $range['max']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate notes sederhana untuk user baru
|
||||
*/
|
||||
private function generateSimpleNotes($category, $duration)
|
||||
{
|
||||
return match($category) {
|
||||
'Ringan' => "📚 Belajar ringan {$duration} menit. Selamat datang di LearnMood!",
|
||||
'Sedang' => "🎯 Belajar {$duration} menit dengan fokus. Selamat datang!",
|
||||
'Intensif' => "🚀 Sesi intensif {$duration} menit. Selamat datang!",
|
||||
default => "Selamat datang di LearnMood!"
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate notes personal berdasarkan faktor-faktor
|
||||
*/
|
||||
private function generatePersonalNotes($category, $factors, $adjustment, $duration, $streak)
|
||||
{
|
||||
$notes = [];
|
||||
|
||||
// Base note
|
||||
$notes[] = match($category) {
|
||||
'Ringan' => "📚 Belajar ringan {$duration} menit",
|
||||
'Sedang' => "🎯 Belajar {$duration} menit dengan fokus",
|
||||
'Intensif' => "🚀 Sesi intensif {$duration} menit"
|
||||
};
|
||||
|
||||
// Notes berdasarkan streak
|
||||
if ($streak >= 7) {
|
||||
$notes[] = "Luar biasa! Streak 7 hari! 🌟";
|
||||
} elseif ($streak >= 5) {
|
||||
$notes[] = "Hebat! Streak 5 hari! 🔥";
|
||||
} elseif ($streak >= 3) {
|
||||
$notes[] = "Mantap! Streak 3 hari! ⭐";
|
||||
}
|
||||
|
||||
// Notes berdasarkan faktor
|
||||
if (in_array('konsisten', $factors)) {
|
||||
$notes[] = "Konsistensimu luar biasa!";
|
||||
}
|
||||
|
||||
if (in_array('trend meningkat', $factors)) {
|
||||
$notes[] = "Durasi belajarmu terus meningkat!";
|
||||
} elseif (in_array('trend menurun', $factors)) {
|
||||
$notes[] = "Semangat! Coba tingkatkan lagi.";
|
||||
}
|
||||
|
||||
if (in_array('mood positif', $factors)) {
|
||||
$notes[] = "Mood positif, belajar jadi lebih mudah!";
|
||||
} elseif (in_array('mood negatif', $factors)) {
|
||||
$notes[] = "Mood sedang kurang, jangan paksakan diri.";
|
||||
}
|
||||
|
||||
if (in_array('tidur ideal', $factors)) {
|
||||
$notes[] = "Tidur cukup mendukung konsentrasi.";
|
||||
} elseif (in_array('kurang tidur', $factors)) {
|
||||
$notes[] = "Coba tidur lebih awal nanti malam.";
|
||||
}
|
||||
|
||||
if (in_array('perlu recovery', $factors)) {
|
||||
$notes[] = "Beberapa hari ini intensif, jaga keseimbangan.";
|
||||
}
|
||||
|
||||
if (in_array('kapasitas tinggi', $factors)) {
|
||||
$notes[] = "Kamu mampu lebih dari target!";
|
||||
} elseif (in_array('target terlalu tinggi', $factors)) {
|
||||
$notes[] = "Target mungkin terlalu tinggi, fokus ke kualitas.";
|
||||
}
|
||||
|
||||
// Khusus Intensif
|
||||
if ($category == 'Intensif') {
|
||||
if ($duration >= 110) {
|
||||
$notes[] = "Wow, super intensif! Pastikan istirahat cukup.";
|
||||
} elseif ($duration >= 90) {
|
||||
$notes[] = "Sesi intensif optimal! Pertahankan.";
|
||||
} elseif ($duration <= 70) {
|
||||
$notes[] = "Intensif ringan, bagus untuk adaptasi.";
|
||||
}
|
||||
}
|
||||
|
||||
// Khusus Sedang
|
||||
if ($category == 'Sedang' && $duration >= 60) {
|
||||
$notes[] = "Hampir masuk intensif! Tingkatkan sedikit lagi.";
|
||||
}
|
||||
|
||||
// Info adjustment
|
||||
if ($adjustment > 5) {
|
||||
$notes[] = "(+{$adjustment} menit dari baseline)";
|
||||
} elseif ($adjustment < -5) {
|
||||
$notes[] = "({$adjustment} menit dari baseline - fokus kualitas)";
|
||||
}
|
||||
|
||||
return implode(' ', $notes);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AppLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.app');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
|
||||
namespace App\View\Components;
|
||||
|
||||
use Illuminate\View\Component;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class GuestLayout extends Component
|
||||
{
|
||||
/**
|
||||
* Get the view / contents that represents the component.
|
||||
*/
|
||||
public function render(): View
|
||||
{
|
||||
return view('layouts.guest');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
define('LARAVEL_START', microtime(true));
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Register The Auto Loader
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Composer provides a convenient, automatically generated class loader
|
||||
| for our application. We just need to utilize it! We'll require it
|
||||
| into the script here so that we do not have to worry about the
|
||||
| loading of any of our classes manually. It's great to relax.
|
||||
|
|
||||
*/
|
||||
|
||||
require __DIR__.'/vendor/autoload.php';
|
||||
|
||||
$app = require_once __DIR__.'/bootstrap/app.php';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Run The Artisan Application
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When we run the console application, the current CLI command will be
|
||||
| executed in this console and the response sent back to a terminal
|
||||
| or another output device for the developers. Here goes nothing!
|
||||
|
|
||||
*/
|
||||
|
||||
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
|
||||
|
||||
$status = $kernel->handle(
|
||||
$input = new Symfony\Component\Console\Input\ArgvInput,
|
||||
new Symfony\Component\Console\Output\ConsoleOutput
|
||||
);
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Shutdown The Application
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Once Artisan has finished running, we will fire off the shutdown events
|
||||
| so that any final work may be done by the application before we shut
|
||||
| down the process. This is the last thing to happen to the request.
|
||||
|
|
||||
*/
|
||||
|
||||
$kernel->terminate($input, $status);
|
||||
|
||||
exit($status);
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Create The Application
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The first thing we will do is create a new Laravel application instance
|
||||
| which serves as the "glue" for all the components of Laravel, and is
|
||||
| the IoC container for the system binding all of the various parts.
|
||||
|
|
||||
*/
|
||||
|
||||
$app = new Illuminate\Foundation\Application(
|
||||
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
|
||||
);
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Bind Important Interfaces
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Next, we need to bind some important interfaces into the container so
|
||||
| we will be able to resolve them when needed. The kernels serve the
|
||||
| incoming requests to this application from both the web and CLI.
|
||||
|
|
||||
*/
|
||||
|
||||
$app->singleton(
|
||||
Illuminate\Contracts\Http\Kernel::class,
|
||||
App\Http\Kernel::class
|
||||
);
|
||||
|
||||
$app->singleton(
|
||||
Illuminate\Contracts\Console\Kernel::class,
|
||||
App\Console\Kernel::class
|
||||
);
|
||||
|
||||
$app->singleton(
|
||||
Illuminate\Contracts\Debug\ExceptionHandler::class,
|
||||
App\Exceptions\Handler::class
|
||||
);
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Return The Application
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This script returns the application instance. The instance is given to
|
||||
| the calling script so we can separate the building of the instances
|
||||
| from the actual running of the application and sending responses.
|
||||
|
|
||||
*/
|
||||
|
||||
return $app;
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
*
|
||||
!.gitignore
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
{
|
||||
"name": "laravel/laravel",
|
||||
"type": "project",
|
||||
"description": "The skeleton application for the Laravel framework.",
|
||||
"keywords": ["laravel", "framework"],
|
||||
"license": "MIT",
|
||||
"require": {
|
||||
"php": "^8.1",
|
||||
"guzzlehttp/guzzle": "^7.10",
|
||||
"laravel/framework": "^10.10",
|
||||
"laravel/sanctum": "^3.3",
|
||||
"laravel/tinker": "^2.8"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.9.1",
|
||||
"laravel/breeze": "^1.29",
|
||||
"laravel/pint": "^1.0",
|
||||
"laravel/sail": "^1.18",
|
||||
"mockery/mockery": "^1.4.4",
|
||||
"nunomaduro/collision": "^7.0",
|
||||
"phpunit/phpunit": "^10.1",
|
||||
"spatie/laravel-ignition": "^2.0"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"App\\": "app/",
|
||||
"Database\\Factories\\": "database/factories/",
|
||||
"Database\\Seeders\\": "database/seeders/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"Tests\\": "tests/"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"post-autoload-dump": [
|
||||
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
|
||||
"@php artisan package:discover --ansi"
|
||||
],
|
||||
"post-update-cmd": [
|
||||
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
|
||||
],
|
||||
"post-root-package-install": [
|
||||
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
|
||||
],
|
||||
"post-create-project-cmd": [
|
||||
"@php artisan key:generate --ansi"
|
||||
]
|
||||
},
|
||||
"extra": {
|
||||
"laravel": {
|
||||
"dont-discover": []
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"optimize-autoloader": true,
|
||||
"preferred-install": "dist",
|
||||
"sort-packages": true,
|
||||
"allow-plugins": {
|
||||
"pestphp/pest-plugin": true,
|
||||
"php-http/discovery": true
|
||||
}
|
||||
},
|
||||
"minimum-stability": "stable",
|
||||
"prefer-stable": true
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,188 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Facade;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value is the name of your application. This value is used when the
|
||||
| framework needs to place the application's name in a notification or
|
||||
| any other location as required by the application or its packages.
|
||||
|
|
||||
*/
|
||||
|
||||
'name' => env('APP_NAME', 'Laravel'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Environment
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value determines the "environment" your application is currently
|
||||
| running in. This may determine how you prefer to configure various
|
||||
| services the application utilizes. Set this in your ".env" file.
|
||||
|
|
||||
*/
|
||||
|
||||
'env' => env('APP_ENV', 'production'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Debug Mode
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When your application is in debug mode, detailed error messages with
|
||||
| stack traces will be shown on every error that occurs within your
|
||||
| application. If disabled, a simple generic error page is shown.
|
||||
|
|
||||
*/
|
||||
|
||||
'debug' => (bool) env('APP_DEBUG', false),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application URL
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This URL is used by the console to properly generate URLs when using
|
||||
| the Artisan command line tool. You should set this to the root of
|
||||
| your application so that it is used when running Artisan tasks.
|
||||
|
|
||||
*/
|
||||
|
||||
'url' => env('APP_URL', 'http://localhost'),
|
||||
|
||||
'asset_url' => env('ASSET_URL'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Timezone
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the default timezone for your application, which
|
||||
| will be used by the PHP date and date-time functions. We have gone
|
||||
| ahead and set this to a sensible default for you out of the box.
|
||||
|
|
||||
*/
|
||||
|
||||
'timezone' => 'UTC',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Locale Configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The application locale determines the default locale that will be used
|
||||
| by the translation service provider. You are free to set this value
|
||||
| to any of the locales which will be supported by the application.
|
||||
|
|
||||
*/
|
||||
|
||||
'locale' => 'en',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Fallback Locale
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The fallback locale determines the locale to use when the current one
|
||||
| is not available. You may change the value to correspond to any of
|
||||
| the language folders that are provided through your application.
|
||||
|
|
||||
*/
|
||||
|
||||
'fallback_locale' => 'en',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Faker Locale
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This locale will be used by the Faker PHP library when generating fake
|
||||
| data for your database seeds. For example, this will be used to get
|
||||
| localized telephone numbers, street address information and more.
|
||||
|
|
||||
*/
|
||||
|
||||
'faker_locale' => 'en_US',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Encryption Key
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This key is used by the Illuminate encrypter service and should be set
|
||||
| to a random, 32 character string, otherwise these encrypted strings
|
||||
| will not be safe. Please do this before deploying an application!
|
||||
|
|
||||
*/
|
||||
|
||||
'key' => env('APP_KEY'),
|
||||
|
||||
'cipher' => 'AES-256-CBC',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Maintenance Mode Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These configuration options determine the driver used to determine and
|
||||
| manage Laravel's "maintenance mode" status. The "cache" driver will
|
||||
| allow maintenance mode to be controlled across multiple machines.
|
||||
|
|
||||
| Supported drivers: "file", "cache"
|
||||
|
|
||||
*/
|
||||
|
||||
'maintenance' => [
|
||||
'driver' => 'file',
|
||||
// 'store' => 'redis',
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Autoloaded Service Providers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The service providers listed here will be automatically loaded on the
|
||||
| request to your application. Feel free to add your own services to
|
||||
| this array to grant expanded functionality to your applications.
|
||||
|
|
||||
*/
|
||||
|
||||
'providers' => ServiceProvider::defaultProviders()->merge([
|
||||
/*
|
||||
* Package Service Providers...
|
||||
*/
|
||||
|
||||
/*
|
||||
* Application Service Providers...
|
||||
*/
|
||||
App\Providers\AppServiceProvider::class,
|
||||
App\Providers\AuthServiceProvider::class,
|
||||
// App\Providers\BroadcastServiceProvider::class,
|
||||
App\Providers\EventServiceProvider::class,
|
||||
App\Providers\RouteServiceProvider::class,
|
||||
])->toArray(),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Class Aliases
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This array of class aliases will be registered when this application
|
||||
| is started. However, feel free to register as many as you wish as
|
||||
| the aliases are "lazy" loaded so they don't hinder performance.
|
||||
|
|
||||
*/
|
||||
|
||||
'aliases' => Facade::defaultAliases()->merge([
|
||||
// 'Example' => App\Facades\Example::class,
|
||||
])->toArray(),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,115 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication Defaults
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default authentication "guard" and password
|
||||
| reset options for your application. You may change these defaults
|
||||
| as required, but they're a perfect start for most applications.
|
||||
|
|
||||
*/
|
||||
|
||||
'defaults' => [
|
||||
'guard' => 'web',
|
||||
'passwords' => 'users',
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication Guards
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Next, you may define every authentication guard for your application.
|
||||
| Of course, a great default configuration has been defined for you
|
||||
| here which uses session storage and the Eloquent user provider.
|
||||
|
|
||||
| All authentication drivers have a user provider. This defines how the
|
||||
| users are actually retrieved out of your database or other storage
|
||||
| mechanisms used by this application to persist your user's data.
|
||||
|
|
||||
| Supported: "session"
|
||||
|
|
||||
*/
|
||||
|
||||
'guards' => [
|
||||
'web' => [
|
||||
'driver' => 'session',
|
||||
'provider' => 'users',
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| User Providers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| All authentication drivers have a user provider. This defines how the
|
||||
| users are actually retrieved out of your database or other storage
|
||||
| mechanisms used by this application to persist your user's data.
|
||||
|
|
||||
| If you have multiple user tables or models you may configure multiple
|
||||
| sources which represent each model / table. These sources may then
|
||||
| be assigned to any extra authentication guards you have defined.
|
||||
|
|
||||
| Supported: "database", "eloquent"
|
||||
|
|
||||
*/
|
||||
|
||||
'providers' => [
|
||||
'users' => [
|
||||
'driver' => 'eloquent',
|
||||
'model' => App\Models\User::class,
|
||||
],
|
||||
|
||||
// 'users' => [
|
||||
// 'driver' => 'database',
|
||||
// 'table' => 'users',
|
||||
// ],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Resetting Passwords
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You may specify multiple password reset configurations if you have more
|
||||
| than one user table or model in the application and you want to have
|
||||
| separate password reset settings based on the specific user types.
|
||||
|
|
||||
| The expiry time is the number of minutes that each reset token will be
|
||||
| considered valid. This security feature keeps tokens short-lived so
|
||||
| they have less time to be guessed. You may change this as needed.
|
||||
|
|
||||
| The throttle setting is the number of seconds a user must wait before
|
||||
| generating more password reset tokens. This prevents the user from
|
||||
| quickly generating a very large amount of password reset tokens.
|
||||
|
|
||||
*/
|
||||
|
||||
'passwords' => [
|
||||
'users' => [
|
||||
'provider' => 'users',
|
||||
'table' => 'password_reset_tokens',
|
||||
'expire' => 60,
|
||||
'throttle' => 60,
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Password Confirmation Timeout
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define the amount of seconds before a password confirmation
|
||||
| times out and the user is prompted to re-enter their password via the
|
||||
| confirmation screen. By default, the timeout lasts for three hours.
|
||||
|
|
||||
*/
|
||||
|
||||
'password_timeout' => 10800,
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Broadcaster
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default broadcaster that will be used by the
|
||||
| framework when an event needs to be broadcast. You may set this to
|
||||
| any of the connections defined in the "connections" array below.
|
||||
|
|
||||
| Supported: "pusher", "ably", "redis", "log", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('BROADCAST_DRIVER', 'null'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Broadcast Connections
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define all of the broadcast connections that will be used
|
||||
| to broadcast events to other systems or over websockets. Samples of
|
||||
| each available type of connection are provided inside this array.
|
||||
|
|
||||
*/
|
||||
|
||||
'connections' => [
|
||||
|
||||
'pusher' => [
|
||||
'driver' => 'pusher',
|
||||
'key' => env('PUSHER_APP_KEY'),
|
||||
'secret' => env('PUSHER_APP_SECRET'),
|
||||
'app_id' => env('PUSHER_APP_ID'),
|
||||
'options' => [
|
||||
'cluster' => env('PUSHER_APP_CLUSTER'),
|
||||
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
|
||||
'port' => env('PUSHER_PORT', 443),
|
||||
'scheme' => env('PUSHER_SCHEME', 'https'),
|
||||
'encrypted' => true,
|
||||
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
|
||||
],
|
||||
'client_options' => [
|
||||
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
|
||||
],
|
||||
],
|
||||
|
||||
'ably' => [
|
||||
'driver' => 'ably',
|
||||
'key' => env('ABLY_KEY'),
|
||||
],
|
||||
|
||||
'redis' => [
|
||||
'driver' => 'redis',
|
||||
'connection' => 'default',
|
||||
],
|
||||
|
||||
'log' => [
|
||||
'driver' => 'log',
|
||||
],
|
||||
|
||||
'null' => [
|
||||
'driver' => 'null',
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Cache Store
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default cache connection that gets used while
|
||||
| using this caching library. This connection is used when another is
|
||||
| not explicitly specified when executing a given caching function.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('CACHE_DRIVER', 'file'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cache Stores
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may define all of the cache "stores" for your application as
|
||||
| well as their drivers. You may even define multiple stores for the
|
||||
| same cache driver to group types of items stored in your caches.
|
||||
|
|
||||
| Supported drivers: "apc", "array", "database", "file",
|
||||
| "memcached", "redis", "dynamodb", "octane", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'stores' => [
|
||||
|
||||
'apc' => [
|
||||
'driver' => 'apc',
|
||||
],
|
||||
|
||||
'array' => [
|
||||
'driver' => 'array',
|
||||
'serialize' => false,
|
||||
],
|
||||
|
||||
'database' => [
|
||||
'driver' => 'database',
|
||||
'table' => 'cache',
|
||||
'connection' => null,
|
||||
'lock_connection' => null,
|
||||
],
|
||||
|
||||
'file' => [
|
||||
'driver' => 'file',
|
||||
'path' => storage_path('framework/cache/data'),
|
||||
'lock_path' => storage_path('framework/cache/data'),
|
||||
],
|
||||
|
||||
'memcached' => [
|
||||
'driver' => 'memcached',
|
||||
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
|
||||
'sasl' => [
|
||||
env('MEMCACHED_USERNAME'),
|
||||
env('MEMCACHED_PASSWORD'),
|
||||
],
|
||||
'options' => [
|
||||
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
|
||||
],
|
||||
'servers' => [
|
||||
[
|
||||
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
|
||||
'port' => env('MEMCACHED_PORT', 11211),
|
||||
'weight' => 100,
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
'redis' => [
|
||||
'driver' => 'redis',
|
||||
'connection' => 'cache',
|
||||
'lock_connection' => 'default',
|
||||
],
|
||||
|
||||
'dynamodb' => [
|
||||
'driver' => 'dynamodb',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
|
||||
'endpoint' => env('DYNAMODB_ENDPOINT'),
|
||||
],
|
||||
|
||||
'octane' => [
|
||||
'driver' => 'octane',
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cache Key Prefix
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
|
||||
| stores there might be other applications using the same cache. For
|
||||
| that reason, you may prefix every cache key to avoid collisions.
|
||||
|
|
||||
*/
|
||||
|
||||
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cross-Origin Resource Sharing (CORS) Configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure your settings for cross-origin resource sharing
|
||||
| or "CORS". This determines what cross-origin operations may execute
|
||||
| in web browsers. You are free to adjust these settings as needed.
|
||||
|
|
||||
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
||||
|
|
||||
*/
|
||||
|
||||
'paths' => ['api/*', 'sanctum/csrf-cookie'],
|
||||
|
||||
'allowed_methods' => ['*'],
|
||||
|
||||
'allowed_origins' => ['*'],
|
||||
|
||||
'allowed_origins_patterns' => [],
|
||||
|
||||
'allowed_headers' => ['*'],
|
||||
|
||||
'exposed_headers' => [],
|
||||
|
||||
'max_age' => 0,
|
||||
|
||||
'supports_credentials' => false,
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Database Connection Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify which of the database connections below you wish
|
||||
| to use as your default connection for all database work. Of course
|
||||
| you may use many connections at once using the Database library.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('DB_CONNECTION', 'mysql'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Database Connections
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here are each of the database connections setup for your application.
|
||||
| Of course, examples of configuring each database platform that is
|
||||
| supported by Laravel is shown below to make development simple.
|
||||
|
|
||||
|
|
||||
| All database work in Laravel is done through the PHP PDO facilities
|
||||
| so make sure you have the driver for your particular database of
|
||||
| choice installed on your machine before you begin development.
|
||||
|
|
||||
*/
|
||||
|
||||
'connections' => [
|
||||
|
||||
'sqlite' => [
|
||||
'driver' => 'sqlite',
|
||||
'url' => env('DATABASE_URL'),
|
||||
'database' => env('DB_DATABASE', database_path('database.sqlite')),
|
||||
'prefix' => '',
|
||||
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
|
||||
],
|
||||
|
||||
'mysql' => [
|
||||
'driver' => 'mysql',
|
||||
'url' => env('DATABASE_URL'),
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '3306'),
|
||||
'database' => env('DB_DATABASE', 'forge'),
|
||||
'username' => env('DB_USERNAME', 'forge'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'unix_socket' => env('DB_SOCKET', ''),
|
||||
'charset' => 'utf8mb4',
|
||||
'collation' => 'utf8mb4_unicode_ci',
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
'strict' => true,
|
||||
'engine' => null,
|
||||
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||
]) : [],
|
||||
],
|
||||
|
||||
'pgsql' => [
|
||||
'driver' => 'pgsql',
|
||||
'url' => env('DATABASE_URL'),
|
||||
'host' => env('DB_HOST', '127.0.0.1'),
|
||||
'port' => env('DB_PORT', '5432'),
|
||||
'database' => env('DB_DATABASE', 'forge'),
|
||||
'username' => env('DB_USERNAME', 'forge'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'charset' => 'utf8',
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
'search_path' => 'public',
|
||||
'sslmode' => 'prefer',
|
||||
],
|
||||
|
||||
'sqlsrv' => [
|
||||
'driver' => 'sqlsrv',
|
||||
'url' => env('DATABASE_URL'),
|
||||
'host' => env('DB_HOST', 'localhost'),
|
||||
'port' => env('DB_PORT', '1433'),
|
||||
'database' => env('DB_DATABASE', 'forge'),
|
||||
'username' => env('DB_USERNAME', 'forge'),
|
||||
'password' => env('DB_PASSWORD', ''),
|
||||
'charset' => 'utf8',
|
||||
'prefix' => '',
|
||||
'prefix_indexes' => true,
|
||||
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
|
||||
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Migration Repository Table
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This table keeps track of all the migrations that have already run for
|
||||
| your application. Using this information, we can determine which of
|
||||
| the migrations on disk haven't actually been run in the database.
|
||||
|
|
||||
*/
|
||||
|
||||
'migrations' => 'migrations',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Redis Databases
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Redis is an open source, fast, and advanced key-value store that also
|
||||
| provides a richer body of commands than a typical key-value system
|
||||
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
||||
|
|
||||
*/
|
||||
|
||||
'redis' => [
|
||||
|
||||
'client' => env('REDIS_CLIENT', 'phpredis'),
|
||||
|
||||
'options' => [
|
||||
'cluster' => env('REDIS_CLUSTER', 'redis'),
|
||||
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
|
||||
],
|
||||
|
||||
'default' => [
|
||||
'url' => env('REDIS_URL'),
|
||||
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||
'username' => env('REDIS_USERNAME'),
|
||||
'password' => env('REDIS_PASSWORD'),
|
||||
'port' => env('REDIS_PORT', '6379'),
|
||||
'database' => env('REDIS_DB', '0'),
|
||||
],
|
||||
|
||||
'cache' => [
|
||||
'url' => env('REDIS_URL'),
|
||||
'host' => env('REDIS_HOST', '127.0.0.1'),
|
||||
'username' => env('REDIS_USERNAME'),
|
||||
'password' => env('REDIS_PASSWORD'),
|
||||
'port' => env('REDIS_PORT', '6379'),
|
||||
'database' => env('REDIS_CACHE_DB', '1'),
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Filesystem Disk
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the default filesystem disk that should be used
|
||||
| by the framework. The "local" disk, as well as a variety of cloud
|
||||
| based disks are available to your application. Just store away!
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('FILESYSTEM_DISK', 'local'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Filesystem Disks
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure as many filesystem "disks" as you wish, and you
|
||||
| may even configure multiple disks of the same driver. Defaults have
|
||||
| been set up for each driver as an example of the required values.
|
||||
|
|
||||
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
||||
|
|
||||
*/
|
||||
|
||||
'disks' => [
|
||||
|
||||
'local' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app'),
|
||||
'throw' => false,
|
||||
],
|
||||
|
||||
'public' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/public'),
|
||||
'url' => env('APP_URL').'/storage',
|
||||
'visibility' => 'public',
|
||||
'throw' => false,
|
||||
],
|
||||
|
||||
's3' => [
|
||||
'driver' => 's3',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION'),
|
||||
'bucket' => env('AWS_BUCKET'),
|
||||
'url' => env('AWS_URL'),
|
||||
'endpoint' => env('AWS_ENDPOINT'),
|
||||
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
|
||||
'throw' => false,
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Symbolic Links
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the symbolic links that will be created when the
|
||||
| `storage:link` Artisan command is executed. The array keys should be
|
||||
| the locations of the links and the values should be their targets.
|
||||
|
|
||||
*/
|
||||
|
||||
'links' => [
|
||||
public_path('storage') => storage_path('app/public'),
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Hash Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default hash driver that will be used to hash
|
||||
| passwords for your application. By default, the bcrypt algorithm is
|
||||
| used; however, you remain free to modify this option if you wish.
|
||||
|
|
||||
| Supported: "bcrypt", "argon", "argon2id"
|
||||
|
|
||||
*/
|
||||
|
||||
'driver' => 'bcrypt',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Bcrypt Options
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the configuration options that should be used when
|
||||
| passwords are hashed using the Bcrypt algorithm. This will allow you
|
||||
| to control the amount of time it takes to hash the given password.
|
||||
|
|
||||
*/
|
||||
|
||||
'bcrypt' => [
|
||||
'rounds' => env('BCRYPT_ROUNDS', 12),
|
||||
'verify' => true,
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Argon Options
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the configuration options that should be used when
|
||||
| passwords are hashed using the Argon algorithm. These will allow you
|
||||
| to control the amount of time it takes to hash the given password.
|
||||
|
|
||||
*/
|
||||
|
||||
'argon' => [
|
||||
'memory' => 65536,
|
||||
'threads' => 1,
|
||||
'time' => 4,
|
||||
'verify' => true,
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
<?php
|
||||
|
||||
use Monolog\Handler\NullHandler;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
use Monolog\Handler\SyslogUdpHandler;
|
||||
use Monolog\Processor\PsrLogMessageProcessor;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Log Channel
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option defines the default log channel that gets used when writing
|
||||
| messages to the logs. The name specified in this option should match
|
||||
| one of the channels defined in the "channels" configuration array.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('LOG_CHANNEL', 'stack'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Deprecations Log Channel
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the log channel that should be used to log warnings
|
||||
| regarding deprecated PHP and library features. This allows you to get
|
||||
| your application ready for upcoming major versions of dependencies.
|
||||
|
|
||||
*/
|
||||
|
||||
'deprecations' => [
|
||||
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
|
||||
'trace' => false,
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Log Channels
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the log channels for your application. Out of
|
||||
| the box, Laravel uses the Monolog PHP logging library. This gives
|
||||
| you a variety of powerful log handlers / formatters to utilize.
|
||||
|
|
||||
| Available Drivers: "single", "daily", "slack", "syslog",
|
||||
| "errorlog", "monolog",
|
||||
| "custom", "stack"
|
||||
|
|
||||
*/
|
||||
|
||||
'channels' => [
|
||||
'stack' => [
|
||||
'driver' => 'stack',
|
||||
'channels' => ['single'],
|
||||
'ignore_exceptions' => false,
|
||||
],
|
||||
|
||||
'single' => [
|
||||
'driver' => 'single',
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'daily' => [
|
||||
'driver' => 'daily',
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'days' => 14,
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'slack' => [
|
||||
'driver' => 'slack',
|
||||
'url' => env('LOG_SLACK_WEBHOOK_URL'),
|
||||
'username' => 'Laravel Log',
|
||||
'emoji' => ':boom:',
|
||||
'level' => env('LOG_LEVEL', 'critical'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'papertrail' => [
|
||||
'driver' => 'monolog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
|
||||
'handler_with' => [
|
||||
'host' => env('PAPERTRAIL_URL'),
|
||||
'port' => env('PAPERTRAIL_PORT'),
|
||||
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
|
||||
],
|
||||
'processors' => [PsrLogMessageProcessor::class],
|
||||
],
|
||||
|
||||
'stderr' => [
|
||||
'driver' => 'monolog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'handler' => StreamHandler::class,
|
||||
'formatter' => env('LOG_STDERR_FORMATTER'),
|
||||
'with' => [
|
||||
'stream' => 'php://stderr',
|
||||
],
|
||||
'processors' => [PsrLogMessageProcessor::class],
|
||||
],
|
||||
|
||||
'syslog' => [
|
||||
'driver' => 'syslog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'facility' => LOG_USER,
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'errorlog' => [
|
||||
'driver' => 'errorlog',
|
||||
'level' => env('LOG_LEVEL', 'debug'),
|
||||
'replace_placeholders' => true,
|
||||
],
|
||||
|
||||
'null' => [
|
||||
'driver' => 'monolog',
|
||||
'handler' => NullHandler::class,
|
||||
],
|
||||
|
||||
'emergency' => [
|
||||
'path' => storage_path('logs/laravel.log'),
|
||||
],
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,134 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Mailer
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default mailer that is used to send any email
|
||||
| messages sent by your application. Alternative mailers may be setup
|
||||
| and used as needed; however, this mailer will be used by default.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('MAIL_MAILER', 'smtp'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Mailer Configurations
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure all of the mailers used by your application plus
|
||||
| their respective settings. Several examples have been configured for
|
||||
| you and you are free to add your own as your application requires.
|
||||
|
|
||||
| Laravel supports a variety of mail "transport" drivers to be used while
|
||||
| sending an e-mail. You will specify which one you are using for your
|
||||
| mailers below. You are free to add additional mailers as required.
|
||||
|
|
||||
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
|
||||
| "postmark", "log", "array", "failover", "roundrobin"
|
||||
|
|
||||
*/
|
||||
|
||||
'mailers' => [
|
||||
'smtp' => [
|
||||
'transport' => 'smtp',
|
||||
'url' => env('MAIL_URL'),
|
||||
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
|
||||
'port' => env('MAIL_PORT', 587),
|
||||
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
|
||||
'username' => env('MAIL_USERNAME'),
|
||||
'password' => env('MAIL_PASSWORD'),
|
||||
'timeout' => null,
|
||||
'local_domain' => env('MAIL_EHLO_DOMAIN'),
|
||||
],
|
||||
|
||||
'ses' => [
|
||||
'transport' => 'ses',
|
||||
],
|
||||
|
||||
'postmark' => [
|
||||
'transport' => 'postmark',
|
||||
// 'message_stream_id' => null,
|
||||
// 'client' => [
|
||||
// 'timeout' => 5,
|
||||
// ],
|
||||
],
|
||||
|
||||
'mailgun' => [
|
||||
'transport' => 'mailgun',
|
||||
// 'client' => [
|
||||
// 'timeout' => 5,
|
||||
// ],
|
||||
],
|
||||
|
||||
'sendmail' => [
|
||||
'transport' => 'sendmail',
|
||||
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
|
||||
],
|
||||
|
||||
'log' => [
|
||||
'transport' => 'log',
|
||||
'channel' => env('MAIL_LOG_CHANNEL'),
|
||||
],
|
||||
|
||||
'array' => [
|
||||
'transport' => 'array',
|
||||
],
|
||||
|
||||
'failover' => [
|
||||
'transport' => 'failover',
|
||||
'mailers' => [
|
||||
'smtp',
|
||||
'log',
|
||||
],
|
||||
],
|
||||
|
||||
'roundrobin' => [
|
||||
'transport' => 'roundrobin',
|
||||
'mailers' => [
|
||||
'ses',
|
||||
'postmark',
|
||||
],
|
||||
],
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Global "From" Address
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You may wish for all e-mails sent by your application to be sent from
|
||||
| the same address. Here, you may specify a name and address that is
|
||||
| used globally for all e-mails that are sent by your application.
|
||||
|
|
||||
*/
|
||||
|
||||
'from' => [
|
||||
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
|
||||
'name' => env('MAIL_FROM_NAME', 'Example'),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Markdown Mail Settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| If you are using Markdown based email rendering, you may configure your
|
||||
| theme and component paths here, allowing you to customize the design
|
||||
| of the emails. Or, you may simply stick with the Laravel defaults!
|
||||
|
|
||||
*/
|
||||
|
||||
'markdown' => [
|
||||
'theme' => 'default',
|
||||
|
||||
'paths' => [
|
||||
resource_path('views/vendor/mail'),
|
||||
],
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,109 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Queue Connection Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Laravel's queue API supports an assortment of back-ends via a single
|
||||
| API, giving you convenient access to each back-end using the same
|
||||
| syntax for every one. Here you may define a default connection.
|
||||
|
|
||||
*/
|
||||
|
||||
'default' => env('QUEUE_CONNECTION', 'sync'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Queue Connections
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may configure the connection information for each server that
|
||||
| is used by your application. A default configuration has been added
|
||||
| for each back-end shipped with Laravel. You are free to add more.
|
||||
|
|
||||
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
||||
|
|
||||
*/
|
||||
|
||||
'connections' => [
|
||||
|
||||
'sync' => [
|
||||
'driver' => 'sync',
|
||||
],
|
||||
|
||||
'database' => [
|
||||
'driver' => 'database',
|
||||
'table' => 'jobs',
|
||||
'queue' => 'default',
|
||||
'retry_after' => 90,
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'beanstalkd' => [
|
||||
'driver' => 'beanstalkd',
|
||||
'host' => 'localhost',
|
||||
'queue' => 'default',
|
||||
'retry_after' => 90,
|
||||
'block_for' => 0,
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'sqs' => [
|
||||
'driver' => 'sqs',
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
|
||||
'queue' => env('SQS_QUEUE', 'default'),
|
||||
'suffix' => env('SQS_SUFFIX'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
'redis' => [
|
||||
'driver' => 'redis',
|
||||
'connection' => 'default',
|
||||
'queue' => env('REDIS_QUEUE', 'default'),
|
||||
'retry_after' => 90,
|
||||
'block_for' => null,
|
||||
'after_commit' => false,
|
||||
],
|
||||
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Job Batching
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The following options configure the database and table that store job
|
||||
| batching information. These options can be updated to any database
|
||||
| connection and table which has been defined by your application.
|
||||
|
|
||||
*/
|
||||
|
||||
'batching' => [
|
||||
'database' => env('DB_CONNECTION', 'mysql'),
|
||||
'table' => 'job_batches',
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Failed Queue Jobs
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| These options configure the behavior of failed queue job logging so you
|
||||
| can control which database and table are used to store the jobs that
|
||||
| have failed. You may change them to any database / table you wish.
|
||||
|
|
||||
*/
|
||||
|
||||
'failed' => [
|
||||
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
|
||||
'database' => env('DB_CONNECTION', 'mysql'),
|
||||
'table' => 'failed_jobs',
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
<?php
|
||||
|
||||
use Laravel\Sanctum\Sanctum;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Stateful Domains
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Requests from the following domains / hosts will receive stateful API
|
||||
| authentication cookies. Typically, these should include your local
|
||||
| and production domains which access your API via a frontend SPA.
|
||||
|
|
||||
*/
|
||||
|
||||
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
|
||||
'%s%s',
|
||||
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
|
||||
Sanctum::currentApplicationUrlWithPort()
|
||||
))),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Sanctum Guards
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This array contains the authentication guards that will be checked when
|
||||
| Sanctum is trying to authenticate a request. If none of these guards
|
||||
| are able to authenticate the request, Sanctum will use the bearer
|
||||
| token that's present on an incoming request for authentication.
|
||||
|
|
||||
*/
|
||||
|
||||
'guard' => ['web'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Expiration Minutes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This value controls the number of minutes until an issued token will be
|
||||
| considered expired. This will override any values set in the token's
|
||||
| "expires_at" attribute, but first-party sessions are not affected.
|
||||
|
|
||||
*/
|
||||
|
||||
'expiration' => null,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Token Prefix
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Sanctum can prefix new tokens in order to take advantage of numerous
|
||||
| security scanning initiatives maintained by open source platforms
|
||||
| that notify developers if they commit tokens into repositories.
|
||||
|
|
||||
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
||||
|
|
||||
*/
|
||||
|
||||
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Sanctum Middleware
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When authenticating your first-party SPA with Sanctum you may need to
|
||||
| customize some of the middleware Sanctum uses while processing the
|
||||
| request. You may change the middleware listed below as required.
|
||||
|
|
||||
*/
|
||||
|
||||
'middleware' => [
|
||||
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
|
||||
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
|
||||
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Third Party Services
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This file is for storing the credentials for third party services such
|
||||
| as Mailgun, Postmark, AWS and more. This file provides the de facto
|
||||
| location for this type of information, allowing packages to have
|
||||
| a conventional file to locate the various service credentials.
|
||||
|
|
||||
*/
|
||||
|
||||
'mailgun' => [
|
||||
'domain' => env('MAILGUN_DOMAIN'),
|
||||
'secret' => env('MAILGUN_SECRET'),
|
||||
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
|
||||
'scheme' => 'https',
|
||||
],
|
||||
|
||||
'postmark' => [
|
||||
'token' => env('POSTMARK_TOKEN'),
|
||||
],
|
||||
|
||||
'ses' => [
|
||||
'key' => env('AWS_ACCESS_KEY_ID'),
|
||||
'secret' => env('AWS_SECRET_ACCESS_KEY'),
|
||||
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
|
||||
],
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,214 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default Session Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option controls the default session "driver" that will be used on
|
||||
| requests. By default, we will use the lightweight native driver but
|
||||
| you may specify any of the other wonderful drivers provided here.
|
||||
|
|
||||
| Supported: "file", "cookie", "database", "apc",
|
||||
| "memcached", "redis", "dynamodb", "array"
|
||||
|
|
||||
*/
|
||||
|
||||
'driver' => env('SESSION_DRIVER', 'file'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Lifetime
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may specify the number of minutes that you wish the session
|
||||
| to be allowed to remain idle before it expires. If you want them
|
||||
| to immediately expire on the browser closing, set that option.
|
||||
|
|
||||
*/
|
||||
|
||||
'lifetime' => env('SESSION_LIFETIME', 120),
|
||||
|
||||
'expire_on_close' => false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Encryption
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option allows you to easily specify that all of your session data
|
||||
| should be encrypted before it is stored. All encryption will be run
|
||||
| automatically by Laravel and you can use the Session like normal.
|
||||
|
|
||||
*/
|
||||
|
||||
'encrypt' => false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session File Location
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using the native session driver, we need a location where session
|
||||
| files may be stored. A default has been set for you but a different
|
||||
| location may be specified. This is only needed for file sessions.
|
||||
|
|
||||
*/
|
||||
|
||||
'files' => storage_path('framework/sessions'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Database Connection
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using the "database" or "redis" session drivers, you may specify a
|
||||
| connection that should be used to manage these sessions. This should
|
||||
| correspond to a connection in your database configuration options.
|
||||
|
|
||||
*/
|
||||
|
||||
'connection' => env('SESSION_CONNECTION'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Database Table
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When using the "database" session driver, you may specify the table we
|
||||
| should use to manage the sessions. Of course, a sensible default is
|
||||
| provided for you; however, you are free to change this as needed.
|
||||
|
|
||||
*/
|
||||
|
||||
'table' => 'sessions',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cache Store
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| While using one of the framework's cache driven session backends you may
|
||||
| list a cache store that should be used for these sessions. This value
|
||||
| must match with one of the application's configured cache "stores".
|
||||
|
|
||||
| Affects: "apc", "dynamodb", "memcached", "redis"
|
||||
|
|
||||
*/
|
||||
|
||||
'store' => env('SESSION_STORE'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Sweeping Lottery
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Some session drivers must manually sweep their storage location to get
|
||||
| rid of old sessions from storage. Here are the chances that it will
|
||||
| happen on a given request. By default, the odds are 2 out of 100.
|
||||
|
|
||||
*/
|
||||
|
||||
'lottery' => [2, 100],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may change the name of the cookie used to identify a session
|
||||
| instance by ID. The name specified here will get used every time a
|
||||
| new session cookie is created by the framework for every driver.
|
||||
|
|
||||
*/
|
||||
|
||||
'cookie' => env(
|
||||
'SESSION_COOKIE',
|
||||
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
|
||||
),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Path
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The session cookie path determines the path for which the cookie will
|
||||
| be regarded as available. Typically, this will be the root path of
|
||||
| your application but you are free to change this when necessary.
|
||||
|
|
||||
*/
|
||||
|
||||
'path' => '/',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session Cookie Domain
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Here you may change the domain of the cookie used to identify a session
|
||||
| in your application. This will determine which domains the cookie is
|
||||
| available to in your application. A sensible default has been set.
|
||||
|
|
||||
*/
|
||||
|
||||
'domain' => env('SESSION_DOMAIN'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| HTTPS Only Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| By setting this option to true, session cookies will only be sent back
|
||||
| to the server if the browser has a HTTPS connection. This will keep
|
||||
| the cookie from being sent to you when it can't be done securely.
|
||||
|
|
||||
*/
|
||||
|
||||
'secure' => env('SESSION_SECURE_COOKIE'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| HTTP Access Only
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to true will prevent JavaScript from accessing the
|
||||
| value of the cookie and the cookie will only be accessible through
|
||||
| the HTTP protocol. You are free to modify this option if needed.
|
||||
|
|
||||
*/
|
||||
|
||||
'http_only' => true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Same-Site Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option determines how your cookies behave when cross-site requests
|
||||
| take place, and can be used to mitigate CSRF attacks. By default, we
|
||||
| will set this value to "lax" since this is a secure default value.
|
||||
|
|
||||
| Supported: "lax", "strict", "none", null
|
||||
|
|
||||
*/
|
||||
|
||||
'same_site' => 'lax',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Partitioned Cookies
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to true will tie the cookie to the top-level site for
|
||||
| a cross-site context. Partitioned cookies are accepted by the browser
|
||||
| when flagged "secure" and the Same-Site attribute is set to "none".
|
||||
|
|
||||
*/
|
||||
|
||||
'partitioned' => false,
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
<?php
|
||||
|
||||
return [
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| View Storage Paths
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Most templating systems load templates from disk. Here you may specify
|
||||
| an array of paths that should be checked for your views. Of course
|
||||
| the usual Laravel view path has already been registered for you.
|
||||
|
|
||||
*/
|
||||
|
||||
'paths' => [
|
||||
resource_path('views'),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Compiled View Path
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This option determines where all the compiled Blade templates will be
|
||||
| stored for your application. Typically, this is within the storage
|
||||
| directory. However, as usual, you are free to change this value.
|
||||
|
|
||||
*/
|
||||
|
||||
'compiled' => env(
|
||||
'VIEW_COMPILED_PATH',
|
||||
realpath(storage_path('framework/views'))
|
||||
),
|
||||
|
||||
];
|
||||
|
|
@ -0,0 +1 @@
|
|||
*.sqlite*
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Factories;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
|
||||
*/
|
||||
class UserFactory extends Factory
|
||||
{
|
||||
/**
|
||||
* The current password being used by the factory.
|
||||
*/
|
||||
protected static ?string $password;
|
||||
|
||||
/**
|
||||
* Define the model's default state.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public function definition(): array
|
||||
{
|
||||
return [
|
||||
'name' => fake()->name(),
|
||||
'email' => fake()->unique()->safeEmail(),
|
||||
'email_verified_at' => now(),
|
||||
'password' => static::$password ??= Hash::make('password'),
|
||||
'remember_token' => Str::random(10),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicate that the model's email address should be unverified.
|
||||
*/
|
||||
public function unverified(): static
|
||||
{
|
||||
return $this->state(fn (array $attributes) => [
|
||||
'email_verified_at' => null,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('password_reset_tokens', function (Blueprint $table) {
|
||||
$table->string('email')->primary();
|
||||
$table->string('token');
|
||||
$table->timestamp('created_at')->nullable();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('password_reset_tokens');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('failed_jobs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('uuid')->unique();
|
||||
$table->text('connection');
|
||||
$table->text('queue');
|
||||
$table->longText('payload');
|
||||
$table->longText('exception');
|
||||
$table->timestamp('failed_at')->useCurrent();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('failed_jobs');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('personal_access_tokens', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->morphs('tokenable');
|
||||
$table->string('name');
|
||||
$table->string('token', 64)->unique();
|
||||
$table->text('abilities')->nullable();
|
||||
$table->timestamp('last_used_at')->nullable();
|
||||
$table->timestamp('expires_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('personal_access_tokens');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_create_users_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->timestamp('email_verified_at')->nullable();
|
||||
$table->string('password');
|
||||
$table->enum('role', ['siswa', 'orang_tua'])->default('siswa');
|
||||
$table->string('ortu_code')->nullable();
|
||||
$table->foreignId('parent_id')->nullable()->constrained('users');
|
||||
$table->rememberToken();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('users');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_create_activity_logs_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('activity_logs', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->onDelete('cascade');
|
||||
$table->time('start_time')->nullable();
|
||||
$table->time('end_time')->nullable();
|
||||
$table->integer('duration_minutes')->nullable();
|
||||
$table->enum('mood', ['Bagus', 'Lumayan', 'Biasa Saja', 'Cukup Jenuh', 'Jenuh']);
|
||||
$table->enum('sleep_duration', ['<4', '4-7', '>7']);
|
||||
$table->date('activity_date');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['user_id', 'activity_date']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('activity_logs');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_create_recommendations_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('recommendations', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('user_id')->constrained()->onDelete('cascade');
|
||||
$table->foreignId('activity_log_id')->constrained()->onDelete('cascade');
|
||||
$table->enum('category', ['Ringan', 'Sedang', 'Intensif']);
|
||||
$table->integer('recommended_minutes');
|
||||
$table->text('notes')->nullable();
|
||||
$table->json('model_input')->nullable();
|
||||
$table->date('recommendation_date');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('recommendations');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_create_parent_connections_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('parent_connections', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('parent_id')->constrained('users')->onDelete('cascade');
|
||||
$table->foreignId('student_id')->constrained('users')->onDelete('cascade');
|
||||
$table->string('connection_code');
|
||||
$table->enum('status', ['pending', 'connected'])->default('pending');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['parent_id', 'student_id']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('parent_connections');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_fix_parent_id_nullable_in_users_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
// Untuk MySQL
|
||||
DB::statement('ALTER TABLE `users` MODIFY `parent_id` BIGINT UNSIGNED NULL');
|
||||
|
||||
// Atau jika menggunakan Schema Builder
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->foreignId('parent_id')->nullable()->change();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->foreignId('parent_id')->nullable(false)->change();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_add_based_on_to_recommendations_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('recommendations', function (Blueprint $table) {
|
||||
$table->string('based_on')->nullable()->after('category');
|
||||
$table->float('confidence')->nullable()->after('based_on');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('recommendations', function (Blueprint $table) {
|
||||
$table->dropColumn(['based_on', 'confidence']);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
// database/migrations/[timestamp]_add_sleep_hours_to_activity_logs_table.php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('activity_logs', function (Blueprint $table) {
|
||||
$table->decimal('sleep_hours', 3, 1)->nullable()->after('sleep_duration');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('activity_logs', function (Blueprint $table) {
|
||||
$table->dropColumn('sleep_hours');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
// Tambahkan kolom avatar (nullable, default null)
|
||||
$table->string('avatar')->nullable()->after('email');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->dropColumn('avatar');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('password_resets', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('email')->index();
|
||||
$table->string('token'); // Menyimpan kode 6 digit
|
||||
$table->timestamp('expires_at');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('password_resets');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('password_otps', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('email')->index();
|
||||
$table->string('otp', 6);
|
||||
$table->timestamp('expires_at');
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('password_otps');
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
// Tambahkan kolom parent_code (nullable, untuk menyimpan kode koneksi siswa)
|
||||
$table->string('parent_code', 8)->nullable()->unique()->after('password');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->dropColumn('parent_code');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
<?php
|
||||
|
||||
namespace Database\Seeders;
|
||||
|
||||
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
|
||||
use Illuminate\Database\Seeder;
|
||||
|
||||
class DatabaseSeeder extends Seeder
|
||||
{
|
||||
/**
|
||||
* Seed the application's database.
|
||||
*/
|
||||
public function run(): void
|
||||
{
|
||||
// \App\Models\User::factory(10)->create();
|
||||
|
||||
// \App\Models\User::factory()->create([
|
||||
// 'name' => 'Test User',
|
||||
// 'email' => 'test@example.com',
|
||||
// ]);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,386 @@
|
|||
# flask-api/app.py
|
||||
from flask import Flask, request, jsonify
|
||||
from flask_cors import CORS
|
||||
import joblib
|
||||
import numpy as np
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app) # Mengizinkan akses dari Laravel
|
||||
|
||||
# ============================================
|
||||
# KONFIGURASI PATH MODEL
|
||||
# ============================================
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
MODELS_DIR = os.path.join(BASE_DIR, 'models')
|
||||
|
||||
# ============================================
|
||||
# LOAD MODEL DAN ENCODERS
|
||||
# ============================================
|
||||
print("=" * 50)
|
||||
print("🚀 Memulai Flask API Server...")
|
||||
print("=" * 50)
|
||||
|
||||
try:
|
||||
# Load model Decision Tree
|
||||
model = joblib.load(os.path.join(MODELS_DIR, 'model_harian.pkl'))
|
||||
print("✅ Model Decision Tree berhasil diload")
|
||||
|
||||
# Load encoder untuk mood (input)
|
||||
encoder_mood = joblib.load(os.path.join(MODELS_DIR, 'encoder_mood.pkl'))
|
||||
print(f"✅ Encoder mood berhasil diload (classes: {list(encoder_mood.classes_)})")
|
||||
|
||||
# Load encoder untuk label (output)
|
||||
encoder_label = joblib.load(os.path.join(MODELS_DIR, 'encoder_label.pkl'))
|
||||
print(f"✅ Encoder label berhasil diload (classes: {list(encoder_label.classes_)})")
|
||||
|
||||
model_loaded = True
|
||||
|
||||
except FileNotFoundError as e:
|
||||
print(f"❌ ERROR: File model tidak ditemukan - {e}")
|
||||
print("Pastikan folder 'models' berisi:")
|
||||
print(" - model_harian.pkl")
|
||||
print(" - encoder_mood.pkl")
|
||||
print(" - encoder_label.pkl")
|
||||
model_loaded = False
|
||||
model = None
|
||||
encoder_mood = None
|
||||
encoder_label = None
|
||||
|
||||
print("=" * 50)
|
||||
|
||||
# ============================================
|
||||
# ENDPOINT HEALTH CHECK
|
||||
# ============================================
|
||||
@app.route('/health', methods=['GET'])
|
||||
def health():
|
||||
"""Cek status server dan model"""
|
||||
return jsonify({
|
||||
'status': 'healthy',
|
||||
'model_loaded': model_loaded,
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'mood_classes': list(encoder_mood.classes_) if encoder_mood else [],
|
||||
'label_classes': list(encoder_label.classes_) if encoder_label else []
|
||||
})
|
||||
|
||||
# ============================================
|
||||
# ENDPOINT INFO MODEL
|
||||
# ============================================
|
||||
@app.route('/info', methods=['GET'])
|
||||
def info():
|
||||
"""Informasi detail tentang model"""
|
||||
if not model_loaded:
|
||||
return jsonify({'error': 'Model tidak tersedia'}), 503
|
||||
|
||||
return jsonify({
|
||||
'model_type': type(model).__name__,
|
||||
'model_parameters': model.get_params() if hasattr(model, 'get_params') else {},
|
||||
'features': ['mood (encoded)', 'durasi_belajar (menit)', 'durasi_tidur (jam)'],
|
||||
'mood_classes': list(encoder_mood.classes_),
|
||||
'label_classes': list(encoder_label.classes_),
|
||||
'description': 'Decision Tree Classifier untuk rekomendasi durasi belajar'
|
||||
})
|
||||
|
||||
# ============================================
|
||||
# ENDPOINT PREDIKSI HARIAN (HARI 1-7)
|
||||
# ============================================
|
||||
@app.route('/predict', methods=['POST'])
|
||||
def predict_daily():
|
||||
"""
|
||||
Prediksi berdasarkan input HARIAN
|
||||
Digunakan untuk 7 hari pertama
|
||||
"""
|
||||
if not model_loaded:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Model tidak tersedia'
|
||||
}), 503
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
|
||||
# ========================================
|
||||
# VALIDASI INPUT
|
||||
# ========================================
|
||||
required_fields = ['mood', 'durasi_belajar', 'durasi_tidur']
|
||||
for field in required_fields:
|
||||
if field not in data:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Field "{field}" diperlukan'
|
||||
}), 400
|
||||
|
||||
mood = data['mood']
|
||||
durasi_belajar = int(data['durasi_belajar'])
|
||||
durasi_tidur = int(data['durasi_tidur'])
|
||||
|
||||
# ========================================
|
||||
# ENCODE MOOD
|
||||
# ========================================
|
||||
try:
|
||||
mood_encoded = encoder_mood.transform([mood])[0]
|
||||
except ValueError as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Mood "{mood}" tidak valid. Mood yang tersedia: {list(encoder_mood.classes_)}'
|
||||
}), 400
|
||||
|
||||
# ========================================
|
||||
# PREDIKSI DENGAN DECISION TREE
|
||||
# ========================================
|
||||
features = np.array([[
|
||||
mood_encoded,
|
||||
durasi_belajar,
|
||||
durasi_tidur
|
||||
]])
|
||||
|
||||
prediction = model.predict(features)
|
||||
label = encoder_label.inverse_transform(prediction)[0]
|
||||
|
||||
# Hitung confidence (probabilitas)
|
||||
proba = model.predict_proba(features)[0]
|
||||
confidence = float(max(proba))
|
||||
|
||||
# Probabilitas per kelas
|
||||
proba_dict = {}
|
||||
for i, prob in enumerate(proba):
|
||||
class_name = encoder_label.inverse_transform([i])[0]
|
||||
proba_dict[class_name] = float(prob)
|
||||
|
||||
# ========================================
|
||||
# RESPONSE
|
||||
# ========================================
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'prediction': label,
|
||||
'confidence': confidence,
|
||||
'probabilities': proba_dict,
|
||||
'input_received': {
|
||||
'mood': mood,
|
||||
'durasi_belajar': durasi_belajar,
|
||||
'durasi_tidur': durasi_tidur
|
||||
},
|
||||
'model_used': 'Decision Tree (daily)'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}), 500
|
||||
|
||||
# ============================================
|
||||
# ENDPOINT PREDIKSI POLA (HARI KE-8 dst)
|
||||
# ============================================
|
||||
@app.route('/predict/pattern', methods=['POST'])
|
||||
def predict_pattern():
|
||||
"""
|
||||
Prediksi berdasarkan POLA 7 HARI TERAKHIR
|
||||
Tetap menggunakan Decision Tree!
|
||||
Digunakan untuk hari ke-8 dan seterusnya
|
||||
"""
|
||||
if not model_loaded:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Model tidak tersedia'
|
||||
}), 503
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
|
||||
# ========================================
|
||||
# VALIDASI INPUT
|
||||
# ========================================
|
||||
required_fields = ['avg_duration', 'most_frequent_mood', 'avg_sleep']
|
||||
for field in required_fields:
|
||||
if field not in data:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Field "{field}" diperlukan'
|
||||
}), 400
|
||||
|
||||
avg_duration = float(data['avg_duration'])
|
||||
most_frequent_mood = data['most_frequent_mood']
|
||||
avg_sleep = float(data['avg_sleep'])
|
||||
trend = data.get('trend', 'stabil')
|
||||
consistency = data.get('consistency', 0)
|
||||
|
||||
# ========================================
|
||||
# ENCODE MOOD
|
||||
# ========================================
|
||||
try:
|
||||
mood_encoded = encoder_mood.transform([most_frequent_mood])[0]
|
||||
except ValueError as e:
|
||||
# Fallback: coba cari mood terdekat
|
||||
available_moods = list(encoder_mood.classes_)
|
||||
print(f"⚠️ Mood '{most_frequent_mood}' tidak dikenal. Menggunakan 'Biasa Saja' sebagai fallback.")
|
||||
mood_encoded = encoder_mood.transform(['Biasa Saja'])[0]
|
||||
|
||||
# ========================================
|
||||
# PREDIKSI DENGAN DECISION TREE
|
||||
# Fitur yang digunakan: [mood_encoded, avg_duration, avg_sleep]
|
||||
# ========================================
|
||||
features = np.array([[
|
||||
mood_encoded,
|
||||
int(avg_duration),
|
||||
int(avg_sleep)
|
||||
]])
|
||||
|
||||
prediction = model.predict(features)
|
||||
label = encoder_label.inverse_transform(prediction)[0]
|
||||
|
||||
# Hitung confidence (probabilitas)
|
||||
proba = model.predict_proba(features)[0]
|
||||
confidence = float(max(proba))
|
||||
|
||||
# ========================================
|
||||
# ANALISIS TAMBAHAN (untuk frontend)
|
||||
# ========================================
|
||||
|
||||
# Rekomendasi berdasarkan trend
|
||||
trend_recommendation = ""
|
||||
if trend == 'meningkat':
|
||||
trend_recommendation = "Bagus! Durasi belajarmu terus meningkat. Pertahankan momentum ini!"
|
||||
elif trend == 'menurun':
|
||||
trend_recommendation = "Durasi belajarmu menurun. Coba buat jadwal belajar yang lebih konsisten."
|
||||
else:
|
||||
trend_recommendation = "Konsistensimu stabil. Tingkatkan sedikit demi sedikit untuk hasil lebih baik."
|
||||
|
||||
# Rekomendasi berdasarkan konsistensi
|
||||
consistency_recommendation = ""
|
||||
if consistency >= 6:
|
||||
consistency_recommendation = "Luar biasa! Kamu sangat konsisten. Terus pertahankan!"
|
||||
elif consistency >= 4:
|
||||
consistency_recommendation = "Cukup baik, tapi masih ada hari yang terlewat. Ayo lebih konsisten lagi!"
|
||||
else:
|
||||
consistency_recommendation = "Masih banyak hari yang terlewat. Yuk, mulai rutin mencatat aktivitas!"
|
||||
|
||||
# Rekomendasi berdasarkan mood
|
||||
mood_recommendation = ""
|
||||
if most_frequent_mood in ['Bagus', 'Lumayan']:
|
||||
mood_recommendation = "Mood positifmu mendukung belajar efektif!"
|
||||
else:
|
||||
mood_recommendation = "Coba cari aktivitas yang menyenangkan sebelum belajar agar mood lebih baik."
|
||||
|
||||
# Rekomendasi berdasarkan tidur
|
||||
sleep_recommendation = ""
|
||||
if avg_sleep >= 7:
|
||||
sleep_recommendation = "Tidur cukup! Ini bagus untuk konsentrasi."
|
||||
elif avg_sleep >= 5:
|
||||
sleep_recommendation = "Tidur kurang ideal. Coba tidur lebih awal."
|
||||
else:
|
||||
sleep_recommendation = "Kurang tidur akan mempengaruhi konsentrasi belajar. Prioritaskan istirahat!"
|
||||
|
||||
# ========================================
|
||||
# RESPONSE
|
||||
# ========================================
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'prediction': label,
|
||||
'confidence': confidence,
|
||||
'pattern_analysis': {
|
||||
'avg_duration': round(avg_duration, 1),
|
||||
'most_frequent_mood': most_frequent_mood,
|
||||
'avg_sleep': round(avg_sleep, 1),
|
||||
'trend': trend,
|
||||
'consistency': f"{consistency}/7 hari",
|
||||
'trend_recommendation': trend_recommendation,
|
||||
'consistency_recommendation': consistency_recommendation,
|
||||
'mood_recommendation': mood_recommendation,
|
||||
'sleep_recommendation': sleep_recommendation
|
||||
},
|
||||
'input_received': {
|
||||
'avg_duration': avg_duration,
|
||||
'most_frequent_mood': most_frequent_mood,
|
||||
'avg_sleep': avg_sleep,
|
||||
'trend': trend,
|
||||
'consistency': consistency
|
||||
},
|
||||
'model_used': 'Decision Tree (pattern-based)',
|
||||
'note': 'Prediksi berdasarkan pola 7 hari terakhir menggunakan Decision Tree'
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}), 500
|
||||
|
||||
# ============================================
|
||||
# ENDPOINT BATCH PREDICTION (Opsional)
|
||||
# ============================================
|
||||
@app.route('/predict/batch', methods=['POST'])
|
||||
def predict_batch():
|
||||
"""
|
||||
Prediksi untuk multiple data (batch)
|
||||
"""
|
||||
if not model_loaded:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Model tidak tersedia'
|
||||
}), 503
|
||||
|
||||
try:
|
||||
data = request.json
|
||||
samples = data.get('samples', [])
|
||||
|
||||
if not samples:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Field "samples" diperlukan'
|
||||
}), 400
|
||||
|
||||
results = []
|
||||
for sample in samples:
|
||||
try:
|
||||
mood_encoded = encoder_mood.transform([sample['mood']])[0]
|
||||
features = np.array([[
|
||||
mood_encoded,
|
||||
int(sample['durasi_belajar']),
|
||||
int(sample['durasi_tidur'])
|
||||
]])
|
||||
|
||||
prediction = model.predict(features)
|
||||
label = encoder_label.inverse_transform(prediction)[0]
|
||||
|
||||
results.append({
|
||||
'input': sample,
|
||||
'prediction': label
|
||||
})
|
||||
except Exception as e:
|
||||
results.append({
|
||||
'input': sample,
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'results': results
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}), 500
|
||||
|
||||
# ============================================
|
||||
# RUN SERVER
|
||||
# ============================================
|
||||
if __name__ == '__main__':
|
||||
print("\n" + "=" * 50)
|
||||
print("🚀 Menjalankan Flask API Server...")
|
||||
print("=" * 50)
|
||||
print(f"📍 Endpoint yang tersedia:")
|
||||
print(f" GET /health - Cek status server")
|
||||
print(f" GET /info - Informasi model")
|
||||
print(f" POST /predict - Prediksi harian (hari 1-7)")
|
||||
print(f" POST /predict/pattern - Prediksi pola (hari 8+)")
|
||||
print(f" POST /predict/batch - Prediksi batch")
|
||||
print("=" * 50)
|
||||
print("\n🔥 Server berjalan di http://127.0.0.1:5000")
|
||||
print(" Tekan Ctrl+C untuk menghentikan server")
|
||||
print("=" * 50)
|
||||
|
||||
app.run(debug=True, host='0.0.0.0', port=5000)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/forms": "^0.5.2",
|
||||
"alpinejs": "^3.4.2",
|
||||
"autoprefixer": "^10.4.2",
|
||||
"axios": "^1.6.4",
|
||||
"laravel-vite-plugin": "^1.0.0",
|
||||
"postcss": "^8.4.31",
|
||||
"tailwindcss": "^3.1.0",
|
||||
"vite": "^5.0.0"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
|
||||
bootstrap="vendor/autoload.php"
|
||||
colors="true"
|
||||
>
|
||||
<testsuites>
|
||||
<testsuite name="Unit">
|
||||
<directory>tests/Unit</directory>
|
||||
</testsuite>
|
||||
<testsuite name="Feature">
|
||||
<directory>tests/Feature</directory>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
<source>
|
||||
<include>
|
||||
<directory>app</directory>
|
||||
</include>
|
||||
</source>
|
||||
<php>
|
||||
<env name="APP_ENV" value="testing"/>
|
||||
<env name="BCRYPT_ROUNDS" value="4"/>
|
||||
<env name="CACHE_DRIVER" value="array"/>
|
||||
<!-- <env name="DB_CONNECTION" value="sqlite"/> -->
|
||||
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
|
||||
<env name="MAIL_MAILER" value="array"/>
|
||||
<env name="PULSE_ENABLED" value="false"/>
|
||||
<env name="QUEUE_CONNECTION" value="sync"/>
|
||||
<env name="SESSION_DRIVER" value="array"/>
|
||||
<env name="TELESCOPE_ENABLED" value="false"/>
|
||||
</php>
|
||||
</phpunit>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue