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.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user