Spaces:
Sleeping
Sleeping
change: move api to controller
Browse filesFiles changed (31)
- app/Http/Controllers/AdminController.php+453-2
- app/Http/Controllers/AuthController.php+165-18
- app/Http/Controllers/Controller.php+44-1
- app/Http/Controllers/DosenController.php+124-15
- app/Http/Controllers/EmbedController.php+192-47
- app/Http/Controllers/MahasiswaController.php+154-19
- app/Services/RagApiClient.phpDeleted-356
- resources/js/components/admin/admin-api-key-card.tsxAdded+89
- resources/js/components/admin/admin-form-parts.tsxAdded+53
- resources/js/components/admin/admin-llm-form.tsxAdded+176
- resources/js/components/admin/admin-overview-cards.tsxAdded+86
- resources/js/components/admin/admin-page.tsxAdded+56
- resources/js/components/admin/admin-rag-summary.tsxAdded+154
- resources/js/components/admin/admin-shell.tsx+55-8
- resources/js/components/admin/admin-user-management.tsxAdded+511
- resources/js/components/admin/admin-vector-retrieval-forms.tsxAdded+277
- resources/js/components/auth/register-role-form.tsx+80-14
- resources/js/lib/admin.tsAdded+73
- resources/js/pages/admin.tsx+1-27
- resources/js/pages/admin/dashboard.tsxAdded+34
- resources/js/pages/admin/llm-config.tsxAdded+19
- resources/js/pages/admin/rag-config.tsxAdded+19
- resources/js/pages/admin/vector-retrieval-config.tsxAdded+22
- resources/js/pages/auth/admin-login.tsx+2-5
- resources/js/pages/auth/login.tsx+2-5
- resources/js/pages/embed.tsx+15-4
- resources/js/types/admin.tsAdded+124
- routes/web.php+20
- sevima-raghub.json+660-68
- tests/Feature/AdminDashboardTest.phpAdded+292
- tests/Feature/AuthProxyTest.php+62
1 unmodified line2345678910111213141510161718192021222324252627282912303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694701 unmodified line
namespace App\Http\Controllers;
use App\Exceptions\RagApiException;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Validation\Rule;use Inertia\Inertia;use Inertia\Response;
class AdminController extends Controller{ private const AUTH_TOKEN_COOKIE = 'sevima_raghub_auth_token';
public function index(): Response public function index(Request $request): Response { $users = []; $token = $this->authToken($request); $userFilters = $this->userFilters($request); $configPayload = $this->resolveRagConfig($token); $backendMessage = $configPayload['backendMessage'];
try { $users = $this->listUsers($userFilters, $token)['founds'] ?? []; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }
return Inertia::render('admin'); return Inertia::render('admin/dashboard', [ 'backendMessage' => $backendMessage, 'generatedApiKey' => $request->session()->get('generatedApiKey'), 'ragConfig' => $configPayload['ragConfig'], 'userFilters' => $userFilters, 'users' => $users, ]); }
public function ragConfig(Request $request): Response { $configPayload = $this->resolveRagConfig($this->authToken($request));
return Inertia::render('admin/rag-config', $configPayload); }
public function llmConfig(Request $request): Response { $configPayload = $this->resolveRagConfig($this->authToken($request), ['llm']);
return Inertia::render('admin/llm-config', $configPayload); }
public function vectorRetrievalConfig(Request $request): Response { $configPayload = $this->resolveRagConfig($this->authToken($request), ['vector_db', 'retrieval']);
return Inertia::render('admin/vector-retrieval-config', $configPayload); }
public function settings(): Response { return Inertia::render('admin/pengaturan'); }
public function generateApiKey(Request $request): RedirectResponse { try { $apiKey = $this->generateApiKeyOnApi($this->authToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['apiKey' => $exception->getMessage()]); }
return to_route('admin.dashboard') ->with('generatedApiKey', $apiKey) ->with('toast', [ 'message' => 'API key berhasil dibuat.', 'type' => 'success', ]); }
public function updateLlmConfig(Request $request): RedirectResponse { $payload = $this->cleanPayload($request->validate([ 'api_key_env' => ['nullable', 'string'], 'base_url' => ['nullable', 'string'], 'max_tokens' => ['nullable', 'integer', 'min:1'], 'model' => ['nullable', 'string'], 'provider' => ['nullable', 'string'], 'reasoning_effort' => ['nullable', 'string'], 'request_timeout' => ['nullable', 'integer', 'min:1'], 'system_prompt' => ['nullable', 'string'], 'temperature' => ['nullable', 'numeric', 'min:0'], ]));
try { $this->updateLlmConfigOnApi($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['llm' => $exception->getMessage()]) ->withInput(); }
return $this->adminSuccess('Konfigurasi LLM berhasil diperbarui.', 'admin.llm-config'); }
public function updateVectorDbConfig(Request $request): RedirectResponse { $payload = $this->cleanPayload($request->validate([ 'chunk_overlap' => ['nullable', 'integer', 'min:0'], 'chunk_size' => ['nullable', 'integer', 'min:1'], 'embedding_model' => ['nullable', 'string'], 'persist_path' => ['nullable', 'string'], ]));
try { $this->updateVectorDbConfigOnApi($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['vectorDb' => $exception->getMessage()]) ->withInput(); }
return $this->adminSuccess('Konfigurasi Vector DB berhasil diperbarui.', 'admin.vector-retrieval-config'); }
public function updateRetrievalConfig(Request $request): RedirectResponse { $payload = $this->cleanPayload($request->validate([ 'bm25_weight' => ['nullable', 'numeric', 'min:0', 'max:1'], 'candidate_pool_size' => ['nullable', 'integer', 'min:1'], 'dense_weight' => ['nullable', 'numeric', 'min:0', 'max:1'], 'enable_reranker' => ['sometimes', 'boolean'], 'history_turns' => ['nullable', 'integer', 'min:0'], 'lexical_weight' => ['nullable', 'numeric', 'min:0', 'max:1'], 'max_context_chars' => ['nullable', 'integer', 'min:1'], 'neighbor_window' => ['nullable', 'integer', 'min:0'], 'reranker_model' => ['nullable', 'string'], 'similarity_threshold' => ['nullable', 'numeric', 'min:0'], 'top_k' => ['nullable', 'integer', 'min:1'], ]));
try { $this->updateRetrievalConfigOnApi($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['retrieval' => $exception->getMessage()]) ->withInput(); }
return $this->adminSuccess('Konfigurasi retrieval berhasil diperbarui.', 'admin.vector-retrieval-config'); }
public function storeUser(Request $request): RedirectResponse { $payload = $this->cleanPayload($this->validatedUserPayload($request));
try { $this->createUser($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['user' => $exception->getMessage()]) ->withInput(); }
return $this->adminSuccess('User berhasil dibuat.'); }
public function updateUser(Request $request, string $userId): RedirectResponse { $payload = $this->cleanPayload($this->validatedUserPayload($request));
try { $this->updateUserOnApi($userId, $payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['user' => $exception->getMessage()]) ->withInput(); }
return $this->adminSuccess('User berhasil diperbarui.'); }
public function destroyUser(Request $request, string $userId): RedirectResponse { try { $this->deleteUser($userId, $this->authToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['user' => $exception->getMessage()]); }
return $this->adminSuccess('User berhasil dihapus.'); }
private function authToken(Request $request): ?string { $token = $request->cookie(self::AUTH_TOKEN_COOKIE);
return is_string($token) && $token !== '' ? $token : null; }
/** * @return array<string, mixed> */ private function userFilters(Request $request): array { return $this->cleanPayload($request->validate([ 'email' => ['nullable', 'string'], 'identity_number' => ['nullable', 'string'], 'is_active' => ['nullable', 'boolean'], 'is_superuser' => ['nullable', 'boolean'], 'name' => ['nullable', 'string'], 'ordering' => ['nullable', 'string'], 'page' => ['nullable', 'integer', 'min:1'], 'page_size' => ['nullable'], 'phone' => ['nullable', 'string'], 'role' => ['nullable', Rule::in(['student', 'lecturer', 'admin'])], 'user_token' => ['nullable', 'string'], ])); }
/** * @return array<string, mixed> */ private function validatedUserPayload(Request $request): array { return $request->validate([ 'email' => ['nullable', 'email'], 'identity_number' => ['nullable', 'string'], 'is_active' => ['sometimes', 'boolean'], 'is_superuser' => ['sometimes', 'boolean'], 'name' => ['nullable', 'string'], 'phone' => ['nullable', 'string'], 'role' => ['nullable', Rule::in(['student', 'lecturer', 'admin'])], 'user_token' => ['nullable', 'string'], ]); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function cleanPayload(array $payload): array { return array_filter( $payload, fn (mixed $value): bool => $value !== null && $value !== '', ); }
private function adminSuccess(string $message, string $routeName = 'admin.dashboard'): RedirectResponse { return to_route($routeName)->with('toast', [ 'message' => $message, 'type' => 'success', ]); }
/** * @param array<string, mixed>|null $config * @param array<string, mixed> $section * @return array<string, mixed> */ private function withConfigSection(?array $config, string $key, array $section): array { $config ??= []; $config[$key] = $section;
return $config; }
/** * @param array<int, 'llm'|'retrieval'|'vector_db'> $sections * @return array{backendMessage: string|null, ragConfig: array<string, mixed>|null} */ private function resolveRagConfig(?string $token, array $sections = ['llm', 'vector_db', 'retrieval']): array { $backendMessage = null; $ragConfig = null;
try { $ragConfig = $this->getRagConfig($token); } catch (RagApiException $exception) { $backendMessage = $exception->getMessage() ?: null; }
foreach ($sections as $section) { try { $ragConfig = match ($section) { 'llm' => $this->withConfigSection($ragConfig, 'llm', $this->getLlmConfig($token)), 'retrieval' => $this->withConfigSection($ragConfig, 'retrieval', $this->getRetrievalConfig($token)), 'vector_db' => $this->withConfigSection($ragConfig, 'vector_db', $this->getVectorDbConfig($token)), default => $ragConfig, }; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; } }
return [ 'backendMessage' => $backendMessage, 'ragConfig' => $ragConfig, ]; }
/** * @return array{api_key: string, expires_at?: string|null} */ private function generateApiKeyOnApi(?string $token = null): array { $response = $this->ragRequest($token)->post('/auth/api-keys');
$this->throwIfRagFailed($response);
/** @var array{api_key: string, expires_at?: string|null} */ return $response->json(); }
/** * @return array<string, mixed> */ private function getRagConfig(?string $token = null): array { $response = $this->ragRequest($token)->get('/admin/rag/config');
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getLlmConfig(?string $token = null): array { $response = $this->ragRequest($token)->get('/admin/rag/config/llm');
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function updateLlmConfigOnApi(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->patch('/admin/rag/config/llm', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getVectorDbConfig(?string $token = null): array { $response = $this->ragRequest($token)->get('/admin/rag/config/vector_db');
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function updateVectorDbConfigOnApi(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->patch('/admin/rag/config/vector_db', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getRetrievalConfig(?string $token = null): array { $response = $this->ragRequest($token)->get('/admin/rag/config/retrieval');
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function updateRetrievalConfigOnApi(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->patch('/admin/rag/config/retrieval', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array<string, mixed> $query * @return array{founds?: array<int, array<string, mixed>>, search_options?: array<string, mixed>} */ private function listUsers(array $query = [], ?string $token = null): array { $response = $this->ragRequest($token)->get('/user', $query);
$this->throwIfRagFailed($response);
/** @var array{founds?: array<int, array<string, mixed>>, search_options?: array<string, mixed>} */ return $response->json(); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function createUser(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/user', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array<string, mixed> $payload * @return array<string, mixed> */ private function updateUserOnApi(string $userId, array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->patch('/user/'.$this->encodePathSegment($userId), $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
private function deleteUser(string $userId, ?string $token = null): void { $response = $this->ragRequest($token)->delete('/user/'.$this->encodePathSegment($userId));
$this->throwIfRagFailed($response); }}2 unmodified lines345667896 unmodified lines1617181920212223242526272829301 unmodified line323334263536283738393140413342434436454647483 unmodified lines5253545556464748495758596061626364656667686970717273747557767778793 unmodified lines83848586678788899071919273939495769697989910010110210310410510610783108109110111112113114861151161171181191201211229012312412512612712812920 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified linesnamespace App\Http\Controllers;
use App\Exceptions\RagApiException;use App\Services\RagApiClient;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Inertia\Inertia;6 unmodified lines
private const AUTH_USER_COOKIE = 'sevima_raghub_auth_user';
private const REGISTER_FIELDS = [ 'email', 'identity_number', 'name', 'password', 'phone', 'role', ];
public function showAdminLogin(Request $request): Response { return Inertia::render('auth/admin-login', [1 unmodified line ]); }
public function login(Request $request, RagApiClient $rag): RedirectResponse public function login(Request $request): RedirectResponse { return $this->attemptLogin($request, $rag); return $this->attemptLogin($request); }
public function adminLogin(Request $request, RagApiClient $rag): RedirectResponse public function adminLogin(Request $request): RedirectResponse { return $this->attemptLogin($request, $rag, 'admin'); return $this->attemptLogin($request, 'admin'); }
private function attemptLogin(Request $request, RagApiClient $rag, ?string $requiredRole = null): RedirectResponse private function attemptLogin(Request $request, ?string $requiredRole = null): RedirectResponse { /** @var array{email: string, password: string, remember?: bool} $payload */ $payload = $request->validate([3 unmodified lines ]);
try { $response = $this->ragRequest() ->asJson() $response = $rag->login([ 'email' => $payload['email'], 'password' => $payload['password'], ]); ->post('/auth/login', [ 'email' => $payload['email'], 'password' => $payload['password'], ]);
$this->throwIfRagFailed($response); } catch (RagApiException $exception) { return back() ->withErrors(['auth' => $exception->getMessage()]) ->withInput($request->except('password')); } catch (ConnectionException) { return back() ->withErrors(['auth' => 'Server login tidak bisa dihubungi. Coba lagi nanti.']) ->withInput($request->except('password')); }
/** @var array{token: string, user: array<string, mixed>} $responsePayload */ $responsePayload = $response->json(); $remember = (bool) ($payload['remember'] ?? false); $user = $response['user']; $user = $responsePayload['user']; $role = $user['role'] ?? null;
if ($requiredRole !== null && $role !== $requiredRole) {3 unmodified lines }
return redirect($this->dashboardPath($role)) ->with('status', 'Login berhasil.') ->withCookie($this->authCookie($request, self::AUTH_TOKEN_COOKIE, $response['token'], $remember)) ->withCookie($this->authCookie($request, self::AUTH_TOKEN_COOKIE, $responsePayload['token'], $remember)) ->withCookie($this->authCookie($request, self::AUTH_USER_COOKIE, json_encode($user, JSON_THROW_ON_ERROR), $remember)); }
public function register(Request $request, RagApiClient $rag): RedirectResponse public function register(Request $request): RedirectResponse { /** @var array{email: string, password: string, name: string, role: string, identity_number: string} $payload */ /** @var array{email: string, password: string, name: string, role: string, identity_number: string, phone?: string|null} $payload */ $payload = $request->validate([ 'email' => ['required', 'email'], 'identity_number' => ['required', 'string'], 'identity_number' => ['required', 'string', 'regex:/^\d+$/'], 'name' => ['required', 'string'], 'password' => ['required', 'string'], 'phone' => ['nullable', 'string'], 'role' => ['required', 'in:student,lecturer,admin'], ]);
if (($payload['phone'] ?? null) === null || $payload['phone'] === '') { unset($payload['phone']); }
try { $response = $rag->register($payload); $response = $this->ragRequest() ->asJson() ->post('/auth/register', $payload);
$this->throwIfRagFailed($response); } catch (RagApiException $exception) { return back() ->withErrors(['auth' => $exception->getMessage()]) ->withErrors($this->registerErrorsFromApiData($exception->data)) ->withInput($request->except('password')); } catch (ConnectionException) { return back() ->withErrors(['auth' => 'Server registrasi tidak bisa dihubungi. Coba lagi nanti.']) ->withInput($request->except('password')); }
return to_route('login')->with('status', $response['message']); return to_route('login')->with( 'status', $response->json('message') ?? 'Registrasi berhasil. Silakan login.', ); }
private function dashboardPath(mixed $role): string20 unmodified lines sameSite: 'lax', ); }
/** * @return array<string, string> */ private function registerErrorsFromApiData(mixed $data): array { if (! is_array($data)) { return ['auth' => 'Registrasi gagal.']; }
$errors = []; $fieldErrors = $data['field_errors'] ?? null;
if (is_array($fieldErrors)) { foreach ($fieldErrors as $field => $message) { if (! is_string($field) || ! is_string($message)) { continue; }
if (in_array($field, self::REGISTER_FIELDS, true)) { $errors[$field] = $message; } } }
$errorItems = $data['errors'] ?? null;
if (is_array($errorItems)) { foreach ($errorItems as $item) { if (! is_array($item)) { continue; }
$field = $this->validationFieldFromItem($item); $message = $this->validationMessageFromItem($item);
if ($field !== null && $message !== null) { $errors[$field] = $message; } } }
$detail = $data['detail'] ?? null; $fallbackMessage = null;
if (is_array($detail)) { foreach ($detail as $item) { if (! is_array($item)) { continue; }
$field = $this->validationFieldFromItem($item); $message = $this->validationMessageFromItem($item);
$fallbackMessage ??= $message;
if ($field !== null && $message !== null) { $errors[$field] = $message; } } }
if ($errors !== []) { return $errors; }
if (is_string($data['message'] ?? null)) { return ['auth' => $data['message']]; }
if ($fallbackMessage !== null) { return ['auth' => $fallbackMessage]; }
return ['auth' => 'Registrasi gagal.']; }
/** * @param array<string, mixed> $item */ private function validationFieldFromItem(array $item): ?string { $location = $item['loc'] ?? null; $field = null;
if (is_array($location)) { $field = end($location); } elseif (is_string($item['field'] ?? null)) { $field = $item['field']; }
if (! is_string($field) || ! in_array($field, self::REGISTER_FIELDS, true)) { return null; }
return $field; }
/** * @param array<string, mixed> $item */ private function validationMessageFromItem(array $item): ?string { foreach (['msg', 'message'] as $key) { if (is_string($item[$key] ?? null)) { return $item[$key]; } }
return null; }}1 unmodified line2345678910111271314151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line
namespace App\Http\Controllers;
use App\Exceptions\RagApiException;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\Client\Response as ClientResponse;use Illuminate\Support\Facades\Http;use RuntimeException;
abstract class Controller{ // protected function ragRequest(?string $token = null): PendingRequest { $baseUrl = config('services.rag.base_url');
if (! is_string($baseUrl) || trim($baseUrl) === '') { throw new RuntimeException('RAG API base URL is not configured.'); }
$request = Http::baseUrl(rtrim($baseUrl, '/')) ->acceptJson() ->connectTimeout(5) ->timeout(20);
if ($token !== null && $token !== '') { $request->withToken($token); }
return $request; }
protected function throwIfRagFailed(ClientResponse $response): void { if ($response->failed()) { throw RagApiException::fromResponse($response); } }
protected function encodePathSegment(string $value): string { return rawurlencode($value); }
protected function isDirectChatMode(): bool { $chatMode = config('services.rag.chat_mode', 'rest');
return is_string($chatMode) && strtolower($chatMode) === 'direct'; }}2 unmodified lines345667891011121314151617171819202122232424252627282930313132333411 unmodified lines46474849495051526 unmodified lines59606162626364653 unmodified lines69707172727374751 unmodified line7778798080818283848586868788896 unmodified lines96979899991001011026 unmodified lines1091101111121121131141153 unmodified lines1191201211221221231241251251261271281 unmodified line1301311321331331341351362 unmodified lines1391401411421421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612 unmodified linesnamespace App\Http\Controllers;
use App\Exceptions\RagApiException;use App\Services\RagApiClient;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Http\UploadedFile;use Inertia\Inertia;use Inertia\Response;use RuntimeException;
class DosenController extends Controller{ private const AUTH_TOKEN_COOKIE = 'sevima_raghub_auth_token';
public function index(Request $request, RagApiClient $rag): Response public function index(Request $request): Response { $backendMessage = null; $knowledgeBases = []; $token = $this->authToken($request);
try { $courses = $rag->listCourses(limit: 100, token: $token)['data']; $courses = $this->listCourses(limit: 100, token: $token)['data'];
foreach ($courses as $course) { $documents = [];
if ($token !== null) { try { $documents = $rag->listCourseDocuments((string) $course['id'], $token)['data']; $documents = $this->listCourseDocuments((string) $course['id'], $token)['data']; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }11 unmodified lines ]); }
public function storeCourse(Request $request, RagApiClient $rag): RedirectResponse public function storeCourse(Request $request): RedirectResponse { /** @var array{title: string, description?: string|null} $payload */ $payload = $request->validate([6 unmodified lines }
try { $rag->createCourse($payload, $this->authToken($request)); $this->createCourse($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['course' => $exception->getMessage()])3 unmodified lines return to_route('dosen'); }
public function show(Request $request, RagApiClient $rag, string $courseId): Response public function show(Request $request, string $courseId): Response { $backendMessage = null; $course = null;1 unmodified line $token = $this->authToken($request);
try { $course = $rag->getCourse($courseId, $token); $course = $this->getCourse($courseId, $token); } catch (RagApiException $exception) { $backendMessage = $exception->getMessage() ?: null; }
try { $documents = $rag->listCourseDocuments($courseId, $token)['data']; $documents = $this->listCourseDocuments($courseId, $token)['data']; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }6 unmodified lines ]); }
public function updateCourse(Request $request, RagApiClient $rag, string $courseId): RedirectResponse public function updateCourse(Request $request, string $courseId): RedirectResponse { /** @var array{title: string, description?: string|null} $payload */ $payload = $request->validate([6 unmodified lines }
try { $rag->updateCourse($courseId, $payload, $this->authToken($request)); $this->updateCourseOnApi($courseId, $payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['course' => $exception->getMessage()])3 unmodified lines return to_route('dosen.show', ['courseId' => $courseId]); }
public function destroyCourse(Request $request, RagApiClient $rag, string $courseId): RedirectResponse public function destroyCourse(Request $request, string $courseId): RedirectResponse { try { $rag->deleteCourse($courseId, $this->authToken($request)); $this->deleteCourse($courseId, $this->authToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['course' => $exception->getMessage()]); }1 unmodified line return to_route('dosen'); }
public function uploadDocument(Request $request, RagApiClient $rag, string $courseId): RedirectResponse public function uploadDocument(Request $request, string $courseId): RedirectResponse { $validated = $request->validate([ 'file' => ['required', 'file', 'mimes:pdf,ppt,pptx,txt', 'max:102400'],2 unmodified lines $file = $validated['file'];
try { $rag->uploadDocument($courseId, $file, $this->authToken($request)); $this->uploadDocumentToApi($courseId, $file, $this->authToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['file' => $exception->getMessage()]); } catch (RuntimeException $exception) { return back()->withErrors(['file' => $exception->getMessage()]); }
return to_route('dosen.show', ['courseId' => $courseId]); }
/** * @return array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ private function listCourses(int $page = 1, int $limit = 100, ?string $token = null): array { $response = $this->ragRequest($token)->get('/courses', [ 'limit' => $limit, 'page' => $page, ]);
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>} */ private function listCourseDocuments(string $courseId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/courses/'.$this->encodePathSegment($courseId).'/documents');
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>} */ return $response->json(); }
/** * @param array{title: string, description?: string|null} $payload * @return array<string, mixed> */ private function createCourse(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/courses', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getCourse(string $courseId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/courses/'.$this->encodePathSegment($courseId));
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @param array{title?: string, description?: string|null} $payload * @return array<string, mixed> */ private function updateCourseOnApi(string $courseId, array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->put('/courses/'.$this->encodePathSegment($courseId), $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
private function deleteCourse(string $courseId, ?string $token = null): void { $response = $this->ragRequest($token)->delete('/courses/'.$this->encodePathSegment($courseId));
$this->throwIfRagFailed($response); }
private function uploadDocumentToApi(string $courseId, UploadedFile $file, ?string $token = null): void { $stream = fopen($file->getRealPath() ?: $file->getPathname(), 'r');
if ($stream === false) { throw new RuntimeException('Uploaded file could not be read.'); }
try { $response = $this->ragRequest($token) ->attach( 'file', $stream, $file->getClientOriginalName(), ['Content-Type' => $file->getMimeType() ?: 'application/octet-stream'], ) ->post('/documents/upload', [ 'course_id' => $courseId, ]); } finally { fclose($stream); }
$this->throwIfRagFailed($response); }
private function authToken(Request $request): ?string { $token = $request->cookie(self::AUTH_TOKEN_COOKIE);2 unmodified lines345667816 unmodified lines252627282930317 unmodified lines39404142434445454647474849505152535448564950515214 unmodified lines676869777071797273748283757677857879808123 unmodified lines1051061071151081091101111 unmodified line1131141151231161171181192 unmodified lines12212312413212512612712818 unmodified lines1471481491571501511521533 unmodified lines1571581591671601611621635 unmodified lines1691701711791721731741753 unmodified lines1791801811891821831841921851861871883 unmodified lines19219319420219519619719819920020420120220320420620720820520621021121221321421521621720720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924022022122224124224324424524624724822524925025125225325422725525625725822923025926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530623323430730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235344 unmodified lines3983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304312874324334344352 unmodified linesnamespace App\Http\Controllers;
use App\Exceptions\RagApiException;use App\Services\RagApiClient;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\Cache;16 unmodified lines * @var array<int, string> */ private const EMBED_QUERY_KEYS = [ 'api_key', 'background', 'border', 'course_id',7 unmodified lines 'surface', 'text', 'title', 'token', 'user_name', ];
public function index(Request $request, RagApiClient $rag): Response|RedirectResponse public function index(Request $request): Response|RedirectResponse { if ($request->filled('api_key')) { return $this->bootstrapTokenFromApiKey($request, $rag); }
if ($request->filled('token')) { return $this->bootstrapTokenFromQuery($request); }
$config = $this->embedConfig($request); $token = $this->embedToken($request); $token = $this->resolveEmbedToken($request);
if ($token === null) { return Inertia::render('embed', [14 unmodified lines $pendingId = $this->stringQuery($request, 'pending_id');
try { $courses = $rag->listCourses(limit: 100, token: $token)['data']; $courses = $this->listCourses(limit: 100, token: $token)['data']; $selectedCourseId = $this->selectedCourseId($selectedCourseId, $courses); $chatSessions = $rag->listChatSessions(limit: 50, token: $token, courseId: $selectedCourseId)['data']; $chatSessions = $this->listChatSessions(limit: 50, token: $token, courseId: $selectedCourseId)['data'];
if ($sessionId !== null) { $currentSession = $rag->getChatSession($sessionId, $token); $messages = $rag->getChatHistory($sessionId, $token)['data']; $currentSession = $this->getChatSession($sessionId, $token); $messages = $this->getChatHistory($sessionId, $token)['data'];
if ($rag->isDirectChatMode()) { if ($this->isDirectChatMode()) { $messages = [ ...$messages, ...$this->directChatMessages($sessionId),23 unmodified lines 'courses' => $courses, 'currentSession' => $currentSession, 'isAuthorized' => $backendMessage === null, 'isDirectChatMode' => $rag->isDirectChatMode(), 'isDirectChatMode' => $this->isDirectChatMode(), 'messages' => $messages, 'pendingInitialChat' => $pendingInitialChat, 'selectedCourseId' => $selectedCourseId,1 unmodified line ]); }
public function storeSession(Request $request, RagApiClient $rag): RedirectResponse public function storeSession(Request $request): RedirectResponse { /** @var array{course_id: string, title: string} $payload */ $payload = $request->validate([2 unmodified lines ]);
try { $session = $rag->createChatSession($payload, $this->requireEmbedToken($request)); $session = $this->createChatSession($payload, $this->requireEmbedToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['chat' => $exception->getMessage()])18 unmodified lines ])); }
public function storeMessage(Request $request, RagApiClient $rag, string $sessionId): RedirectResponse public function storeMessage(Request $request, string $sessionId): RedirectResponse { /** @var array{content: string, course_id: string} $payload */ $payload = $request->validate([3 unmodified lines $userMessage = $this->localUserMessage($payload['content']);
try { $assistantMessage = $rag->sendConfiguredChatMessage( $assistantMessage = $this->sendConfiguredChatMessage( $sessionId, $payload['course_id'], $payload['content'],5 unmodified lines ->withInput(); }
if ($rag->isDirectChatMode()) { if ($this->isDirectChatMode()) { $this->appendDirectChatMessages($sessionId, [ $userMessage, $assistantMessage,3 unmodified lines return redirect($this->embedRoute($request, ['session_id' => $sessionId])); }
public function destroySession(Request $request, RagApiClient $rag, string $sessionId): RedirectResponse public function destroySession(Request $request, string $sessionId): RedirectResponse { try { $rag->deleteChatSession($sessionId, $this->requireEmbedToken($request)); $this->deleteChatSession($sessionId, $this->requireEmbedToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['session' => $exception->getMessage()]); }3 unmodified lines return redirect($this->embedRoute($request, ['session_id' => null])); }
private function bootstrapTokenFromApiKey(Request $request, RagApiClient $rag): Response|RedirectResponse /** * @param array{api_key: string} $payload * @return array{token: string, user: array<string, mixed>} */ private function loginWithApiKey(array $payload): array { $apiKey = $this->stringQuery($request, 'api_key'); $response = $this->ragRequest() ->asJson() ->post('/auth/login/api-key', $payload);
if ($apiKey === null) { return redirect($this->embedRoute($request)); } $this->throwIfRagFailed($response);
try { $response = $rag->loginWithApiKey(['api_key' => $apiKey]); } catch (RagApiException $exception) { return Inertia::render('embed', [ ...$this->emptyPayload($this->embedConfig($request)), 'backendMessage' => $exception->getMessage(), 'isAuthorized' => false, ]); /** @var array{token: string, user: array<string, mixed>} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ private function listCourses(int $page = 1, int $limit = 100, ?string $token = null): array { $response = $this->ragRequest($token)->get('/courses', [ 'limit' => $limit, 'page' => $page, ]);
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ private function listChatSessions(int $page = 1, int $limit = 20, ?string $token = null, ?string $courseId = null): array { $query = [ 'limit' => $limit, 'page' => $page, ];
if ($courseId !== null && $courseId !== '') { $query['course_id'] = $courseId; }
return redirect($this->embedRoute($request)) ->withCookie($this->embedCookie($request, self::EMBED_TOKEN_COOKIE, $response['token'])) ->withCookie($this->embedCookie($request, self::EMBED_USER_COOKIE, json_encode($response['user'], JSON_THROW_ON_ERROR))); $response = $this->ragRequest($token)->get('/chats/sessions', $query);
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ return $response->json(); }
private function bootstrapTokenFromQuery(Request $request): RedirectResponse /** * @param array{course_id: string, title: string} $payload * @return array<string, mixed> */ private function createChatSession(array $payload, ?string $token = null): array { $token = $this->stringQuery($request, 'token'); $response = $this->ragRequest($token) ->asJson() ->post('/chats/sessions', $payload);
if ($token === null) { return redirect($this->embedRoute($request)); $this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getChatSession(string $sessionId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId));
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>} */ private function getChatHistory(string $sessionId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages');
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>} */ return $response->json(); }
private function deleteChatSession(string $sessionId, ?string $token = null): void { $response = $this->ragRequest($token)->delete('/chats/sessions/'.$this->encodePathSegment($sessionId));
$this->throwIfRagFailed($response); }
/** * @return array<string, mixed> */ private function sendConfiguredChatMessage(string $sessionId, string $courseId, string $content, ?string $token = null): array { if ($this->isDirectChatMode()) { return $this->queryAiDirect($courseId, $content, $token); }
return redirect($this->embedRoute($request)) ->withCookie($this->embedCookie($request, self::EMBED_TOKEN_COOKIE, $token)); return $this->sendRestChatMessage($sessionId, $content, $token); }
/** * @return array<string, mixed> */ private function sendRestChatMessage(string $sessionId, string $content, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages', [ 'content' => $content, ]);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array{uuid_id: string, role: string, content: string, sources: array<int, mixed>, created_at: string} */ private function queryAiDirect(string $courseId, string $content, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/ai/query', [ 'course_id' => $courseId, 'prompt' => $content, ]);
$this->throwIfRagFailed($response);
/** @var array{message_id: string, role?: string, content: string, sources?: array<int, mixed>, created_at: string} $payload */ $payload = $response->json();
return [ 'content' => $payload['content'], 'created_at' => $payload['created_at'], 'role' => $payload['role'] ?? 'assistant', 'sources' => $payload['sources'] ?? [], 'uuid_id' => $payload['message_id'], ]; }
/**44 unmodified lines return is_string($token) && trim($token) !== '' ? $token : null; }
private function resolveEmbedToken(Request $request): ?string { $cookieToken = $this->embedToken($request);
if ($cookieToken !== null) { return $cookieToken; }
$queryToken = $this->stringQuery($request, 'token');
if ($queryToken !== null) { return $queryToken; }
$apiKey = $this->stringQuery($request, 'api_key');
if ($apiKey === null) { return null; }
try { $response = $this->loginWithApiKey(['api_key' => $apiKey]); } catch (RagApiException) { return null; }
return $response['token']; }
private function requireEmbedToken(Request $request): string { $token = $this->embedToken($request); $token = $this->resolveEmbedToken($request);
if ($token === null) { abort(401, 'Token iframe tidak tersedia.');2 unmodified lines34566788 unmodified lines17181921202123222324251 unmodified line27282931303132332 unmodified lines363738403940414210 unmodified lines53545557565759585960616263646665666768697072717273747577767778794 unmodified lines84858688878889903 unmodified lines949596989798991003 unmodified lines1041051061081071081091105 unmodified lines1161171181201191201211223 unmodified lines12612712813012913013113313213313413510 unmodified lines1461471481501491501511521 unmodified line1541551561581571581591601611621631651641651661676 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified linesnamespace App\Http\Controllers;
use App\Exceptions\RagApiException;use App\Services\RagApiClient;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Str;8 unmodified lines
private const PENDING_INITIAL_CHAT_SESSION_PREFIX = 'sevima_raghub_pending_initial_chat';
public function index(Request $request, RagApiClient $rag): Response public function index(Request $request): Response { $payload = $this->studentDashboardPayload($request, $rag); $payload = $this->studentDashboardPayload($request);
return Inertia::render('mahasiswa', [ ...$payload,1 unmodified line ]); }
public function storeSession(Request $request, RagApiClient $rag): RedirectResponse public function storeSession(Request $request): RedirectResponse { /** @var array{course_id: string, title: string} $payload */ $payload = $request->validate([2 unmodified lines ]);
try { $session = $rag->createChatSession($payload, $this->authToken($request)); $session = $this->createChatSession($payload, $this->authToken($request)); } catch (RagApiException $exception) { return back() ->withErrors(['chat' => $exception->getMessage()])10 unmodified lines return to_route('mahasiswa.show', ['sessionId' => $sessionId]); }
public function show(Request $request, RagApiClient $rag, string $sessionId): Response public function show(Request $request, string $sessionId): Response { $payload = $this->studentDashboardPayload($request, $rag); $payload = $this->studentDashboardPayload($request); $backendMessage = $payload['backendMessage']; $currentSession = null; $messages = []; $token = $this->authToken($request);
try { $currentSession = $rag->getChatSession($sessionId, $token); $currentSession = $this->getChatSession($sessionId, $token); } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }
try { $messages = $rag->getChatHistory($sessionId, $token)['data']; $messages = $this->getChatHistory($sessionId, $token)['data']; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }
if ($rag->isDirectChatMode()) { if ($this->isDirectChatMode()) { $messages = [ ...$messages, ...$this->directChatMessages($request, $sessionId),4 unmodified lines ...$payload, 'backendMessage' => $backendMessage, 'currentSession' => $currentSession, 'isDirectChatMode' => $rag->isDirectChatMode(), 'isDirectChatMode' => $this->isDirectChatMode(), 'messages' => $messages, 'pendingInitialChat' => $request->session()->pull($this->pendingInitialChatKey($sessionId)), 'selectedCourseId' => is_string($currentSession['course_id'] ?? null)3 unmodified lines ]); }
public function storeMessage(Request $request, RagApiClient $rag, string $sessionId): RedirectResponse public function storeMessage(Request $request, string $sessionId): RedirectResponse { /** @var array{content: string, course_id: string} $payload */ $payload = $request->validate([3 unmodified lines $userMessage = $this->localUserMessage($payload['content']);
try { $assistantMessage = $rag->sendConfiguredChatMessage( $assistantMessage = $this->sendConfiguredChatMessage( $sessionId, $payload['course_id'], $payload['content'],5 unmodified lines ->withInput(); }
if ($rag->isDirectChatMode()) { if ($this->isDirectChatMode()) { $this->appendDirectChatMessages($request, $sessionId, [ $userMessage, $assistantMessage,3 unmodified lines return to_route('mahasiswa.show', ['sessionId' => $sessionId]); }
public function destroySession(Request $request, RagApiClient $rag, string $sessionId): RedirectResponse public function destroySession(Request $request, string $sessionId): RedirectResponse { try { $rag->deleteChatSession($sessionId, $this->authToken($request)); $this->deleteChatSession($sessionId, $this->authToken($request)); } catch (RagApiException $exception) { return back()->withErrors(['session' => $exception->getMessage()]); }10 unmodified lines /** * @return array{backendMessage: ?string, chatSessions: array<int, array<string, mixed>>, courses: array<int, array<string, mixed>>} */ private function studentDashboardPayload(Request $request, RagApiClient $rag): array private function studentDashboardPayload(Request $request): array { $backendMessage = null; $courses = [];1 unmodified line $token = $this->authToken($request);
try { $courses = $rag->listCourses(limit: 100, token: $token)['data']; $courses = $this->listCourses(limit: 100, token: $token)['data']; } catch (RagApiException $exception) { $backendMessage = $exception->getMessage() ?: null; }
if ($token !== null) { try { $chatSessions = $rag->listChatSessions(limit: 20, token: $token)['data']; $chatSessions = $this->listChatSessions(limit: 20, token: $token)['data']; } catch (RagApiException $exception) { $backendMessage ??= $exception->getMessage() ?: null; }6 unmodified lines ]; }
/** * @return array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ private function listCourses(int $page = 1, int $limit = 100, ?string $token = null): array { $response = $this->ragRequest($token)->get('/courses', [ 'limit' => $limit, 'page' => $page, ]);
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>, total?: int, page?: int, limit?: int} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ private function listChatSessions(int $page = 1, int $limit = 20, ?string $token = null): array { $response = $this->ragRequest($token)->get('/chats/sessions', [ 'limit' => $limit, 'page' => $page, ]);
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ return $response->json(); }
/** * @param array{course_id: string, title: string} $payload * @return array<string, mixed> */ private function createChatSession(array $payload, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/chats/sessions', $payload);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ private function getChatSession(string $sessionId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId));
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>} */ private function getChatHistory(string $sessionId, ?string $token = null): array { $response = $this->ragRequest($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages');
$this->throwIfRagFailed($response);
/** @var array{data: array<int, array<string, mixed>>} */ return $response->json(); }
private function deleteChatSession(string $sessionId, ?string $token = null): void { $response = $this->ragRequest($token)->delete('/chats/sessions/'.$this->encodePathSegment($sessionId));
$this->throwIfRagFailed($response); }
/** * @return array<string, mixed> */ private function sendConfiguredChatMessage(string $sessionId, string $courseId, string $content, ?string $token = null): array { if ($this->isDirectChatMode()) { return $this->queryAiDirect($courseId, $content, $token); }
return $this->sendRestChatMessage($sessionId, $content, $token); }
/** * @return array<string, mixed> */ private function sendRestChatMessage(string $sessionId, string $content, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages', [ 'content' => $content, ]);
$this->throwIfRagFailed($response);
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array{uuid_id: string, role: string, content: string, sources: array<int, mixed>, created_at: string} */ private function queryAiDirect(string $courseId, string $content, ?string $token = null): array { $response = $this->ragRequest($token) ->asJson() ->post('/ai/query', [ 'course_id' => $courseId, 'prompt' => $content, ]);
$this->throwIfRagFailed($response);
/** @var array{message_id: string, role?: string, content: string, sources?: array<int, mixed>, created_at: string} $payload */ $payload = $response->json();
return [ 'content' => $payload['content'], 'created_at' => $payload['created_at'], 'role' => $payload['role'] ?? 'assistant', 'sources' => $payload['sources'] ?? [], 'uuid_id' => $payload['message_id'], ]; }
private function authToken(Request $request): ?string { $token = $request->cookie(self::AUTH_TOKEN_COOKIE);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356<?php
namespace App\Services;
use App\Exceptions\RagApiException;use Illuminate\Http\Client\PendingRequest;use Illuminate\Http\UploadedFile;use Illuminate\Support\Facades\Http;use RuntimeException;
class RagApiClient{ /** * @param array{email: string, password: string} $payload * @return array{token: string, user: array<string, mixed>} */ public function login(array $payload): array { $response = $this->request()->post('/auth/login', $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{token: string, user: array<string, mixed>} */ return $response->json(); }
/** * @param array{api_key: string} $payload * @return array{token: string, user: array<string, mixed>} */ public function loginWithApiKey(array $payload): array { $response = $this->request()->post('/auth/login/api-key', $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{token: string, user: array<string, mixed>} */ return $response->json(); }
/** * @param array{email: string, password: string, name: string, role: string, identity_number: string} $payload * @return array{message: string, user: array<string, mixed>} */ public function register(array $payload): array { $response = $this->request()->post('/auth/register', $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{message: string, user: array<string, mixed>} */ return $response->json(); }
/** * @return array{data: array<int, array{id: int|string, title: string, description?: string|null}>, total?: int, page?: int, limit?: int} */ public function listCourses(int $page = 1, int $limit = 100, ?string $token = null): array { $response = $this->request($token)->get('/courses', [ 'limit' => $limit, 'page' => $page, ]);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{data: array<int, array{id: int|string, title: string, description?: string|null}>, total?: int, page?: int, limit?: int} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>} */ public function listCourseDocuments(string $courseId, ?string $token = null): array { $response = $this->request($token)->get('/courses/'.$this->encodePathSegment($courseId).'/documents');
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{data: array<int, array<string, mixed>>} */ return $response->json(); }
/** * @param array{title: string, description?: string|null} $payload * @return array{id: int|string, title: string, description?: string|null} */ public function createCourse(array $payload, ?string $token = null): array { $response = $this->request($token)->post('/courses', $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{id: int|string, title: string, description?: string|null} */ return $response->json(); }
/** * @return array{id: int|string, title: string, description?: string|null} */ public function getCourse(string $courseId, ?string $token = null): array { $response = $this->request($token)->get('/courses/'.$this->encodePathSegment($courseId));
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{id: int|string, title: string, description?: string|null} */ return $response->json(); }
/** * @param array{title?: string, description?: string|null} $payload * @return array{id: int|string, title: string, description?: string|null} */ public function updateCourse(string $courseId, array $payload, ?string $token = null): array { $response = $this->request($token)->put('/courses/'.$this->encodePathSegment($courseId), $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{id: int|string, title: string, description?: string|null} */ return $response->json(); }
public function deleteCourse(string $courseId, ?string $token = null): void { $response = $this->request($token)->delete('/courses/'.$this->encodePathSegment($courseId));
if ($response->failed()) { throw RagApiException::fromResponse($response); } }
/** * @return array{document_id: string, filename: string, status: string, message: string} */ public function uploadDocument(string $courseId, UploadedFile $file, ?string $token = null): array { $stream = fopen($file->getRealPath() ?: $file->getPathname(), 'r');
if ($stream === false) { throw new RuntimeException('Uploaded file could not be read.'); }
try { $response = $this->request($token) ->attach( 'file', $stream, $file->getClientOriginalName(), ['Content-Type' => $file->getMimeType() ?: 'application/octet-stream'], ) ->post('/documents/upload', [ 'course_id' => $courseId, ]); } finally { fclose($stream); }
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{document_id: string, filename: string, status: string, message: string} */ return $response->json(); }
/** * @return array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ public function listChatSessions(int $page = 1, int $limit = 20, ?string $token = null, ?string $courseId = null): array { $query = [ 'limit' => $limit, 'page' => $page, ];
if ($courseId !== null && $courseId !== '') { $query['course_id'] = $courseId; }
$response = $this->request($token)->get('/chats/sessions', $query);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{data: array<int, array<string, mixed>>, pagination?: array<string, mixed>} */ return $response->json(); }
/** * @param array{course_id: string, title: string} $payload * @return array<string, mixed> */ public function createChatSession(array $payload, ?string $token = null): array { $response = $this->request($token)->post('/chats/sessions', $payload);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array<string, mixed> */ public function getChatSession(string $sessionId, ?string $token = null): array { $response = $this->request($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId));
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array<string, mixed> */ return $response->json(); }
public function deleteChatSession(string $sessionId, ?string $token = null): void { $response = $this->request($token)->delete('/chats/sessions/'.$this->encodePathSegment($sessionId));
if ($response->failed()) { throw RagApiException::fromResponse($response); } }
/** * @return array{data: array<int, array<string, mixed>>} */ public function getChatHistory(string $sessionId, ?string $token = null): array { $response = $this->request($token)->get('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages');
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{data: array<int, array<string, mixed>>} */ return $response->json(); }
/** * @return array<string, mixed> */ public function sendConfiguredChatMessage(string $sessionId, string $courseId, string $content, ?string $token = null): array { if ($this->isDirectChatMode()) { return $this->queryAiDirect($courseId, $content, $token); }
return $this->sendRestChatMessage($sessionId, $content, $token); }
/** * @return array<string, mixed> */ public function sendRestChatMessage(string $sessionId, string $content, ?string $token = null): array { $response = $this->request($token)->post('/chats/sessions/'.$this->encodePathSegment($sessionId).'/messages', [ 'content' => $content, ]);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array<string, mixed> */ return $response->json(); }
/** * @return array{uuid_id: string, role: string, content: string, sources: array<int, mixed>, created_at: string} */ public function queryAiDirect(string $courseId, string $content, ?string $token = null): array { $response = $this->request($token)->post('/ai/query', [ 'course_id' => $courseId, 'prompt' => $content, ]);
if ($response->failed()) { throw RagApiException::fromResponse($response); }
/** @var array{message_id: string, role?: string, content: string, sources?: array<int, mixed>, created_at: string} $payload */ $payload = $response->json();
return [ 'content' => $payload['content'], 'created_at' => $payload['created_at'], 'role' => $payload['role'] ?? 'assistant', 'sources' => $payload['sources'] ?? [], 'uuid_id' => $payload['message_id'], ]; }
public function isDirectChatMode(): bool { return $this->chatMode() === 'direct'; }
private function request(?string $token = null): PendingRequest { $baseUrl = config('services.rag.base_url');
if (! is_string($baseUrl) || trim($baseUrl) === '') { throw new RuntimeException('RAG API base URL is not configured.'); }
$request = Http::baseUrl(rtrim($baseUrl, '/')) ->acceptJson() ->connectTimeout(5) ->timeout(20);
if ($token !== null && $token !== '') { $request->withToken($token); }
return $request; }
private function encodePathSegment(string $value): string { return rawurlencode($value); }
private function chatMode(): string { $chatMode = config('services.rag.chat_mode', 'rest');
return is_string($chatMode) && strtolower($chatMode) === 'direct' ? 'direct' : 'rest'; }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889import { useForm } from '@inertiajs/react';import { Copy, KeyRound } from 'lucide-react';import { toast } from 'sonner';
import { generateApiKey } from '@/actions/App/Http/Controllers/AdminController';import { ConfigError } from '@/components/admin/admin-form-parts';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { Spinner } from '@/components/ui/spinner';import { readError } from '@/lib/admin';import type { GeneratedApiKey } from '@/types/admin';
export function AdminApiKeyCard({ generatedApiKey,}: { generatedApiKey?: GeneratedApiKey | null;}) { const apiKeyForm = useForm({});
function handleGenerateApiKey(): void { apiKeyForm.post(generateApiKey.url(), { preserveScroll: true }); }
function handleCopyApiKey(): void { if (!generatedApiKey?.api_key) { return; }
void navigator.clipboard.writeText(generatedApiKey.api_key); toast.success('API key disalin.'); }
return ( <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle className="flex items-center gap-2"> <KeyRound className="size-5 text-[var(--app-primary)]" /> API Key Iframe </CardTitle> <CardDescription> API key hanya ditampilkan sekali setelah dibuat. </CardDescription> </CardHeader> <CardContent className="grid gap-4"> <Button disabled={apiKeyForm.processing} onClick={handleGenerateApiKey} type="button" > {apiKeyForm.processing ? ( <Spinner className="size-4" /> ) : ( <KeyRound className="size-4" /> )} Generate API Key </Button>
<ConfigError message={readError(apiKeyForm.errors, 'apiKey')} />
{generatedApiKey ? ( <div className="grid gap-3 rounded-xl border border-[var(--app-border)] bg-[var(--app-background)] p-4"> <Label>API Key Baru</Label> <div className="flex gap-2"> <Input readOnly value={generatedApiKey.api_key} /> <Button onClick={handleCopyApiKey} type="button" variant="outline" > <Copy className="size-4" /> </Button> </div> <p className="text-sm text-muted-foreground"> Expired: {generatedApiKey.expires_at ?? '-'} </p> </div> ) : null} </CardContent> </Card> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import type { InertiaFormProps } from '@inertiajs/react';import type { ReactNode } from 'react';
import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import type { RetrievalForm } from '@/types/admin';
export function ConfigError({ message }: { message?: string }) { if (!message) { return null; }
return <p className="text-sm font-medium text-destructive">{message}</p>;}
export function Field({ children, label,}: { children: ReactNode; label: string;}) { return ( <div className="grid gap-2"> <Label>{label}</Label> {children} </div> );}
export function RetrievalNumberField({ form, label, name, step = '1',}: { form: InertiaFormProps<RetrievalForm>; label: string; name: keyof Omit<RetrievalForm, 'enable_reranker' | 'reranker_model'>; step?: string;}) { return ( <Field label={label}> <Input min="0" step={step} type="number" value={form.data[name]} onChange={(event) => form.setData(name, event.target.value)} /> </Field> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import { useForm } from '@inertiajs/react';import { Save } from 'lucide-react';import type { FormEvent } from 'react';
import { updateLlmConfig } from '@/actions/App/Http/Controllers/AdminController';import { ConfigError, Field } from '@/components/admin/admin-form-parts';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import { Input } from '@/components/ui/input';import { Spinner } from '@/components/ui/spinner';import { readError, stringValue } from '@/lib/admin';import type { LlmConfig, LlmForm } from '@/types/admin';
export function AdminLlmForm({ llm }: { llm?: LlmConfig | null }) { const llmConfig = llm ?? {}; const llmForm = useForm<LlmForm>({ api_key_env: stringValue(llmConfig.api_key_env), base_url: stringValue(llmConfig.base_url), max_tokens: stringValue(llmConfig.max_tokens), model: stringValue(llmConfig.model), provider: stringValue(llmConfig.provider), reasoning_effort: stringValue(llmConfig.reasoning_effort), request_timeout: stringValue(llmConfig.request_timeout), system_prompt: stringValue(llmConfig.system_prompt), temperature: stringValue(llmConfig.temperature), });
function handleLlmSubmit(event: FormEvent<HTMLFormElement>): void { event.preventDefault(); llmForm.patch(updateLlmConfig.url(), { preserveScroll: true }); }
return ( <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle>LLM Config</CardTitle> <CardDescription> Ubah provider, model, timeout, token, dan system prompt. </CardDescription> </CardHeader> <CardContent> <form className="grid gap-4" onSubmit={handleLlmSubmit}> <ConfigError message={readError(llmForm.errors, 'llm')} />
<div className="grid gap-3 md:grid-cols-2"> <Field label="Provider"> <Input value={llmForm.data.provider} onChange={(event) => llmForm.setData( 'provider', event.target.value, ) } /> </Field> <Field label="Model"> <Input value={llmForm.data.model} onChange={(event) => llmForm.setData( 'model', event.target.value, ) } /> </Field> <Field label="Base URL"> <Input value={llmForm.data.base_url} onChange={(event) => llmForm.setData( 'base_url', event.target.value, ) } /> </Field> <Field label="API Key Env"> <Input value={llmForm.data.api_key_env} onChange={(event) => llmForm.setData( 'api_key_env', event.target.value, ) } /> </Field> <Field label="Reasoning Effort"> <Input value={llmForm.data.reasoning_effort} onChange={(event) => llmForm.setData( 'reasoning_effort', event.target.value, ) } /> </Field> <Field label="Temperature"> <Input min="0" step="0.01" type="number" value={llmForm.data.temperature} onChange={(event) => llmForm.setData( 'temperature', event.target.value, ) } /> </Field> <Field label="Max Tokens"> <Input min="1" type="number" value={llmForm.data.max_tokens} onChange={(event) => llmForm.setData( 'max_tokens', event.target.value, ) } /> </Field> <Field label="Request Timeout"> <Input min="1" type="number" value={llmForm.data.request_timeout} onChange={(event) => llmForm.setData( 'request_timeout', event.target.value, ) } /> </Field> </div>
<Field label="System Prompt"> <textarea className="border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring min-h-36 w-full rounded-md border px-3 py-2 text-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none" value={llmForm.data.system_prompt} onChange={(event) => llmForm.setData( 'system_prompt', event.target.value, ) } /> </Field>
<div className="flex justify-end"> <Button disabled={llmForm.processing} type="submit"> {llmForm.processing ? ( <Spinner className="size-4" /> ) : ( <Save className="size-4" /> )} Simpan LLM </Button> </div> </form> </CardContent> </Card> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586import { Search, Shield, Users } from 'lucide-react';import { useMemo } from 'react';
import { Badge } from '@/components/ui/badge';import { Card, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import { isUserActive } from '@/lib/admin';import type { AdminUser, RagConfig } from '@/types/admin';
export function AdminOverviewCards({ ragConfig, users = [],}: { ragConfig?: RagConfig | null; users?: AdminUser[];}) { const userStats = useMemo(() => { const activeCount = users.filter(isUserActive).length; const adminCount = users.filter((user) => user.role === 'admin').length;
return { activeCount, adminCount, total: users.length, }; }, [users]);
return ( <section className="grid gap-4 md:grid-cols-3"> <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader className="gap-3"> <div className="flex items-center justify-between gap-3"> <span className="rounded-xl bg-[var(--app-primary-soft)] p-3 text-[var(--app-primary)]"> <Shield className="size-5" /> </span> <Badge variant="outline">LLM</Badge> </div> <div> <CardDescription>Model aktif</CardDescription> <CardTitle className="mt-2 text-2xl"> {ragConfig?.llm?.model ?? '-'} </CardTitle> </div> </CardHeader> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader className="gap-3"> <div className="flex items-center justify-between gap-3"> <span className="rounded-xl bg-[var(--app-primary-soft)] p-3 text-[var(--app-primary)]"> <Search className="size-5" /> </span> <Badge variant="outline">Retrieval</Badge> </div> <div> <CardDescription>Top K</CardDescription> <CardTitle className="mt-2 text-2xl"> {ragConfig?.retrieval?.top_k ?? '-'} </CardTitle> </div> </CardHeader> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader className="gap-3"> <div className="flex items-center justify-between gap-3"> <span className="rounded-xl bg-[var(--app-primary-soft)] p-3 text-[var(--app-primary)]"> <Users className="size-5" /> </span> <Badge variant="outline">User</Badge> </div> <div> <CardDescription>User aktif</CardDescription> <CardTitle className="mt-2 text-2xl"> {userStats.activeCount}/{userStats.total} </CardTitle> </div> </CardHeader> </Card> </section> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import { Head } from '@inertiajs/react';import { AlertCircle } from 'lucide-react';import type { ReactNode } from 'react';
import { AdminShell } from '@/components/admin/admin-shell';import type { AdminMenu } from '@/components/admin/admin-shell';import AppearanceToggle from '@/components/appearance-toggle';import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
export function AdminPage({ activeMenu, backendMessage, children, description, title,}: { activeMenu: AdminMenu; backendMessage?: string | null; children: ReactNode; description: string; title: string;}) { return ( <> <Head title={title} />
<AdminShell activeMenu={activeMenu}> <main className="lecturer-page"> <section className="lecturer-page-header"> <div> <h1>{title}</h1> <p>{description}</p> </div>
<div className="lecturer-header-actions"> <AppearanceToggle className="lecturer-theme-toggle" /> </div> </section>
{backendMessage ? ( <Alert className="border-destructive/30 bg-destructive/10" variant="destructive" > <AlertCircle className="size-4" /> <AlertTitle>Response backend</AlertTitle> <AlertDescription>{backendMessage}</AlertDescription> </Alert> ) : null}
{children} </main> </AdminShell> </> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import { Database, FileSliders, Search, Shield } from 'lucide-react';
import { Badge } from '@/components/ui/badge';import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import type { RagConfig } from '@/types/admin';
function valueOrDash(value: unknown): string { if (value === null || value === undefined || value === '') { return '-'; }
if (typeof value === 'boolean') { return value ? 'Ya' : 'Tidak'; }
return String(value);}
function ConfigRows({ rows,}: { rows: Array<[label: string, value: unknown]>;}) { return ( <dl className="grid gap-3 text-sm"> {rows.map(([label, value]) => ( <div className="flex items-start justify-between gap-4 rounded-lg border border-[var(--app-border)] px-3 py-2" key={label} > <dt className="text-muted-foreground">{label}</dt> <dd className="max-w-[60%] text-right font-medium break-words"> {valueOrDash(value)} </dd> </div> ))} </dl> );}
export function AdminRagSummary({ ragConfig,}: { ragConfig?: RagConfig | null;}) { const llm = ragConfig?.llm ?? {}; const vectorDb = ragConfig?.vector_db ?? {}; const retrieval = ragConfig?.retrieval ?? {};
return ( <section className="grid gap-6 xl:grid-cols-2"> <Card className="border-[var(--app-border)] bg-[var(--app-surface)] xl:col-span-2"> <CardHeader className="gap-3"> <div className="flex items-center justify-between gap-3"> <span className="rounded-xl bg-[var(--app-primary-soft)] p-3 text-[var(--app-primary)]"> <FileSliders className="size-5" /> </span> <Badge variant="outline">RAG</Badge> </div> <div> <CardTitle>Konfigurasi RAG</CardTitle> <CardDescription> Path config: {ragConfig?.path ?? '-'} </CardDescription> </div> </CardHeader> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle className="flex items-center gap-2"> <Shield className="size-5 text-[var(--app-primary)]" /> LLM </CardTitle> <CardDescription>Ringkasan model aktif.</CardDescription> </CardHeader> <CardContent> <ConfigRows rows={[ ['Provider', llm.provider], ['Model', llm.model], ['Base URL', llm.base_url], ['API Key Env', llm.api_key_env], ['Temperature', llm.temperature], ['Max Tokens', llm.max_tokens], ['Request Timeout', llm.request_timeout], ]} /> </CardContent> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle className="flex items-center gap-2"> <Database className="size-5 text-[var(--app-primary)]" /> VectorDB </CardTitle> <CardDescription>Ringkasan embedding dan chunk.</CardDescription> </CardHeader> <CardContent> <ConfigRows rows={[ ['Embedding Model', vectorDb.embedding_model], ['Persist Path', vectorDb.persist_path], ['Chunk Size', vectorDb.chunk_size], ['Chunk Overlap', vectorDb.chunk_overlap], ]} /> </CardContent> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)] xl:col-span-2"> <CardHeader> <CardTitle className="flex items-center gap-2"> <Search className="size-5 text-[var(--app-primary)]" /> Retrieval </CardTitle> <CardDescription> Ringkasan bobot dan batas konteks retrieval. </CardDescription> </CardHeader> <CardContent> <ConfigRows rows={[ ['Top K', retrieval.top_k], ['Max Context Chars', retrieval.max_context_chars], ['BM25 Weight', retrieval.bm25_weight], ['Dense Weight', retrieval.dense_weight], ['Lexical Weight', retrieval.lexical_weight], [ 'Similarity Threshold', retrieval.similarity_threshold, ], ['History Turns', retrieval.history_turns], [ 'Candidate Pool Size', retrieval.candidate_pool_size, ], ['Neighbor Window', retrieval.neighbor_window], ['Reranker Model', retrieval.reranker_model], ['Enable Reranker', retrieval.enable_reranker], ]} /> </CardContent> </Card> </section> );}122345678910111226 unmodified lines394041424336444546473948495051525354555694 unmodified lines151152153140154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186142187188189190144191192146147193194195196197import { router } from '@inertiajs/react';import { LayoutDashboard, LogOut, MessageSquare, Settings } from 'lucide-react';import { BrainCircuit, Database, FileSliders, LayoutDashboard, LogOut, MessageSquare,} from 'lucide-react';import type { CSSProperties, ReactNode } from 'react';import { useState, useSyncExternalStore } from 'react';
26 unmodified linesimport { clearAuthSession, getStoredAuthUser } from '@/lib/auth';import { dashboard as adminDashboard, llmConfig as adminLlmConfig, login as adminLogin, pengaturan as adminPengaturan, ragConfig as adminRagConfig, vectorRetrievalConfig as adminVectorRetrievalConfig,} from '@/routes/admin';
type AdminMenu = 'dashboard' | 'settings';export type AdminMenu = | 'dashboard' | 'llm-config' | 'rag-config' | 'settings' | 'vector-retrieval-config';
const adminSidebarStyle = { '--sidebar-width': '212px',94 unmodified lines <SidebarMenuItem> <SidebarMenuButton className="lecturer-nav-button" isActive={activeMenu === 'settings'} isActive={activeMenu === 'rag-config'} onClick={() => router.visit(adminRagConfig()) } tooltip="RAG Config" > <FileSliders className="size-4" /> <span>RAG Config</span> </SidebarMenuButton> </SidebarMenuItem>
<SidebarMenuItem> <SidebarMenuButton className="lecturer-nav-button" isActive={activeMenu === 'llm-config'} onClick={() => router.visit(adminLlmConfig()) } tooltip="LLM Config" > <BrainCircuit className="size-4" /> <span>LLM Config</span> </SidebarMenuButton> </SidebarMenuItem>
<SidebarMenuItem> <SidebarMenuButton className="lecturer-nav-button" isActive={ activeMenu === 'vector-retrieval-config' } onClick={() => router.visit(adminPengaturan()) router.visit( adminVectorRetrievalConfig(), ) } tooltip="Pengaturan" tooltip="VectorDB & Retrieval" > <Settings className="size-4" /> <span>Pengaturan</span> <Database className="size-4" /> <span>VectorDB & Retrieval</span> </SidebarMenuButton> </SidebarMenuItem> </SidebarMenu>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import { router, useForm } from '@inertiajs/react';import type { InertiaFormProps } from '@inertiajs/react';import { Search, Trash2, UserPlus } from 'lucide-react';import type { FormEvent } from 'react';import { useMemo, useState } from 'react';
import { destroyUser, index as adminIndex, storeUser, updateUser,} from '@/actions/App/Http/Controllers/AdminController';import { ConfigError, Field } from '@/components/admin/admin-form-parts';import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import { Checkbox } from '@/components/ui/checkbox';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,} from '@/components/ui/dialog';import { Input } from '@/components/ui/input';import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from '@/components/ui/select';import { Spinner } from '@/components/ui/spinner';import { buildFilterQuery, emptyUserForm, formatDate, isUserActive, readError, roleLabel, stringValue, userToForm,} from '@/lib/admin';import type { AdminRole, AdminUser, UserFilterForm, UserForm,} from '@/types/admin';
export function AdminUserCreateCard() { const userForm = useForm<UserForm>(emptyUserForm);
function handleStoreUser(event: FormEvent<HTMLFormElement>): void { event.preventDefault(); userForm.post(storeUser.url(), { onSuccess: () => userForm.reset(), preserveScroll: true, }); }
return ( <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle className="flex items-center gap-2"> <UserPlus className="size-5 text-[var(--app-primary)]" /> Tambah User </CardTitle> <CardDescription> Payload mengikuti schema UpsertUser dari API. </CardDescription> </CardHeader> <CardContent> <UserFormFields form={userForm} onSubmit={handleStoreUser} submitLabel="Buat User" /> </CardContent> </Card> );}
export function AdminUserManagement({ userFilters, users = [],}: { userFilters?: Record<string, unknown>; users?: AdminUser[];}) { const [editingUser, setEditingUser] = useState<AdminUser | null>(null); const [deletingUser, setDeletingUser] = useState<AdminUser | null>(null);
const editUserForm = useForm<UserForm>(emptyUserForm); const deleteUserForm = useForm({}); const filterForm = useForm<UserFilterForm>({ email: stringValue(userFilters?.email), name: stringValue(userFilters?.name), role: userFilters?.role === 'student' || userFilters?.role === 'lecturer' || userFilters?.role === 'admin' ? userFilters.role : 'all', });
const userStats = useMemo(() => { const adminCount = users.filter((user) => user.role === 'admin').length;
return { adminCount, total: users.length, }; }, [users]);
function handleUserFilter(event: FormEvent<HTMLFormElement>): void { event.preventDefault(); router.get(adminIndex.url(), buildFilterQuery(filterForm.data), { preserveScroll: true, preserveState: true, }); }
function openEditUserDialog(user: AdminUser): void { setEditingUser(user); editUserForm.setData(userToForm(user)); editUserForm.clearErrors(); }
function handleUpdateUser(event: FormEvent<HTMLFormElement>): void { event.preventDefault();
if (!editingUser) { return; }
editUserForm.patch(updateUser.url(editingUser.id), { onSuccess: () => setEditingUser(null), preserveScroll: true, }); }
function handleDestroyUser(): void { if (!deletingUser) { return; }
deleteUserForm.delete(destroyUser.url(deletingUser.id), { onSuccess: () => setDeletingUser(null), preserveScroll: true, }); }
return ( <> <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between"> <div> <CardTitle>User Management</CardTitle> <CardDescription> Total {userStats.total} user,{' '} {userStats.adminCount} admin. </CardDescription> </div>
<form className="grid gap-2 sm:grid-cols-[1fr_1fr_160px_auto]" onSubmit={handleUserFilter} > <Input placeholder="Cari nama..." value={filterForm.data.name} onChange={(event) => filterForm.setData( 'name', event.target.value, ) } /> <Input placeholder="Cari email..." value={filterForm.data.email} onChange={(event) => filterForm.setData( 'email', event.target.value, ) } /> <Select value={filterForm.data.role} onValueChange={(value) => filterForm.setData( 'role', value as UserFilterForm['role'], ) } > <SelectTrigger className="w-full"> <SelectValue placeholder="Role" /> </SelectTrigger> <SelectContent> <SelectItem value="all"> Semua role </SelectItem> <SelectItem value="student"> Mahasiswa </SelectItem> <SelectItem value="lecturer"> Dosen </SelectItem> <SelectItem value="admin">Admin</SelectItem> </SelectContent> </Select> <Button type="submit"> {filterForm.processing ? ( <Spinner className="size-4" /> ) : ( <Search className="size-4" /> )} Cari </Button> </form> </div> </CardHeader> <CardContent> <div className="overflow-hidden rounded-xl border border-[var(--app-border)]"> <div className="overflow-x-auto"> <table className="w-full min-w-[760px] text-sm"> <thead className="bg-muted/50 text-left text-muted-foreground"> <tr> <th className="px-4 py-3">Nama</th> <th className="px-4 py-3">Role</th> <th className="px-4 py-3">Status</th> <th className="px-4 py-3"> Superuser </th> <th className="px-4 py-3">Dibuat</th> <th className="px-4 py-3 text-right"> Aksi </th> </tr> </thead> <tbody> {users.map((user) => ( <tr className="border-t border-[var(--app-border)]" key={user.id} > <td className="px-4 py-3"> <div className="font-medium"> {user.name ?? '-'} </div> <div className="text-muted-foreground"> {user.email ?? '-'} </div> </td> <td className="px-4 py-3"> <Badge variant="outline"> {roleLabel(user.role)} </Badge> </td> <td className="px-4 py-3"> <Badge className={ isUserActive(user) ? 'bg-[var(--app-primary-soft)] text-[var(--app-primary)]' : '' } variant={ isUserActive(user) ? 'secondary' : 'outline' } > {isUserActive(user) ? 'Aktif' : 'Nonaktif'} </Badge> </td> <td className="px-4 py-3"> {user.is_superuser ? 'Ya' : 'Tidak'} </td> <td className="px-4 py-3"> {formatDate(user.created_at)} </td> <td className="px-4 py-3"> <div className="flex justify-end gap-2"> <Button onClick={() => openEditUserDialog( user, ) } size="sm" type="button" variant="outline" > Edit </Button> <Button className="text-destructive hover:text-destructive" onClick={() => setDeletingUser( user, ) } size="sm" type="button" variant="outline" > <Trash2 className="size-4" /> </Button> </div> </td> </tr> ))}
{users.length === 0 ? ( <tr> <td className="px-4 py-8 text-center text-muted-foreground" colSpan={6} > Tidak ada user dari response backend. </td> </tr> ) : null} </tbody> </table> </div> </div> </CardContent> </Card>
<Dialog onOpenChange={(open) => setEditingUser(open ? editingUser : null)} open={editingUser !== null} > <DialogContent className="max-w-2xl"> <DialogHeader> <DialogTitle>Edit User</DialogTitle> <DialogDescription> Perubahan dikirim ke endpoint update user backend. </DialogDescription> </DialogHeader>
<UserFormFields form={editUserForm} onSubmit={handleUpdateUser} submitLabel="Simpan User" /> </DialogContent> </Dialog>
<Dialog onOpenChange={(open) => setDeletingUser(open ? deletingUser : null)} open={deletingUser !== null} > <DialogContent> <DialogHeader> <DialogTitle>Hapus user?</DialogTitle> <DialogDescription> User {deletingUser?.email ?? '-'} akan dihapus lewat backend API. </DialogDescription> </DialogHeader> <DialogFooter> <Button onClick={() => setDeletingUser(null)} type="button" variant="outline" > Batal </Button> <Button className="bg-destructive text-white hover:bg-destructive/90" disabled={deleteUserForm.processing} onClick={handleDestroyUser} type="button" > {deleteUserForm.processing ? ( <Spinner className="size-4" /> ) : null} Hapus </Button> </DialogFooter> </DialogContent> </Dialog> </> );}
function UserFormFields({ form, onSubmit, submitLabel,}: { form: InertiaFormProps<UserForm>; onSubmit: (event: FormEvent<HTMLFormElement>) => void; submitLabel: string;}) { return ( <form className="grid gap-4" onSubmit={onSubmit}> <ConfigError message={readError(form.errors, 'user')} />
<div className="grid gap-3 md:grid-cols-2"> <Field label="Nama"> <Input value={form.data.name} onChange={(event) => form.setData('name', event.target.value) } /> </Field> <Field label="Email"> <Input type="email" value={form.data.email} onChange={(event) => form.setData('email', event.target.value) } /> </Field> <Field label="Nomor Identitas"> <Input value={form.data.identity_number} onChange={(event) => form.setData( 'identity_number', event.target.value, ) } /> </Field> <Field label="Telepon"> <Input value={form.data.phone} onChange={(event) => form.setData('phone', event.target.value) } /> </Field> <Field label="Role"> <Select value={form.data.role} onValueChange={(value) => form.setData('role', value as AdminRole) } > <SelectTrigger className="w-full"> <SelectValue placeholder="Pilih role" /> </SelectTrigger> <SelectContent> <SelectItem value="student">Mahasiswa</SelectItem> <SelectItem value="lecturer">Dosen</SelectItem> <SelectItem value="admin">Admin</SelectItem> </SelectContent> </Select> </Field> <Field label="User Token"> <Input value={form.data.user_token} onChange={(event) => form.setData('user_token', event.target.value) } /> </Field> </div>
<div className="grid gap-3 sm:grid-cols-2"> <label className="flex items-center gap-3 rounded-lg border border-[var(--app-border)] p-3 text-sm"> <Checkbox checked={form.data.is_active} onCheckedChange={(value) => form.setData('is_active', value === true) } /> User aktif </label> <label className="flex items-center gap-3 rounded-lg border border-[var(--app-border)] p-3 text-sm"> <Checkbox checked={form.data.is_superuser} onCheckedChange={(value) => form.setData('is_superuser', value === true) } /> Superuser </label> </div>
<div className="flex justify-end"> <Button disabled={form.processing} type="submit"> {form.processing ? <Spinner className="size-4" /> : null} {submitLabel} </Button> </div> </form> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277import { useForm } from '@inertiajs/react';import { Save } from 'lucide-react';import type { FormEvent } from 'react';
import { updateRetrievalConfig, updateVectorDbConfig,} from '@/actions/App/Http/Controllers/AdminController';import { ConfigError, Field, RetrievalNumberField,} from '@/components/admin/admin-form-parts';import { Button } from '@/components/ui/button';import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from '@/components/ui/card';import { Checkbox } from '@/components/ui/checkbox';import { Input } from '@/components/ui/input';import { Spinner } from '@/components/ui/spinner';import { readError, stringValue } from '@/lib/admin';import type { RetrievalConfig, RetrievalForm, VectorDbConfig, VectorDbForm,} from '@/types/admin';
export function AdminVectorRetrievalForms({ retrieval, vectorDb,}: { retrieval?: RetrievalConfig | null; vectorDb?: VectorDbConfig | null;}) { const vectorDbConfig = vectorDb ?? {}; const retrievalConfig = retrieval ?? {};
const vectorDbForm = useForm<VectorDbForm>({ chunk_overlap: stringValue(vectorDbConfig.chunk_overlap), chunk_size: stringValue(vectorDbConfig.chunk_size), embedding_model: stringValue(vectorDbConfig.embedding_model), persist_path: stringValue(vectorDbConfig.persist_path), });
const retrievalForm = useForm<RetrievalForm>({ bm25_weight: stringValue(retrievalConfig.bm25_weight), candidate_pool_size: stringValue(retrievalConfig.candidate_pool_size), dense_weight: stringValue(retrievalConfig.dense_weight), enable_reranker: Boolean(retrievalConfig.enable_reranker), history_turns: stringValue(retrievalConfig.history_turns), lexical_weight: stringValue(retrievalConfig.lexical_weight), max_context_chars: stringValue(retrievalConfig.max_context_chars), neighbor_window: stringValue(retrievalConfig.neighbor_window), reranker_model: stringValue(retrievalConfig.reranker_model), similarity_threshold: stringValue(retrievalConfig.similarity_threshold), top_k: stringValue(retrievalConfig.top_k), });
function handleVectorDbSubmit(event: FormEvent<HTMLFormElement>): void { event.preventDefault(); vectorDbForm.patch(updateVectorDbConfig.url(), { preserveScroll: true, }); }
function handleRetrievalSubmit(event: FormEvent<HTMLFormElement>): void { event.preventDefault(); retrievalForm.patch(updateRetrievalConfig.url(), { preserveScroll: true, }); }
return ( <section className="grid gap-6 xl:grid-cols-2"> <Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle>VectorDB Config</CardTitle> <CardDescription> Atur model embedding dan konfigurasi chunking dokumen. </CardDescription> </CardHeader> <CardContent> <form className="grid gap-4" onSubmit={handleVectorDbSubmit} > <ConfigError message={readError(vectorDbForm.errors, 'vectorDb')} />
<div className="grid gap-3 md:grid-cols-2"> <Field label="Embedding Model"> <Input value={vectorDbForm.data.embedding_model} onChange={(event) => vectorDbForm.setData( 'embedding_model', event.target.value, ) } /> </Field> <Field label="Persist Path"> <Input value={vectorDbForm.data.persist_path} onChange={(event) => vectorDbForm.setData( 'persist_path', event.target.value, ) } /> </Field> <Field label="Chunk Size"> <Input min="1" type="number" value={vectorDbForm.data.chunk_size} onChange={(event) => vectorDbForm.setData( 'chunk_size', event.target.value, ) } /> </Field> <Field label="Chunk Overlap"> <Input min="0" type="number" value={vectorDbForm.data.chunk_overlap} onChange={(event) => vectorDbForm.setData( 'chunk_overlap', event.target.value, ) } /> </Field> </div>
<div className="flex justify-end"> <Button disabled={vectorDbForm.processing} type="submit" > {vectorDbForm.processing ? ( <Spinner className="size-4" /> ) : ( <Save className="size-4" /> )} Simpan Vector </Button> </div> </form> </CardContent> </Card>
<Card className="border-[var(--app-border)] bg-[var(--app-surface)]"> <CardHeader> <CardTitle>Retrieval Config</CardTitle> <CardDescription> Atur bobot retrieval, reranker, dan konteks jawaban. </CardDescription> </CardHeader> <CardContent> <form className="grid gap-4" onSubmit={handleRetrievalSubmit} > <ConfigError message={readError( retrievalForm.errors, 'retrieval', )} />
<div className="grid gap-3 md:grid-cols-2"> <RetrievalNumberField form={retrievalForm} label="Top K" name="top_k" /> <RetrievalNumberField form={retrievalForm} label="Max Context Chars" name="max_context_chars" /> <RetrievalNumberField form={retrievalForm} label="BM25 Weight" name="bm25_weight" step="0.01" /> <RetrievalNumberField form={retrievalForm} label="Dense Weight" name="dense_weight" step="0.01" /> <RetrievalNumberField form={retrievalForm} label="Lexical Weight" name="lexical_weight" step="0.01" /> <RetrievalNumberField form={retrievalForm} label="Similarity Threshold" name="similarity_threshold" step="0.01" /> <RetrievalNumberField form={retrievalForm} label="History Turns" name="history_turns" /> <RetrievalNumberField form={retrievalForm} label="Candidate Pool" name="candidate_pool_size" /> <RetrievalNumberField form={retrievalForm} label="Neighbor Window" name="neighbor_window" /> <Field label="Reranker Model"> <Input value={retrievalForm.data.reranker_model} onChange={(event) => retrievalForm.setData( 'reranker_model', event.target.value, ) } /> </Field> </div>
<label className="flex items-center gap-3 text-sm"> <Checkbox checked={retrievalForm.data.enable_reranker} onCheckedChange={(value) => retrievalForm.setData( 'enable_reranker', value === true, ) } /> Enable reranker </label>
<div className="flex justify-end"> <Button disabled={retrievalForm.processing} type="submit" > {retrievalForm.processing ? ( <Spinner className="size-4" /> ) : ( <Save className="size-4" /> )} Simpan Retrieval </Button> </div> </form> </CardContent> </Card> </section> );}6 unmodified lines789101011121323 unmodified lines37383940414243444546475 unmodified lines535455545657585911 unmodified lines717273747576777578798081828315 unmodified lines99100101981021031041055 unmodified lines11111211311411511611711811912012112212313 unmodified lines1371381391401411421433 unmodified lines147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187119 unmodified lines30730830931031131231331426731531631731831932032132232332449 unmodified lines37437537632337737837938038138238333038438538633338738838939014 unmodified lines4054064074084094104114124134144154164174184194204214224234244256 unmodified lines4324334343664354364374384394404413734424434444454463783793803814474484494506 unmodified linesimport { Card, CardContent } from '@/components/ui/card';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { LoadingIndicator } from '@/components/ui/loading-indicator';import { Spinner } from '@/components/ui/spinner';import { register } from '@/routes';import { store as registerStore } from '@/routes/auth/register';
23 unmodified lines identity_number: string; name: string; password: string; phone: string;};
type RegisterFormErrors = Partial<Record<keyof RegisterFormValues, string>>;type ServerErrors = Record<string, string | string[]>;type RegisterTouchedFields = Partial<Record<keyof RegisterFormValues, boolean>>;type RegisterPageProps = { flash?: {5 unmodified lines autoComplete?: string; autoFocus?: boolean; error?: string; inputMode?: 'email' | 'numeric' | 'text'; inputMode?: 'email' | 'numeric' | 'tel' | 'text'; label: string; name: string; onBlur?: () => void;11 unmodified lines identity_number: '', name: '', password: '', phone: '',};
const namePattern = /^[\p{L}\s.'-]+$/u;const identityNumberPattern = /^(?:\d{5,30}|[A-Z]{2,10}\d{3,30})$/;const identityNumberPattern = /^\d{5,30}$/;const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;const phonePattern = /^\+?\d{8,20}$/;
function validateRegisterForm( values: RegisterFormValues,15 unmodified lines if (!normalizedIdentityNumber) { errors.identity_number = `${identifierLabel} wajib diisi.`; } else if (!identityNumberPattern.test(normalizedIdentityNumber)) { errors.identity_number = `${identifierLabel} hanya boleh angka, atau kode huruf besar diikuti angka.`; errors.identity_number = `${identifierLabel} hanya boleh angka.`; }
if (!normalizedEmail) {5 unmodified lines errors.email = 'Format email tidak valid.'; }
const normalizedPhone = values.phone.trim().replace(/[\s().-]/g, '');
if (normalizedPhone && !phonePattern.test(normalizedPhone)) { errors.phone = 'Nomor telepon hanya boleh angka dan opsional diawali tanda +.'; }
if (!values.password) { errors.password = 'Password wajib diisi.'; } else if (values.password.length < 6) {13 unmodified lines identity_number: values.identity_number.trim(), name: values.name.trim().replace(/\s+/g, ' '), password: values.password, phone: values.phone.trim().replace(/[\s().-]/g, ''), };}
3 unmodified lines return Array.isArray(message) ? message[0] : message;}
function errorMessage(message?: string | string[]): string | undefined { return Array.isArray(message) ? message[0] : message;}
function splitServerErrors(errors: ServerErrors): { backendError?: string; fieldErrors: RegisterFormErrors;} { const nextFieldErrors: RegisterFormErrors = {}; const formFields = Object.keys(emptyFormValues);
for (const field of formFields as Array<keyof RegisterFormValues>) { const message = errorMessage(errors[field]);
if (message) { nextFieldErrors[field] = message; } }
const authError = errorMessage(errors.auth); const unmappedError = Object.entries(errors) .filter(([field]) => field !== 'auth' && !formFields.includes(field)) .map(([, message]) => errorMessage(message)) .find(Boolean); const hasFieldErrors = Object.keys(nextFieldErrors).length > 0;
return { backendError: authError ?? unmappedError ?? (hasFieldErrors ? undefined : firstError(errors)), fieldErrors: nextFieldErrors, };}
function RegisterField({ autoComplete, autoFocus = false,119 unmodified lines identity_number: normalizedValues.identity_number, name: normalizedValues.name, password: normalizedValues.password, phone: normalizedValues.phone, role: content.apiRole, }, { onError: (errors) => { setBackendError(firstError(errors)); const serverErrors = splitServerErrors(errors);
setFieldErrors((currentErrors) => ({ ...currentErrors, ...serverErrors.fieldErrors, })); setBackendError(serverErrors.backendError); }, onFinish: () => setIsProcessing(false), onStart: () => setIsProcessing(true),49 unmodified lines placeholder={content.identifierPlaceholder} autoComplete="off" error={fieldErrors.identity_number} inputMode="text" inputMode="numeric" onBlur={() => validateFieldOnBlur('identity_number') } onChange={(value) => updateField( 'identity_number', value.toUpperCase(), value.replace(/\D/g, ''), ) } pattern="(?:\d{5,30}|[A-Z]{2,10}\d{3,30})" pattern="\d{5,30}" required tabIndex={2} value={formValues.identity_number}14 unmodified lines tabIndex={3} value={formValues.email} /> <RegisterField name="phone" type="tel" label="Nomor Telepon" placeholder="08xxxxxxxxxx" autoComplete="tel" error={fieldErrors.phone} inputMode="tel" onBlur={() => validateFieldOnBlur('phone')} onChange={(value) => updateField('phone', value) } tabIndex={4} value={formValues.phone} /> <RegisterField name="password" type="password"6 unmodified lines updateField('password', value) } required tabIndex={4} tabIndex={5} value={formValues.password} />
<Button type="submit" className="register-submit" tabIndex={5} tabIndex={6} disabled={isProcessing} data-test="register-role-button" > {isProcessing ? ( <LoadingIndicator label="Mendaftar" spinnerClassName="size-3.5" /> <Spinner className="size-3.5" /> ) : ( 'Register' )}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import type { AdminRole, AdminUser, UserFilterForm, UserForm } from '@/types/admin';
export const emptyUserForm: UserForm = { email: '', identity_number: '', is_active: true, is_superuser: false, name: '', phone: '', role: 'student', user_token: '',};
export function stringValue(value: unknown): string { if (value === null || value === undefined) { return ''; }
return String(value);}
export function roleLabel(role?: AdminRole | null): string { return ( { admin: 'Admin', lecturer: 'Dosen', student: 'Mahasiswa', }[role ?? 'student'] ?? 'Mahasiswa' );}
export function isUserActive(user: AdminUser): boolean { if (typeof user.is_active === 'boolean') { return user.is_active; }
return user.status === 'active';}
export function formatDate(value?: string | null): string { if (!value) { return '-'; }
return value.split('T')[0] || value;}
export function readError(errors: object, key: string): string | undefined { return (errors as Record<string, string | undefined>)[key];}
export function userToForm(user: AdminUser): UserForm { return { email: stringValue(user.email), identity_number: stringValue(user.identity_number), is_active: isUserActive(user), is_superuser: Boolean(user.is_superuser), name: stringValue(user.name), phone: stringValue(user.phone), role: user.role ?? 'student', user_token: stringValue(user.user_token), };}
export function buildFilterQuery(filters: UserFilterForm): Record<string, string> { return Object.fromEntries( Object.entries({ email: filters.email, name: filters.name, role: filters.role === 'all' ? '' : filters.role, }).filter(([, value]) => value !== ''), );}1234567891011121314151617181920212223242526271import { Head } from '@inertiajs/react';
import { AdminShell } from '@/components/admin/admin-shell';import AppearanceToggle from '@/components/appearance-toggle';
export default function AdminDashboard() { return ( <> <Head title="Dashboard Admin" />
<AdminShell> <main className="lecturer-page"> <section className="lecturer-page-header"> <div> <h1>Dashboard Admin</h1> <p>Halaman ini masih kosong.</p> </div>
<div className="lecturer-header-actions"> <AppearanceToggle className="lecturer-theme-toggle" /> </div> </section> </main> </AdminShell> </> );}export { default } from './admin/dashboard';12345678910111213141516171819202122232425262728293031323334import { AdminApiKeyCard } from '@/components/admin/admin-api-key-card';import { AdminOverviewCards } from '@/components/admin/admin-overview-cards';import { AdminPage } from '@/components/admin/admin-page';import { AdminUserCreateCard, AdminUserManagement,} from '@/components/admin/admin-user-management';import type { AdminDashboardProps } from '@/types/admin';
export default function AdminDashboard({ backendMessage, generatedApiKey, ragConfig, userFilters, users = [],}: AdminDashboardProps) { return ( <AdminPage activeMenu="dashboard" backendMessage={backendMessage} description="Kelola akses iframe dan user dari satu tempat." title="Dashboard Admin" > <AdminOverviewCards ragConfig={ragConfig} users={users} />
<section className="grid gap-6 xl:grid-cols-[0.85fr_1.15fr]"> <AdminApiKeyCard generatedApiKey={generatedApiKey} /> <AdminUserCreateCard /> </section>
<AdminUserManagement userFilters={userFilters} users={users} /> </AdminPage> );}12345678910111213141516171819import { AdminLlmForm } from '@/components/admin/admin-llm-form';import { AdminPage } from '@/components/admin/admin-page';import type { AdminConfigPageProps } from '@/types/admin';
export default function AdminLlmConfig({ backendMessage, ragConfig,}: AdminConfigPageProps) { return ( <AdminPage activeMenu="llm-config" backendMessage={backendMessage} description="Kelola provider, model, dan parameter LLM." title="LLM Config" > <AdminLlmForm llm={ragConfig?.llm} /> </AdminPage> );}12345678910111213141516171819import { AdminPage } from '@/components/admin/admin-page';import { AdminRagSummary } from '@/components/admin/admin-rag-summary';import type { AdminConfigPageProps } from '@/types/admin';
export default function AdminRagConfig({ backendMessage, ragConfig,}: AdminConfigPageProps) { return ( <AdminPage activeMenu="rag-config" backendMessage={backendMessage} description="Lihat ringkasan konfigurasi RAG yang aktif dari backend." title="RAG Config" > <AdminRagSummary ragConfig={ragConfig} /> </AdminPage> );}12345678910111213141516171819202122import { AdminPage } from '@/components/admin/admin-page';import { AdminVectorRetrievalForms } from '@/components/admin/admin-vector-retrieval-forms';import type { AdminConfigPageProps } from '@/types/admin';
export default function AdminVectorRetrievalConfig({ backendMessage, ragConfig,}: AdminConfigPageProps) { return ( <AdminPage activeMenu="vector-retrieval-config" backendMessage={backendMessage} description="Kelola konfigurasi VectorDB dan Retrieval." title="VectorDB & Retrieval Config" > <AdminVectorRetrievalForms retrieval={ragConfig?.retrieval} vectorDb={ragConfig?.vector_db} /> </AdminPage> );}7 unmodified lines89101111121314128 unmodified lines1431441451461471481491461471481497 unmodified linesimport { Checkbox } from '@/components/ui/checkbox';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { LoadingIndicator } from '@/components/ui/loading-indicator';import { Spinner } from '@/components/ui/spinner';import { home } from '@/routes';import { store as adminLoginStore } from '@/routes/admin/login';import type { FlashToast } from '@/types/ui';128 unmodified lines data-test="admin-login-button" > {processing ? ( <LoadingIndicator label="Masuk" spinnerClassName="size-3.5" /> <Spinner className="size-3.5" /> ) : ( 'Sign In' )}7 unmodified lines89101111121314128 unmodified lines1431441451461471481491461471481497 unmodified linesimport { Checkbox } from '@/components/ui/checkbox';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';import { LoadingIndicator } from '@/components/ui/loading-indicator';import { Spinner } from '@/components/ui/spinner';import { home, register } from '@/routes';import { store as loginStore } from '@/routes/auth/login';import type { FlashToast } from '@/types/ui';128 unmodified lines data-test="login-button" > {processing ? ( <LoadingIndicator label="Masuk" spinnerClassName="size-3.5" /> <Spinner className="size-3.5" /> ) : ( 'Sign In' )}122345678910111213141583 unmodified lines99100101921029410310410579 unmodified lines185186187180188189190191192193194import { Head, router } from '@inertiajs/react';import { BookOpen, Bot, MessageSquare, Plus, Send, Sparkles, Trash2, UserRound, X } from 'lucide-react';import { BookOpen, Bot, MessageSquare, Plus, Send, Sparkles, Trash2, UserRound, X,} from 'lucide-react';import type { CSSProperties, FormEvent, KeyboardEvent } from 'react';import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
83 unmodified lines }
const params = new URLSearchParams(window.location.search); params.delete('api_key'); params.delete('pending_id'); params.delete('token');
for (const [key, value] of Object.entries(overrides)) { if (value === null || value === '') {79 unmodified lines <div className="embed-message-bubble"> <p className="embed-message-content"> {!isUser && shouldAnimateTyping ? ( <TypingText key={message.uuid_id} text={message.content} /> <TypingText key={message.uuid_id} text={message.content} /> ) : ( message.content )}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124export type AdminRole = 'student' | 'lecturer' | 'admin';
export type LlmConfig = { api_key_env?: string | null; base_url?: string | null; max_tokens?: number | null; model?: string | null; provider?: string | null; reasoning_effort?: string | null; request_timeout?: number | null; system_prompt?: string | null; temperature?: number | null;};
export type VectorDbConfig = { chunk_overlap?: number | null; chunk_size?: number | null; embedding_model?: string | null; persist_path?: string | null;};
export type RetrievalConfig = { bm25_weight?: number | null; candidate_pool_size?: number | null; dense_weight?: number | null; enable_reranker?: boolean | null; history_turns?: number | null; lexical_weight?: number | null; max_context_chars?: number | null; neighbor_window?: number | null; reranker_model?: string | null; similarity_threshold?: number | null; top_k?: number | null;};
export type RagConfig = { llm?: LlmConfig | null; path?: string | null; retrieval?: RetrievalConfig | null; vector_db?: VectorDbConfig | null;};
export type AdminUser = { created_at?: string | null; email?: string | null; id: number; identity_number?: string | null; is_active?: boolean | null; is_superuser?: boolean | null; name?: string | null; phone?: string | null; role?: AdminRole | null; status?: 'active' | 'inactive' | null; updated_at?: string | null; user_token?: string | null;};
export type GeneratedApiKey = { api_key: string; expires_at?: string | null;};
export type AdminDashboardProps = { backendMessage?: string | null; generatedApiKey?: GeneratedApiKey | null; ragConfig?: RagConfig | null; userFilters?: Record<string, unknown>; users?: AdminUser[];};
export type AdminConfigPageProps = { backendMessage?: string | null; ragConfig?: RagConfig | null;};
export type LlmForm = { api_key_env: string; base_url: string; max_tokens: string; model: string; provider: string; reasoning_effort: string; request_timeout: string; system_prompt: string; temperature: string;};
export type VectorDbForm = { chunk_overlap: string; chunk_size: string; embedding_model: string; persist_path: string;};
export type RetrievalForm = { bm25_weight: string; candidate_pool_size: string; dense_weight: string; enable_reranker: boolean; history_turns: string; lexical_weight: string; max_context_chars: string; neighbor_window: string; reranker_model: string; similarity_threshold: string; top_k: string;};
export type UserForm = { email: string; identity_number: string; is_active: boolean; is_superuser: boolean; name: string; phone: string; role: AdminRole; user_token: string;};
export type UserFilterForm = { email: string; name: string; role: AdminRole | 'all';};36 unmodified lines373839404142434445464748495051525354555657585960616236 unmodified linesRoute::middleware('rag.auth:admin')->prefix('admin')->name('admin.')->group(function (): void { Route::get('/', [AdminController::class, 'index'])->name('dashboard');
Route::get('rag-config', [AdminController::class, 'ragConfig'])->name('rag-config');
Route::get('llm-config', [AdminController::class, 'llmConfig'])->name('llm-config');
Route::get('vector-retrieval-config', [AdminController::class, 'vectorRetrievalConfig'])->name('vector-retrieval-config');
Route::post('api-keys', [AdminController::class, 'generateApiKey'])->name('api-keys.store');
Route::patch('rag/llm', [AdminController::class, 'updateLlmConfig'])->name('rag.llm.update');
Route::patch('rag/retrieval', [AdminController::class, 'updateRetrievalConfig'])->name('rag.retrieval.update');
Route::patch('rag/vector-db', [AdminController::class, 'updateVectorDbConfig'])->name('rag.vector-db.update');
Route::post('users', [AdminController::class, 'storeUser'])->name('users.store');
Route::patch('users/{userId}', [AdminController::class, 'updateUser'])->name('users.update');
Route::delete('users/{userId}', [AdminController::class, 'destroyUser'])->name('users.destroy');
Route::get('pengaturan', [AdminController::class, 'settings'])->name('pengaturan');});
100 unmodified lines101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147397 unmodified lines545546547548549550551552553554555556557558559608 unmodified lines11681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122738 unmodified lines1266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518464 unmodified lines198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209148 unmodified lines214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421659 unmodified lines217521762177217821792180218121822183218429 unmodified lines22142215221617432217221817452219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224717472248224922501749225122521751225322542255175317541755175617571758175917601761176222562257225822592260176422612262176617671768176917701771177217731774177517762263226422651778177917801781226622672268226922702271227222732274227522762277178517862278227917882280228117901791179222822283228422852286228722882289179422902291229222932294229522962297229822992300230123022303179617972304230523062307230823092310231123122313179918002314231523162317231823192320232123222323232423252326232718041805232823292330233123322333233423352336233723382339234023412342180723432344180918101811181218132345234618151816234723481818181918202349235023512352182218232353235423552356235723582359236023612362236318251826182723642365236623672368236918311832183318341835183618371838237023712372237346 unmodified lines242024212422242324242425242624272428242927 unmodified lines245724582459246024612462246324642465246641 unmodified lines250825092510251125122513251425152516251763 unmodified lines258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634100 unmodified lines } } }, "/api/v1/auth/activate/{token}": { "get": { "tags": ["v1", "auth"], "summary": "Activate Account", "description": "Activate an account from an email verification link.", "operationId": "activate_account_api_v1_auth_activate__token__get", "parameters": [ { "required": true, "schema": { "type": "string", "title": "Token" }, "name": "token", "in": "path" } ], "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ActivateAccountResponse" } } } }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } } } } } }, "/api/v1/auth/login/api-key": { "post": { "tags": ["v1", "auth"],397 unmodified lines "name": "name", "in": "query" }, { "required": false, "schema": { "type": "string", "title": "Phone" }, "name": "phone", "in": "query" }, { "required": false, "schema": {608 unmodified lines ] } }, "/api/v1/chats/sessions/{session_id}/stream": { "post": { "tags": ["v1", "Chat"], "summary": "Stream message (SSE)", "description": "Send a message to AI and stream the response via Server-Sent Events (SSE).", "operationId": "send_message_stream_sse_api_v1_chats_sessions__session_id__stream_post", "parameters": [ { "required": true, "schema": { "type": "string", "title": "Session Id" }, "name": "session_id", "in": "path" } ], "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ChatRESTRequest" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": {} } } }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } } } }, "security": [ { "JWTBearer": [] } ] } }, "/api/v1/ai/query": { "post": { "tags": ["v1", "Chat"],38 unmodified lines } ] } }, "/api/v1/admin/rag/config": { "get": { "tags": ["v1", "admin"], "summary": "Get full RAG config", "description": "Returns the current LLM, VectorDB, and Retrieval configuration from the YAML file.", "operationId": "get_full_config_api_v1_admin_rag_config_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RAGConfigResponse" } } } } }, "security": [ { "JWTBearer": [] } ] } }, "/api/v1/admin/rag/config/llm": { "get": { "tags": ["v1", "admin"], "summary": "Get LLM config", "description": "Returns the current LLM configuration (model, temperature, max_tokens, request_timeout).", "operationId": "get_llm_config_api_v1_admin_rag_config_llm_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LLMConfigResponse" } } } } }, "security": [ { "JWTBearer": [] } ] }, "patch": { "tags": ["v1", "admin"], "summary": "Update LLM config", "description": "Partially update the LLM configuration. Only provided fields will be changed.", "operationId": "update_llm_config_api_v1_admin_rag_config_llm_patch", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LLMConfigPayload" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/LLMConfigResponse" } } } }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } } } }, "security": [ { "JWTBearer": [] } ] } }, "/api/v1/admin/rag/config/vector_db": { "get": { "tags": ["v1", "admin"], "summary": "Get VectorDB config", "description": "Returns the current VectorDB configuration (embedding model, chunk settings, persist path).", "operationId": "get_vector_db_config_api_v1_admin_rag_config_vector_db_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VectorDBConfigResponse" } } } } }, "security": [ { "JWTBearer": [] } ] }, "patch": { "tags": ["v1", "admin"], "summary": "Update VectorDB config", "description": "Partially update the VectorDB configuration. Only provided fields will be changed.", "operationId": "update_vector_db_config_api_v1_admin_rag_config_vector_db_patch", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VectorDBConfigPayload" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VectorDBConfigResponse" } } } }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } } } }, "security": [ { "JWTBearer": [] } ] } }, "/api/v1/admin/rag/config/retrieval": { "get": { "tags": ["v1", "admin"], "summary": "Get Retrieval config", "description": "Returns the current Retrieval configuration (top_k, weights, reranker, thresholds).", "operationId": "get_retrieval_config_api_v1_admin_rag_config_retrieval_get", "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RetrievalConfigResponse" } } } } }, "security": [ { "JWTBearer": [] } ] }, "patch": { "tags": ["v1", "admin"], "summary": "Update Retrieval config", "description": "Partially update retrieval configuration. Only provided fields will be changed.", "operationId": "update_retrieval_config_api_v1_admin_rag_config_retrieval_patch", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RetrievalConfigPayload" } } }, "required": true }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/RetrievalConfigResponse" } } } }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } } } }, "security": [ { "JWTBearer": [] } ] } } }, "components": { "schemas": { "ActivateAccountResponse": { "properties": { "message": { "type": "string", "title": "Message" }, "user": { "$ref": "#/components/schemas/UserResponse" } }, "type": "object", "required": ["message", "user"], "title": "ActivateAccountResponse" }, "ApiKeyGenerateResponse": { "properties": { "api_key": {464 unmodified lines "type": "object", "title": "HTTPValidationError" }, "LLMConfigPayload": { "properties": { "provider": { "type": "string", "minLength": 1, "title": "Provider", "description": "LLM provider, for example openai or deepseek." }, "model": { "type": "string", "minLength": 1, "title": "Model" }, "base_url": { "type": "string", "minLength": 1, "title": "Base Url", "description": "Optional OpenAI-compatible base URL for non-default providers." }, "api_key_env": { "type": "string", "minLength": 1, "title": "Api Key Env", "description": "Environment variable name that contains the provider API key." }, "reasoning_effort": { "type": "string", "title": "Reasoning Effort", "description": "Reasoning effort for supported models. Use null for models without reasoning effort." }, "temperature": { "type": "number", "minimum": 0.0, "title": "Temperature" }, "max_tokens": { "type": "integer", "minimum": 1.0, "title": "Max Tokens" }, "request_timeout": { "type": "integer", "minimum": 1.0, "title": "Request Timeout" }, "system_prompt": { "type": "string", "minLength": 1, "title": "System Prompt", "description": "Default RAG system prompt. Use {context} where retrieved context should be inserted." } }, "type": "object", "title": "LLMConfigPayload" }, "LLMConfigResponse": { "properties": { "provider": { "type": "string", "title": "Provider" }, "model": { "type": "string", "title": "Model" }, "base_url": { "type": "string", "title": "Base Url" }, "api_key_env": { "type": "string", "title": "Api Key Env" }, "reasoning_effort": { "type": "string", "title": "Reasoning Effort" }, "temperature": { "type": "number", "title": "Temperature" }, "max_tokens": { "type": "integer", "title": "Max Tokens" }, "request_timeout": { "type": "integer", "title": "Request Timeout" }, "system_prompt": { "type": "string", "title": "System Prompt" } }, "type": "object", "required": [ "model", "temperature", "max_tokens", "request_timeout" ], "title": "LLMConfigResponse" }, "LoginRequest": { "properties": { "email": {48 unmodified lines "required": ["page", "limit", "total", "total_pages"], "title": "PaginationDTO" }, "RAGConfigResponse": { "properties": { "path": { "type": "string", "title": "Path" }, "llm": { "$ref": "#/components/schemas/LLMConfigResponse" }, "vector_db": { "$ref": "#/components/schemas/VectorDBConfigResponse" }, "retrieval": { "$ref": "#/components/schemas/RetrievalConfigResponse" } }, "type": "object", "required": ["path", "llm", "vector_db", "retrieval"], "title": "RAGConfigResponse" }, "RegisterRequest": { "properties": { "email": {9 unmodified lines "type": "string", "title": "Name" }, "phone": { "type": "string", "title": "Phone" }, "role": { "$ref": "#/components/schemas/app__schema__auth_schema__Role" },29 unmodified lines "title": "RegisterResponse", "description": "POST /auth/register â 201 response." }, "SearchOptions": { "RetrievalConfigPayload": { "properties": { "ordering": { "top_k": { "type": "integer", "minimum": 1.0, "title": "Top K" }, "bm25_weight": { "type": "number", "maximum": 1.0, "minimum": 0.0, "title": "Bm25 Weight" }, "dense_weight": { "type": "number", "maximum": 1.0, "minimum": 0.0, "title": "Dense Weight" }, "lexical_weight": { "type": "number", "maximum": 1.0, "minimum": 0.0, "title": "Lexical Weight" }, "enable_reranker": { "type": "boolean", "title": "Enable Reranker" }, "reranker_model": { "type": "string", "title": "Ordering" "minLength": 1, "title": "Reranker Model" }, "page": { "max_context_chars": { "type": "integer", "title": "Page" "minimum": 1.0, "title": "Max Context Chars" }, "page_size": { "anyOf": [ { "type": "integer" }, { "type": "string" } ], "title": "Page Size" "similarity_threshold": { "type": "number", "minimum": 0.0, "title": "Similarity Threshold" }, "total_count": { "history_turns": { "type": "integer", "title": "Total Count" } }, "type": "object", "title": "SearchOptions" }, "SignIn": { "properties": { "email__eq": { "type": "string", "title": "Email Eq" "minimum": 0.0, "title": "History Turns" }, "password": { "type": "string", "minLength": 6, "title": "Password" "candidate_pool_size": { "type": "integer", "minimum": 1.0, "title": "Candidate Pool Size" }, "neighbor_window": { "type": "integer", "minimum": 0.0, "title": "Neighbor Window" } }, "type": "object", "required": ["email__eq", "password"], "title": "SignIn" "title": "RetrievalConfigPayload" }, "SignInResponse": { "RetrievalConfigResponse": { "properties": { "access_token": { "type": "string", "title": "Access Token" "top_k": { "type": "integer", "title": "Top K" }, "bm25_weight": { "type": "number", "title": "Bm25 Weight" }, "expiration": { "dense_weight": { "type": "number", "title": "Dense Weight" }, "lexical_weight": { "type": "number", "title": "Lexical Weight" }, "enable_reranker": { "type": "boolean", "title": "Enable Reranker" }, "reranker_model": { "type": "string", "format": "date-time", "title": "Expiration" "title": "Reranker Model" }, "max_context_chars": { "type": "integer", "title": "Max Context Chars" }, "similarity_threshold": { "type": "number", "title": "Similarity Threshold" }, "user_info": { "title": "User Info" "history_turns": { "type": "integer", "title": "History Turns" }, "candidate_pool_size": { "type": "integer", "title": "Candidate Pool Size" }, "neighbor_window": { "type": "integer", "title": "Neighbor Window" } }, "type": "object", "required": ["access_token", "expiration"], "title": "SignInResponse" "required": [ "top_k", "bm25_weight", "dense_weight", "lexical_weight", "enable_reranker", "reranker_model", "max_context_chars", "similarity_threshold", "history_turns", "candidate_pool_size", "neighbor_window" ], "title": "RetrievalConfigResponse" }, "SignUp": { "SearchOptions": { "properties": { "email": { "type": "string", "title": "Email" }, "password": { "ordering": { "type": "string", "minLength": 6, "title": "Password" "title": "Ordering" }, "name": { "type": "string", "title": "Name" "page": { "type": "integer", "title": "Page" }, "role": { "$ref": "#/components/schemas/app__schema__auth_schema__Role" "page_size": { "anyOf": [ { "type": "integer" }, { "type": "string" } ], "title": "Page Size" }, "identity_number": { "type": "string", "title": "Identity Number" "total_count": { "type": "integer", "title": "Total Count" } }, "type": "object", "required": [ "email", "password", "name", "role", "identity_number" ], "title": "SignUp" "title": "SearchOptions" }, "UpdateCourseRequest": { "properties": {46 unmodified lines "type": "string", "title": "Name" }, "phone": { "type": "string", "title": "Phone" }, "role": { "$ref": "#/components/schemas/app__schema__user_schema__Role" },27 unmodified lines "type": "string", "title": "Name" }, "phone": { "type": "string", "title": "Phone" }, "role": { "$ref": "#/components/schemas/app__schema__user_schema__Role" },41 unmodified lines "type": "string", "title": "Name" }, "phone": { "type": "string", "title": "Phone" }, "role": { "$ref": "#/components/schemas/app__schema__auth_schema__Role" },63 unmodified lines "required": ["loc", "msg", "type"], "title": "ValidationError" }, "VectorDBConfigPayload": { "properties": { "embedding_model": { "type": "string", "minLength": 1, "title": "Embedding Model" }, "chunk_size": { "type": "integer", "minimum": 1.0, "title": "Chunk Size" }, "chunk_overlap": { "type": "integer", "minimum": 0.0, "title": "Chunk Overlap" }, "persist_path": { "type": "string", "title": "Persist Path" } }, "type": "object", "title": "VectorDBConfigPayload" }, "VectorDBConfigResponse": { "properties": { "embedding_model": { "type": "string", "title": "Embedding Model" }, "chunk_size": { "type": "integer", "title": "Chunk Size" }, "chunk_overlap": { "type": "integer", "title": "Chunk Overlap" }, "persist_path": { "type": "string", "title": "Persist Path" } }, "type": "object", "required": ["embedding_model", "chunk_size", "chunk_overlap"], "title": "VectorDBConfigResponse" }, "app__schema__auth_schema__Role": { "type": "string", "enum": ["admin", "student", "lecturer"],123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292<?php
use Illuminate\Http\Client\Request as HttpRequest;use Illuminate\Support\Facades\Http;use Inertia\Testing\AssertableInertia as Assert;
function adminAuthUserCookie(): string{ return json_encode([ 'email' => 'admin@example.com', 'id' => 99, 'identity_number' => 'ADM001', 'name' => 'Admin', 'role' => 'admin', 'status' => 'active', ], JSON_THROW_ON_ERROR);}
test('admin dashboard fetches rag config and users from backend', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/admin/rag/config' => Http::response([ 'llm' => [], 'path' => 'config/rag.yaml', 'retrieval' => [], 'vector_db' => [], ]), 'https://rag.test/api/v1/admin/rag/config/llm' => Http::response([ 'max_tokens' => 2048, 'model' => 'gpt-test', 'request_timeout' => 30, 'temperature' => 0.2, ]), 'https://rag.test/api/v1/admin/rag/config/retrieval' => Http::response([ 'bm25_weight' => 0.2, 'candidate_pool_size' => 20, 'dense_weight' => 0.6, 'enable_reranker' => true, 'history_turns' => 3, 'lexical_weight' => 0.2, 'max_context_chars' => 6000, 'neighbor_window' => 1, 'reranker_model' => 'rerank-test', 'similarity_threshold' => 0.1, 'top_k' => 4, ]), 'https://rag.test/api/v1/admin/rag/config/vector_db' => Http::response([ 'chunk_overlap' => 100, 'chunk_size' => 800, 'embedding_model' => 'embed-test', ]), 'https://rag.test/api/v1/user*' => Http::response([ 'founds' => [ [ 'created_at' => '2026-05-01T10:00:00Z', 'email' => 'admin@example.com', 'id' => 99, 'identity_number' => 'ADM001', 'is_active' => true, 'is_superuser' => true, 'name' => 'Admin', 'role' => 'admin', 'updated_at' => '2026-05-01T10:00:00Z', ], ], 'search_options' => [], ]), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->get(route('admin.dashboard', ['name' => 'Admin'])) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->component('admin/dashboard') ->where('backendMessage', null) ->where('ragConfig.path', 'config/rag.yaml') ->where('ragConfig.llm.model', 'gpt-test') ->has('users', 1) ->where('users.0.email', 'admin@example.com') ->where('userFilters.name', 'Admin'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'GET' && $request->url() === 'https://rag.test/api/v1/admin/rag/config' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'GET' && $request->url() === 'https://rag.test/api/v1/admin/rag/config/llm' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'GET' && $request->url() === 'https://rag.test/api/v1/admin/rag/config/vector_db' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'GET' && $request->url() === 'https://rag.test/api/v1/admin/rag/config/retrieval' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'GET' && str_starts_with($request->url(), 'https://rag.test/api/v1/user?') && $request['name'] === 'Admin' && $request->hasHeader('Authorization', 'Bearer token'));});
test('admin config pages render separate inertia components', function (string $routeName, string $component) { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/admin/rag/config' => Http::response([ 'llm' => [], 'path' => 'config/rag.yaml', 'retrieval' => [], 'vector_db' => [], ]), 'https://rag.test/api/v1/admin/rag/config/llm' => Http::response([ 'model' => 'gpt-test', ]), 'https://rag.test/api/v1/admin/rag/config/retrieval' => Http::response([ 'top_k' => 4, ]), 'https://rag.test/api/v1/admin/rag/config/vector_db' => Http::response([ 'chunk_size' => 800, ]), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->get(route($routeName)) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->component($component) ->where('backendMessage', null) ->where('ragConfig.path', 'config/rag.yaml'));})->with([ 'rag config' => ['admin.rag-config', 'admin/rag-config'], 'llm config' => ['admin.llm-config', 'admin/llm-config'], 'vector retrieval config' => ['admin.vector-retrieval-config', 'admin/vector-retrieval-config'],]);
test('admin config update endpoints are proxied to backend', function (string $routeName, string $redirectRouteName, string $url, array $payload, string $assertKey) { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ $url => Http::response($payload), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->patch(route($routeName), $payload) ->assertRedirect(route($redirectRouteName)) ->assertSessionHasNoErrors();
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'PATCH' && $request->url() === $url && $request[$assertKey] === $payload[$assertKey] && $request->hasHeader('Authorization', 'Bearer token'));})->with([ 'llm' => [ 'admin.rag.llm.update', 'admin.llm-config', 'https://rag.test/api/v1/admin/rag/config/llm', ['model' => 'gpt-test', 'temperature' => 0.1], 'model', ], 'vector db' => [ 'admin.rag.vector-db.update', 'admin.vector-retrieval-config', 'https://rag.test/api/v1/admin/rag/config/vector_db', ['chunk_size' => 900, 'embedding_model' => 'embed-test'], 'chunk_size', ], 'retrieval' => [ 'admin.rag.retrieval.update', 'admin.vector-retrieval-config', 'https://rag.test/api/v1/admin/rag/config/retrieval', ['enable_reranker' => true, 'top_k' => 5], 'top_k', ],]);
test('admin api key generation is proxied and flashes generated key', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/auth/api-keys' => Http::response([ 'api_key' => 'rag_sk_test', 'expires_at' => null, ], 201), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->post(route('admin.api-keys.store')) ->assertRedirect(route('admin.dashboard')) ->assertSessionHas('generatedApiKey.api_key', 'rag_sk_test') ->assertSessionHasNoErrors();
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST' && $request->url() === 'https://rag.test/api/v1/auth/api-keys' && $request->hasHeader('Authorization', 'Bearer token'));});
test('admin user crud actions are proxied to backend', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/user' => Http::response([ 'email' => 'student@example.com', 'id' => 10, 'role' => 'student', ]), 'https://rag.test/api/v1/user/10' => Http::response([ 'email' => 'student@example.com', 'id' => 10, 'role' => 'student', ]), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->post(route('admin.users.store'), [ 'email' => 'student@example.com', 'identity_number' => 'M001', 'is_active' => true, 'is_superuser' => false, 'name' => 'Student', 'role' => 'student', ]) ->assertRedirect(route('admin.dashboard')) ->assertSessionHasNoErrors();
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->patch(route('admin.users.update', ['userId' => 10]), [ 'email' => 'student@example.com', 'identity_number' => 'M001', 'is_active' => false, 'is_superuser' => false, 'name' => 'Student Updated', 'role' => 'student', ]) ->assertRedirect(route('admin.dashboard')) ->assertSessionHasNoErrors();
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->delete(route('admin.users.destroy', ['userId' => 10])) ->assertRedirect(route('admin.dashboard')) ->assertSessionHasNoErrors();
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'POST' && $request->url() === 'https://rag.test/api/v1/user' && $request['email'] === 'student@example.com' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'PATCH' && $request->url() === 'https://rag.test/api/v1/user/10' && $request['name'] === 'Student Updated' && $request->hasHeader('Authorization', 'Bearer token'));
Http::assertSent(fn (HttpRequest $request): bool => $request->method() === 'DELETE' && $request->url() === 'https://rag.test/api/v1/user/10' && $request->hasHeader('Authorization', 'Bearer token'));});
test('admin actions use backend error messages', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/user' => Http::response([ 'detail' => [ ['msg' => 'Email already exists.'], ], ], 422), ]);
$this->withCookie('sevima_raghub_auth_token', 'token') ->withCookie('sevima_raghub_auth_user', adminAuthUserCookie()) ->from(route('admin.dashboard')) ->post(route('admin.users.store'), [ 'email' => 'admin@example.com', 'role' => 'admin', ]) ->assertRedirect(route('admin.dashboard')) ->assertSessionHasErrors(['user' => 'Email already exists.']);});14 unmodified lines1516171819202162 unmodified lines848586878889906 unmodified lines97989910010110210319 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318414 unmodified lines 'id' => 1, 'identity_number' => '123456', 'name' => 'Alma', 'phone' => '081234567890', 'role' => 'student', 'status' => 'active', 'updated_at' => '2026-05-01T10:00:00Z',62 unmodified lines 'identity_number' => '123456', 'name' => 'Alma', 'password' => 'secret123', 'phone' => '081234567890', 'role' => 'student', ]) ->assertRedirect(route('login'))6 unmodified lines && $request['identity_number'] === '123456' && $request['name'] === 'Alma' && $request['password'] === 'secret123' && $request['phone'] === '081234567890' && $request['role'] === 'student');});
19 unmodified lines ->assertRedirect(route('register.mahasiswa')) ->assertSessionHasErrors(['auth' => 'Email already registered.']);});
test('register maps backend field validation errors to matching fields', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake([ 'https://rag.test/api/v1/auth/register' => Http::response([ 'errors' => [ [ 'field' => 'name', 'label' => 'Full Name', 'message' => 'Full Name harus berisi minimal nama depan dan nama belakang.', ], [ 'field' => 'role', 'label' => 'Role', 'message' => 'admin is not allowed for self-registration', ], ], 'field_errors' => [ 'name' => 'Full Name harus berisi minimal nama depan dan nama belakang.', 'role' => 'admin is not allowed for self-registration', ], 'message' => 'Periksa kembali field yang ditandai.', ], 422), ]);
$this->from(route('register.mahasiswa')) ->post(route('auth.register.store'), [ 'email' => 'student@example.com', 'identity_number' => '123456', 'name' => 'Alma', 'password' => 'secret123', 'role' => 'student', ]) ->assertRedirect(route('register.mahasiswa')) ->assertSessionHasErrors([ 'name' => 'Full Name harus berisi minimal nama depan dan nama belakang.', 'role' => 'admin is not allowed for self-registration', ]);});
test('register rejects identity number with letters before calling backend', function () { config(['services.rag.base_url' => 'https://rag.test/api/v1']);
Http::fake();
$this->from(route('register.mahasiswa')) ->post(route('auth.register.store'), [ 'email' => 'student@example.com', 'identity_number' => 'AB123456', 'name' => 'Alma Putri', 'password' => 'secret123', 'role' => 'student', ]) ->assertRedirect(route('register.mahasiswa')) ->assertSessionHasErrors(['identity_number']);
Http::assertNothingSent();});app/Http/Controllers/AdminController.php+453-2
app/Http/Controllers/AuthController.php+165-18
app/Http/Controllers/Controller.php+44-1
app/Http/Controllers/DosenController.php+124-15
app/Http/Controllers/EmbedController.php+192-47
app/Http/Controllers/MahasiswaController.php+154-19
app/Services/RagApiClient.phpDeleted-356
resources/js/components/admin/admin-api-key-card.tsxAdded+89
resources/js/components/admin/admin-form-parts.tsxAdded+53
resources/js/components/admin/admin-llm-form.tsxAdded+176
resources/js/components/admin/admin-overview-cards.tsxAdded+86
resources/js/components/admin/admin-page.tsxAdded+56
resources/js/components/admin/admin-rag-summary.tsxAdded+154
resources/js/components/admin/admin-shell.tsx+55-8
resources/js/components/admin/admin-user-management.tsxAdded+511
resources/js/components/admin/admin-vector-retrieval-forms.tsxAdded+277
resources/js/components/auth/register-role-form.tsx+80-14
resources/js/lib/admin.tsAdded+73
resources/js/pages/admin.tsx+1-27
resources/js/pages/admin/dashboard.tsxAdded+34
resources/js/pages/admin/llm-config.tsxAdded+19
resources/js/pages/admin/rag-config.tsxAdded+19
resources/js/pages/admin/vector-retrieval-config.tsxAdded+22
resources/js/pages/auth/admin-login.tsx+2-5
resources/js/pages/auth/login.tsx+2-5
resources/js/pages/embed.tsx+15-4
resources/js/types/admin.tsAdded+124
routes/web.php+20
sevima-raghub.json+660-68
tests/Feature/AdminDashboardTest.phpAdded+292
tests/Feature/AuthProxyTest.php+62