Files
usher-manage-stack/app/Http/Controllers/Api/PublicDocumentController.php

90 lines
2.9 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Resources\PublicDocumentCollectionResource;
use App\Http\Resources\PublicDocumentResource;
use App\Models\Document;
use Illuminate\Http\Request;
class PublicDocumentController extends Controller
{
/**
* List public documents for external site consumption.
*/
public function index(Request $request)
{
$query = Document::query()
->with(['category', 'currentVersion.uploadedBy'])
->where('status', 'active')
->where('access_level', 'public')
->whereNotNull('current_version_id')
->orderByDesc('updated_at');
if ($request->filled('search')) {
$search = trim((string) $request->input('search'));
$query->where(function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%")
->orWhere('description', 'like', "%{$search}%")
->orWhere('document_number', 'like', "%{$search}%");
});
}
if ($request->filled('category')) {
$category = (string) $request->input('category');
if (ctype_digit($category)) {
$query->where('document_category_id', (int) $category);
} else {
$query->whereHas('category', function ($q) use ($category) {
$q->where('slug', $category);
});
}
}
$perPage = min(max($request->integer('per_page', 100), 1), 500);
return PublicDocumentCollectionResource::collection(
$query->paginate($perPage)->withQueryString()
);
}
/**
* Show a single public document with version history.
*/
public function show(string $uuid)
{
$document = Document::query()
->with([
'category',
'currentVersion.uploadedBy',
'versions.uploadedBy',
'versions.document',
'createdBy',
'lastUpdatedBy',
])
->where('public_uuid', $uuid)
->where('status', 'active')
->where('access_level', 'public')
->whereNotNull('current_version_id')
->firstOrFail();
$related = Document::query()
->with(['category', 'currentVersion.uploadedBy'])
->where('status', 'active')
->where('access_level', 'public')
->whereNotNull('current_version_id')
->where('id', '!=', $document->id)
->where('document_category_id', $document->document_category_id)
->orderByDesc('updated_at')
->limit(4)
->get();
return response()->json([
'data' => new PublicDocumentResource($document),
'related' => PublicDocumentCollectionResource::collection($related),
]);
}
}