updated apis

This commit is contained in:
m.razaghi
2026-07-14 00:10:53 +03:30
parent 39e85df27a
commit a173f17cae
11 changed files with 304 additions and 102 deletions

View File

@@ -79,7 +79,6 @@ class BylawApiController extends Controller
$perPage = min(max((int) $request->input('per_page', 15), 10), 100); $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage); $paginator = $query->paginate($perPage);
// واکشی دسته‌جمعی و ایمنِ گره‌ها با استفاده از Eloquent
$docIds = collect($paginator->items())->pluck('id')->map(fn($id) => (int)$id)->toArray(); $docIds = collect($paginator->items())->pluck('id')->map(fn($id) => (int)$id)->toArray();
$nodesByDoc = collect(); $nodesByDoc = collect();
@@ -121,6 +120,12 @@ class BylawApiController extends Controller
$formatted = $this->formatBylaw($bylaw); $formatted = $this->formatBylaw($bylaw);
// --- FETCH NOTE EXACTLY LIKE ART CONTROLLER ---
$formatted['note'] = \App\Models\BylawNote::select('id', 'note', 'color_code', 'created_at')
->where('user_id', auth()->user()->id)
->where('bylaw_document_id', $bylaw->id)
->get();
if (!$formatted['is_locked']) { if (!$formatted['is_locked']) {
$eloquentNodes = BylawNode::with('type') $eloquentNodes = BylawNode::with('type')
->where('document_id', $bylaw->id) ->where('document_id', $bylaw->id)
@@ -340,7 +345,15 @@ class BylawApiController extends Controller
$results = collect($itemsToFormat)->map(function($item) use ($nodesByDoc) { $results = collect($itemsToFormat)->map(function($item) use ($nodesByDoc) {
$itemNodes = $nodesByDoc->get((int)$item->id, collect()); $itemNodes = $nodesByDoc->get((int)$item->id, collect());
return $this->formatBylaw($item, $itemNodes); $formatted = $this->formatBylaw($item, $itemNodes);
// --- FETCH NOTE EXACTLY LIKE ART CONTROLLER ---
$formatted['note'] = \App\Models\BylawNote::select('id', 'note', 'color_code', 'created_at')
->where('user_id', auth()->user()->id)
->where('bylaw_document_id', $item->id)
->get();
return $formatted;
})->values()->toArray(); })->values()->toArray();
return $this->success($results, 'Success', 'Pager Window Details'); return $this->success($results, 'Success', 'Pager Window Details');
@@ -354,22 +367,16 @@ class BylawApiController extends Controller
return (bool) ($item->is_locked ?? false); return (bool) ($item->is_locked ?? false);
} }
/**
* متد قدرتمند برای استخراج ایمن متون
*/
private function formatBylaw($item, $itemNodes = null) private function formatBylaw($item, $itemNodes = null)
{ {
$isLocked = $this->isLockedForCurrentUser($item); $isLocked = $this->isLockedForCurrentUser($item);
// واکشی در صورت خالی بودن کالکشن
if ($itemNodes === null) { if ($itemNodes === null) {
$itemNodes = BylawNode::where('document_id', $item->id)->orderBy('sort_order', 'asc')->get(); $itemNodes = BylawNode::where('document_id', $item->id)->orderBy('sort_order', 'asc')->get();
} }
// استخراج محتوا و تبدیل امنِ Encoding (ضد باگِ JSON Encode لاراول) $nodeContentAsDescription = collect($itemNodes)->pluck('node_content')
$nodeContentAsDescription = $itemNodes->pluck('node_content')
->map(function ($text) { ->map(function ($text) {
// اطمینان از حذف فاصله‌ها و اعمال انکودینگ استاندارد برای جلوگیری از باگ‌های نامرئی
$safeText = trim((string)$text); $safeText = trim((string)$text);
return mb_convert_encoding($safeText, 'UTF-8', 'UTF-8'); return mb_convert_encoding($safeText, 'UTF-8', 'UTF-8');
}) })
@@ -378,7 +385,6 @@ class BylawApiController extends Controller
}) })
->implode("\n\n"); ->implode("\n\n");
// اگر همچنان خالی ماند (فقط در صورتی که دیتابیس واقعاً رکورد نداشته باشد)
if (empty($nodeContentAsDescription)) { if (empty($nodeContentAsDescription)) {
$nodeContentAsDescription = mb_convert_encoding(trim((string)$item->description), 'UTF-8', 'UTF-8'); $nodeContentAsDescription = mb_convert_encoding(trim((string)$item->description), 'UTF-8', 'UTF-8');
} }
@@ -401,13 +407,8 @@ class BylawApiController extends Controller
'bylaw_type' => $item->bylaw_type, 'bylaw_type' => $item->bylaw_type,
'global_status' => $item->global_status, 'global_status' => $item->global_status,
'pdf_file_url' => $isLocked ? null : ($item->pdf_file_path ? asset('storage/' . $item->pdf_file_path) : null), 'pdf_file_url' => $isLocked ? null : ($item->pdf_file_path ? asset('storage/' . $item->pdf_file_path) : null),
// نتیجه استخراج ۱۰۰٪ در اینجا می‌نشیند
'description' => $isLocked ? null : $nodeContentAsDescription, 'description' => $isLocked ? null : $nodeContentAsDescription,
'debug_node_count' => collect($itemNodes)->count(),
// 🚨 پارامتر عیب‌یابی: این عدد نشان می‌دهد چند گره متصل به این فایل در دیتابیس پیدا شد
'debug_node_count' => $itemNodes->count(),
'is_locked' => $isLocked, 'is_locked' => $isLocked,
]; ];
} }

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\BylawNote;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class BylawNoteController extends Controller
{
use BaseApiResponse;
public function create(Request $request)
{
$validated = $request->validate([
'bylaw_document_id' => 'required',
'note' => 'required',
'color_code' => 'nullable',
]);
BylawNote::query()->create([
'user_id' => auth()->user()->id,
'bylaw_document_id' => $validated['bylaw_document_id'],
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'با موفقیت اضافه شد');
}
public function update($id, Request $request)
{
$validated = $request->validate([
'note' => 'required',
'color_code' => 'nullable',
]);
$note = BylawNote::findOrFail($id);
$note->update([
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'بروز شد');
}
public function destroy($id)
{
$note = BylawNote::findOrFail($id);
$note->delete();
return $this->success([], 'حذف شد');
}
}

View File

@@ -90,7 +90,7 @@ class GlobalSearchApiController extends Controller
} }
// ========================================================= // =========================================================
// 3. Search Bylaw Documents (With 100% Bulletproof Node Fetching) // 3. Search Bylaw Documents
// ========================================================= // =========================================================
$bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) $bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true) ->where('is_published', true)
@@ -103,7 +103,7 @@ class GlobalSearchApiController extends Controller
$subQuery->select('document_id') $subQuery->select('document_id')
->from('bylaw_nodes') ->from('bylaw_nodes')
->where('node_content', 'LIKE', "%{$searchTerm}%") ->where('node_content', 'LIKE', "%{$searchTerm}%")
->orWhere('title', 'LIKE', "%{$searchTerm}%"); // Fixed: Title added! ->orWhere('title', 'LIKE', "%{$searchTerm}%");
}); });
})->take($limitPerTable)->get(); })->take($limitPerTable)->get();
@@ -265,7 +265,7 @@ class GlobalSearchApiController extends Controller
} }
} }
// 3. Bylaw Documents (With 100% Bulletproof Node Fetching) // 3. Bylaw Documents
$bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']) $bylawsQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true) ->where('is_published', true)
->where(function ($q) use ($searchTerm) { ->where(function ($q) use ($searchTerm) {
@@ -284,7 +284,7 @@ class GlobalSearchApiController extends Controller
$totalCount += $bylawsQuery->count(); $totalCount += $bylawsQuery->count();
$bylawsRaw = $bylawsQuery->take($limitPerTable)->get(); $bylawsRaw = $bylawsQuery->take($limitPerTable)->get();
// Safely bulk-fetch nodes using DB facade // Bulk-fetch nodes safely using DB facade
$docIds = $bylawsRaw->pluck('id')->toArray(); $docIds = $bylawsRaw->pluck('id')->toArray();
$allNodes = collect(); $allNodes = collect();
if (!empty($docIds)) { if (!empty($docIds)) {
@@ -346,46 +346,35 @@ class GlobalSearchApiController extends Controller
private function isLockedForCurrentUserGeneric($item): bool private function isLockedForCurrentUserGeneric($item): bool
{ {
if (auth()->check() && auth()->user() && method_exists(auth()->user(), 'isSubscriber')) {
return !auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false); return !auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
} }
return (bool) ($item->is_locked ?? false);
}
/** /**
* BULLETPROOF DESCRIPTION GENERATOR (Matches BylawApiController Exactly) * Exact 1:1 match with BylawApiController's encoding approach
*/ */
private function formatBylaw($item, $itemNodes = null) private function formatBylaw($item, $itemNodes = null)
{ {
$isLocked = $this->isLockedForCurrentUserGeneric($item); $isLocked = $this->isLockedForCurrentUserGeneric($item);
$description = $item->description;
// Check if description is practically empty (less than 5 chars = garbage HTML) if ($itemNodes === null) {
$cleanDesc = trim(str_replace(['&nbsp;', '&zwnj;', "\r", "\n", "\t", ' '], '', strip_tags($description ?? ''))); $itemNodes = DB::table('bylaw_nodes')->where('document_id', $item->id)->orderBy('sort_order', 'asc')->get();
if (strlen($cleanDesc) < 5) {
// Absolute Safety Net: If somehow $itemNodes is still null or empty array, FORCE a direct query.
if ($itemNodes === null || (is_object($itemNodes) && $itemNodes->isEmpty())) {
// Verify against DB just in case
$dbNodes = DB::table('bylaw_nodes')->where('document_id', $item->id)->count();
if ($dbNodes > 0) {
$itemNodes = DB::table('bylaw_nodes')
->where('document_id', $item->id)
->orderBy('sort_order', 'asc')
->get();
}
} }
$nodeContents = []; $nodeContentAsDescription = collect($itemNodes)->pluck('node_content')
if ($itemNodes) { ->map(function ($text) {
foreach ($itemNodes as $node) { $safeText = trim((string)$text);
// EXPLICITLY GET node_content return mb_convert_encoding($safeText, 'UTF-8', 'UTF-8');
$content = trim(strip_tags($node->node_content ?? '')); })
if (!empty($content)) { ->filter(function ($text) {
$nodeContents[] = $content; return $text !== '';
} })
} ->implode("\n\n");
}
$description = implode("\n\n", $nodeContents); if (empty($nodeContentAsDescription)) {
$nodeContentAsDescription = mb_convert_encoding(trim((string)$item->description), 'UTF-8', 'UTF-8');
} }
return [ return [
@@ -395,7 +384,7 @@ class GlobalSearchApiController extends Controller
'approval_authority_name' => optional($item->approvalAuthority)->name, 'approval_authority_name' => optional($item->approvalAuthority)->name,
'approval_date' => $item->approval_date, 'approval_date' => $item->approval_date,
'promulgation_number' => $item->promulgation_number, 'promulgation_number' => $item->promulgation_number,
'description' => $isLocked ? null : $description, 'description' => $isLocked ? null : $nodeContentAsDescription,
'is_locked' => $isLocked, 'is_locked' => $isLocked,
]; ];
} }
@@ -432,9 +421,6 @@ class GlobalSearchApiController extends Controller
]; ];
} }
/**
* Exact 1:1 match with ArtController format mapping
*/
private function formatArt($item, $searchTerm, $modelClass) private function formatArt($item, $searchTerm, $modelClass)
{ {
$law = $item->law ?? Law::find($item->law_id); $law = $item->law ?? Law::find($item->law_id);

View File

@@ -146,38 +146,38 @@ class JudicialPrecedentApiController extends Controller
$current = JudicialPrecedent::find($id); $current = JudicialPrecedent::find($id);
if (!$current) { if (!$current) {
return $this->failed([], [ return $this->failed([], ['title' => 'خطا', 'message' => 'رأی وحدت رویه مورد نظر یافت نشد.'], 404);
'title' => 'خطا',
'message' => 'رأی وحدت رویه مورد نظر یافت نشد.'
], 404);
} }
$previousItem = JudicialPrecedent::where(function ($query) use ($current) { $previousItem = JudicialPrecedent::where(function ($query) use ($current) {
$query->where('ruling_date', '<', $current->ruling_date) $query->where('ruling_date', '<', $current->ruling_date)
->orWhere(function ($subQuery) use ($current) { ->orWhere(function ($subQuery) use ($current) {
$subQuery->where('ruling_date', '=', $current->ruling_date) $subQuery->where('ruling_date', '=', $current->ruling_date)->where('id', '<', $current->id);
->where('id', '<', $current->id);
}); });
}) })->orderBy('ruling_date', 'desc')->orderBy('id', 'desc')->first();
->orderBy('ruling_date', 'desc')
->orderBy('id', 'desc')
->first();
$nextItem = JudicialPrecedent::where(function ($query) use ($current) { $nextItem = JudicialPrecedent::where(function ($query) use ($current) {
$query->where('ruling_date', '>', $current->ruling_date) $query->where('ruling_date', '>', $current->ruling_date)
->orWhere(function ($subQuery) use ($current) { ->orWhere(function ($subQuery) use ($current) {
$subQuery->where('ruling_date', '=', $current->ruling_date) $subQuery->where('ruling_date', '=', $current->ruling_date)->where('id', '>', $current->id);
->where('id', '>', $current->id);
}); });
}) })->orderBy('ruling_date', 'asc')->orderBy('id', 'asc')->first();
->orderBy('ruling_date', 'asc')
->orderBy('id', 'asc') // Apply format and add Notes
->first(); $formatWithNote = function($item) {
if (!$item) return null;
$formatted = $this->formatItem($item);
$formatted['note'] = \App\Models\JudicialPrecedentNote::select('id', 'note', 'color_code', 'created_at')
->where('user_id', auth()->user()->id)
->where('judicial_precedent_id', $item->id)
->get();
return $formatted;
};
$results = array_values(array_filter([ $results = array_values(array_filter([
$previousItem ? $this->formatItem($previousItem) : null, $previousItem ? $formatWithNote($previousItem) : null,
$this->formatItem($current), $formatWithNote($current),
$nextItem ? $this->formatItem($nextItem) : null $nextItem ? $formatWithNote($nextItem) : null
])); ]));
return $this->success($results, 'Success', 'Pager Window Details'); return $this->success($results, 'Success', 'Pager Window Details');

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\JudicialPrecedentNote;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class JudicialPrecedentNoteController extends Controller
{
use BaseApiResponse;
public function create(Request $request)
{
$validated = $request->validate([
'judicial_precedent_id' => 'required',
'note' => 'required',
'color_code' => 'nullable',
]);
JudicialPrecedentNote::query()->create([
'user_id' => auth()->id(),
'judicial_precedent_id' => $validated['judicial_precedent_id'],
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'با موفقیت اضافه شد');
}
public function update($id, Request $request)
{
$validated = $request->validate([
'note' => 'required',
'color_code' => 'nullable',
]);
// SECURITY FIX: Only allow the owner of the note to update it
$note = JudicialPrecedentNote::where('user_id', auth()->id())->findOrFail($id);
$note->update([
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'بروز شد');
}
public function destroy($id)
{
$note = JudicialPrecedentNote::where('user_id', auth()->id())->findOrFail($id);
$note->delete();
return $this->success([], 'حذف شد');
}
}

View File

@@ -147,49 +147,46 @@ class LegalOpinionApiController extends Controller
$current = LegalOpinion::find($id); $current = LegalOpinion::find($id);
if (!$current) { if (!$current) {
return $this->failed([], [ return $this->failed([], ['title' => 'خطا', 'message' => 'نظریه قانونی مورد نظر یافت نشد.'], 404);
'title' => 'خطا',
'message' => 'نظریه قانونی مورد نظر یافت نشد.'
], 404);
} }
$previousItem = LegalOpinion::where(function ($query) use ($current) { $previousItem = LegalOpinion::where(function ($query) use ($current) {
if ($current->opinion_date) { if ($current->opinion_date) {
$query->where('opinion_date', '<', $current->opinion_date) $query->where('opinion_date', '<', $current->opinion_date)->orWhere(function ($subQuery) use ($current) {
->orWhere(function ($subQuery) use ($current) { $subQuery->where('opinion_date', '=', $current->opinion_date)->where('id', '<', $current->id);
$subQuery->where('opinion_date', '=', $current->opinion_date)
->where('id', '<', $current->id);
}); });
} else { } else {
$query->whereNull('opinion_date')->where('id', '<', $current->id); $query->whereNull('opinion_date')->where('id', '<', $current->id);
} }
}) })->orderBy('opinion_date', 'desc')->orderBy('id', 'desc')->first();
->orderBy('opinion_date', 'desc')
->orderBy('id', 'desc')
->first();
$nextItem = LegalOpinion::where(function ($query) use ($current) { $nextItem = LegalOpinion::where(function ($query) use ($current) {
if ($current->opinion_date) { if ($current->opinion_date) {
$query->where('opinion_date', '>', $current->opinion_date) $query->where('opinion_date', '>', $current->opinion_date)->orWhere(function ($subQuery) use ($current) {
->orWhere(function ($subQuery) use ($current) { $subQuery->where('opinion_date', '=', $current->opinion_date)->where('id', '>', $current->id);
$subQuery->where('opinion_date', '=', $current->opinion_date)
->where('id', '>', $current->id);
}); });
} else { } else {
$query->whereNotNull('opinion_date') $query->whereNotNull('opinion_date')->orWhere(function ($subQuery) use ($current) {
->orWhere(function ($subQuery) use ($current) {
$subQuery->whereNull('opinion_date')->where('id', '>', $current->id); $subQuery->whereNull('opinion_date')->where('id', '>', $current->id);
}); });
} }
}) })->orderBy('opinion_date', 'asc')->orderBy('id', 'asc')->first();
->orderBy('opinion_date', 'asc')
->orderBy('id', 'asc') // Apply format and add Notes
->first(); $formatWithNote = function($item) {
if (!$item) return null;
$formatted = $this->formatItem($item);
$formatted['note'] = \App\Models\LegalOpinionNote::select('id', 'note', 'color_code', 'created_at')
->where('user_id', auth()->user()->id)
->where('legal_opinion_id', $item->id)
->get();
return $formatted;
};
$results = array_values(array_filter([ $results = array_values(array_filter([
$previousItem ? $this->formatItem($previousItem) : null, $previousItem ? $formatWithNote($previousItem) : null,
$this->formatItem($current), $formatWithNote($current),
$nextItem ? $this->formatItem($nextItem) : null $nextItem ? $formatWithNote($nextItem) : null
])); ]));
return $this->success($results, 'Success', 'Pager Window Details'); return $this->success($results, 'Success', 'Pager Window Details');

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\LegalOpinionNote;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class LegalOpinionNoteController extends Controller
{
use BaseApiResponse;
public function create(Request $request)
{
$validated = $request->validate([
'legal_opinion_id' => 'required',
'note' => 'required',
'color_code' => 'nullable',
]);
LegalOpinionNote::query()->create([
'user_id' => auth()->id(), // Cleaner way to get the user ID
'legal_opinion_id' => $validated['legal_opinion_id'],
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'با موفقیت اضافه شد');
}
public function update($id, Request $request)
{
$validated = $request->validate([
'note' => 'required',
'color_code' => 'nullable',
]);
$note = LegalOpinionNote::where('user_id', auth()->id())->findOrFail($id);
$note->update([
'note' => $validated['note'],
'color_code' => $validated['color_code'],
]);
return $this->success([], 'بروز شد');
}
public function destroy($id)
{
$note = LegalOpinionNote::where('user_id', auth()->id())->findOrFail($id);
$note->delete();
return $this->success([], 'حذف شد');
}
}

11
app/Models/BylawNote.php Normal file
View File

@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawNote extends Model
{
protected $table = 'bylaw_notes';
protected $guarded = [];
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class JudicialPrecedentNote extends Model
{
protected $table = 'judicial_precedent_notes';
protected $guarded = [];
}

View File

@@ -0,0 +1,11 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class LegalOpinionNote extends Model
{
protected $table = 'legal_opinion_notes';
protected $guarded = [];
}

View File

@@ -95,4 +95,21 @@ Route::prefix('v1')->middleware('auth:sanctum')->group(function () {
// Global Search // Global Search
Route::post('global-search', [\App\Http\Controllers\api\GlobalSearchApiController::class, 'search']); Route::post('global-search', [\App\Http\Controllers\api\GlobalSearchApiController::class, 'search']);
Route::post('global-search/fast-search', [\App\Http\Controllers\api\GlobalSearchApiController::class, 'fast_search']); // NEW Route::post('global-search/fast-search', [\App\Http\Controllers\api\GlobalSearchApiController::class, 'fast_search']); // NEW
// Bylaw Notes
Route::post('/bylaw-notes', [\App\Http\Controllers\api\BylawNoteController::class, 'create']);
Route::put('/bylaw-notes/{id}', [\App\Http\Controllers\api\BylawNoteController::class, 'update']);
Route::delete('/bylaw-notes/{id}', [\App\Http\Controllers\api\BylawNoteController::class, 'destroy']);
// Judicial Precedent Notes
Route::post('/judicial-notes', [\App\Http\Controllers\api\JudicialPrecedentNoteController::class, 'create']);
Route::put('/judicial-notes/{id}', [\App\Http\Controllers\api\JudicialPrecedentNoteController::class, 'update']);
Route::delete('/judicial-notes/{id}', [\App\Http\Controllers\api\JudicialPrecedentNoteController::class, 'destroy']);
// Legal Opinion Notes
Route::post('/opinion-notes', [\App\Http\Controllers\api\LegalOpinionNoteController::class, 'create']);
Route::put('/opinion-notes/{id}', [\App\Http\Controllers\api\LegalOpinionNoteController::class, 'update']);
Route::delete('/opinion-notes/{id}', [\App\Http\Controllers\api\LegalOpinionNoteController::class, 'destroy']);
}); });