First commit
This commit is contained in:
45
app/Http/Controllers/Admin/AuditLogController.php
Normal file
45
app/Http/Controllers/Admin/AuditLogController.php
Normal file
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AuditLog;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class AuditLogController extends Controller
|
||||
{
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = AuditLog::with('user')->latest('created_at');
|
||||
|
||||
if ($request->filled('event')) {
|
||||
$query->where('event', $request->event);
|
||||
}
|
||||
|
||||
if ($request->filled('user_id')) {
|
||||
$query->where('user_id', $request->user_id);
|
||||
}
|
||||
|
||||
if ($request->filled('date_from')) {
|
||||
$query->where('created_at', '>=', $request->date_from . ' 00:00:00');
|
||||
}
|
||||
|
||||
if ($request->filled('date_to')) {
|
||||
$query->where('created_at', '<=', $request->date_to . ' 23:59:59');
|
||||
}
|
||||
|
||||
$logs = $query->paginate(30)->withQueryString();
|
||||
|
||||
$eventTypes = AuditLog::distinct()->pluck('event')->sort()->values();
|
||||
|
||||
return view('admin.audit-logs.index', compact('logs', 'eventTypes'));
|
||||
}
|
||||
|
||||
public function show(AuditLog $auditLog): View
|
||||
{
|
||||
$auditLog->load('user');
|
||||
|
||||
return view('admin.audit-logs.show', compact('auditLog'));
|
||||
}
|
||||
}
|
||||
102
app/Http/Controllers/Admin/CategoryController.php
Normal file
102
app/Http/Controllers/Admin/CategoryController.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Admin\StoreCategoryRequest;
|
||||
use App\Models\Category;
|
||||
use App\Services\KnowledgeBase\AuditService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class CategoryController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AuditService $auditService
|
||||
) {}
|
||||
|
||||
public function index(): View
|
||||
{
|
||||
$categories = Category::withCount([
|
||||
'documents as total_documents',
|
||||
'documents as active_documents' => fn($q) => $q->where('is_active', true),
|
||||
'knowledgeItems as total_knowledge_items',
|
||||
])
|
||||
->ordered()
|
||||
->withTrashed()
|
||||
->paginate(20);
|
||||
|
||||
return view('admin.categories.index', compact('categories'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
return view('admin.categories.create');
|
||||
}
|
||||
|
||||
public function store(StoreCategoryRequest $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
if (empty($data['slug'])) {
|
||||
$data['slug'] = Str::slug($data['name']);
|
||||
}
|
||||
|
||||
$data['created_by'] = auth()->id();
|
||||
|
||||
$category = Category::create($data);
|
||||
|
||||
$this->auditService->categoryCreated($category);
|
||||
|
||||
return redirect()
|
||||
->route('admin.categories.index')
|
||||
->with('success', "Kategori '{$category->name}' berjaya dicipta.");
|
||||
}
|
||||
|
||||
public function edit(Category $category): View
|
||||
{
|
||||
return view('admin.categories.edit', compact('category'));
|
||||
}
|
||||
|
||||
public function update(StoreCategoryRequest $request, Category $category): RedirectResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
|
||||
if (empty($data['slug'])) {
|
||||
$data['slug'] = Str::slug($data['name']);
|
||||
}
|
||||
|
||||
$category->update($data);
|
||||
|
||||
return redirect()
|
||||
->route('admin.categories.index')
|
||||
->with('success', "Kategori '{$category->name}' berjaya dikemaskini.");
|
||||
}
|
||||
|
||||
public function toggleStatus(Category $category): RedirectResponse
|
||||
{
|
||||
$category->update(['is_active' => !$category->is_active]);
|
||||
|
||||
$status = $category->is_active ? 'diaktifkan' : 'dinyahaktifkan';
|
||||
|
||||
return back()->with('success', "Kategori '{$category->name}' telah {$status}.");
|
||||
}
|
||||
|
||||
public function destroy(Category $category): RedirectResponse
|
||||
{
|
||||
// Semak sama ada ada dokumen aktif dalam kategori ini
|
||||
if ($category->documents()->where('is_active', true)->exists()) {
|
||||
return back()->with('error',
|
||||
'Kategori tidak boleh dipadam kerana masih ada dokumen aktif di dalamnya.'
|
||||
);
|
||||
}
|
||||
|
||||
$category->delete(); // SoftDelete
|
||||
|
||||
return redirect()
|
||||
->route('admin.categories.index')
|
||||
->with('success', "Kategori '{$category->name}' telah dipadam.");
|
||||
}
|
||||
}
|
||||
117
app/Http/Controllers/Admin/ChatFeedbackController.php
Normal file
117
app/Http/Controllers/Admin/ChatFeedbackController.php
Normal file
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Category;
|
||||
use App\Models\ChatFeedback;
|
||||
use App\Models\ChatLog;
|
||||
use App\Models\KnowledgeItem;
|
||||
use App\Services\KnowledgeBase\AuditService;
|
||||
use App\Services\KnowledgeBase\IngestionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class ChatFeedbackController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AuditService $auditService,
|
||||
private readonly IngestionService $ingestionService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Senarai log chat dengan filter dan status feedback.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = ChatLog::with(['session', 'category', 'feedback'])
|
||||
->latest();
|
||||
|
||||
if ($request->filled('has_answer')) {
|
||||
$query->where('has_answer', (bool) $request->has_answer);
|
||||
}
|
||||
|
||||
if ($request->filled('is_flagged')) {
|
||||
$query->where('is_flagged', true);
|
||||
}
|
||||
|
||||
if ($request->filled('category_id')) {
|
||||
$query->where('category_id', $request->category_id);
|
||||
}
|
||||
|
||||
if ($request->filled('rating')) {
|
||||
$query->whereHas('feedback', fn($q) => $q->where('rating', $request->rating));
|
||||
}
|
||||
|
||||
$logs = $query->paginate(20)->withQueryString();
|
||||
$categories = Category::active()->ordered()->get();
|
||||
|
||||
return view('admin.chat-feedback.index', compact('logs', 'categories'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Semak satu log chat dengan butiran penuh.
|
||||
*/
|
||||
public function show(ChatLog $chatLog): View
|
||||
{
|
||||
$chatLog->load(['session', 'category', 'feedback.convertedFaq']);
|
||||
|
||||
return view('admin.chat-feedback.show', compact('chatLog'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert soalan yang tidak dijawab dengan baik kepada FAQ rasmi.
|
||||
*/
|
||||
public function convertToFaq(Request $request, ChatLog $chatLog): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'category_id' => ['required', 'exists:categories,id'],
|
||||
'title' => ['required', 'string', 'max:500'],
|
||||
'content' => ['required', 'string', 'max:10000'],
|
||||
]);
|
||||
|
||||
$knowledgeItem = KnowledgeItem::create([
|
||||
'category_id' => $validated['category_id'],
|
||||
'item_type' => KnowledgeItem::TYPE_FAQ,
|
||||
'title' => $validated['title'],
|
||||
'content' => $validated['content'],
|
||||
'is_active' => true,
|
||||
'is_public' => true,
|
||||
'created_by' => auth()->id(),
|
||||
'updated_by' => auth()->id(),
|
||||
]);
|
||||
|
||||
// Kemaskini feedback jika ada
|
||||
if ($feedback = $chatLog->feedback) {
|
||||
$feedback->update([
|
||||
'converted_to_faq' => true,
|
||||
'converted_faq_id' => $knowledgeItem->id,
|
||||
'reviewed_by' => auth()->id(),
|
||||
'reviewed_at' => now(),
|
||||
]);
|
||||
}
|
||||
|
||||
// Flag log chat sebagai dah diselesaikan
|
||||
$chatLog->update(['is_flagged' => false]);
|
||||
|
||||
$this->auditService->faqConvertedFromFeedback($feedback, $knowledgeItem);
|
||||
|
||||
// Embed knowledge item baru
|
||||
\App\Jobs\ReindexKnowledgeItemJob::dispatch($knowledgeItem->id);
|
||||
|
||||
return redirect()
|
||||
->route('admin.knowledge-items.show', $knowledgeItem)
|
||||
->with('success', "FAQ baru '{$knowledgeItem->title}' berjaya dicipta dari log chat.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle flag pada log chat untuk tanda perlu semakan.
|
||||
*/
|
||||
public function toggleFlag(ChatLog $chatLog): RedirectResponse
|
||||
{
|
||||
$chatLog->update(['is_flagged' => !$chatLog->is_flagged]);
|
||||
|
||||
return back()->with('success', $chatLog->is_flagged ? 'Log ditanda untuk semakan.' : 'Flag dibuang.');
|
||||
}
|
||||
}
|
||||
271
app/Http/Controllers/Admin/ChunkReviewController.php
Normal file
271
app/Http/Controllers/Admin/ChunkReviewController.php
Normal file
@@ -0,0 +1,271 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Admin\SplitChunkRequest;
|
||||
use App\Http\Requests\Admin\UpdateChunkRequest;
|
||||
use App\Models\Document;
|
||||
use App\Models\DocumentChunk;
|
||||
use App\Models\DocumentVersion;
|
||||
use App\Services\Document\ChunkEditingService;
|
||||
use App\Services\Document\ChunkSplitService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* ChunkReviewController
|
||||
*
|
||||
* Menguruskan UI dan operasi Chunk Review & Editing:
|
||||
* - index() → Senarai chunk per versi (enhanced list dengan status filter)
|
||||
* - show() → Detail satu chunk + preview 3 teks + form edit
|
||||
* - update() → Simpan final_text yang diedit
|
||||
* - exclude() → Kecualikan chunk dari indexing
|
||||
* - include() → Kembalikan chunk ke indexing
|
||||
* - reindex() → Trigger reindex manual
|
||||
* - splitForm() → Form split chunk
|
||||
* - doSplit() → Jalankan split
|
||||
*
|
||||
* NOTA: Hanya admin yang boleh akses (dikuatkuasakan di routes via 'role:admin').
|
||||
*/
|
||||
class ChunkReviewController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ChunkEditingService $editor,
|
||||
private readonly ChunkSplitService $splitter,
|
||||
) {}
|
||||
|
||||
// =========================================================================
|
||||
// LIST VIEW
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Senarai chunk untuk satu versi dokumen.
|
||||
* Menggantikan DocumentController::chunks().
|
||||
*
|
||||
* Route: GET /admin/documents/{document}/versions/{version}/chunks
|
||||
*/
|
||||
public function index(Document $document, DocumentVersion $version): View
|
||||
{
|
||||
abort_if($version->document_id !== $document->id, 404);
|
||||
|
||||
$statusFilter = request('status');
|
||||
|
||||
$query = $version->chunks()
|
||||
->with(['editor', 'parentChunk', 'childChunks'])
|
||||
->withCount('audits')
|
||||
->orderBy('chunk_index');
|
||||
|
||||
if ($statusFilter) {
|
||||
$query->where('chunk_status', $statusFilter);
|
||||
}
|
||||
|
||||
$chunks = $query->paginate(20)->withQueryString();
|
||||
|
||||
// Bilangan chunk mengikut status untuk filter pills
|
||||
$statusCounts = $version->chunks()
|
||||
->selectRaw('chunk_status, count(*) as total')
|
||||
->groupBy('chunk_status')
|
||||
->pluck('total', 'chunk_status')
|
||||
->toArray();
|
||||
|
||||
$allStatuses = DocumentChunk::STATUS_PENDING === 'pending'
|
||||
? [
|
||||
DocumentChunk::STATUS_PENDING,
|
||||
DocumentChunk::STATUS_INDEXED,
|
||||
DocumentChunk::STATUS_NEEDS_REVIEW,
|
||||
DocumentChunk::STATUS_NEEDS_REINDEX,
|
||||
DocumentChunk::STATUS_EXCLUDED,
|
||||
DocumentChunk::STATUS_SUPERSEDED,
|
||||
DocumentChunk::STATUS_FAILED_EMBEDDING,
|
||||
]
|
||||
: [];
|
||||
|
||||
return view('admin.documents.chunks', compact(
|
||||
'document',
|
||||
'version',
|
||||
'chunks',
|
||||
'statusCounts',
|
||||
'statusFilter'
|
||||
));
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// DETAIL + EDIT VIEW
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Detail satu chunk: preview raw/cleaned/final text + form edit + audit trail.
|
||||
*
|
||||
* Route: GET /admin/chunks/{chunk}
|
||||
*/
|
||||
public function show(DocumentChunk $chunk): View
|
||||
{
|
||||
$chunk->load([
|
||||
'document.category',
|
||||
'documentVersion',
|
||||
'editor',
|
||||
'parentChunk',
|
||||
'childChunks.editor',
|
||||
'audits' => fn($q) => $q->with('user')->limit(10),
|
||||
]);
|
||||
|
||||
return view('admin.chunks.show', compact('chunk'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Simpan perubahan final_text.
|
||||
*
|
||||
* Route: PATCH /admin/chunks/{chunk}
|
||||
*/
|
||||
public function update(UpdateChunkRequest $request, DocumentChunk $chunk): RedirectResponse
|
||||
{
|
||||
try {
|
||||
$this->editor->editFinalText(
|
||||
$chunk,
|
||||
$request->validated('final_text'),
|
||||
$request->validated('notes')
|
||||
);
|
||||
|
||||
return redirect()
|
||||
->route('admin.chunks.show', $chunk)
|
||||
->with('success', 'final_text berjaya disimpan. Reindex sedang diantrikan dalam queue.');
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// EXCLUDE / INCLUDE
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Kecualikan chunk dari indexing.
|
||||
*
|
||||
* Route: POST /admin/chunks/{chunk}/exclude
|
||||
*/
|
||||
public function exclude(Request $request, DocumentChunk $chunk): RedirectResponse
|
||||
{
|
||||
$request->validate(['notes' => ['nullable', 'string', 'max:500']]);
|
||||
|
||||
try {
|
||||
$this->editor->excludeChunk($chunk, $request->input('notes'));
|
||||
|
||||
return back()->with(
|
||||
'success',
|
||||
"Chunk #{$chunk->chunk_index} berjaya dikecualikan dari indexing."
|
||||
);
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Kembalikan chunk ke indexing.
|
||||
*
|
||||
* Route: POST /admin/chunks/{chunk}/include
|
||||
*/
|
||||
public function include(Request $request, DocumentChunk $chunk): RedirectResponse
|
||||
{
|
||||
$request->validate(['notes' => ['nullable', 'string', 'max:500']]);
|
||||
|
||||
try {
|
||||
$this->editor->includeChunk($chunk, $request->input('notes'));
|
||||
|
||||
return back()->with(
|
||||
'success',
|
||||
"Chunk #{$chunk->chunk_index} berjaya dikembalikan ke indexing."
|
||||
);
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// REINDEX
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Trigger reindex manual untuk satu chunk.
|
||||
*
|
||||
* Route: POST /admin/chunks/{chunk}/reindex
|
||||
*/
|
||||
public function reindex(Request $request, DocumentChunk $chunk): RedirectResponse
|
||||
{
|
||||
$request->validate(['notes' => ['nullable', 'string', 'max:500']]);
|
||||
|
||||
try {
|
||||
$this->editor->triggerReindex($chunk, $request->input('notes'));
|
||||
|
||||
return back()->with(
|
||||
'success',
|
||||
"Chunk #{$chunk->chunk_index} sedang diantrikan untuk reindex."
|
||||
);
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// SPLIT
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Form split chunk.
|
||||
*
|
||||
* Route: GET /admin/chunks/{chunk}/split
|
||||
*/
|
||||
public function splitForm(DocumentChunk $chunk): View
|
||||
{
|
||||
if ($chunk->isSuperseded()) {
|
||||
abort(403, 'Chunk yang telah digantikan tidak boleh di-split semula.');
|
||||
}
|
||||
|
||||
if ($chunk->chunk_status === DocumentChunk::STATUS_EXCLUDED) {
|
||||
abort(403, 'Chunk yang dikecualikan tidak boleh di-split. Include semula dahulu.');
|
||||
}
|
||||
|
||||
$chunk->load(['document', 'documentVersion', 'childChunks']);
|
||||
|
||||
return view('admin.chunks.split', compact('chunk'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Jalankan split chunk.
|
||||
*
|
||||
* Route: POST /admin/chunks/{chunk}/split
|
||||
*/
|
||||
public function doSplit(SplitChunkRequest $request, DocumentChunk $chunk): RedirectResponse
|
||||
{
|
||||
if ($chunk->isSuperseded()) {
|
||||
return back()->with('error', 'Chunk yang telah digantikan tidak boleh di-split.');
|
||||
}
|
||||
|
||||
try {
|
||||
$children = $this->splitter->split(
|
||||
$chunk,
|
||||
$request->validated('segments'),
|
||||
$request->validated('notes')
|
||||
);
|
||||
|
||||
return redirect()
|
||||
->route('admin.documents.chunks', [
|
||||
'document' => $chunk->document_id,
|
||||
'version' => $chunk->document_version_id,
|
||||
])
|
||||
->with(
|
||||
'success',
|
||||
"Chunk #{$chunk->chunk_index} berjaya di-split kepada "
|
||||
. count($children)
|
||||
. " chunk baharu. Reindex sedang dijalankan dalam queue."
|
||||
);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
return back()->withInput()->with('error', $e->getMessage());
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->withInput()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
54
app/Http/Controllers/Admin/DashboardController.php
Normal file
54
app/Http/Controllers/Admin/DashboardController.php
Normal file
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Category;
|
||||
use App\Models\ChatLog;
|
||||
use App\Models\Document;
|
||||
use App\Models\DocumentVersion;
|
||||
use App\Models\KnowledgeItem;
|
||||
use App\Services\Ollama\OllamaService;
|
||||
use App\Services\Qdrant\QdrantService;
|
||||
use Illuminate\View\View;
|
||||
|
||||
class DashboardController extends Controller
|
||||
{
|
||||
public function index(
|
||||
OllamaService $ollamaService,
|
||||
QdrantService $qdrantService
|
||||
): View {
|
||||
$stats = [
|
||||
'total_documents' => Document::count(),
|
||||
'active_documents' => Document::where('is_active', true)->count(),
|
||||
'processing_documents' => Document::where('status', 'processing')->count(),
|
||||
'failed_documents' => Document::whereIn('status', ['failed', 'extraction_failed'])->count(),
|
||||
'total_categories' => Category::where('is_active', true)->count(),
|
||||
'total_knowledge_items' => KnowledgeItem::where('is_active', true)->count(),
|
||||
'total_chats_today' => ChatLog::whereDate('created_at', today())->count(),
|
||||
'unanswered_chats' => ChatLog::where('has_answer', false)->count(),
|
||||
'flagged_chats' => ChatLog::where('is_flagged', true)->count(),
|
||||
];
|
||||
|
||||
$recentActivity = AuditLog::with('user')
|
||||
->latest('created_at')
|
||||
->limit(10)
|
||||
->get();
|
||||
|
||||
$recentChats = ChatLog::with('category')
|
||||
->latest()
|
||||
->limit(5)
|
||||
->get();
|
||||
|
||||
// Health check (cache 60 saat supaya tidak lambat setiap load)
|
||||
$health = cache()->remember('service_health', 60, function () use ($ollamaService, $qdrantService) {
|
||||
return [
|
||||
'ollama' => $ollamaService->healthCheck(),
|
||||
'qdrant' => $qdrantService->healthCheck(),
|
||||
];
|
||||
});
|
||||
|
||||
return view('admin.dashboard', compact('stats', 'recentActivity', 'recentChats', 'health'));
|
||||
}
|
||||
}
|
||||
214
app/Http/Controllers/Admin/DocumentController.php
Normal file
214
app/Http/Controllers/Admin/DocumentController.php
Normal file
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Actions\Document\CreateDocumentAction;
|
||||
use App\Actions\Document\UploadNewVersionAction;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Admin\StoreDocumentRequest;
|
||||
use App\Jobs\ReindexDocumentJob;
|
||||
use App\Models\Category;
|
||||
use App\Models\Document;
|
||||
use App\Models\DocumentVersion;
|
||||
use App\Services\KnowledgeBase\AuditService;
|
||||
use App\Services\KnowledgeBase\IngestionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\View\View;
|
||||
use RuntimeException;
|
||||
|
||||
class DocumentController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AuditService $auditService,
|
||||
private readonly IngestionService $ingestionService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = Document::with(['category', 'currentVersion'])
|
||||
->withCount('versions');
|
||||
|
||||
if ($request->filled('category_id')) {
|
||||
$query->where('category_id', $request->category_id);
|
||||
}
|
||||
|
||||
if ($request->filled('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$query->where('title', 'like', '%' . $request->search . '%');
|
||||
}
|
||||
|
||||
$documents = $query->latest()->paginate(15)->withQueryString();
|
||||
$categories = Category::active()->ordered()->get();
|
||||
|
||||
return view('admin.documents.index', compact('documents', 'categories'));
|
||||
}
|
||||
|
||||
public function create(): View
|
||||
{
|
||||
$categories = Category::active()->ordered()->get();
|
||||
return view('admin.documents.create', compact('categories'));
|
||||
}
|
||||
|
||||
public function store(StoreDocumentRequest $request, CreateDocumentAction $action): RedirectResponse
|
||||
{
|
||||
try {
|
||||
$document = $action->execute(
|
||||
$request->validated(),
|
||||
$request->file('file')
|
||||
);
|
||||
|
||||
return redirect()
|
||||
->route('admin.documents.show', $document)
|
||||
->with('success', "Dokumen '{$document->title}' berjaya diupload dan sedang diproses.");
|
||||
} catch (RuntimeException $e) {
|
||||
return back()
|
||||
->withInput()
|
||||
->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public function show(Document $document): View
|
||||
{
|
||||
$document->load([
|
||||
'category',
|
||||
'versions.uploader',
|
||||
'currentVersion.chunks' => fn($q) => $q->limit(20),
|
||||
]);
|
||||
|
||||
return view('admin.documents.show', compact('document'));
|
||||
}
|
||||
|
||||
public function edit(Document $document): View
|
||||
{
|
||||
$categories = Category::active()->ordered()->get();
|
||||
return view('admin.documents.edit', compact('document', 'categories'));
|
||||
}
|
||||
|
||||
public function update(Request $request, Document $document): RedirectResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'description' => ['nullable', 'string', 'max:1000'],
|
||||
'category_id' => ['required', 'exists:categories,id'],
|
||||
'effective_date' => ['nullable', 'date'],
|
||||
'expiry_date' => ['nullable', 'date'],
|
||||
'tags' => ['nullable', 'array'],
|
||||
'language' => ['nullable', 'in:ms,en'],
|
||||
]);
|
||||
|
||||
$validated['updated_by'] = auth()->id();
|
||||
$document->update($validated);
|
||||
|
||||
return redirect()
|
||||
->route('admin.documents.show', $document)
|
||||
->with('success', 'Maklumat dokumen berjaya dikemaskini.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload versi baru untuk dokumen yang sedia ada.
|
||||
*/
|
||||
public function uploadVersion(
|
||||
Request $request,
|
||||
Document $document,
|
||||
UploadNewVersionAction $action
|
||||
): RedirectResponse {
|
||||
$request->validate([
|
||||
'file' => ['required', 'file', 'mimes:pdf', 'max:' . config('knowledgebase.upload.max_file_size', 20480)],
|
||||
'change_notes' => ['nullable', 'string', 'max:500'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$action->execute($document, $request->file('file'), $request->only('change_notes'));
|
||||
|
||||
return redirect()
|
||||
->route('admin.documents.show', $document)
|
||||
->with('success', 'Versi baru berjaya diupload dan sedang diproses.');
|
||||
} catch (RuntimeException $e) {
|
||||
return back()->with('error', $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle status aktif/tidak aktif dokumen.
|
||||
* Apabila dinyahaktifkan, chunk dalam Qdrant juga dimatikan.
|
||||
*/
|
||||
public function toggleStatus(Document $document): RedirectResponse
|
||||
{
|
||||
$newStatus = !$document->is_active;
|
||||
|
||||
if ($newStatus) {
|
||||
// Aktifkan — versi semasa mesti sudah indexed
|
||||
$currentVersion = $document->currentVersion;
|
||||
if (!$currentVersion || !$currentVersion->isProcessed()) {
|
||||
return back()->with('error',
|
||||
'Dokumen tidak boleh diaktifkan kerana pemprosesan belum selesai.'
|
||||
);
|
||||
}
|
||||
|
||||
$document->update([
|
||||
'is_active' => true,
|
||||
'status' => Document::STATUS_ACTIVE,
|
||||
]);
|
||||
|
||||
$this->auditService->documentActivated($document);
|
||||
} else {
|
||||
// Deactivate — matikan juga dalam Qdrant
|
||||
$document->update([
|
||||
'is_active' => false,
|
||||
'status' => Document::STATUS_INACTIVE,
|
||||
]);
|
||||
|
||||
if ($currentVersion = $document->currentVersion) {
|
||||
$this->ingestionService->deactivateVersionInQdrant($currentVersion);
|
||||
}
|
||||
|
||||
$this->auditService->documentDeactivated($document);
|
||||
}
|
||||
|
||||
$status = $newStatus ? 'diaktifkan' : 'dinyahaktifkan';
|
||||
|
||||
return back()->with('success', "Dokumen '{$document->title}' telah {$status}.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger reindex untuk versi tertentu.
|
||||
*/
|
||||
public function reindex(Document $document): RedirectResponse
|
||||
{
|
||||
$currentVersion = $document->currentVersion;
|
||||
|
||||
if (!$currentVersion) {
|
||||
return back()->with('error', 'Tiada versi semasa untuk diindeks semula.');
|
||||
}
|
||||
|
||||
ReindexDocumentJob::dispatch($currentVersion->id);
|
||||
|
||||
$this->auditService->documentReindexed($document, $currentVersion);
|
||||
|
||||
return back()->with('success', 'Reindeks telah dimulakan. Sila semak semula sebentar lagi.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Download PDF asal.
|
||||
*/
|
||||
public function download(Document $document, DocumentVersion $version)
|
||||
{
|
||||
abort_if($version->document_id !== $document->id, 404);
|
||||
|
||||
$disk = config('knowledgebase.upload.storage_disk', 'local');
|
||||
|
||||
if (!Storage::disk($disk)->exists($version->stored_path)) {
|
||||
abort(404, 'Fail tidak dijumpai.');
|
||||
}
|
||||
|
||||
return Storage::disk($disk)->download(
|
||||
$version->stored_path,
|
||||
$version->original_filename
|
||||
);
|
||||
}
|
||||
}
|
||||
152
app/Http/Controllers/Admin/KnowledgeItemController.php
Normal file
152
app/Http/Controllers/Admin/KnowledgeItemController.php
Normal file
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Admin\StoreKnowledgeItemRequest;
|
||||
use App\Jobs\ReindexKnowledgeItemJob;
|
||||
use App\Models\Category;
|
||||
use App\Models\KnowledgeItem;
|
||||
use App\Services\KnowledgeBase\AuditService;
|
||||
use App\Services\KnowledgeBase\IngestionService;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use RuntimeException;
|
||||
|
||||
class KnowledgeItemController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AuditService $auditService,
|
||||
private readonly IngestionService $ingestionService,
|
||||
) {}
|
||||
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$query = KnowledgeItem::with('category')
|
||||
->withTrashed();
|
||||
|
||||
if ($request->filled('category_id')) {
|
||||
$query->where('category_id', $request->category_id);
|
||||
}
|
||||
|
||||
if ($request->filled('item_type')) {
|
||||
$query->where('item_type', $request->item_type);
|
||||
}
|
||||
|
||||
if ($request->filled('search')) {
|
||||
$query->where(function ($q) use ($request) {
|
||||
$q->where('title', 'like', '%' . $request->search . '%')
|
||||
->orWhere('content', 'like', '%' . $request->search . '%');
|
||||
});
|
||||
}
|
||||
|
||||
$items = $query->latest()->paginate(20)->withQueryString();
|
||||
$categories = Category::active()->ordered()->get();
|
||||
$typeLabels = KnowledgeItem::typeLabels();
|
||||
|
||||
return view('admin.knowledge-items.index', compact('items', 'categories', 'typeLabels'));
|
||||
}
|
||||
|
||||
public function create(Request $request): View
|
||||
{
|
||||
$categories = Category::active()->ordered()->get();
|
||||
$typeLabels = KnowledgeItem::typeLabels();
|
||||
$prefillData = $request->only(['category_id', 'item_type', 'title', 'content']);
|
||||
// prefillData berguna bila convert dari feedback
|
||||
|
||||
return view('admin.knowledge-items.create', compact('categories', 'typeLabels', 'prefillData'));
|
||||
}
|
||||
|
||||
public function store(StoreKnowledgeItemRequest $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validated();
|
||||
$data['created_by'] = auth()->id();
|
||||
$data['updated_by'] = auth()->id();
|
||||
|
||||
$item = KnowledgeItem::create($data);
|
||||
|
||||
$this->auditService->knowledgeItemCreated($item);
|
||||
|
||||
// Embed secara async
|
||||
ReindexKnowledgeItemJob::dispatch($item->id);
|
||||
|
||||
return redirect()
|
||||
->route('admin.knowledge-items.show', $item)
|
||||
->with('success', "Knowledge item '{$item->title}' berjaya dicipta dan sedang di-embed.");
|
||||
}
|
||||
|
||||
public function show(KnowledgeItem $knowledgeItem): View
|
||||
{
|
||||
$knowledgeItem->load('category', 'creator');
|
||||
|
||||
return view('admin.knowledge-items.show', compact('knowledgeItem'));
|
||||
}
|
||||
|
||||
public function edit(KnowledgeItem $knowledgeItem): View
|
||||
{
|
||||
$categories = Category::active()->ordered()->get();
|
||||
$typeLabels = KnowledgeItem::typeLabels();
|
||||
|
||||
return view('admin.knowledge-items.edit', compact('knowledgeItem', 'categories', 'typeLabels'));
|
||||
}
|
||||
|
||||
public function update(StoreKnowledgeItemRequest $request, KnowledgeItem $knowledgeItem): RedirectResponse
|
||||
{
|
||||
$oldValues = $knowledgeItem->only(['title', 'content', 'is_active']);
|
||||
|
||||
$data = $request->validated();
|
||||
$data['updated_by'] = auth()->id();
|
||||
|
||||
$knowledgeItem->update($data);
|
||||
|
||||
$this->auditService->knowledgeItemUpdated($knowledgeItem, $oldValues);
|
||||
|
||||
// Re-embed kerana kandungan mungkin berubah
|
||||
ReindexKnowledgeItemJob::dispatch($knowledgeItem->id);
|
||||
|
||||
return redirect()
|
||||
->route('admin.knowledge-items.show', $knowledgeItem)
|
||||
->with('success', 'Knowledge item berjaya dikemaskini dan sedang di-embed semula.');
|
||||
}
|
||||
|
||||
public function toggleStatus(KnowledgeItem $knowledgeItem): RedirectResponse
|
||||
{
|
||||
$newStatus = !$knowledgeItem->is_active;
|
||||
|
||||
$knowledgeItem->update(['is_active' => $newStatus]);
|
||||
|
||||
if (!$newStatus && $knowledgeItem->qdrant_point_id) {
|
||||
$this->ingestionService->deactivateKnowledgeItemInQdrant($knowledgeItem);
|
||||
$this->auditService->knowledgeItemDeactivated($knowledgeItem);
|
||||
} elseif ($newStatus) {
|
||||
// Reactivate — update payload Qdrant
|
||||
ReindexKnowledgeItemJob::dispatch($knowledgeItem->id);
|
||||
}
|
||||
|
||||
$status = $newStatus ? 'diaktifkan' : 'dinyahaktifkan';
|
||||
|
||||
return back()->with('success', "Item '{$knowledgeItem->title}' telah {$status}.");
|
||||
}
|
||||
|
||||
public function reindex(KnowledgeItem $knowledgeItem): RedirectResponse
|
||||
{
|
||||
ReindexKnowledgeItemJob::dispatch($knowledgeItem->id);
|
||||
|
||||
return back()->with('success', 'Re-embed telah dimulakan.');
|
||||
}
|
||||
|
||||
public function destroy(KnowledgeItem $knowledgeItem): RedirectResponse
|
||||
{
|
||||
// Deactivate dalam Qdrant dulu
|
||||
if ($knowledgeItem->qdrant_point_id) {
|
||||
$this->ingestionService->deactivateKnowledgeItemInQdrant($knowledgeItem);
|
||||
}
|
||||
|
||||
$knowledgeItem->delete(); // SoftDelete
|
||||
|
||||
return redirect()
|
||||
->route('admin.knowledge-items.index')
|
||||
->with('success', 'Knowledge item telah dipadam.');
|
||||
}
|
||||
}
|
||||
59
app/Http/Controllers/Chatbot/ChatController.php
Normal file
59
app/Http/Controllers/Chatbot/ChatController.php
Normal file
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Chatbot;
|
||||
|
||||
use App\Actions\Chatbot\AskQuestionAction;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Chatbot\AskQuestionRequest;
|
||||
use App\Models\Category;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\View\View;
|
||||
use RuntimeException;
|
||||
|
||||
class ChatController extends Controller
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AskQuestionAction $askQuestionAction
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Paparan chatbot UI.
|
||||
*/
|
||||
public function index(Request $request): View
|
||||
{
|
||||
$categories = Category::active()->ordered()->get();
|
||||
$selectedCatId = $request->query('category_id');
|
||||
|
||||
return view('chatbot.index', compact('categories', 'selectedCatId'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Endpoint untuk submit soalan.
|
||||
* Return JSON — AJAX call dari chatbot UI.
|
||||
*/
|
||||
public function ask(AskQuestionRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result = $this->askQuestionAction->execute(
|
||||
$request->question,
|
||||
$request->category_id,
|
||||
$request
|
||||
);
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'answer' => $result['answer'],
|
||||
'has_answer' => $result['has_answer'],
|
||||
'sources' => $result['sources'],
|
||||
'session_token' => $result['session_token'],
|
||||
]);
|
||||
} catch (RuntimeException $e) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Perkhidmatan AI tidak tersedia pada masa ini. Sila cuba sebentar lagi.',
|
||||
'error' => config('app.debug') ? $e->getMessage() : null,
|
||||
], 503);
|
||||
}
|
||||
}
|
||||
}
|
||||
53
app/Http/Controllers/Chatbot/FeedbackController.php
Normal file
53
app/Http/Controllers/Chatbot/FeedbackController.php
Normal file
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Chatbot;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\ChatFeedback;
|
||||
use App\Models\ChatLog;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class FeedbackController extends Controller
|
||||
{
|
||||
/**
|
||||
* Simpan feedback untuk satu jawapan chatbot.
|
||||
*/
|
||||
public function store(Request $request): JsonResponse
|
||||
{
|
||||
$validated = $request->validate([
|
||||
'chat_log_id' => ['required', 'integer', 'exists:chat_logs,id'],
|
||||
'rating' => ['required', 'in:helpful,not_helpful,partially_helpful'],
|
||||
'comment' => ['nullable', 'string', 'max:1000'],
|
||||
'correct_answer' => ['nullable', 'string', 'max:5000'],
|
||||
]);
|
||||
|
||||
$chatLog = ChatLog::findOrFail($validated['chat_log_id']);
|
||||
|
||||
// Elak duplikasi feedback
|
||||
if ($chatLog->feedback) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Anda sudah memberikan feedback untuk soalan ini.',
|
||||
], 409);
|
||||
}
|
||||
|
||||
$feedback = ChatFeedback::create([
|
||||
'chat_log_id' => $chatLog->id,
|
||||
'user_id' => auth()->id(),
|
||||
'rating' => $validated['rating'],
|
||||
'comment' => $validated['comment'] ?? null,
|
||||
'correct_answer' => $validated['correct_answer'] ?? null,
|
||||
]);
|
||||
|
||||
// Flag untuk semakan admin jika jawapan tidak membantu
|
||||
if ($validated['rating'] === ChatFeedback::RATING_NOT_HELPFUL) {
|
||||
$chatLog->update(['is_flagged' => true]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'success' => true,
|
||||
'message' => 'Terima kasih atas maklum balas anda.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
8
app/Http/Controllers/Controller.php
Normal file
8
app/Http/Controllers/Controller.php
Normal file
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
}
|
||||
29
app/Http/Middleware/EnsureUserRole.php
Normal file
29
app/Http/Middleware/EnsureUserRole.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* EnsureUserRole Middleware
|
||||
*
|
||||
* Periksa sama ada user mempunyai role yang diperlukan.
|
||||
* Guna: ->middleware('role:admin') atau ->middleware('role:admin,staff')
|
||||
*/
|
||||
class EnsureUserRole
|
||||
{
|
||||
public function handle(Request $request, Closure $next, string ...$roles): Response
|
||||
{
|
||||
if (!$request->user()) {
|
||||
return redirect()->route('login');
|
||||
}
|
||||
|
||||
if (!in_array($request->user()->role, $roles)) {
|
||||
abort(403, 'Anda tidak mempunyai kebenaran untuk akses halaman ini.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
51
app/Http/Requests/Admin/SplitChunkRequest.php
Normal file
51
app/Http/Requests/Admin/SplitChunkRequest.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class SplitChunkRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
// Hanya admin yang boleh split chunk
|
||||
return auth()->check() && auth()->user()->role === 'admin';
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'segments' => ['required', 'array', 'min:2', 'max:10'],
|
||||
'segments.*' => ['required', 'string', 'min:20', 'max:10000'],
|
||||
'notes' => ['nullable', 'string', 'max:500'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'segments.required' => 'Sila masukkan segmen untuk split.',
|
||||
'segments.min' => 'Split memerlukan sekurang-kurangnya 2 segmen.',
|
||||
'segments.max' => 'Maksimum 10 segmen dibenarkan dalam satu operasi split.',
|
||||
'segments.*.required' => 'Segmen tidak boleh kosong.',
|
||||
'segments.*.min' => 'Setiap segmen mesti sekurang-kurangnya 20 aksara untuk embedding bermakna.',
|
||||
'segments.*.max' => 'Setiap segmen tidak boleh melebihi 10,000 aksara.',
|
||||
'notes.max' => 'Nota tidak boleh melebihi 500 aksara.',
|
||||
];
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
// Trim setiap segmen dan buang segmen yang benar-benar kosong
|
||||
if ($this->has('segments')) {
|
||||
$segments = array_values(
|
||||
array_filter(
|
||||
array_map('trim', $this->input('segments', [])),
|
||||
fn($s) => $s !== ''
|
||||
)
|
||||
);
|
||||
|
||||
$this->merge(['segments' => $segments]);
|
||||
}
|
||||
}
|
||||
}
|
||||
44
app/Http/Requests/Admin/StoreCategoryRequest.php
Normal file
44
app/Http/Requests/Admin/StoreCategoryRequest.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class StoreCategoryRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()->canManageCategories();
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
$categoryId = $this->route('category')?->id;
|
||||
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:100'],
|
||||
'slug' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:100',
|
||||
'regex:/^[a-z0-9-]+$/',
|
||||
Rule::unique('categories', 'slug')->ignore($categoryId)->whereNull('deleted_at'),
|
||||
],
|
||||
'description' => ['nullable', 'string', 'max:500'],
|
||||
'color' => ['nullable', 'string', 'regex:/^#[0-9A-Fa-f]{6}$/'],
|
||||
'is_active' => ['boolean'],
|
||||
'sort_order' => ['nullable', 'integer', 'min:0'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'name.required' => 'Nama kategori wajib diisi.',
|
||||
'slug.unique' => 'Slug ini sudah digunakan.',
|
||||
'slug.regex' => 'Slug hanya boleh mengandungi huruf kecil, angka, dan tanda (-)',
|
||||
'color.regex' => 'Warna mesti dalam format hex (contoh: #3b82f6)',
|
||||
];
|
||||
}
|
||||
}
|
||||
51
app/Http/Requests/Admin/StoreDocumentRequest.php
Normal file
51
app/Http/Requests/Admin/StoreDocumentRequest.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreDocumentRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()->canManageDocuments();
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
$maxSizeKb = config('knowledgebase.upload.max_file_size', 20480);
|
||||
|
||||
return [
|
||||
'category_id' => ['required', 'integer', 'exists:categories,id'],
|
||||
'title' => ['required', 'string', 'max:255'],
|
||||
'description' => ['nullable', 'string', 'max:1000'],
|
||||
'file' => [
|
||||
'required',
|
||||
'file',
|
||||
'mimes:pdf',
|
||||
"max:{$maxSizeKb}",
|
||||
],
|
||||
'effective_date' => ['nullable', 'date'],
|
||||
'expiry_date' => ['nullable', 'date', 'after_or_equal:effective_date'],
|
||||
'tags' => ['nullable', 'array'],
|
||||
'tags.*' => ['string', 'max:50'],
|
||||
'language' => ['nullable', 'in:ms,en'],
|
||||
'change_notes' => ['nullable', 'string', 'max:500'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
$maxMb = round(config('knowledgebase.upload.max_file_size', 20480) / 1024);
|
||||
|
||||
return [
|
||||
'category_id.required' => 'Kategori wajib dipilih.',
|
||||
'category_id.exists' => 'Kategori tidak wujud.',
|
||||
'title.required' => 'Tajuk dokumen wajib diisi.',
|
||||
'file.required' => 'Fail PDF wajib diupload.',
|
||||
'file.mimes' => 'Hanya fail PDF yang dibenarkan.',
|
||||
'file.max' => "Saiz fail tidak boleh melebihi {$maxMb}MB.",
|
||||
'expiry_date.after_or_equal' => 'Tarikh luput mesti selepas atau sama dengan tarikh kuat kuasa.',
|
||||
];
|
||||
}
|
||||
}
|
||||
44
app/Http/Requests/Admin/StoreKnowledgeItemRequest.php
Normal file
44
app/Http/Requests/Admin/StoreKnowledgeItemRequest.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin;
|
||||
|
||||
use App\Models\KnowledgeItem;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class StoreKnowledgeItemRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return $this->user()->canManageDocuments();
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'category_id' => ['required', 'integer', 'exists:categories,id'],
|
||||
'item_type' => ['required', 'in:' . implode(',', array_keys(KnowledgeItem::typeLabels()))],
|
||||
'title' => ['required', 'string', 'max:500'],
|
||||
'content' => ['required', 'string', 'max:10000'],
|
||||
'content_short' => ['nullable', 'string', 'max:500'],
|
||||
'tags' => ['nullable', 'array'],
|
||||
'tags.*' => ['string', 'max:50'],
|
||||
'language' => ['nullable', 'in:ms,en'],
|
||||
'effective_date' => ['nullable', 'date'],
|
||||
'expiry_date' => ['nullable', 'date'],
|
||||
'is_active' => ['boolean'],
|
||||
'is_public' => ['boolean'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'category_id.required' => 'Kategori wajib dipilih.',
|
||||
'item_type.required' => 'Jenis item wajib dipilih.',
|
||||
'item_type.in' => 'Jenis item tidak sah.',
|
||||
'title.required' => 'Tajuk/soalan wajib diisi.',
|
||||
'content.required' => 'Kandungan/jawapan wajib diisi.',
|
||||
'content.max' => 'Kandungan terlalu panjang (had: 10,000 karakter).',
|
||||
];
|
||||
}
|
||||
}
|
||||
42
app/Http/Requests/Admin/UpdateChunkRequest.php
Normal file
42
app/Http/Requests/Admin/UpdateChunkRequest.php
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class UpdateChunkRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
// Hanya admin yang boleh edit chunk
|
||||
return auth()->check() && auth()->user()->role === 'admin';
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'final_text' => ['required', 'string', 'min:20', 'max:10000'],
|
||||
'notes' => ['nullable', 'string', 'max:500'],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'final_text.required' => 'final_text tidak boleh kosong.',
|
||||
'final_text.min' => 'final_text terlalu pendek. Minimum 20 aksara diperlukan untuk embedding bermakna.',
|
||||
'final_text.max' => 'final_text terlalu panjang. Maksimum 10,000 aksara.',
|
||||
'notes.max' => 'Nota tidak boleh melebihi 500 aksara.',
|
||||
];
|
||||
}
|
||||
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
// Trim whitespace pada final_text sebelum validasi
|
||||
if ($this->has('final_text')) {
|
||||
$this->merge([
|
||||
'final_text' => trim($this->input('final_text')),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
58
app/Http/Requests/Chatbot/AskQuestionRequest.php
Normal file
58
app/Http/Requests/Chatbot/AskQuestionRequest.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Requests\Chatbot;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
class AskQuestionRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true; // Public access
|
||||
}
|
||||
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'question' => [
|
||||
'required',
|
||||
'string',
|
||||
'min:3',
|
||||
'max:1000',
|
||||
],
|
||||
'category_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
'exists:categories,id',
|
||||
],
|
||||
'session_token' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:64',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public function messages(): array
|
||||
{
|
||||
return [
|
||||
'question.required' => 'Soalan wajib diisi.',
|
||||
'question.min' => 'Soalan terlalu pendek (minimum 3 karakter).',
|
||||
'question.max' => 'Soalan terlalu panjang (maksimum 1000 karakter).',
|
||||
'category_id.exists' => 'Kategori tidak wujud.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize soalan sebelum diproses.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('question')) {
|
||||
// Buang karakter kawalan berbahaya yang mungkin prompt injection
|
||||
$sanitized = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $this->question);
|
||||
$sanitized = trim($sanitized);
|
||||
$this->merge(['question' => $sanitized]);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user