Compare commits

..

46 Commits

Author SHA1 Message Date
m.razaghi
dcea6423ff Fixed api issue 2026-07-12 16:52:28 +03:30
m.razaghi
51c4570f97 Fixed api issue 2026-07-12 16:49:12 +03:30
m.razaghi
19db0fd24d Fixed api issue 2026-07-12 16:40:27 +03:30
m.razaghi
4d15014621 Fixed api issue 2026-07-12 16:24:16 +03:30
m.razaghi
6c0b1f83f2 Fixed api issue 2026-07-12 16:19:20 +03:30
m.razaghi
cad3fa9e1f Fixed api issue 2026-07-12 16:11:38 +03:30
m.razaghi
1a3f41ca8a Merge remote-tracking branch 'upstream-local/new-api' into clean-main 2026-07-12 16:05:05 +03:30
m.razaghi
e4dad6f9a4 Fixed api issue 2026-07-12 16:02:53 +03:30
16e68c3048 Merge pull request 'Fixed api issue' (#11) from new-api into clean-main
Reviewed-on: #11
2026-07-12 12:27:18 +00:00
m.razaghi
10463e2f71 Fixed api issue 2026-07-12 15:46:34 +03:30
ed95f5b3ee Merge pull request 'Fixed api issue' (#10) from new-api into clean-main
Reviewed-on: #10
2026-07-12 11:56:37 +00:00
m.razaghi
1eedb30acc Fixed api issue 2026-07-12 15:21:01 +03:30
0962801c96 Merge pull request 'Fixed api issue' (#9) from new-api into clean-main
Reviewed-on: #9
2026-07-12 10:42:17 +00:00
m.razaghi
b2ac3d6ec8 Fixed api issue 2026-07-12 14:03:45 +03:30
ecccab9edc Merge pull request 'new-api' (#8) from new-api into clean-main
Reviewed-on: #8
2026-07-12 09:50:32 +00:00
m.razaghi
737f06f68e Fixed api issue 2026-07-12 13:16:57 +03:30
370f4c0a78 Merge pull request 'Fixed api issue' (#7) from new-api into clean-main
Reviewed-on: #7
2026-07-12 09:13:47 +00:00
m.razaghi
a95826e5e5 Fixed api issue 2026-07-12 12:43:28 +03:30
m.razaghi
398fcb4eec Fixed api issue 2026-07-12 11:58:07 +03:30
4214a4b007 Merge pull request 'new-api' (#6) from new-api into clean-main
Reviewed-on: #6
2026-07-12 06:07:23 +00:00
m.razaghi
9d124a07c1 Fixed api issue 2026-07-11 17:27:55 +03:30
m.razaghi
ffea0e3c11 Fixed api issue 2026-07-11 12:25:46 +03:30
2a6313802b Merge pull request 'updated apis' (#5) from new-api into clean-main
Reviewed-on: #5
2026-07-10 20:56:19 +00:00
m.razaghi
3b9fcd76df updated apis 2026-07-10 23:22:56 +03:30
d47f148f12 Merge pull request 'new-api' (#4) from new-api into clean-main
Reviewed-on: #4
2026-07-10 10:58:40 +00:00
m.razaghi
d19d4b8667 updated apis 2026-07-10 13:38:47 +03:30
m.razaghi
3b47d78ee8 Added new apis, fast search 2026-07-09 19:23:06 +03:30
m.razaghi
71a6f683a7 Fixed major bugs 2026-07-09 19:11:39 +03:30
m.razaghi
71dc7da8a4 Fixed major bugs 2026-07-09 17:06:07 +03:30
4ed77dd060 Merge pull request 'Fixed major bugs' (#3) from new-api into clean-main
Reviewed-on: #3
2026-07-08 07:24:33 +00:00
m.razaghi
b7f139b935 Fixed major bugs 2026-07-08 10:51:47 +03:30
0b6851ebe2 Update README.md 2026-07-08 05:44:27 +00:00
80a271d325 Merge pull request 'fixed major bugs' (#2) from new-api into clean-main
Reviewed-on: #2
2026-07-08 05:44:00 +00:00
m.razaghi
83ff22b5a4 fixed major bugs 2026-07-07 21:25:27 +03:30
d27c32c918 Merge pull request 'Added new api' (#1) from new-api into clean-main
Reviewed-on: #1
2026-07-05 10:22:22 +00:00
m.razaghi
ce5ccc00a1 Added new api 2026-07-04 17:05:50 +03:30
f242b8936a feat(BylawDocument): enhance bylaw document forms with improved validation and file upload support 2026-06-26 15:59:45 +03:30
9cf6957675 feat: add bylaw management features including documents, legal authorities, subject categories, and nodes 2026-06-26 13:49:50 +03:30
2e26bd229b refactor(testing): remove dd 2026-05-17 00:47:59 +03:30
e695a80e36 refactor(timeout): set timeout 2026-05-17 00:47:13 +03:30
ece9e6e017 refactor(Core): sent cache 2026-05-17 00:45:58 +03:30
c3d798689c fix(Core): fix bug is lock 2026-05-17 00:00:13 +03:30
2796ce7de7 feat(myket): add myket 2026-05-16 23:44:08 +03:30
c05587474f fix(syntax): fix syntax bug 2026-05-14 19:07:28 +03:30
8fda92ead5 Merge branch 'clean-main' of https://git.geekgrove.ir/soheilkhaledabadi/law-api into clean-main 2026-05-08 18:17:54 +03:30
ae522c5640 feat: add legal opinions admin management 2026-05-08 18:15:21 +03:30
133 changed files with 3853 additions and 421 deletions

View File

@@ -1 +1 @@
Persian ping
## Law

View File

@@ -31,37 +31,41 @@ class AddSubscriptionDays extends Command
if ($days <= 0) {
$this->error('Days must be a positive integer.');
return self::FAILURE;
}
if ($onlyWithoutSubscription && !$allUsers) {
if ($onlyWithoutSubscription && ! $allUsers) {
$this->error('The --only-without-subscription option can only be used with --all-users.');
return self::FAILURE;
}
if ($allUsers) {
$planId = $this->option('plan-id');
if (!$planId) {
if (! $planId) {
$this->error('When using --all-users you must provide --plan-id for users without a subscription.');
return self::FAILURE;
}
$plan = SubscribePlan::find($planId);
if (!$plan) {
if (! $plan) {
$this->error('Subscribe plan not found for the given --plan-id.');
return self::FAILURE;
}
}
if ($allUsers) {
if ($onlyWithoutSubscription) {
$this->info("Granting {$days} day(s) only to users without a subscription." . ($dryRun ? ' (dry-run)' : ''));
$this->info("Granting {$days} day(s) only to users without a subscription.".($dryRun ? ' (dry-run)' : ''));
} else {
$this->info("Granting {$days} day(s) to every user." . ($dryRun ? ' (dry-run)' : ''));
$this->info("Granting {$days} day(s) to every user.".($dryRun ? ' (dry-run)' : ''));
}
} else {
$scopeLabel = $includeExpired ? 'all' : 'active';
$this->info("Extending {$scopeLabel} subscriptions by {$days} day(s)." . ($dryRun ? ' (dry-run)' : ''));
$this->info("Extending {$scopeLabel} subscriptions by {$days} day(s).".($dryRun ? ' (dry-run)' : ''));
}
$touched = 0;
@@ -100,7 +104,7 @@ class AddSubscriptionDays extends Command
});
} else {
$query = UserSubscriber::query();
if (!$includeExpired) {
if (! $includeExpired) {
$query->where('expired_at', '>', now());
}

View File

@@ -44,9 +44,9 @@ class ArtController extends Controller
$laws = Law::all();
$sections = Section::all();
$divisions = Division::all();
$branches = Branch::all();
$branches = Branch::all();
return view('admin.art.create', compact('chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections','branches','divisions'));
return view('admin.art.create', compact('chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections', 'branches', 'divisions'));
}
public function store(Request $request)
@@ -64,7 +64,7 @@ class ArtController extends Controller
'law_id' => 'required',
'division_id' => 'nullable',
'branch_id' => 'nullable',
'is_free' => 'nullable'
'is_free' => 'nullable',
]);
$validated['is_free'] = $request->input('is_free') ? true : false;
@@ -84,10 +84,9 @@ class ArtController extends Controller
$laws = Law::all();
$sections = Section::all();
$divisions = Division::all();
$branches = Branch::all();
$branches = Branch::all();
return view('admin.art.update', compact('art', 'chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections','branches','divisions'));
return view('admin.art.update', compact('art', 'chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections', 'branches', 'divisions'));
}
public function update(Request $request, Art $art)
@@ -106,14 +105,14 @@ class ArtController extends Controller
'law_id' => 'required',
'division_id' => 'nullable',
'branch_id' => 'nullable',
'is_free' => 'nullable'
'is_free' => 'nullable',
]);
$validated['is_free'] = $request->input('is_free') ? true : false;
$art->update($validated);
return redirect(route('art.edit',$art->id));
return redirect(route('art.edit', $art->id));
}
public function destroy(Art $art)

View File

@@ -15,7 +15,7 @@ class BookController extends Controller
$query = Book::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);

View File

@@ -21,7 +21,7 @@ class BranchController extends Controller
$query = Branch::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -41,7 +41,7 @@ class BranchController extends Controller
$sections = Section::all();
$divisions = Division::all();
return view('admin.branch.create', compact('chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections','divisions'));
return view('admin.branch.create', compact('chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections', 'divisions'));
}
public function store(Request $request)
@@ -75,7 +75,7 @@ class BranchController extends Controller
$sections = Section::all();
$divisions = Division::all();
return view('admin.branch.update', compact('branch', 'chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections','divisions'));
return view('admin.branch.update', compact('branch', 'chapters', 'parts', 'gates', 'books', 'volums', 'laws', 'sections', 'divisions'));
}
public function update(Request $request, Branch $branch)
@@ -83,7 +83,7 @@ class BranchController extends Controller
$validated = $request->validate([
'title' => 'required',
'number' => 'required',
'number' => 'required',
'chapter_id' => 'nullable',
'part_id' => 'nullable',
'gate_id' => 'nullable',

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawCodificationLink;
use Illuminate\Http\Request;
class BylawCodificationLinkController extends Controller
{
public function index()
{
$items = BylawCodificationLink::latest('created_at')->paginate(15);
return view('admin.bylaw-codification-link.index', compact('items'));
}
public function create()
{
return view('admin.bylaw-codification-link.create');
}
public function store(Request $request)
{
$data = $request->validate(['source_entity_type' => 'required|in:bylaw_node,bylaw_doc,law_doc,court_verdict,advisory_opinion', 'source_entity_id' => 'required|integer', 'target_entity_type' => 'required|in:bylaw_node,bylaw_doc,law_doc,court_verdict,advisory_opinion', 'target_entity_id' => 'required|integer', 'link_type' => 'required|in:repeals_explicitly,repeals_implicitly,annuls_entirely,annuls_partially,amends,adds_to,interprets,is_executive_bylaw_of', 'effective_date' => 'nullable|date', 'justification' => 'nullable|string']);
$data['created_at'] = now();
BylawCodificationLink::create($data);
return redirect(route('bylaw-codification-link.index'));
}
public function edit(BylawCodificationLink $bylawCodificationLink)
{
return view('admin.bylaw-codification-link.update', compact('bylawCodificationLink'));
}
public function show(BylawCodificationLink $bylawCodificationLink)
{
return redirect(route('bylaw-codification-link.edit', $bylawCodificationLink));
}
public function update(Request $request, BylawCodificationLink $bylawCodificationLink)
{
$data = $request->validate(['source_entity_type' => 'required|in:bylaw_node,bylaw_doc,law_doc,court_verdict,advisory_opinion', 'source_entity_id' => 'required|integer', 'target_entity_type' => 'required|in:bylaw_node,bylaw_doc,law_doc,court_verdict,advisory_opinion', 'target_entity_id' => 'required|integer', 'link_type' => 'required|in:repeals_explicitly,repeals_implicitly,annuls_entirely,annuls_partially,amends,adds_to,interprets,is_executive_bylaw_of', 'effective_date' => 'nullable|date', 'justification' => 'nullable|string']);
$bylawCodificationLink->update($data);
return redirect(route('bylaw-codification-link.edit', $bylawCodificationLink));
}
public function destroy(BylawCodificationLink $bylawCodificationLink)
{
$bylawCodificationLink->delete();
return redirect(route('bylaw-codification-link.index'));
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawDocument;
use App\Models\BylawLegalAuthority;
use App\Models\BylawSubjectCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
class BylawDocumentController extends Controller
{
public function index(Request $request)
{
$query = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority']);
if ($request->filled('q')) {
$query->where('title', 'like', "%{$request->q}%");
}
$items = $query->latest()->paginate(15)->withQueryString();
return view('admin.bylaw-document.index', compact('items'));
}
public function create()
{
$categories = BylawSubjectCategory::all();
$authorities = BylawLegalAuthority::all();
return view('admin.bylaw-document.create', compact('categories', 'authorities'));
}
public function store(Request $request)
{
$data = $request->validate([
'title' => 'required|string|max:1000',
'category_id' => 'nullable|exists:bylaw_subject_categories,id',
'approval_authority_id' => 'nullable|exists:bylaw_legal_authorities,id',
'approval_date' => 'nullable|date',
'promulgation_authority_id' => 'nullable|exists:bylaw_legal_authorities,id',
'promulgation_date' => 'nullable|date',
'promulgation_number' => 'nullable|string|max:100',
'official_gazette_number' => 'nullable|string|max:100',
'official_gazette_date' => 'nullable|date',
'execution_date' => 'nullable|date',
'bylaw_type' => 'required|in:executive,delegated,independent',
'global_status' => 'required|in:valid,explicitly_repealed,implicitly_repealed,annulled,expired,draft',
'pdf_file' => 'nullable|file|mimes:pdf|max:20480',
'pdf_file_path' => 'nullable|string|max:500',
'is_published' => 'nullable|boolean',
'description' => 'nullable|string',
]);
if ($request->hasFile('pdf_file')) {
$data['pdf_file_path'] = $request->file('pdf_file')->store('pdfs', 'public');
}
$data['is_published'] = $request->boolean('is_published');
BylawDocument::create($data);
return redirect(route('bylaw-document.index'));
}
public function edit(BylawDocument $bylawDocument)
{
$categories = BylawSubjectCategory::all();
$authorities = BylawLegalAuthority::all();
return view('admin.bylaw-document.update', compact('bylawDocument', 'categories', 'authorities'));
}
public function show(BylawDocument $bylawDocument)
{
return redirect(route('bylaw-document.edit', $bylawDocument));
}
public function update(Request $request, BylawDocument $bylawDocument)
{
$data = $request->validate([
'title' => 'required|string|max:1000',
'category_id' => 'nullable|exists:bylaw_subject_categories,id',
'approval_authority_id' => 'nullable|exists:bylaw_legal_authorities,id',
'approval_date' => 'nullable|date',
'promulgation_authority_id' => 'nullable|exists:bylaw_legal_authorities,id',
'promulgation_date' => 'nullable|date',
'promulgation_number' => 'nullable|string|max:100',
'official_gazette_number' => 'nullable|string|max:100',
'official_gazette_date' => 'nullable|date',
'execution_date' => 'nullable|date',
'bylaw_type' => 'required|in:executive,delegated,independent',
'global_status' => 'required|in:valid,explicitly_repealed,implicitly_repealed,annulled,expired,draft',
'pdf_file' => 'nullable|file|mimes:pdf|max:20480',
'pdf_file_path' => 'nullable|string|max:500',
'is_published' => 'nullable|boolean',
'description' => 'nullable|string',
]);
if ($request->hasFile('pdf_file')) {
if ($bylawDocument->pdf_file_path && Storage::disk('public')->exists($bylawDocument->pdf_file_path)) {
Storage::disk('public')->delete($bylawDocument->pdf_file_path);
}
$data['pdf_file_path'] = $request->file('pdf_file')->store('pdfs', 'public');
}
$data['is_published'] = $request->boolean('is_published');
$bylawDocument->update($data);
return redirect(route('bylaw-document.edit', $bylawDocument));
}
public function destroy(BylawDocument $bylawDocument)
{
$bylawDocument->delete();
return redirect(route('bylaw-document.index'));
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawLegalAuthority;
use Illuminate\Http\Request;
class BylawLegalAuthorityController extends Controller
{
public function index(Request $request)
{
$query = BylawLegalAuthority::query();
if ($request->filled('q')) {
$query->where('name', 'like', "%{$request->q}%");
}
$items = $query->latest()->paginate(15)->withQueryString();
return view('admin.bylaw-legal-authority.index', compact('items'));
}
public function create()
{
return view('admin.bylaw-legal-authority.create');
}
public function store(Request $request)
{
$data = $request->validate(['name' => 'required|unique:bylaw_legal_authorities,name', 'authority_type' => 'required|in:executive,judicial,legislative,administrative,other', 'description' => 'nullable|string']);
BylawLegalAuthority::create($data);
return redirect(route('bylaw-legal-authority.index'));
}
public function edit(BylawLegalAuthority $bylawLegalAuthority)
{
return view('admin.bylaw-legal-authority.update', compact('bylawLegalAuthority'));
}
public function show(BylawLegalAuthority $bylawLegalAuthority)
{
return redirect(route('bylaw-legal-authority.edit', $bylawLegalAuthority));
}
public function update(Request $request, BylawLegalAuthority $bylawLegalAuthority)
{
$data = $request->validate(['name' => 'required|unique:bylaw_legal_authorities,name,'.$bylawLegalAuthority->id, 'authority_type' => 'required|in:executive,judicial,legislative,administrative,other', 'description' => 'nullable|string']);
$bylawLegalAuthority->update($data);
return redirect(route('bylaw-legal-authority.edit', $bylawLegalAuthority));
}
public function destroy(BylawLegalAuthority $bylawLegalAuthority)
{
$bylawLegalAuthority->delete();
return redirect(route('bylaw-legal-authority.index'));
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawDocument;
use App\Models\BylawNode;
use App\Models\BylawNodeType;
use Illuminate\Http\Request;
class BylawNodeController extends Controller
{
public function index()
{
$items = BylawNode::with(['document', 'type'])->latest()->paginate(15);
return view('admin.bylaw-node.index', compact('items'));
}
public function create()
{
return view('admin.bylaw-node.create', ['documents' => BylawDocument::all(), 'types' => BylawNodeType::all(), 'parents' => BylawNode::all()]);
}
public function store(Request $request)
{
$data = $request->validate(['document_id' => 'required|exists:bylaw_documents,id', 'parent_id' => 'nullable|exists:bylaw_nodes,id', 'node_type_id' => 'required|exists:bylaw_node_types,id', 'node_identifier' => 'nullable|string|max:50', 'title' => 'nullable|string|max:500', 'node_content' => 'nullable|string', 'sort_order' => 'nullable|integer', 'valid_from' => 'nullable|date', 'valid_to' => 'nullable|date', 'node_status' => 'required|in:valid,repealed,annulled,amended,suspended']);
BylawNode::create($data);
return redirect(route('bylaw-node.index'));
}
public function edit(BylawNode $bylawNode)
{
return view('admin.bylaw-node.update', ['bylawNode' => $bylawNode, 'documents' => BylawDocument::all(), 'types' => BylawNodeType::all(), 'parents' => BylawNode::where('id', '!=', $bylawNode->id)->get()]);
}
public function show(BylawNode $bylawNode)
{
return redirect(route('bylaw-node.edit', $bylawNode));
}
public function update(Request $request, BylawNode $bylawNode)
{
$data = $request->validate(['document_id' => 'required|exists:bylaw_documents,id', 'parent_id' => 'nullable|exists:bylaw_nodes,id', 'node_type_id' => 'required|exists:bylaw_node_types,id', 'node_identifier' => 'nullable|string|max:50', 'title' => 'nullable|string|max:500', 'node_content' => 'nullable|string', 'sort_order' => 'nullable|integer', 'valid_from' => 'nullable|date', 'valid_to' => 'nullable|date', 'node_status' => 'required|in:valid,repealed,annulled,amended,suspended']);
$bylawNode->update($data);
return redirect(route('bylaw-node.edit', $bylawNode));
}
public function destroy(BylawNode $bylawNode)
{
$bylawNode->delete();
return redirect(route('bylaw-node.index'));
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawNodeType;
use Illuminate\Http\Request;
class BylawNodeTypeController extends Controller
{
public function index(Request $request)
{
$items = BylawNodeType::latest()->paginate(15)->withQueryString();
return view('admin.bylaw-node-type.index', compact('items'));
}
public function create()
{
return view('admin.bylaw-node-type.create');
}
public function store(Request $request)
{
$data = $request->validate(['name' => 'required|unique:bylaw_node_types,name', 'hierarchy_level' => 'required|integer']);
BylawNodeType::create($data);
return redirect(route('bylaw-node-type.index'));
}
public function edit(BylawNodeType $bylawNodeType)
{
return view('admin.bylaw-node-type.update', compact('bylawNodeType'));
}
public function show(BylawNodeType $bylawNodeType)
{
return redirect(route('bylaw-node-type.edit', $bylawNodeType));
}
public function update(Request $request, BylawNodeType $bylawNodeType)
{
$data = $request->validate(['name' => 'required|unique:bylaw_node_types,name,'.$bylawNodeType->id, 'hierarchy_level' => 'required|integer']);
$bylawNodeType->update($data);
return redirect(route('bylaw-node-type.edit', $bylawNodeType));
}
public function destroy(BylawNodeType $bylawNodeType)
{
$bylawNodeType->delete();
return redirect(route('bylaw-node-type.index'));
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\BylawSubjectCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class BylawSubjectCategoryController extends Controller
{
public function index(Request $request)
{
$query = BylawSubjectCategory::query();
if ($request->filled('q')) {
$query->where('name', 'like', "%{$request->q}%");
} $items = $query->latest()->paginate(15)->withQueryString();
return view('admin.bylaw-subject-category.index', compact('items'));
}
public function create()
{
$parents = BylawSubjectCategory::all();
return view('admin.bylaw-subject-category.create', compact('parents'));
}
public function store(Request $request)
{
$data = $request->validate(['parent_id' => 'nullable|exists:bylaw_subject_categories,id', 'name' => 'required|string', 'slug' => 'nullable|string|unique:bylaw_subject_categories,slug', 'sort_order' => 'nullable|integer']);
$data['slug'] = $data['slug'] ?? Str::slug($data['name']);
BylawSubjectCategory::create($data);
return redirect(route('bylaw-subject-category.index'));
}
public function edit(BylawSubjectCategory $bylawSubjectCategory)
{
$parents = BylawSubjectCategory::where('id', '!=', $bylawSubjectCategory->id)->get();
return view('admin.bylaw-subject-category.update', compact('bylawSubjectCategory', 'parents'));
}
public function show(BylawSubjectCategory $bylawSubjectCategory)
{
return redirect(route('bylaw-subject-category.edit', $bylawSubjectCategory));
}
public function update(Request $request, BylawSubjectCategory $bylawSubjectCategory)
{
$data = $request->validate(['parent_id' => 'nullable|exists:bylaw_subject_categories,id', 'name' => 'required|string', 'slug' => 'required|string|unique:bylaw_subject_categories,slug,'.$bylawSubjectCategory->id, 'sort_order' => 'nullable|integer']);
$bylawSubjectCategory->update($data);
return redirect(route('bylaw-subject-category.edit', $bylawSubjectCategory));
}
public function destroy(BylawSubjectCategory $bylawSubjectCategory)
{
$bylawSubjectCategory->delete();
return redirect(route('bylaw-subject-category.index'));
}
}

View File

@@ -13,7 +13,7 @@ class CategoryController extends Controller
$query = Category::query();
if ($request->filled('q')) {
$query->where('name', 'like', '%' . $request->q . '%');
$query->where('name', 'like', '%'.$request->q.'%');
}
if ($request->filled('type')) {
$query->where('type', $request->type);
@@ -32,12 +32,11 @@ class CategoryController extends Controller
public function store(Request $request)
{
$validated = $request->validate([
$validated = $request->validate([
'name' => 'required',
'type' => 'required'
'type' => 'required',
]);
Category::create($validated);
return redirect(route('categories.index'));
@@ -45,14 +44,14 @@ class CategoryController extends Controller
public function edit(Category $category)
{
return view('admin.categories.update',compact('category'));
return view('admin.categories.update', compact('category'));
}
public function update(Request $request, Category $category)
{
$validated = $request->validate([
$validated = $request->validate([
'name' => 'required',
'type' => 'required'
'type' => 'required',
]);
$category->update($validated);

View File

@@ -18,7 +18,7 @@ class ChapterController extends Controller
$query = Chapter::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -35,7 +35,7 @@ class ChapterController extends Controller
$sections = Section::all();
$divisions = Division::all();
return view('admin.chapter.create', compact('sections', 'books', 'volums', 'laws','divisions'));
return view('admin.chapter.create', compact('sections', 'books', 'volums', 'laws', 'divisions'));
}
public function store(Request $request)
@@ -47,7 +47,7 @@ class ChapterController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
Chapter::query()->create($validated);
@@ -63,7 +63,7 @@ class ChapterController extends Controller
$laws = Law::all();
$divisions = Division::all();
return view('admin.chapter.update', compact('sections', 'chapter', 'books', 'volums', 'laws','divisions'));
return view('admin.chapter.update', compact('sections', 'chapter', 'books', 'volums', 'laws', 'divisions'));
}
public function update(Request $request, Chapter $chapter)
@@ -75,7 +75,7 @@ class ChapterController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
$chapter->update($validated);

View File

@@ -16,7 +16,7 @@ class DivisionController extends Controller
$query = Division::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -55,7 +55,7 @@ class DivisionController extends Controller
$volums = Volum::all();
$laws = Law::all();
return view('admin.division.update', compact('division','books', 'volums', 'laws'));
return view('admin.division.update', compact('division', 'books', 'volums', 'laws'));
}
public function update(Request $request, Division $division)

View File

@@ -20,7 +20,7 @@ class GateController extends Controller
$query = Gate::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -37,9 +37,9 @@ class GateController extends Controller
$books = Book::all();
$volums = Volum::all();
$laws = Law::all();
$divisions = Division::all();
$divisions = Division::all();
return view('admin.gate.create', compact('parts', 'chapters', 'sections', 'books', 'volums', 'laws','divisions'));
return view('admin.gate.create', compact('parts', 'chapters', 'sections', 'books', 'volums', 'laws', 'divisions'));
}
public function store(Request $request)
@@ -64,9 +64,9 @@ class GateController extends Controller
$books = Book::all();
$volums = Volum::all();
$laws = Law::all();
$divisions = Division::all();
$divisions = Division::all();
return view('admin.gate.update', compact('gate', 'parts', 'chapters', 'sections', 'books', 'volums', 'laws','divisions'));
return view('admin.gate.update', compact('gate', 'parts', 'chapters', 'sections', 'books', 'volums', 'laws', 'divisions'));
}
public function update(Request $request, Gate $gate)

View File

@@ -40,7 +40,7 @@ class JudicialPrecedentCategoryController extends Controller
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|unique:judicial_precedent_categories,name'
'name' => 'required|string|unique:judicial_precedent_categories,name',
]);
JudicialPrecedentCategory::create($validated);
@@ -70,7 +70,7 @@ class JudicialPrecedentCategoryController extends Controller
public function update(Request $request, JudicialPrecedentCategory $judicialPrecedentCategory)
{
$validated = $request->validate([
'name' => 'required|string|unique:judicial_precedent_categories,name,' . $judicialPrecedentCategory->id
'name' => 'required|string|unique:judicial_precedent_categories,name,'.$judicialPrecedentCategory->id,
]);
$judicialPrecedentCategory->update($validated);
@@ -84,6 +84,7 @@ class JudicialPrecedentCategoryController extends Controller
public function destroy(JudicialPrecedentCategory $judicialPrecedentCategory)
{
$judicialPrecedentCategory->delete();
return redirect(route('judicial-precedent-category.index'));
}
}

View File

@@ -33,6 +33,7 @@ class JudicialPrecedentController extends Controller
{
$arts = Art::all();
$categories = JudicialPrecedentCategory::all();
return view('admin.judicial-precedent.create', compact('arts', 'categories'));
}
@@ -46,7 +47,7 @@ class JudicialPrecedentController extends Controller
'issuing_authority' => 'nullable|string',
'category_id' => 'nullable|exists:judicial_precedent_categories,id',
'art_ids' => 'nullable|array',
'art_ids.*' => 'exists:arts,id'
'art_ids.*' => 'exists:arts,id',
]);
$judicialPrecedent = JudicialPrecedent::create([
@@ -55,10 +56,10 @@ class JudicialPrecedentController extends Controller
'subject' => $validated['subject'],
'full_text' => $validated['full_text'],
'issuing_authority' => $validated['issuing_authority'] ?? 'هیأت عمومی دیوان عالی کشور',
'category_id' => $validated['category_id']
'category_id' => $validated['category_id'],
]);
if (!empty($validated['art_ids'])) {
if (! empty($validated['art_ids'])) {
$judicialPrecedent->arts()->attach($validated['art_ids']);
}
@@ -77,14 +78,14 @@ class JudicialPrecedentController extends Controller
public function update(Request $request, JudicialPrecedent $judicialPrecedent)
{
$validated = $request->validate([
'ruling_number' => 'required|unique:judicial_precedents,ruling_number,' . $judicialPrecedent->id,
'ruling_number' => 'required|unique:judicial_precedents,ruling_number,'.$judicialPrecedent->id,
'ruling_date' => 'required|date',
'subject' => 'required|string',
'full_text' => 'required|string',
'issuing_authority' => 'nullable|string',
'category_id' => 'nullable|exists:judicial_precedent_categories,id',
'art_ids' => 'nullable|array',
'art_ids.*' => 'exists:arts,id'
'art_ids.*' => 'exists:arts,id',
]);
$judicialPrecedent->update($validated);
@@ -97,6 +98,7 @@ class JudicialPrecedentController extends Controller
public function destroy(JudicialPrecedent $judicialPrecedent)
{
$judicialPrecedent->delete();
return redirect(route('judicial-precedent.index'));
}
}

View File

@@ -14,7 +14,7 @@ class LawController extends Controller
$query = Law::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
if ($request->filled('locked')) {
$query->where('is_locked', $request->locked === '1');
@@ -46,8 +46,7 @@ class LawController extends Controller
$validated['is_locked'] = $request->has('is_locked', false);
if ($request->hasFile('image') && $request->file('image')->isValid()) {
dd($request->has('image'));
$imageName = uniqid('image_', true) . '.' . $request->file('image')->getClientOriginalExtension();
$imageName = uniqid('image_', true).'.'.$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(public_path('images'), $imageName);
@@ -59,11 +58,10 @@ class LawController extends Controller
return redirect()->route('law.index')->with('success', 'Law created successfully.');
}
public function edit(Law $law)
{
$categories = Category::all();
return view('admin.law.update', compact('law', 'categories'));
}
@@ -80,7 +78,7 @@ class LawController extends Controller
$validated['is_locked'] = $request->boolean('is_locked');
if ($request->hasFile('image') && $request->file('image')->isValid()) {
$imageName = uniqid('image_', true) . '.' . $request->file('image')->getClientOriginalExtension();
$imageName = uniqid('image_', true).'.'.$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(public_path('images'), $imageName);
$validated['image'] = $imageName;
}

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\LegalOpinionCategory;
use Illuminate\Http\Request;
class LegalOpinionCategoryController extends Controller
{
public function index(Request $request)
{
$query = LegalOpinionCategory::query();
if ($request->filled('q')) {
$q = $request->q;
$query->where('name', 'like', "%{$q}%");
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$categories = $query->paginate($perPage)->withQueryString();
return view('admin.legal-opinion-category.index', compact('categories'));
}
public function create()
{
return view('admin.legal-opinion-category.create');
}
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|unique:legal_opinion_categories,name',
]);
LegalOpinionCategory::create($validated);
return redirect(route('legal-opinion-category.index'));
}
public function edit(LegalOpinionCategory $legalOpinionCategory)
{
return view('admin.legal-opinion-category.update', compact('legalOpinionCategory'));
}
public function show(LegalOpinionCategory $legalOpinionCategory)
{
return redirect(route('legal-opinion-category.edit', $legalOpinionCategory->id));
}
public function update(Request $request, LegalOpinionCategory $legalOpinionCategory)
{
$validated = $request->validate([
'name' => 'required|string|unique:legal_opinion_categories,name,'.$legalOpinionCategory->id,
]);
$legalOpinionCategory->update($validated);
return redirect(route('legal-opinion-category.edit', $legalOpinionCategory->id));
}
public function destroy(LegalOpinionCategory $legalOpinionCategory)
{
$legalOpinionCategory->delete();
return redirect(route('legal-opinion-category.index'));
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Art;
use App\Models\LegalOpinion;
use App\Models\LegalOpinionCategory;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class LegalOpinionController extends Controller
{
public function index(Request $request)
{
$query = LegalOpinion::with('category');
if ($request->filled('q')) {
$q = $request->q;
$query->where(function ($qry) use ($q) {
$qry->where('opinion_number', 'like', "%{$q}%")
->orWhere('subject', 'like', "%{$q}%")
->orWhere('full_text', 'like', "%{$q}%")
->orWhere('issuing_authority', 'like', "%{$q}%");
});
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$legalOpinions = $query->latest()->paginate($perPage)->withQueryString();
return view('admin.legal-opinion.index', compact('legalOpinions'));
}
public function create()
{
$arts = Art::all();
$categories = LegalOpinionCategory::all();
return view('admin.legal-opinion.create', compact('arts', 'categories'));
}
public function store(Request $request)
{
$validated = $request->validate([
'opinion_number' => [
'required',
Rule::unique('legal_opinions', 'opinion_number')->where('category_id', $request->input('category_id')),
],
'opinion_date' => 'nullable|date',
'subject' => 'nullable|string|max:1000',
'full_text' => 'required|string',
'issuing_authority' => 'nullable|string',
'category_id' => 'required|exists:legal_opinion_categories,id',
'art_ids' => 'nullable|array',
'art_ids.*' => 'exists:art,id',
]);
$legalOpinion = LegalOpinion::create([
'opinion_number' => $validated['opinion_number'],
'opinion_date' => $validated['opinion_date'] ?? null,
'subject' => $validated['subject'] ?? null,
'full_text' => $validated['full_text'],
'issuing_authority' => $validated['issuing_authority'] ?? null,
'category_id' => $validated['category_id'],
]);
if (! empty($validated['art_ids'])) {
$legalOpinion->arts()->attach($validated['art_ids']);
}
return redirect(route('legal-opinion.index'));
}
public function edit(LegalOpinion $legalOpinion)
{
$arts = Art::all();
$categories = LegalOpinionCategory::all();
$selectedArtIds = $legalOpinion->arts->pluck('id')->toArray();
return view('admin.legal-opinion.update', compact('legalOpinion', 'arts', 'categories', 'selectedArtIds'));
}
public function show(LegalOpinion $legalOpinion)
{
return redirect(route('legal-opinion.edit', $legalOpinion->id));
}
public function update(Request $request, LegalOpinion $legalOpinion)
{
$validated = $request->validate([
'opinion_number' => [
'required',
Rule::unique('legal_opinions', 'opinion_number')
->where('category_id', $request->input('category_id'))
->ignore($legalOpinion->id),
],
'opinion_date' => 'nullable|date',
'subject' => 'nullable|string|max:1000',
'full_text' => 'required|string',
'issuing_authority' => 'nullable|string',
'category_id' => 'required|exists:legal_opinion_categories,id',
'art_ids' => 'nullable|array',
'art_ids.*' => 'exists:art,id',
]);
$legalOpinion->update([
'opinion_number' => $validated['opinion_number'],
'opinion_date' => $validated['opinion_date'] ?? null,
'subject' => $validated['subject'] ?? null,
'full_text' => $validated['full_text'],
'issuing_authority' => $validated['issuing_authority'] ?? null,
'category_id' => $validated['category_id'],
]);
$legalOpinion->arts()->sync($validated['art_ids'] ?? []);
return redirect(route('legal-opinion.edit', $legalOpinion->id));
}
public function destroy(LegalOpinion $legalOpinion)
{
$legalOpinion->delete();
return redirect(route('legal-opinion.index'));
}
}

View File

@@ -36,6 +36,7 @@ class NotificationController extends Controller
public function store(StoreRequest $request)
{
Notification::create($request->validated());
return redirect()->route('notifications.index');
}
@@ -47,12 +48,14 @@ class NotificationController extends Controller
public function update(UpdateRequest $request, Notification $notification)
{
$notification->update($request->validated());
return redirect()->route('notifications.index');
}
public function destroy(Notification $notification)
{
$notification->delete();
return redirect()->route('notifications.index');
}
}

View File

@@ -19,7 +19,7 @@ class PartController extends Controller
$query = Part::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -37,7 +37,7 @@ class PartController extends Controller
$laws = Law::all();
$divisions = Division::all();
return view('admin.part.create', compact('chapters', 'sections', 'books', 'volums', 'laws','divisions'));
return view('admin.part.create', compact('chapters', 'sections', 'books', 'volums', 'laws', 'divisions'));
}
public function store(Request $request)
@@ -50,7 +50,7 @@ class PartController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
Part::query()->create($validated);
@@ -67,7 +67,7 @@ class PartController extends Controller
$laws = Law::all();
$divisions = Division::all();
return view('admin.part.update', compact('part', 'chapters', 'sections', 'books', 'volums', 'laws','divisions'));
return view('admin.part.update', compact('part', 'chapters', 'sections', 'books', 'volums', 'laws', 'divisions'));
}
public function update(Request $request, Part $part)
@@ -80,7 +80,7 @@ class PartController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
$part->update($validated);

View File

@@ -17,7 +17,7 @@ class SectionController extends Controller
$query = Section::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
@@ -34,7 +34,7 @@ class SectionController extends Controller
$sections = Section::all();
$divisions = Division::all();
return view('admin.section.create', compact('books', 'volums', 'laws','sections','divisions'));
return view('admin.section.create', compact('books', 'volums', 'laws', 'sections', 'divisions'));
}
public function store(Request $request)
@@ -45,7 +45,7 @@ class SectionController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
section::query()->create($validated);
@@ -61,7 +61,7 @@ class SectionController extends Controller
$sections = Section::all();
$divisions = Division::all();
return view('admin.section.update', compact('section', 'books', 'volums', 'laws','sections','divisions'));
return view('admin.section.update', compact('section', 'books', 'volums', 'laws', 'sections', 'divisions'));
}
public function update(Request $request, Section $section)
@@ -72,7 +72,7 @@ class SectionController extends Controller
'book_id' => 'nullable',
'volum_id' => 'nullable',
'law_id' => 'nullable',
'division_id' => 'nullable'
'division_id' => 'nullable',
]);
$section->update($validated);

View File

@@ -37,10 +37,10 @@ class SubscribePlanController extends Controller
$validated['is_free'] = $request->has('is_free');
SubscribePlan::create($validated);
return redirect()->route('subscribe-plans.index');
}
public function edit(SubscribePlan $subscribePlan)
{
return view('admin.subscribe-plans.update', compact('subscribePlan'));
@@ -53,12 +53,14 @@ class SubscribePlanController extends Controller
$validated['is_free'] = $request->has('is_free');
$subscribePlan->update($validated);
return redirect()->route('subscribe-plans.index');
}
public function destroy(SubscribePlan $subscribePlan)
{
$subscribePlan->delete();
return redirect()->route('subscribe-plans.index');
}
}

View File

@@ -41,6 +41,7 @@ class VersionController extends Controller
$validated['force_update'] = $validated['force_update'] == 'on' ? 1 : 0;
}
Version::create($validated);
return redirect(route('versions.index'));
}
@@ -56,12 +57,14 @@ class VersionController extends Controller
$validated['force_update'] = $validated['force_update'] == 'on' ? 1 : 0;
}
$version->update($validated);
return redirect(route('versions.index'));
}
public function destroy(Version $version)
{
$version->delete();
return redirect(route('versions.index'));
}
}

View File

@@ -14,7 +14,7 @@ class VolumController extends Controller
$query = Volum::query();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
$query->where('title', 'like', '%'.$request->q.'%');
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);

View File

@@ -14,9 +14,9 @@ class SuggestionController extends Controller
{
Suggestion::create([
'user_id' => auth()->user()->id,
'text' => $requst->text
'text' => $requst->text,
]);
return $this->success(null,'موفقیت','پیشنهاد شما با موفقیت برای مدیر ارسال شد');
return $this->success(null, 'موفقیت', 'پیشنهاد شما با موفقیت برای مدیر ارسال شد');
}
}

View File

@@ -26,6 +26,13 @@ class ArtController extends Controller
public function index(GetApiRequest $request)
{
$book = Book::find($request->book_id);
$law = Law::find($book?->law_id);
if ($this->isLockedForCurrentUser($law)) {
return $this->failed([], ['title' => 'Subscription Required', 'message' => 'This content requires an active subscription.'], 403);
}
$arts = Art::with(['chapter', 'part', 'volum', 'law', 'book', 'section', 'gate'])->where('book_id', $request->book_id)->orderBy('number')->get();
$arts = $arts->map(function ($art) {
@@ -78,19 +85,23 @@ class ArtController extends Controller
{
$art = Art::select('id', 'title', 'number', 'text', 'law_id')->find($id);
if (!$art) {
if (! $art) {
return $this->failed([], 'Art not found');
}
$law = Law::find($art?->law_id);
if ($this->isLockedForCurrentUser($law)) {
return $this->failed([], ['title' => 'Subscription Required', 'message' => 'This content requires an active subscription.'], 403);
}
$art->is_like = $this->isLiked($art->id);
$art->note = Note::select('id', 'note', 'color_code','created_at')->where('user_id', auth()->user()->id)->where('art_id', $id)->get();
$art->note = Note::select('id', 'note', 'color_code', 'created_at')->where('user_id', auth()->user()->id)->where('art_id', $id)->get();
$art->category = $law?->category?->name;
$art->route = array_values($this->route(Art::class, $art));
$previousArt = Art::select('id', 'title', 'number', 'text', 'law_id')
->where('law_id',$art->law_id)
->where('law_id', $art->law_id)
->where('number', '<', $art->number)
->orderBy('number', 'desc')
->first();
@@ -104,7 +115,7 @@ class ArtController extends Controller
}
$nextArt = Art::select('id', 'title', 'number', 'text', 'law_id')
->where('law_id',$art->law_id)
->where('law_id', $art->law_id)
->where('number', '>', $art->number)
->orderBy('number')
->first();
@@ -144,7 +155,6 @@ class ArtController extends Controller
return $this->success(null, 'Success', 'Art liked successfully');
}
private function isLiked($art_id): bool
{
return LikeArt::query()->where('art_id', $art_id)
@@ -152,23 +162,29 @@ class ArtController extends Controller
->exists();
}
private function isLockedForCurrentUser(?Law $law): bool
{
return ! auth()->user()->isSubscriber() && (bool) $law?->is_locked;
}
public function likes()
{
$likes = LikeArt::query()->where('user_id', auth()->user()->id)
->with('art')
->with('art.law')
->get()
->map(function ($q) {
$isLocked = $this->isLockedForCurrentUser($q->art?->law);
return [
'id' => $q->art->id,
'title' => $q->art->title,
'text' => $q->art->text
'text' => $isLocked ? null : $q->art->text,
];
});
return $this->success($likes);
}
public function search(Request $request)
{
$validated = $request->validate([
@@ -183,7 +199,7 @@ class ArtController extends Controller
'branch_id' => 'nullable|array',
'category_id' => 'nullable|int',
'per_page' => 'nullable|integer',
'search' => 'nullable|string'
'search' => 'nullable|string',
]);
$models = [
@@ -196,7 +212,7 @@ class ArtController extends Controller
Part::class,
Gate::class,
Branch::class,
Art::class
Art::class,
];
$results = [];
@@ -220,13 +236,13 @@ class ArtController extends Controller
'part_id',
'gate_id',
'chapter_id',
'branch_id'
'branch_id',
];
$model = new $modelClass;
if ($model->getTable() == 'art') {
$query->where(function ($query) use ($validated, $filters) {
if (!empty($validated['search'])) {
if (! empty($validated['search'])) {
$query->where(function ($q) use ($validated) {
$q->where('title', 'LIKE', "%{$validated['search']}%")
->orWhere('text', 'LIKE', "%{$validated['search']}%");
@@ -234,14 +250,13 @@ class ArtController extends Controller
}
foreach ($filters as $filter) {
if (!empty($validated[$filter])) {
if (! empty($validated[$filter])) {
$query->whereIn($filter, $validated[$filter]);
}
}
});
if (!empty($validated['category_id'])) {
if (! empty($validated['category_id'])) {
$query->whereIn('law_id', Category::where('type', $this->convertValueTo($validated['category_id']))->get()->pluck('id'));
}
@@ -250,19 +265,20 @@ class ArtController extends Controller
return $items->map(function ($item) use ($validated, $modelClass) {
$text = $item->text ?? '';
$search = preg_quote($validated['search'] ?? '', '/');
if (!empty($text) && preg_match('/\b(.{0,50})\b(' . $search . ')\b(.{0,50})\b/i', $text, $matches)) {
$context = trim($matches[1] ?? '') . ' ' . $matches[2] . ' ' . trim($matches[3] ?? '');
if (! empty($text) && preg_match('/\b(.{0,50})\b('.$search.')\b(.{0,50})\b/i', $text, $matches)) {
$context = trim($matches[1] ?? '').' '.$matches[2].' '.trim($matches[3] ?? '');
} else {
$context = $text;
}
$law = Law::find($item->law_id);
$isLocked = $this->isLockedForCurrentUser($law);
return [
'id' => $item->id,
'title' => $item->title,
'text' => $context,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'text' => $isLocked ? null : $context,
'is_locked' => $isLocked,
'type' => 'art',
'route' => array_values($this->route($modelClass, $item)),
'category' => optional($law->category)->name,
@@ -270,11 +286,11 @@ class ArtController extends Controller
'count_art' => $law->arts->count(),
'count_volums' => $law->volums->count(),
'price' => $law->price,
'image' => $law->image
'image' => $law->image,
];
})->toArray();
} else {
$query = $query->where('title', 'LIKE', '%' . ($validated['search'] ?? '') . '%');
$query = $query->where('title', 'LIKE', '%'.($validated['search'] ?? '').'%');
}
$items = $query->paginate($validated['per_page'] ?? 10);
@@ -287,21 +303,21 @@ class ArtController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => (new $modelClass)->getTable(),
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'route' => array_values($this->route($modelClass, $item)),
'category' => optional($law?->category)?->name ?? '',
'image' => $law->image
'image' => $law->image,
];
} else if ((new $modelClass)->getTable() == 'art') {
} elseif ((new $modelClass)->getTable() == 'art') {
return [
'id' => $item->id,
'title' => $item->title,
'number' => $item->number,
'type' => (new $modelClass)->getTable(),
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'route' => array_values($this->route($modelClass, $item)),
'law' => $law?->title ?? '',
'image' => $law->image
'image' => $law->image,
];
} else {
return [
@@ -309,7 +325,7 @@ class ArtController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => (new $modelClass)->getTable(),
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : optional($law)->is_locked,
'route' => array_values($this->route($modelClass, $item)),
'law' => $law?->title ?? '',
];
@@ -317,8 +333,6 @@ class ArtController extends Controller
})->toArray();
}
private function route($modelClass, $query)
{
if ((new $modelClass)->getTable() == 'art') {
@@ -331,12 +345,14 @@ class ArtController extends Controller
Chapter::find($query->chapter_id)?->title,
Part::find($query->part_id)?->title,
Gate::find($query->gate_id)?->title,
Branch::find($query->branch_id)?->title
Branch::find($query->branch_id)?->title,
]);
$route = array_values($route);
return $route;
}
return [];
}
@@ -346,7 +362,7 @@ class ArtController extends Controller
$models = [
Law::class,
Art::class
Art::class,
];
$results = [];
@@ -355,7 +371,6 @@ class ArtController extends Controller
$results = array_merge($results, $this->searchModelFastSearch($modelClass, $search));
}
$models_other = [
Volum::class,
Book::class,
@@ -369,13 +384,12 @@ class ArtController extends Controller
$found = false;
foreach ($models_other as $modelClass) {
if (count($this->searchModelFastSearch($modelClass, $search)) > 0 && !$found) {
if (count($this->searchModelFastSearch($modelClass, $search)) > 0 && ! $found) {
$results = array_merge($results, $this->searchModelFastSearch($modelClass, $search));
$found = true;
}
}
$models = [
Law::class,
Volum::class,
@@ -386,7 +400,7 @@ class ArtController extends Controller
Part::class,
Gate::class,
Branch::class,
Art::class
Art::class,
];
$count_all = 0;
@@ -395,7 +409,6 @@ class ArtController extends Controller
$count_all += count($this->searchModel($modelClass, $search));
}
return $this->success(['items' => $results, 'count' => $count_all]);
}
@@ -430,7 +443,7 @@ class ArtController extends Controller
'title' => $q->title,
'type' => $table === 'section' ? 'sections' : $table,
'category' => $category,
'law' => Law::where('id', $q->law_id)->first()?->title
'law' => Law::where('id', $q->law_id)->first()?->title,
];
}
@@ -439,7 +452,7 @@ class ArtController extends Controller
'title' => $q->title,
'type' => $table === 'section' ? 'sections' : $table,
'category' => $category,
'image' => Law::where('id', $q->id)->first()?->image
'image' => Law::where('id', $q->id)->first()?->image,
];
}
@@ -455,22 +468,24 @@ class ArtController extends Controller
Chapter::find($q->chapter_id)?->title,
Part::find($q->part_id)?->title,
Gate::find($q->gate_id)?->title,
Branch::find($q->branch_id)?->title
Branch::find($q->branch_id)?->title,
]);
$text = $q->text;
$search = preg_quote($search, '/');
if (preg_match('/\b(.{0,50})\b(' . $search . ')\b(.{0,50})\b/i', $text, $matches)) {
$context = trim($matches[1]) . ' ' . $matches[2] . ' ' . trim($matches[3]);
if (preg_match('/\b(.{0,50})\b('.$search.')\b(.{0,50})\b/i', $text, $matches)) {
$context = trim($matches[1]).' '.$matches[2].' '.trim($matches[3]);
} else {
$context = $text;
}
$isLocked = $this->isLockedForCurrentUser($law);
return [
'id' => $q->id,
'title' => $q->title,
'text' => $context,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : $law->is_locked,
'text' => $isLocked ? null : $context,
'is_locked' => $isLocked,
'type' => 'art',
'route' => $route,
'category' => $law?->category?->name,
@@ -478,7 +493,7 @@ class ArtController extends Controller
'count_art' => $law->arts->count(),
'count_volum' => $law->volums->count(),
'price' => $law->price,
'image' => $law->image
'image' => $law->image,
];
}

View File

@@ -24,7 +24,7 @@ class AuthController extends Controller
return User::create([
'name' => 'Law',
'mobile' => $request->mobile,
'email' => 'law' . $request->mobile . '@law.com',
'email' => 'law'.$request->mobile.'@law.com',
'password' => Hash::make($request->mobile),
]);
});
@@ -59,7 +59,10 @@ class AuthController extends Controller
if ($response->successful()) {
return $this->success([], 'موفق', 'کد ورود به شماره موبایل شما ارسال شد');
} else {
return $this->failed([], 'نا موفق', 'در ارسال کد به شماره شما مشکلی وجود دارد');
return $this->failed([], [
'title' => 'نا موفق',
'message' => 'در ارسال کد به شماره شما مشکلی وجود دارد',
]);
}
}
@@ -73,7 +76,7 @@ class AuthController extends Controller
$user = User::where('mobile', $request->mobile)->first();
if (! $user) {
return response()->json(['error' => 'User not found'], 404);
return response()->json(['error' => 'کاربر یافت نشد'], 404);
}
$latestCode = UserCode::where('user_id', $user->id)

View File

@@ -6,7 +6,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\BookRequest;
use App\Models\Book;
use App\Models\Law;
use App\Models\Order;
use App\Traits\BaseApiResponse;
class BookController extends Controller
@@ -23,7 +22,7 @@ class BookController extends Controller
$books = Book::where('volum_id', $validated['volum_id'])->paginate($perPage, ['*'], 'page', $page);
$books->getCollection()->transform(function ($section) {
$section['is_locked'] = auth()->user()->isSubscriber() !== true ? true : Law::where('is_locked',$section['law_id'])->first()?->is_locked ?? false;
$section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $section['law_id'])->first()?->is_locked ?? false;
unset($section['law_id']);
unset($section['volum_id']);

View File

@@ -0,0 +1,349 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\BylawDocument;
use App\Models\BylawLegalAuthority;
use App\Models\BylawSubjectCategory;
use App\Models\BylawNode;
use App\Models\BylawCodificationLink;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BylawApiController extends Controller
{
use BaseApiResponse;
public function categories()
{
$categories = BylawSubjectCategory::all()->map(function ($category) {
return [
'id' => $category->id,
'name' => $category->name,
];
});
return $this->success($categories, 'Success', 'Bylaw Categories List');
}
public function authorities()
{
$authorities = BylawLegalAuthority::all()->map(function ($authority) {
return [
'id' => $authority->id,
'name' => $authority->name,
'authority_type' => $authority->authority_type,
];
});
return $this->success($authorities, 'Success', 'Bylaw Authorities List');
}
public function index(Request $request)
{
$request->validate([
'category_id' => 'nullable|exists:bylaw_subject_categories,id',
'approval_authority_id' => 'nullable|exists:bylaw_legal_authorities,id',
'bylaw_type' => 'nullable|in:executive,delegated,independent',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true);
if ($request->filled('category_id')) {
$query->where('category_id', $request->category_id);
}
if ($request->filled('approval_authority_id')) {
$query->where('approval_authority_id', $request->approval_authority_id);
}
if ($request->filled('bylaw_type')) {
$query->where('bylaw_type', $request->bylaw_type);
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'promulgation_number' : 'approval_date';
if ($sortBy === 'number') {
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatBylaw($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Bylaws Fetched');
}
public function single($id)
{
$bylaw = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->find($id);
if (!$bylaw) {
return $this->failed([], [
'title' => 'خطا',
'message' => 'آیین‌نامه مورد نظر یافت نشد.'
], 404);
}
$formatted = $this->formatBylaw($bylaw);
if (!$formatted['is_locked']) {
$nodes = BylawNode::with('type')
->where('document_id', $bylaw->id)
->orderBy('sort_order', 'asc')
->get()
->map(function ($node) {
return [
'id' => $node->id,
'parent_id' => $node->parent_id,
'node_type' => optional($node->type)->name,
'node_identifier' => $node->node_identifier,
'title' => $node->title,
'node_content' => $node->node_content,
'sort_order' => $node->sort_order,
'valid_from' => $node->valid_from,
'valid_to' => $node->valid_to,
'node_status' => $node->node_status,
];
});
$formatted['nodes'] = $nodes->toArray();
$links = BylawCodificationLink::where('source_entity_type', 'bylaw_doc')
->where('source_entity_id', $bylaw->id)
->get()
->map(function ($link) {
return [
'id' => $link->id,
'target_entity_type' => $link->target_entity_type,
'target_entity_id' => $link->target_entity_id,
'link_type' => $link->link_type,
'effective_date' => $link->effective_date,
'justification' => $link->justification,
];
});
$formatted['links'] = $links->toArray();
}
return $this->success($formatted, 'Success', 'Bylaw Document Details Fetched');
}
public function search(Request $request)
{
$request->validate([
'search' => 'nullable|string',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true);
if ($request->filled('search')) {
$searchTerm = $request->input('search');
$query->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('description', 'LIKE', "%{$searchTerm}%")
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
->orWhereIn('id', function($subQuery) use ($searchTerm) {
$subQuery->select('document_id')
->from('bylaw_nodes')
->where('node_content', 'LIKE', "%{$searchTerm}%");
});
});
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'promulgation_number' : 'approval_date';
if ($sortBy === 'number') {
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatBylaw($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Search Results Fetched');
}
public function fast_search(Request $request)
{
$searchTerm = $request->input('search');
$query = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true);
if (!empty($searchTerm)) {
$query->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('description', 'LIKE', "%{$searchTerm}%")
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
->orWhereIn('id', function($subQuery) use ($searchTerm) {
$subQuery->select('document_id')
->from('bylaw_nodes')
->where('node_content', 'LIKE', "%{$searchTerm}%");
});
});
}
$count = $query->count();
$items = $query->orderBy('approval_date', 'desc')->take(5)->get()->map(function ($item) {
return $this->formatBylaw($item);
});
return $this->success([
'items' => $items,
'count' => $count
], 'Success', 'Fast Search Results');
}
public function pager($id)
{
$current = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->find($id);
if (!$current) {
return $this->failed([], [
'title' => 'خطا',
'message' => 'آیین‌نامه مورد نظر یافت نشد.'
], 404);
}
$previousItem = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->where(function ($query) use ($current) {
if ($current->approval_date) {
$query->where('approval_date', '<', $current->approval_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('approval_date', '=', $current->approval_date)
->where('id', '<', $current->id);
});
} else {
$query->whereNull('approval_date')->where('id', '<', $current->id);
}
})
->orderBy('approval_date', 'desc')
->orderBy('id', 'desc')
->first();
$nextItem = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->where(function ($query) use ($current) {
if ($current->approval_date) {
$query->where('approval_date', '>', $current->approval_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('approval_date', '=', $current->approval_date)
->where('id', '>', $current->id);
});
} else {
$query->whereNotNull('approval_date')
->orWhere(function ($subQuery) use ($current) {
$subQuery->whereNull('approval_date')->where('id', '>', $current->id);
});
}
})
->orderBy('approval_date', 'asc')
->orderBy('id', 'asc')
->first();
$results = array_values(array_filter([
$previousItem ? $this->formatBylaw($previousItem) : null,
$this->formatBylaw($current),
$nextItem ? $this->formatBylaw($nextItem) : null
]));
return $this->success($results, 'Success', 'Pager Window Details');
}
private function isLockedForCurrentUser($item): bool
{
return ! auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
}
private function formatBylaw($item)
{
$isLocked = $this->isLockedForCurrentUser($item);
$description = $item->description;
// Check if description is practically empty (null, empty string, or just empty WYSIWYG HTML like <p></p>)
$cleanDesc = trim(strip_tags($description ?? ''));
// Direct Query Fallback: Fetch node_content manually via DB facade to bypass any Model restrictions
if (empty($cleanDesc)) {
$nodeContents = DB::table('bylaw_nodes')
->where('document_id', $item->id)
->orderBy('sort_order', 'asc')
->pluck('node_content')
->toArray();
$description = implode("\n\n", array_filter($nodeContents));
}
return [
'id' => $item->id,
'title' => $item->title,
'category_id' => $item->category_id,
'category_name' => optional($item->category)->name,
'approval_authority_id' => $item->approval_authority_id,
'approval_authority_name' => optional($item->approvalAuthority)->name,
'approval_date' => $item->approval_date,
'promulgation_authority_id' => $item->promulgation_authority_id,
'promulgation_authority_name'=> optional($item->promulgationAuthority)->name,
'promulgation_date' => $item->promulgation_date,
'promulgation_number' => $item->promulgation_number,
'official_gazette_number' => $item->official_gazette_number,
'official_gazette_date' => $item->official_gazette_date,
'execution_date' => $item->execution_date,
'bylaw_type' => $item->bylaw_type,
'global_status' => $item->global_status,
'pdf_file_url' => $isLocked ? null : ($item->pdf_file_path ? asset('storage/' . $item->pdf_file_path) : null),
'description' => $isLocked ? null : $description,
'is_locked' => $isLocked,
];
}
}

View File

@@ -18,7 +18,6 @@ class CategoriesController extends Controller
$categories = Category::paginate($perPage, ['*'], 'page', $page);
return $this->success($categories->items());
}
}

View File

@@ -6,7 +6,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\ChapterRequest;
use App\Models\Chapter;
use App\Models\Law;
use App\Models\Order;
use App\Traits\BaseApiResponse;
class ChapterController extends Controller
@@ -20,11 +19,11 @@ class ChapterController extends Controller
$perPage = $validated['per_page'] ?? 15;
$page = $validated['page'] ?? 1;
$chapters = Chapter::where('book_id' , $validated['book_id'])->paginate($perPage, ['*'], 'page', $page);
$chapters = Chapter::where('book_id', $validated['book_id'])->paginate($perPage, ['*'], 'page', $page);
$chapters->getCollection()->transform(function ($section) {
$section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $section['law_id'])->first()?->is_locked;
$section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $section['law_id'])->first()?->is_locked;
unset($section['law_id']);
unset($section['section_id']);

View File

@@ -5,7 +5,6 @@ namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\Folder;
use App\Models\FolderArt;
use App\Models\Law;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
@@ -18,26 +17,25 @@ class FolderController extends Controller
$folder = Folder::query()->where('user_id', auth()->id())->get()
->map(function ($q) {
return [
"id" => $q->id,
"name" => $q->name,
"count_of_arts" => $q->arts->count(),
"created_at" => $q->created_at,
'id' => $q->id,
'name' => $q->name,
'count_of_arts' => $q->arts->count(),
'created_at' => $q->created_at,
];
});
return $this->success($folder);
}
public function create(Request $request)
{
$validted = $request->validate([
'name' => 'required'
'name' => 'required',
]);
Folder::create([
'user_id' => auth()->user()->id,
'name' => $validted['name']
'name' => $validted['name'],
]);
return $this->success([], 'ایجاد شد', 'پوشه با موفقیت ایجاد شد.');
@@ -47,7 +45,7 @@ class FolderController extends Controller
{
$validted = $request->validate([
'folder_id' => 'required',
'art_id' => 'required'
'art_id' => 'required',
]);
if (Folder::query()->where('id', $validted['folder_id'])->count() == 0) {
@@ -60,7 +58,7 @@ class FolderController extends Controller
FolderArt::create([
'folder_id' => $validted['folder_id'],
'art_id' => $validted['art_id']
'art_id' => $validted['art_id'],
]);
return $this->success([], 'اضافه شد', 'ارت با موفیت اضافه شد');
@@ -79,17 +77,18 @@ class FolderController extends Controller
$shortText = '';
if (strlen($text) > 50) {
$shortText = substr($text, 0, 50);
$shortText = substr($shortText, 0, strrpos($shortText, ' ')) . '...';
$shortText = substr($shortText, 0, strrpos($shortText, ' ')).'...';
} else {
$shortText = $text;
}
$isLocked = ! auth()->user()->isSubscriber() && (bool) $art->law?->is_locked;
return [
'id' => $art->id,
'title' => $art->title,
'text' => $shortText,
'text' => $isLocked ? null : $shortText,
'number' => $art->number,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $art->law->id)->first()?->is_locked,
'is_locked' => $isLocked,
'chapter' => $art->chapter != null ? [
'id' => $art->chapter->id,
'title' => $art->chapter->title,
@@ -137,15 +136,17 @@ class FolderController extends Controller
return $this->failed('پوشه یافت نشد', 'پوشه مورد نظر یافت نشد', 404);
}
Folder::query()->where('id', $id)->delete();
return $this->success([], 'حذف شد', 'پوشه با موفقیت حذف شد');
}
public function delete_art($id,$art_id)
public function delete_art($id, $art_id)
{
if (FolderArt::query()->where('folder_id', $id)->where('art_id', $art_id)->count() == 0) {
return $this->failed([], 'ارت مورد نظر یافت نشد', 404);
}
FolderArt::query()->where('folder_id', $id)->where('art_id', $art_id)->delete();
return $this->success([], 'حذف شد', 'ارت با موفقیت حذف شد');
}
}

View File

@@ -6,9 +6,7 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\ChapterRequest;
use App\Models\Gate;
use App\Models\Law;
use App\Models\Order;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class GateController extends Controller
{
@@ -23,15 +21,13 @@ class GateController extends Controller
$gates->getCollection()->transform(function ($gate) {
unset($gate['book_id']);
$gate['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $gate['law_id'])->first()?->is_locked;
$gate['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $gate['law_id'])->first()?->is_locked;
unset($gate['law_id']);
return $gate;
});
return $this->success($gates->items());
}
}

View File

@@ -0,0 +1,461 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\Art;
use App\Models\Book;
use App\Models\Branch;
use App\Models\BylawDocument;
use App\Models\Chapter;
use App\Models\Division;
use App\Models\Gate;
use App\Models\JudicialPrecedent;
use App\Models\Law;
use App\Models\LegalOpinion;
use App\Models\Part;
use App\Models\Section;
use App\Models\Volum;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
class GlobalSearchApiController extends Controller
{
use BaseApiResponse;
/**
* Massive Search across ALL data types
*/
public function search(Request $request)
{
$request->validate([
'search' => 'nullable|string',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
'page' => 'nullable|integer|min:1',
]);
$searchTerm = $request->input('search');
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$page = (int) $request->input('page', 1);
$staticResults = collect(); // Arts and Structures (Always at the top)
$sortableResults = collect(); // Bylaws, Opinions, Precedents (Sorted if requested)
if (!empty($searchTerm)) {
$limitPerTable = 100;
// =========================================================
// 1. Search Arts (Exact match to ArtController)
// =========================================================
$arts = Art::with(['law.category', 'chapter', 'part', 'volum', 'book', 'section', 'gate'])
->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('text', 'LIKE', "%{$searchTerm}%");
})
->take($limitPerTable)->get()->map(function($item) use ($searchTerm) {
$formatted = $this->formatArt($item, $searchTerm, Art::class);
$formatted['type'] = 'art';
return $formatted;
});
$staticResults = $staticResults->concat($arts);
// =========================================================
// 2. Search Laws and Structural Models (Exact match to ArtController)
// =========================================================
$structuralModels = [
Law::class, Volum::class, Book::class, Division::class,
Section::class, Chapter::class, Part::class, Gate::class,
Branch::class
];
foreach ($structuralModels as $modelClass) {
$query = $modelClass::query();
$modelInstance = new $modelClass;
$table = $modelInstance->getTable();
$query->where('title', 'LIKE', "%{$searchTerm}%");
$items = $query->take($limitPerTable)->get()->map(function($item) use ($modelClass, $table) {
$formatted = $this->formatStructure($item, $modelClass);
$formatted['type'] = ($table === 'section') ? 'sections' : $table;
return $formatted;
});
$staticResults = $staticResults->concat($items);
}
// =========================================================
// 3. Search Bylaw Documents
// =========================================================
$bylaws = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('description', 'LIKE', "%{$searchTerm}%")
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
->orWhereIn('id', function($subQuery) use ($searchTerm) {
$subQuery->select('document_id')
->from('bylaw_nodes')
->where('node_content', 'LIKE', "%{$searchTerm}%");
});
})->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatBylaw($item);
$formatted['type'] = 'bylaw';
return $formatted;
});
$sortableResults = $sortableResults->concat($bylaws);
// =========================================================
// 4. Search Judicial Precedents
// =========================================================
$judicials = JudicialPrecedent::with('category')
->where(function ($q) use ($searchTerm) {
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
})->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatJudicial($item);
$formatted['type'] = 'judicial_precedent';
return $formatted;
});
$sortableResults = $sortableResults->concat($judicials);
// =========================================================
// 5. Search Legal Opinions
// =========================================================
$opinions = LegalOpinion::with('category')
->where(function ($q) use ($searchTerm) {
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
})->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatOpinion($item);
$formatted['type'] = 'legal_opinion';
return $formatted;
});
$sortableResults = $sortableResults->concat($opinions);
}
// --- Apply Dynamic Memory Sorting ONLY to Legal Docs ---
if ($request->has('sort_by') && $request->input('sort_by') != null) {
$sortBy = $request->input('sort_by');
$sortOrder = $request->input('sort', 'desc');
if ($sortBy === 'number') {
$sortCallback = function ($item) {
return (string) ($item['promulgation_number'] ?? $item['ruling_number'] ?? $item['opinion_number'] ?? '0');
};
if ($sortOrder === 'asc') {
$sortableResults = $sortableResults->sortBy($sortCallback, SORT_NATURAL)->values();
} else {
$sortableResults = $sortableResults->sortByDesc($sortCallback, SORT_NATURAL)->values();
}
} elseif ($sortBy === 'date') {
$sortCallback = function ($item) {
return (string) ($item['approval_date'] ?? $item['ruling_date'] ?? $item['opinion_date'] ?? '1970-01-01');
};
if ($sortOrder === 'asc') {
$sortableResults = $sortableResults->sortBy($sortCallback)->values();
} else {
$sortableResults = $sortableResults->sortByDesc($sortCallback)->values();
}
}
}
// Combine Results: Arts and Structures ALWAYS pin to the top!
$results = $staticResults->concat($sortableResults);
// --- Execute Manual Pagination on the final Collection ---
$total = $results->count();
$paginatedItems = $results->forPage($page, $perPage)->values();
$paginator = new LengthAwarePaginator(
$paginatedItems,
$total,
$perPage,
$page,
['path' => $request->url(), 'query' => $request->query()]
);
$responseData = [
'items' => $paginator->items(),
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, '', '');
}
/**
* Top-level fast search for quick dropdown UI elements
*/
public function fast_search(Request $request)
{
$searchTerm = $request->input('search');
$results = collect();
$totalCount = 0;
$limitPerTable = 3;
if (!empty($searchTerm)) {
// 1. Search Arts FIRST
$artQuery = Art::with(['law', 'law.category', 'chapter', 'part', 'volum', 'book', 'section', 'gate'])
->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('text', 'LIKE', "%{$searchTerm}%");
});
$totalCount += $artQuery->count();
$arts = $artQuery->take($limitPerTable)->get()->map(function($item) use ($searchTerm) {
$formatted = $this->formatArt($item, $searchTerm, Art::class);
$formatted['type'] = 'art';
return $formatted;
});
$results = $results->concat($arts);
// 2. Structural Models
$structuralModels = [
Law::class, Volum::class, Book::class, Division::class,
Section::class, Chapter::class, Part::class, Gate::class,
Branch::class
];
foreach ($structuralModels as $modelClass) {
$query = $modelClass::query();
$modelInstance = new $modelClass;
$table = $modelInstance->getTable();
$query->where('title', 'LIKE', "%{$searchTerm}%");
$totalCount += $query->count();
if ($results->count() < 15) {
$items = $query->take($limitPerTable)->get()->map(function($item) use ($modelClass, $table) {
$formatted = $this->formatStructure($item, $modelClass);
$formatted['type'] = ($table === 'section') ? 'sections' : $table;
return $formatted;
});
$results = $results->concat($items);
}
}
// 3. Bylaw Documents
$bylawQuery = BylawDocument::with(['category', 'approvalAuthority', 'promulgationAuthority'])
->where('is_published', true)
->where(function ($q) use ($searchTerm) {
$q->where('title', 'LIKE', "%{$searchTerm}%")
->orWhere('description', 'LIKE', "%{$searchTerm}%")
->orWhere('promulgation_number', 'LIKE', "%{$searchTerm}%")
->orWhere('official_gazette_number', 'LIKE', "%{$searchTerm}%")
->orWhereIn('id', function($subQuery) use ($searchTerm) {
$subQuery->select('document_id')
->from('bylaw_nodes')
->where('node_content', 'LIKE', "%{$searchTerm}%");
});
});
$totalCount += $bylawQuery->count();
$bylaws = $bylawQuery->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatBylaw($item);
$formatted['type'] = 'bylaw';
return $formatted;
});
$results = $results->concat($bylaws);
// 4. Judicial Precedents
$judicialQuery = JudicialPrecedent::with('category')
->where(function ($q) use ($searchTerm) {
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
});
$totalCount += $judicialQuery->count();
$judicials = $judicialQuery->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatJudicial($item);
$formatted['type'] = 'judicial_precedent';
return $formatted;
});
$results = $results->concat($judicials);
// 5. Legal Opinions
$opinionQuery = LegalOpinion::with('category')
->where(function ($q) use ($searchTerm) {
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
});
$totalCount += $opinionQuery->count();
$opinions = $opinionQuery->take($limitPerTable)->get()->map(function($item) {
$formatted = $this->formatOpinion($item);
$formatted['type'] = 'legal_opinion';
return $formatted;
});
$results = $results->concat($opinions);
}
return $this->success([
'items' => $results->take(15)->values(),
'count' => $totalCount
], '', '');
}
/* -----------------------------------------------------------------
* FORMATTING HELPERS
* ----------------------------------------------------------------- */
private function isLockedForCurrentUserGeneric($item): bool
{
return ! auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
}
private function formatBylaw($item)
{
$isLocked = $this->isLockedForCurrentUserGeneric($item);
$description = $item->description;
$cleanDesc = trim(strip_tags($description ?? ''));
if (empty($cleanDesc)) {
$nodeContents = DB::table('bylaw_nodes')
->where('document_id', $item->id)
->orderBy('sort_order', 'asc')
->pluck('node_content')
->toArray();
$description = implode("\n\n", array_filter($nodeContents));
}
return [
'id' => $item->id,
'title' => $item->title,
'category_name' => optional($item->category)->name,
'approval_authority_name' => optional($item->approvalAuthority)->name,
'approval_date' => $item->approval_date,
'promulgation_number' => $item->promulgation_number,
'description' => $isLocked ? null : $description,
'is_locked' => $isLocked,
];
}
private function formatJudicial($item)
{
$isLocked = $this->isLockedForCurrentUserGeneric($item);
return [
'id' => $item->id,
'title' => $item->subject,
'ruling_number' => $item->ruling_number,
'ruling_date' => $item->ruling_date,
'text' => $isLocked ? null : $item->full_text,
'issuing_authority' => $item->issuing_authority,
'category_name' => optional($item->category)->name,
'is_locked' => $isLocked,
];
}
private function formatOpinion($item)
{
$isLocked = $this->isLockedForCurrentUserGeneric($item);
return [
'id' => $item->id,
'title' => $item->subject,
'opinion_number' => $item->opinion_number,
'opinion_date' => $item->opinion_date,
'text' => $isLocked ? null : $item->full_text,
'issuing_authority' => $item->issuing_authority,
'category_name' => optional($item->category)->name,
'is_locked' => $isLocked,
];
}
/**
* Exact 1:1 match with ArtController::searchModel mapping
* All relations (law, chapter, etc) are strictly Strings to prevent App Crashes!
*/
private function formatArt($item, $searchTerm, $modelClass)
{
$law = $item->law ?? Law::find($item->law_id);
$isLocked = ! auth()->user()->isSubscriber() && (bool) ($law?->is_locked ?? false);
$text = $item->text ?? '';
$searchQuoted = preg_quote($searchTerm, '/');
if (!empty($searchTerm) && preg_match('/\b(.{0,50})\b('.$searchQuoted.')\b(.{0,50})\b/i', $text, $matches)) {
$context = trim($matches[1] ?? '').' '.($matches[2] ?? '').' '.trim($matches[3] ?? '');
} else {
$context = $text;
}
return [
'id' => $item->id,
'title' => $item->title,
'number' => $item->number,
'text' => $isLocked ? null : $context,
'is_locked' => $isLocked,
'route' => array_values($this->route($modelClass, $item)),
'category' => optional($law?->category)->name,
'law' => $law?->title ?? '', // STRICLY STRING! Prevents Android App Crash!
'count_art' => $law?->arts?->count() ?? 0,
'count_volums' => $law?->volums?->count() ?? 0, // WITH S
'count_volum' => $law?->volums?->count() ?? 0, // WITHOUT S (Fallback)
'price' => $law?->price,
'image' => $law?->image,
];
}
private function formatStructure($item, $modelClass)
{
$law = Law::find($item?->law_id ?? $item->id);
$isLocked = ! auth()->user()->isSubscriber() && (bool) ($law?->is_locked ?? false);
$payload = [
'id' => $item->id,
'title' => $item->title,
'number' => $item->number,
'is_locked' => $isLocked,
'route' => array_values($this->route($modelClass, $item)),
'law' => $law?->title ?? '', // STRICTLY STRING
];
if ((new $modelClass)->getTable() == 'laws') {
$payload['category'] = optional($law?->category)?->name ?? '';
$payload['image'] = $law?->image;
}
return $payload;
}
private function route($modelClass, $query)
{
if ((new $modelClass)->getTable() == 'art') {
$route = array_filter([
$query->relationLoaded('law') ? $query->law?->title : Law::find($query->law_id)?->title,
$query->relationLoaded('volum') ? $query->volum?->title : Volum::find($query->volum_id)?->title,
$query->relationLoaded('book') ? $query->book?->title : Book::find($query->book_id)?->title,
Division::find($query->division_id)?->title,
$query->relationLoaded('section') ? $query->section?->title : Section::find($query->section_id)?->title,
$query->relationLoaded('chapter') ? $query->chapter?->title : Chapter::find($query->chapter_id)?->title,
$query->relationLoaded('part') ? $query->part?->title : Part::find($query->part_id)?->title,
$query->relationLoaded('gate') ? $query->gate?->title : Gate::find($query->gate_id)?->title,
Branch::find($query->branch_id)?->title,
]);
return array_values($route);
}
if ((new $modelClass)->getTable() == 'laws') {
return array_values(array_filter([Law::find($query->id)?->title]));
}
return [];
}
}

View File

@@ -3,46 +3,33 @@
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
// 1. IMPORT THE JOB WE CREATED
use App\Jobs\CheckBazaarSubscription;
// These are your existing imports
use App\Models\Law;
use App\Models\Notification;
use App\Models\Category;
use App\Models\RecentArt;
use App\Models\UserSubscriber;
use App\Services\AppMarketPurchaseVerifier;
use App\Traits\BaseApiResponse;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
class HomeController extends Controller
{
use BaseApiResponse;
public function index()
public function __construct(private AppMarketPurchaseVerifier $marketVerifier)
{
}
public function homeV2()
{
$user = auth()->user();
// 2. DISPATCH THE JOB AT THE VERY BEGINNING
// ===================================================================
// Find the user's latest subscription that has a purchase token
$latestSubscription = $user->userSubscribers()->whereNotNull('purchase_token')->latest()->first();
// If such a subscription exists, create a new job and hand it to the queue
// if ($latestSubscription) {
// CheckBazaarSubscription::dispatch($latestSubscription);
// }
// ===================================================================
// Your API now continues immediately without waiting for the check to finish.
// --- ALL THE REST OF YOUR CODE REMAINS EXACTLY THE SAME ---
$this->refreshMarketSubscriptionAfterResponse($user);
$recent = RecentArt::query()->where('user_id', $user->id)->get()->map(function ($q) {
return [
'id' => $q->law?->id,
'name' => $q->law?->title,
'is_locked' => $q->law?->is_locked
'is_locked' => $q->law?->is_locked,
];
});
@@ -50,7 +37,7 @@ class HomeController extends Controller
return [
'id' => $q->id,
'name' => $q->title,
'is_locked' => $q->is_locked
'is_locked' => $q->is_locked,
];
});
@@ -62,13 +49,13 @@ class HomeController extends Controller
$q->where('type', $category);
})->get()->map(function ($q) {
return [
"id" => $q->id,
"title" => $q->title,
"is_locked" => $q->is_locked,
"category_id" => $q->category_id,
"price" => $q->price,
"image" => $q->image,
"type" => 'law'
'id' => $q->id,
'title' => $q->title,
'is_locked' => $q->is_locked,
'category_id' => $q->category_id,
'price' => $q->price,
'image' => $q->image,
'type' => 'law',
];
});
}
@@ -77,12 +64,10 @@ class HomeController extends Controller
return [
'id' => $q->id,
'name' => $q->title,
'is_locked' => $q->is_locked
'is_locked' => $q->is_locked,
];
});
$current_plan = null;
$freeSubscription = $user->userSubscribers()
->whereHas('subscribe', function ($query) {
$query->where('is_free', true);
@@ -90,33 +75,171 @@ class HomeController extends Controller
->where('expired_at', '>=', now())
->first();
$expiredAt = null;
$current_plan = null;
if ($freeSubscription) {
$expiredAt = $freeSubscription->expired_at;
$current_plan = [
'id' => $freeSubscription->id,
'name' => $freeSubscription->subscribe->name,
'price' => $freeSubscription->subscribe->price,
'expired_day' => $freeSubscription->expired_at->diffInDays(now()),
'is_free' => true
'is_free' => true,
];
}
$latestSubscription = $user->userSubscribers()->latest()->first();
$latestSubscription = $user->userSubscribers()
->where('expired_at', '>=', now())
->latest('expired_at')
->first();
$expiredDays = UserSubscriber::query()->where('user_id', $user->id)->where('expired_at', '>=', now())->get()->sum(function ($subscriber) {return $subscriber->expired_at->diffInDays(now());});
$expiredDays = UserSubscriber::query()->where('user_id', $user->id)->where('expired_at', '>=', now())->get()->sum(function ($subscriber) {
return $subscriber->expired_at->diffInDays(now());
});
$purchase_token = $latestSubscription?->purchase_token;
$current_plan = [
'id' => $latestSubscription->id,
'name' => $latestSubscription->subscribe->name ?? 'Subscription',
'price' => $latestSubscription->subscribe->price ?? 100,
'expired_day' => $expiredDays,
'is_free' => false
if ($latestSubscription) {
$current_plan = [
'id' => $latestSubscription->id,
'name' => $latestSubscription->subscribe->name ?? 'Subscription',
'price' => $latestSubscription->subscribe->price ?? 100,
'expired_day' => $expiredDays,
'is_free' => (bool)$latestSubscription->is_free,
];
}
$unread_notifications_count = Notification::unreadForUser($user->id)->count();
$homeData = [
'recent' => $recent,
'laws' => $lawsByCategory,
'last_law' => $laws,
'free' => $free_law,
'current_plan' => $current_plan,
'unread_notifications_count' => $unread_notifications_count,
];
return $this->success([
'home' => $homeData,
'hoqoqi_list' => $this->getCategoryList(1), // Category 1
'keyfari_list' => $this->getCategoryList(2), // Category 2
]);
}
private function getCategoryList(int $categoryId)
{
$type = $categoryId === 1 ? 'hagigi' : 'kifari';
$categories = Category::with(['laws'])->where('type', $type)->get()->pluck('id');
$items = Law::query()->whereIn('category_id', $categories)->get();
$data = [];
$user = auth()->user();
foreach ($items as $item) {
$data[] = [
'id' => $item->id,
'title' => $item->title,
'number' => $item->number,
'type' => 'laws',
'is_locked' => $user->isSubscriber() !== false ? false : Law::where('id', $item->id)->first()?->is_locked,
'image' => $item?->image,
'law' => $item?->title,
'count_art' => $item->arts->count(),
'count_volums' => $item->volums->count(),
'price' => $item->price,
];
}
return $data;
}
public function index()
{
$user = auth()->user();
$this->refreshMarketSubscriptionAfterResponse($user);
$recent = RecentArt::query()->where('user_id', $user->id)->get()->map(function ($q) {
return [
'id' => $q->law?->id,
'name' => $q->law?->title,
'is_locked' => $q->law?->is_locked,
];
});
$laws = Law::orderBy('created_at')->get()->map(function ($q) {
return [
'id' => $q->id,
'name' => $q->title,
'is_locked' => $q->is_locked,
];
});
$categories = ['hagigi', 'kifari'];
$lawsByCategory = [];
foreach ($categories as $category) {
$lawsByCategory[$category] = Law::whereHas('category', function ($q) use ($category) {
$q->where('type', $category);
})->get()->map(function ($q) {
return [
'id' => $q->id,
'title' => $q->title,
'is_locked' => $q->is_locked,
'category_id' => $q->category_id,
'price' => $q->price,
'image' => $q->image,
'type' => 'law',
];
});
}
$free_law = Law::where('is_locked', false)->orderBy('created_at')->get()->map(function ($q) {
return [
'id' => $q->id,
'name' => $q->title,
'is_locked' => $q->is_locked,
];
});
$freeSubscription = $user->userSubscribers()
->whereHas('subscribe', function ($query) {
$query->where('is_free', true);
})
->where('expired_at', '>=', now())
->first();
$current_plan = null;
if ($freeSubscription) {
$current_plan = [
'id' => $freeSubscription->id,
'name' => $freeSubscription->subscribe->name,
'price' => $freeSubscription->subscribe->price,
'expired_day' => $freeSubscription->expired_at->diffInDays(now()),
'is_free' => true,
];
}
$latestSubscription = $user->userSubscribers()
->where('expired_at', '>=', now())
->latest('expired_at')
->first();
$expiredDays = UserSubscriber::query()->where('user_id', $user->id)->where('expired_at', '>=', now())->get()->sum(function ($subscriber) {
return $subscriber->expired_at->diffInDays(now());
});
if ($latestSubscription) {
$current_plan = [
'id' => $latestSubscription->id,
'name' => $latestSubscription->subscribe->name ?? 'Subscription',
'price' => $latestSubscription->subscribe->price ?? 100,
'expired_day' => $expiredDays,
'is_free' => (bool)$latestSubscription->is_free,
];
}
$unread_notifications_count = Notification::unreadForUser($user->id)->count();
return $this->success([
@@ -128,4 +251,55 @@ class HomeController extends Controller
'unread_notifications_count' => $unread_notifications_count,
]);
}
private function refreshMarketSubscriptionAfterResponse($user): void
{
$cacheKey = "home-market-refresh-user-{$user->id}";
$this->refreshMarketSubscription($user);
if (!Cache::add($cacheKey, true, now()->addHours(24))) {
return;
}
app()->terminating(function () use ($user) {
$this->refreshMarketSubscription($user);
});
}
private function refreshMarketSubscription($user): void
{
$bazaarSubscription = $user->userSubscribers()
->whereNotNull('purchase_token')
->whereNotNull('subscription_id')
->where(function ($query) {
$query->where('market_provider', 'bazaar')
->orWhereNull('market_provider');
})
->latest()
->first();
if ($bazaarSubscription && $this->shouldRefreshMarketSubscription($bazaarSubscription) && $this->marketVerifier->refreshBazaarSubscriber($bazaarSubscription)) {
return;
}
$myketSubscription = $user->userSubscribers()
->where('market_provider', 'myket')
->whereNotNull('purchase_token')
->whereNotNull('product_id')
->latest()
->first();
if ($myketSubscription && $this->shouldRefreshMarketSubscription($myketSubscription)) {
$this->marketVerifier->refreshMyketSubscriber($myketSubscription);
}
}
private function shouldRefreshMarketSubscription(UserSubscriber $subscriber): bool
{
if ($subscriber->expired_at && $subscriber->expired_at->lessThanOrEqualTo(now())) {
return true;
}
return !$subscriber->last_verified_at || $subscriber->last_verified_at->lessThan(now()->subHours(12));
}
}

View File

@@ -0,0 +1,207 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\JudicialPrecedent;
use App\Models\JudicialPrecedentCategory;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class JudicialPrecedentApiController extends Controller
{
use BaseApiResponse;
public function categories()
{
$categories = JudicialPrecedentCategory::all()->map(function ($category) {
return [
'id' => $category->id,
'name' => $category->name,
];
});
return $this->success($categories, 'Success', 'Categories List');
}
public function index(Request $request)
{
$request->validate([
'category_id' => 'nullable|exists:judicial_precedent_categories,id',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = JudicialPrecedent::query();
if ($request->filled('category_id')) {
$query->where('category_id', $request->category_id);
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'ruling_number' : 'ruling_date';
if ($sortBy === 'number') {
// Natural numeric sorting for string numbers
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatItem($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Judicial Precedents Fetched');
}
public function search(Request $request)
{
$request->validate([
'search' => 'nullable|string',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = JudicialPrecedent::query();
if ($request->filled('search')) {
$searchTerm = $request->input('search');
$query->where(function ($q) use ($searchTerm) {
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
});
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'ruling_number' : 'ruling_date';
if ($sortBy === 'number') {
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatItem($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Search Results Fetched');
}
public function fast_search(Request $request)
{
$searchTerm = $request->input('search');
$query = JudicialPrecedent::query();
if (!empty($searchTerm)) {
$query->where(function ($q) use ($searchTerm) {
$q->where('ruling_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%");
});
}
$count = $query->count();
$items = $query->orderBy('ruling_date', 'desc')->take(5)->get()->map(function ($item) {
return $this->formatItem($item);
});
return $this->success([
'items' => $items,
'count' => $count
], 'Success', 'Fast Search Results');
}
public function pager($id)
{
$current = JudicialPrecedent::find($id);
if (!$current) {
return $this->failed([], [
'title' => 'خطا',
'message' => 'رأی وحدت رویه مورد نظر یافت نشد.'
], 404);
}
$previousItem = JudicialPrecedent::where(function ($query) use ($current) {
$query->where('ruling_date', '<', $current->ruling_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('ruling_date', '=', $current->ruling_date)
->where('id', '<', $current->id);
});
})
->orderBy('ruling_date', 'desc')
->orderBy('id', 'desc')
->first();
$nextItem = JudicialPrecedent::where(function ($query) use ($current) {
$query->where('ruling_date', '>', $current->ruling_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('ruling_date', '=', $current->ruling_date)
->where('id', '>', $current->id);
});
})
->orderBy('ruling_date', 'asc')
->orderBy('id', 'asc')
->first();
$results = array_values(array_filter([
$previousItem ? $this->formatItem($previousItem) : null,
$this->formatItem($current),
$nextItem ? $this->formatItem($nextItem) : null
]));
return $this->success($results, 'Success', 'Pager Window Details');
}
private function isLockedForCurrentUser($item): bool
{
return ! auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
}
private function formatItem($item)
{
$isLocked = $this->isLockedForCurrentUser($item);
return [
'id' => $item->id,
'ruling_number' => $item->ruling_number,
'ruling_date' => $item->ruling_date,
'subject' => $item->subject,
'full_text' => $isLocked ? null : $item->full_text,
'issuing_authority' => $item->issuing_authority,
'category_id' => $item->category_id,
'category_name' => optional($item->category)->name,
'is_locked' => $isLocked,
];
}
}

View File

@@ -0,0 +1,219 @@
<?php
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\LegalOpinion;
use App\Models\LegalOpinionCategory;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class LegalOpinionApiController extends Controller
{
use BaseApiResponse;
public function categories()
{
$categories = LegalOpinionCategory::all()->map(function ($category) {
return [
'id' => $category->id,
'name' => $category->name,
];
});
return $this->success($categories, 'Success', 'Categories List');
}
public function index(Request $request)
{
$request->validate([
'category_id' => 'nullable|exists:legal_opinion_categories,id',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = LegalOpinion::query();
if ($request->filled('category_id')) {
$query->where('category_id', $request->category_id);
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'opinion_number' : 'opinion_date';
if ($sortBy === 'number') {
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatItem($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Legal Opinions Fetched');
}
public function search(Request $request)
{
$request->validate([
'search' => 'nullable|string',
'sort_by' => 'nullable|in:date,number',
'sort' => 'nullable|in:asc,desc',
'per_page' => 'nullable|integer|min:1|max:100',
]);
$query = LegalOpinion::query();
if ($request->filled('search')) {
$searchTerm = $request->input('search');
$query->where(function ($q) use ($searchTerm) {
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
});
}
$sortBy = $request->input('sort_by', 'date');
$sortOrder = $request->input('sort', 'desc');
$sortColumn = $sortBy === 'number' ? 'opinion_number' : 'opinion_date';
if ($sortBy === 'number') {
$query->orderByRaw("LENGTH({$sortColumn}) {$sortOrder}")->orderBy($sortColumn, $sortOrder);
} else {
$query->orderBy($sortColumn, $sortOrder);
}
$perPage = min(max((int) $request->input('per_page', 15), 10), 100);
$paginator = $query->paginate($perPage);
$items = collect($paginator->items())->map(function ($item) {
return $this->formatItem($item);
});
$responseData = [
'items' => $items,
'current_page' => $paginator->currentPage(),
'last_page' => $paginator->lastPage(),
'per_page' => $paginator->perPage(),
'total' => $paginator->total(),
];
return $this->success($responseData, 'Success', 'Search Results Fetched');
}
public function fast_search(Request $request)
{
$searchTerm = $request->input('search');
$query = LegalOpinion::query();
if ($request->filled('search')) {
$query->where(function ($q) use ($searchTerm) {
$q->where('opinion_number', 'LIKE', "%{$searchTerm}%")
->orWhere('subject', 'LIKE', "%{$searchTerm}%")
->orWhere('full_text', 'LIKE', "%{$searchTerm}%")
->orWhere('issuing_authority', 'LIKE', "%{$searchTerm}%");
});
}
$count = $query->count();
$items = $query->orderBy('opinion_date', 'desc')->take(5)->get()->map(function ($item) {
return $this->formatItem($item);
});
return $this->success([
'items' => $items,
'count' => $count
], 'Success', 'Fast Search Results');
}
public function pager($id)
{
$current = LegalOpinion::find($id);
if (!$current) {
return $this->failed([], [
'title' => 'خطا',
'message' => 'نظریه قانونی مورد نظر یافت نشد.'
], 404);
}
$previousItem = LegalOpinion::where(function ($query) use ($current) {
if ($current->opinion_date) {
$query->where('opinion_date', '<', $current->opinion_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('opinion_date', '=', $current->opinion_date)
->where('id', '<', $current->id);
});
} else {
$query->whereNull('opinion_date')->where('id', '<', $current->id);
}
})
->orderBy('opinion_date', 'desc')
->orderBy('id', 'desc')
->first();
$nextItem = LegalOpinion::where(function ($query) use ($current) {
if ($current->opinion_date) {
$query->where('opinion_date', '>', $current->opinion_date)
->orWhere(function ($subQuery) use ($current) {
$subQuery->where('opinion_date', '=', $current->opinion_date)
->where('id', '>', $current->id);
});
} else {
$query->whereNotNull('opinion_date')
->orWhere(function ($subQuery) use ($current) {
$subQuery->whereNull('opinion_date')->where('id', '>', $current->id);
});
}
})
->orderBy('opinion_date', 'asc')
->orderBy('id', 'asc')
->first();
$results = array_values(array_filter([
$previousItem ? $this->formatItem($previousItem) : null,
$this->formatItem($current),
$nextItem ? $this->formatItem($nextItem) : null
]));
return $this->success($results, 'Success', 'Pager Window Details');
}
private function isLockedForCurrentUser($item): bool
{
return ! auth()->user()->isSubscriber() && (bool) ($item->is_locked ?? false);
}
private function formatItem($item)
{
$isLocked = $this->isLockedForCurrentUser($item);
return [
'id' => $item->id,
'opinion_number' => $item->opinion_number,
'opinion_date' => $item->opinion_date,
'subject' => $item->subject,
'full_text' => $isLocked ? null : $item->full_text,
'issuing_authority' => $item->issuing_authority,
'category_id' => $item->category_id,
'category_name' => optional($item->category)->name,
'is_locked' => $isLocked,
];
}
}

View File

@@ -16,7 +16,7 @@ class NoteController extends Controller
$validated = $request->validate([
'art_id' => 'required',
'note' => 'required',
'color_code' => 'nullable'
'color_code' => 'nullable',
]);
Note::query()->create(
@@ -29,14 +29,14 @@ class NoteController extends Controller
]
);
return $this->success([], 'successfully created.');
return $this->success([], 'با موفقیت اضافه شد');
}
public function update($id, Request $request)
{
$validated = $request->validate([
'note' => 'required',
'color_code' => 'nullable'
'color_code' => 'nullable',
]);
$note = Note::findOrFail($id);
@@ -45,7 +45,7 @@ class NoteController extends Controller
'color_code' => $validated['color_code'],
]);
return $this->success([], 'successfully updated.');
return $this->success([], 'بروز شد');
}
public function destroy($id)
@@ -53,6 +53,6 @@ class NoteController extends Controller
$note = Note::findOrFail($id);
$note->delete();
return $this->success([], 'successfully deleted.');
return $this->success([], 'حذف شد');
}
}

View File

@@ -5,10 +5,8 @@ namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Http\Requests\ChapterRequest;
use App\Models\Law;
use App\Models\Order;
use App\Models\Part;
use App\Traits\BaseApiResponse;
use Illuminate\Http\Request;
class PartController extends Controller
{
@@ -21,18 +19,17 @@ class PartController extends Controller
$perPage = $request->input('per_page', 15);
$page = $request->input('page', 1);
$parts = Part::where('book_id' , $request->input('book_id'))->paginate($perPage, ['*'], 'page', $page);
$parts = Part::where('book_id', $request->input('book_id'))->paginate($perPage, ['*'], 'page', $page);
$parts->getCollection()->transform(function ($part) {
unset($part['book_id']);
$gate['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $part['law_id'])->first()?->is_locked;
$part['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $part['law_id'])->first()?->is_locked;
unset($gate['law_id']);
unset($part['law_id']);
return $gate;
return $part;
});
return $this->success($parts->items());
}
}

View File

@@ -3,7 +3,6 @@
namespace App\Http\Controllers\api;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PaymentTransaction;
use App\Models\SubscribePlan;
use App\Models\UserSubscriber;
@@ -29,7 +28,7 @@ class PayController extends Controller
$invoice = (new Invoice)->amount($subscribePlan->price);
$callback = 'https://ghaafapp.ir';
$payment = Payment::callbackUrl($callback . '/payment/callback')
$payment = Payment::callbackUrl($callback.'/payment/callback')
->purchase($invoice, function ($driver, $transaction_id) use ($subscribePlan) {
PaymentTransaction::create([
'user_id' => auth()->user()->id,
@@ -43,7 +42,8 @@ class PayController extends Controller
return $this->success(['url' => $payment]);
} catch (\Exception $e) {
Log::error('Payment initiation failed: ' . $e->getMessage());
Log::error('Payment initiation failed: '.$e->getMessage());
return $this->failed('Payment initialization failed', $e->getMessage());
}
}
@@ -72,26 +72,27 @@ class PayController extends Controller
'expired_at' => $expiredAt,
]);
return $this->success([], 'Payment Successful', 'Subscription successfully activated.');
return $this->success([], 'موفق', 'اشتراک با موفقیت فعال شد');
}
return $this->failed([], ['title' => 'Payment Failed', 'message' => 'Payment verification failed.']);
return $this->failed([], ['title' => 'پرداخت ناموفق', 'message' => 'پرداخت ناموفق']);
} catch (\Exception $e) {
Log::info('error in callback function', ['error' => $e->getMessage()]);
return $this->failed([], ['title' => 'Payment Failed', 'message' => 'Payment verification failed.']);
return $this->failed([], ['title' => 'پرداخت ناموفق', 'message' => 'پرداخت ناموفق']);
}
}
private function send($url, $api, $amount, $redirect, $factorId, $name, $email, $description)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&amount=$amount&redirect=$redirect&factorId=$factorId&name=$name&email=$email&description=$description");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
@@ -100,10 +101,11 @@ class PayController extends Controller
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&id_get=$id_get&trans_id=$trans_id&json=1");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
}

View File

@@ -6,7 +6,6 @@ use App\Http\Controllers\Controller;
use App\Http\Requests\SectionRequest;
use App\Models\Law;
use App\Models\LikeSection;
use App\Models\Order;
use App\Models\Section;
use App\Traits\BaseApiResponse;
@@ -25,7 +24,7 @@ class SectionController extends Controller
$section->getCollection()->transform(function ($section) {
unset($section['book_id']);
$section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked',$section['law_id'])->first()?->is_locked;
$section['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $section['law_id'])->first()?->is_locked;
unset($section['law_id']);

View File

@@ -6,6 +6,7 @@ use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use App\Models\SubscribePlan;
use App\Models\UserSubscriber;
use App\Services\AppMarketPurchaseVerifier;
use App\Traits\BaseApiResponse;
use Carbon\Carbon;
use Illuminate\Http\Request;
@@ -17,6 +18,10 @@ class SubscribePlanController extends Controller
{
use BaseApiResponse;
public function __construct(private AppMarketPurchaseVerifier $marketVerifier)
{
}
public function index()
{
$subscribePlans = SubscribePlan::query()->where('is_active', true)->get()->map(function ($q) {
@@ -25,6 +30,7 @@ class SubscribePlanController extends Controller
return null;
}
}
return [
'id' => $q->id,
'name' => $q->name,
@@ -32,7 +38,7 @@ class SubscribePlanController extends Controller
'expired_day' => $q->expired_day,
'is_free' => $q->is_free == 1 ? true : false,
'type' => $q->type,
'transaction' => $q->transaction
'transaction' => $q->transaction,
];
})->filter(function ($q) {
@@ -55,8 +61,8 @@ class SubscribePlanController extends Controller
->where('expired_at', '>', now())
->first();
if ($activeSubscription && !$activeSubscription?->subscribe?->is_free && !$subscribePlan->is_free) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'You already have an active subscription. Please wait until it expires.']);
if ($activeSubscription && ! $activeSubscription?->subscribe?->is_free && ! $subscribePlan->is_free) {
return $this->failed(null, ['title' => 'اشتراک', 'message' => 'شما درحال حاظر اشتراک فعال دارید']);
}
if ($subscribePlan->is_free) {
@@ -66,7 +72,7 @@ class SubscribePlanController extends Controller
})->exists();
if ($hasUsedFreePlan) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'You have already used the free plan.']);
return $this->failed(null, ['title' => 'اشتراک', 'message' => 'شما قبلا اشتراک رایگان فعال کردید']);
}
$expiredAt = now()->addDays($subscribePlan->expired_day + 1);
@@ -76,7 +82,7 @@ class SubscribePlanController extends Controller
'expired_at' => $expiredAt,
]);
return $this->success(null, 'Subscribe Plan', 'Free Subscribe Plan Successfully Activated');
return $this->success(null, 'اشتراک', 'اشتراک رایگان شما فعال شد');
}
try {
@@ -97,19 +103,18 @@ class SubscribePlanController extends Controller
return $this->success(['url' => $payment]);
} catch (\Exception $e) {
Log::error('Payment initiation failed: ' . $e->getMessage());
Log::error('Payment initiation failed: '.$e->getMessage());
return $this->failed(null, 'درگاه پرداخت در دسترس نیست');
}
}
public function subscribe_new(Request $request)
{
$package_name_bazzar = 'com.razzaghi.lawbook.android';
$request->validate([
'subscribe_plan_id' => 'required|exists:subscribe_plans,id',
'subscription_id' => 'nullable',
'purchase_token' => 'nullable'
'purchase_token' => 'nullable',
]);
$subscribePlan = SubscribePlan::findOrFail($request->subscribe_plan_id);
@@ -128,7 +133,7 @@ class SubscribePlanController extends Controller
->exists();
if ($hasUsedFreePlan) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'You have already used the free plan.']);
return $this->failed(null, ['title' => 'اشتراک', 'message' => 'شما قبلا اشتراک رایگان فعال کردید']);
}
$expiredAt = $activeSubscription ? $activeSubscription->expired_at->addDays($subscribePlan->expired_day) : now()->addDays($subscribePlan->expired_day);
@@ -136,36 +141,26 @@ class SubscribePlanController extends Controller
$user->userSubscribers()->create([
'subscribe_plan_id' => $subscribePlan->id,
'expired_at' => $expiredAt,
'is_free' => true
'is_free' => true,
]);
return $this->success(null, 'Subscribe Plan', 'Free Subscribe Plan Successfully Activated');
return $this->success(null, 'اشتراک', 'اشتراک رایگان فعال شد');
}
$subscription_id = $request->input('subscription_id');
$purchase_token = $request->input('purchase_token');
if (!$subscription_id || !$purchase_token) {
if (! $subscription_id || ! $purchase_token) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Invalid subscription details.']);
}
$url = "https://pardakht.cafebazaar.ir/devapi/v2/api/applications/$package_name_bazzar/subscriptions/$subscription_id/purchases/$purchase_token";
$client = new \GuzzleHttp\Client();
try {
$response = $client->get($url, [
'headers' => [
'CAFEBAZAAR-PISHKHAN-API-SECRET' => 'eyJhbGciOiJIUzI1NiIsImtpZCI6ImFuY2llbnQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJuYXNoZXItcGlzaGtoYW4tYXBpIiwiaWF0IjoxNzQwMjQ3NTMzLCJleHAiOjQ4OTM4NDc1MzMsImFwaV9hZ2VudF9pZCI6MzQ2NX0.UCrr3IHxCqn77ckxfnaubrsyCfrhPm18gJgyg1qNqwA',
]
]);
$bazaarExpiredAt = $this->marketVerifier->verifyBazaarSubscription($subscription_id, $purchase_token);
$data = json_decode($response->getBody(), true);
if (!isset($data['validUntilTimestampMsec']) || $data['validUntilTimestampMsec'] < now()->timestamp * 1000) {
if (! $bazaarExpiredAt) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Invalid or expired subscription.']);
}
$bazaarExpiredAt = Carbon::createFromTimestampMs($data['validUntilTimestampMsec']);
$expiredAt = $activeSubscription ? $activeSubscription->expired_at->addDays($subscribePlan->expired_day) : $bazaarExpiredAt;
$user->userSubscribers()->whereHas('subscribe', function ($query) {
$query->where('is_free', true);
@@ -177,16 +172,82 @@ class SubscribePlanController extends Controller
'expired_at' => $expiredAt,
'subscription_id' => $subscription_id,
'purchase_token' => $purchase_token,
'is_free' => false
'market_provider' => 'bazaar',
'last_verified_at' => now(),
'is_free' => false,
]);
return $this->success(null, 'Subscribe Plan', 'Subscription successfully activated.');
return $this->success(null, 'اشتراک', 'اشتراک شما فعال شد');
} catch (\Exception $e) {
Log::error('Error in subscription', ['Error' => $e->getMessage()]);
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Failed to verify subscription.']);
}
}
public function subscribeMyket(Request $request)
{
$request->validate([
'subscribe_plan_id' => 'required|exists:subscribe_plans,id',
'sku_id' => 'required|string',
'token' => 'required_without_all:tokenId,token_id,purchase_token|string',
'tokenId' => 'required_without_all:token,token_id,purchase_token|string',
'token_id' => 'required_without_all:token,tokenId,purchase_token|string',
'purchase_token' => 'required_without_all:token,tokenId,token_id|string',
]);
$subscribePlan = SubscribePlan::findOrFail($request->subscribe_plan_id);
$user = auth()->user();
$token = $request->input('token')
?? $request->input('tokenId')
?? $request->input('token_id')
?? $request->input('purchase_token');
if ($subscribePlan->is_free) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Invalid subscription details.']);
}
try {
$purchase = $this->marketVerifier->verifyMyketProduct($request->sku_id, $token);
if (! $purchase) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Invalid or failed Myket purchase.']);
}
$expiredAt = $purchase['purchased_at']->copy()->addDays($subscribePlan->expired_day);
if ($expiredAt->lessThan(now())) {
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Invalid or expired subscription.']);
}
$user->userSubscribers()->whereHas('subscribe', function ($query) {
$query->where('is_free', true);
})->update(['expired_at' => now()]);
$user->userSubscribers()->updateOrCreate(
[
'market_provider' => 'myket',
'purchase_token' => $token,
],
[
'subscribe_plan_id' => $subscribePlan->id,
'expired_at' => $expiredAt,
'subscription_id' => $request->sku_id,
'product_id' => $request->sku_id,
'purchased_at' => $purchase['purchased_at'],
'last_verified_at' => now(),
'is_free' => false,
]
);
return $this->success(null, 'Subscribe Plan', 'Myket subscription successfully activated.');
} catch (\Exception $e) {
Log::error('Error in Myket subscription', ['Error' => $e->getMessage()]);
return $this->failed(null, ['title' => 'Subscribe Plan', 'message' => 'Failed to verify Myket subscription.']);
}
}
public function paymentCallback(Request $request)
{
try {
@@ -248,16 +309,16 @@ class SubscribePlanController extends Controller
return $this->success(null, 'Subscribe Plan', 'No Subscribe Plan');
}
private function send($url, $api, $amount, $redirect, $factorId, $name, $email, $description)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&amount=$amount&redirect=$redirect&factorId=$factorId&name=$name&email=$email&description=$description");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
@@ -266,10 +327,11 @@ class SubscribePlanController extends Controller
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, "api=$api&id_get=$id_get&trans_id=$trans_id&json=1");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
}

View File

@@ -15,18 +15,18 @@ class VersionController extends Controller
{
$version = Version::query()->where('type', $versionRequest->type)->orderBy('id', 'desc')->first();
if (!$version) {
if (! $version) {
return $this->failed([], 'Version not found');
}
if (intval($version->number) > $versionRequest->number) {
return $this->success([
'force_update' => $version->force_update == 1 ? true : false
'force_update' => $version->force_update == 1 ? true : false,
], 'Your app need to be updated');
}
return $this->success([
'force_update' => false
'force_update' => false,
], 'Version successfully');
}
}

View File

@@ -14,7 +14,6 @@ use App\Models\Chapter;
use App\Models\Division;
use App\Models\Gate;
use App\Models\Law;
use App\Models\Order;
use App\Models\Part;
use App\Models\RecentArt;
use App\Models\Section;
@@ -35,7 +34,7 @@ class VolumController extends Controller
$volumes->getCollection()->transform(function ($volume) {
$volume['has_book'] = Book::where('volum_id', $volume->id)->exists();
$volume['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $volume['law_id'])->first()?->is_locked;
$volume['is_locked'] = auth()->user()->isSubscriber() !== false ? false : Law::where('id', $volume['law_id'])->first()?->is_locked;
unset($volume['law_id']);
@@ -63,7 +62,7 @@ class VolumController extends Controller
$book = Book::with(['divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs', 'art'])
->find($bookId);
if (!$book) {
if (! $book) {
return $this->success([], 'Book not found');
}
@@ -79,7 +78,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
$paginationData = [
@@ -100,11 +99,10 @@ class VolumController extends Controller
$division = Division::with(['sections', 'chapters', 'parts', 'gate', 'branch', 'art'])
->find($division_id);
if (!$division) {
if (! $division) {
return $this->success([], 'Division not found');
}
$data = [];
$foundRelation = false;
foreach (['sections', 'chapters', 'parts', 'gate', 'branch', 'art'] as $relation) {
@@ -117,7 +115,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -135,7 +133,7 @@ class VolumController extends Controller
$section = Section::with(['chapters', 'parts', 'gate', 'branch', 'art'])
->find($section_id);
if (!$section) {
if (! $section) {
return $this->success([], 'Section not found');
}
@@ -151,7 +149,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -168,7 +166,7 @@ class VolumController extends Controller
if ($volumeId) {
$volume = Volum::with(['book', 'divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs', 'art'])
->find($volumeId);
if (!$volume) {
if (! $volume) {
return $this->success([], 'Volume not found');
}
@@ -184,7 +182,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -202,7 +200,7 @@ class VolumController extends Controller
$part = Part::with(['gate', 'branch', 'art'])
->find($part_id);
if (!$part) {
if (! $part) {
return $this->success([], 'Part not found');
}
@@ -218,7 +216,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -236,7 +234,7 @@ class VolumController extends Controller
$chapter = Chapter::with(['parts', 'gate', 'branch', 'art'])
->find($chapter_id);
if (!$chapter) {
if (! $chapter) {
return $this->success([], 'Chapter not found');
}
@@ -252,7 +250,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -270,7 +268,7 @@ class VolumController extends Controller
$branch = Branch::with(['art'])
->find($branch_id);
if (!$branch) {
if (! $branch) {
return $this->success([], 'Branch not found');
}
@@ -286,7 +284,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -300,12 +298,11 @@ class VolumController extends Controller
}
}
if ($gate_id) {
$gate = Gate::with(['branch', 'art'])
->find($gate_id);
if (!$gate) {
if (! $gate) {
return $this->success([], 'Gate not found');
}
@@ -321,7 +318,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -339,7 +336,7 @@ class VolumController extends Controller
$volume = Volum::with(['book', 'divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs'])
->find($volumeId);
if (!$volume) {
if (! $volume) {
return $this->success([], 'Volume not found');
}
@@ -355,7 +352,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => $relation,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
];
}
break;
@@ -372,7 +369,7 @@ class VolumController extends Controller
if ($law_Id) {
$law = Law::find($law_Id);
if (!$law) {
if (! $law) {
return $this->success([], 'Law not found');
}
@@ -380,16 +377,14 @@ class VolumController extends Controller
->where('law_id', $law->id)
->get();
RecentArt::query()->updateOrCreate([
'user_id' => auth()->user()->id,
'law_id' => $law_Id
'law_id' => $law_Id,
], [
'user_id' => auth()->user()->id,
'law_id' => $law_Id
'law_id' => $law_Id,
]);
$data = [];
if (count($arts) > 0) {
@@ -399,9 +394,10 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => 'volume',
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $law->id)->first()?->is_locked,
];
}
return $this->success($data, 'Success');
}
@@ -423,9 +419,10 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => 'art',
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $law->id)->first()?->is_locked,
];
}
return $this->success($data, 'Success');
}
@@ -504,8 +501,8 @@ class VolumController extends Controller
'foreign_key' => 'branch_id',
'type' => (new Art)->getTable(),
'check_mode' => Art::class,
'check_key' => 'branch_id'
]
'check_key' => 'branch_id',
],
];
foreach ($filters as $filterKey => $filterInfo) {
@@ -533,7 +530,7 @@ class VolumController extends Controller
'title' => $item?->title,
'number' => $item?->number,
'type' => $type,
'is_end' => $check_model::where($check_key, $item?->id)->count() !== 0 ? false : true
'is_end' => $check_model::where($check_key, $item?->id)->count() !== 0 ? false : true,
];
});
@@ -544,7 +541,6 @@ class VolumController extends Controller
return $this->success([], 'No law or book or volume specified');
}
public function check_filter_with_art(CheckBookFilterRequest $request)
{
$lawId = $request->law_id;
@@ -570,7 +566,7 @@ class VolumController extends Controller
'title' => $item->title,
'number' => $item->number,
'type' => 'laws',
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->id)->first()?->is_locked,
'image' => $item?->image,
'law' => $item?->title,
'count_art' => $item->arts->count(),
@@ -584,7 +580,7 @@ class VolumController extends Controller
if ($lawId) {
$law = Law::with(['volums', 'divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs', 'arts'])->find($lawId);
if (!$law) {
if (! $law) {
return $this->success([], 'Law not found');
}
@@ -596,10 +592,9 @@ class VolumController extends Controller
return $this->success([], 'No related records found in the law');
}
if ($bookId) {
$book = Book::with(['divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs', 'art'])->find($bookId);
if (!$book) {
if (! $book) {
return $this->success([], 'Book not found');
}
@@ -613,7 +608,7 @@ class VolumController extends Controller
if ($volumeId) {
$volume = Volum::with(['book', 'divisions', 'sections', 'gates', 'parts', 'chapters', 'branchs', 'art'])->find($volumeId);
if (!$volume) {
if (! $volume) {
return $this->success([], 'Volume not found');
}
@@ -627,7 +622,7 @@ class VolumController extends Controller
if ($sectionId) {
$section = Section::with(['gates', 'parts', 'chapters', 'branchs', 'art'])->find($sectionId);
if (!$section) {
if (! $section) {
return $this->success([], 'Section not found');
}
@@ -641,7 +636,7 @@ class VolumController extends Controller
if ($divisionId) {
$division = Division::with(['gates', 'parts', 'chapters', 'branchs', 'art'])->find($divisionId);
if (!$division) {
if (! $division) {
return $this->success([], 'Division not found');
}
@@ -655,7 +650,7 @@ class VolumController extends Controller
if ($partId) {
$part = Part::with(['gates', 'art'])->find($partId);
if (!$part) {
if (! $part) {
return $this->success([], 'Part not found');
}
@@ -669,7 +664,7 @@ class VolumController extends Controller
if ($branchId) {
$branch = Branch::with(['gates', 'chapters', 'art'])->find($branchId);
if (!$branch) {
if (! $branch) {
return $this->success([], 'Branch not found');
}
@@ -683,7 +678,7 @@ class VolumController extends Controller
if ($chapterId) {
$chapter = Chapter::with(['gate', 'parts', 'art'])->find($chapterId);
if (!$chapter) {
if (! $chapter) {
return $this->success([], 'Chapter not found');
}
@@ -697,7 +692,7 @@ class VolumController extends Controller
if ($gateId) {
$gate = Gate::with(['art'])->find($gateId);
if (!$gate) {
if (! $gate) {
return $this->success([], 'Gate not found');
}
@@ -712,7 +707,6 @@ class VolumController extends Controller
return $this->success([], 'No valid filter specified');
}
private function prepareItemsData($items, $type)
{
$data = [];
@@ -724,14 +718,15 @@ class VolumController extends Controller
'number' => $item->number,
'type' => $type,
'route' => $this->route($item, $item),
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('is_locked', $item->law_id)->first()?->is_locked,
'is_locked' => auth()->user()->isSubscriber() !== false ? false : Law::where('id', $item->law_id)->first()?->is_locked,
'law' => $law?->title,
'image' => $law?->image,
'count_art' => $law?->arts?->count() ?? 0,
'count_art' => $law?->arts?->count() ?? 0,
'count_volums' => $law?->volums?->count() ?? 0,
'price' => $law?->price,
];
}
return $data;
}
@@ -740,13 +735,14 @@ class VolumController extends Controller
foreach ($relations as $relation) {
if ($model->{$relation} && $model->{$relation}->count() > 0) {
$items = $model->{$relation}()->paginate($perPage);
return $this->prepareItemsData($items, $relation);
}
}
return null;
}
private function convertValueTo($var)
{
switch ($var) {
@@ -769,13 +765,13 @@ class VolumController extends Controller
switch ((new $modelClass)->getTable()) {
case 'laws':
$route = array_filter([
Law::find($query->id)?->title
Law::find($query->id)?->title,
]);
break;
case 'volums':
$route = array_filter([
Law::find($query->law_id)?->title,
Volum::find($query->id)?->title
Volum::find($query->id)?->title,
]);
break;
case 'books':

View File

@@ -17,7 +17,7 @@ class GetApiRequest extends FormRequest
public function rules(): array
{
return [
'book_id' => 'required'
'book_id' => 'required',
];
}
}

View File

@@ -25,7 +25,7 @@ class SuggestionRequest extends FormRequest
public function rules(): array
{
return [
'text' => 'required'
'text' => 'required',
];
}
}

View File

@@ -18,7 +18,7 @@ class CreateVersionStore extends FormRequest
'number' => 'required',
'log' => 'required',
'force_update' => 'nullable',
'type' => 'required'
'type' => 'required',
];
}
}

View File

@@ -28,7 +28,7 @@ class CreateRequest extends FormRequest
'is_active' => 'nullable',
'is_free' => 'nullable',
'type' => 'nullable',
'transaction' => 'nullable'
'transaction' => 'nullable',
];
}
}

View File

@@ -28,7 +28,7 @@ class UpdateRequest extends FormRequest
'is_active' => 'nullable',
'is_free' => 'nullable',
'type' => 'nullable',
'transaction' => 'nullable'
'transaction' => 'nullable',
];
}
}

View File

@@ -18,7 +18,7 @@ class UpdateVersionStore extends FormRequest
'number' => 'required',
'log' => 'required',
'force_update' => 'nullable',
'type' => 'required'
'type' => 'required',
];
}
}

View File

@@ -3,13 +3,13 @@
namespace App\Jobs;
// These are the classes we need to import for our job to work
use App\Models\UserSubscriber;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\InteractsWithQueue; // Your model for tracking user subscriptions
use Illuminate\Queue\SerializesModels;
use App\Models\UserSubscriber; // Your model for tracking user subscriptions
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
@@ -40,8 +40,9 @@ class CheckBazaarSubscription implements ShouldQueue
$package_name = 'com.razzaghi.lawbook.android'; // Your app's package name
// If there's no purchase token, we can't do anything, so we stop.
if (!$purchase_token) {
Log::info('Job skipped: No purchase token for UserSubscriber ID: ' . $this->userSubscriber->id);
if (! $purchase_token) {
Log::info('Job skipped: No purchase token for UserSubscriber ID: '.$this->userSubscriber->id);
return;
}
@@ -69,16 +70,16 @@ class CheckBazaarSubscription implements ShouldQueue
// If the expiration date in our database is different, update it
if ($this->userSubscriber->expired_at->notEqualTo($bazaarExpiredAt)) {
$this->userSubscriber->update(['expired_at' => $bazaarExpiredAt]);
Log::info('Subscription date updated for user: ' . $this->userSubscriber->user_id);
Log::info('Subscription date updated for user: '.$this->userSubscriber->user_id);
}
} else {
// If the subscription is no longer valid, update it in our database to expire now
$this->userSubscriber->update(['expired_at' => now()]);
Log::warning('Subscription found expired on Bazaar for user: ' . $this->userSubscriber->user_id);
Log::warning('Subscription found expired on Bazaar for user: '.$this->userSubscriber->user_id);
}
} else {
// If the API call failed, log the error for debugging
Log::error('Failed to fetch subscription from Bazaar', ['status' => $response->status(), 'body' => $response->body()]);
// If the API call failed, log the error for debugging
Log::error('Failed to fetch subscription from Bazaar', ['status' => $response->status(), 'body' => $response->body()]);
}
} catch (\Exception $e) {

View File

@@ -53,6 +53,11 @@ class Art extends Model
return $this->belongsToMany(JudicialPrecedent::class, 'art_judicial_precedent');
}
public function legalOpinions()
{
return $this->belongsToMany(LegalOpinion::class, 'art_legal_opinion');
}
public static function search($searchTerm)
{
return self::where('title', 'LIKE', "%{$searchTerm}%")

View File

@@ -48,7 +48,6 @@ class Book extends Model
return $this->hasMany(Branch::class);
}
public static function searchLimit($searchTerm)
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->limit(3)->get();

View File

@@ -9,8 +9,7 @@ class Branch extends Model
{
use HasFactory;
protected $fillable = ['title', 'number', 'chapter_id', 'part_id', 'volum_id', 'law_id', 'book_id', 'section_id', 'gate_id','division_id'];
protected $fillable = ['title', 'number', 'chapter_id', 'part_id', 'volum_id', 'law_id', 'book_id', 'section_id', 'gate_id', 'division_id'];
public function art()
{

View File

@@ -0,0 +1,14 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawCodificationLink extends Model
{
protected $table = 'bylaw_codification_links';
public $timestamps = false;
protected $fillable = ['source_entity_type', 'source_entity_id', 'target_entity_type', 'target_entity_id', 'link_type', 'effective_date', 'justification', 'created_at'];
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawDocument extends Model
{
protected $table = 'bylaw_documents';
protected $fillable = ['title', 'category_id', 'approval_authority_id', 'approval_date', 'promulgation_authority_id', 'promulgation_date', 'promulgation_number', 'official_gazette_number', 'official_gazette_date', 'execution_date', 'bylaw_type', 'global_status', 'pdf_file_path', 'is_published', 'description'];
protected $casts = ['is_published' => 'boolean'];
public function category()
{
return $this->belongsTo(BylawSubjectCategory::class, 'category_id');
}
public function approvalAuthority()
{
return $this->belongsTo(BylawLegalAuthority::class, 'approval_authority_id');
}
public function promulgationAuthority()
{
return $this->belongsTo(BylawLegalAuthority::class, 'promulgation_authority_id');
}
public function nodes()
{
return $this->hasMany(BylawNode::class, 'document_id');
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawLegalAuthority extends Model
{
protected $table = 'bylaw_legal_authorities';
protected $fillable = ['name', 'authority_type', 'description'];
}

27
app/Models/BylawNode.php Normal file
View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawNode extends Model
{
protected $table = 'bylaw_nodes';
protected $fillable = ['document_id', 'parent_id', 'node_type_id', 'node_identifier', 'title', 'node_content', 'sort_order', 'valid_from', 'valid_to', 'node_status'];
public function document()
{
return $this->belongsTo(BylawDocument::class, 'document_id');
}
public function parent()
{
return $this->belongsTo(self::class, 'parent_id');
}
public function type()
{
return $this->belongsTo(BylawNodeType::class, 'node_type_id');
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawNodeType extends Model
{
protected $table = 'bylaw_node_types';
protected $fillable = ['name', 'hierarchy_level'];
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class BylawSubjectCategory extends Model
{
protected $table = 'bylaw_subject_categories';
protected $fillable = ['parent_id', 'name', 'slug', 'sort_order'];
public function parent()
{
return $this->belongsTo(self::class, 'parent_id');
}
}

View File

@@ -11,22 +11,19 @@ class Category extends Model
protected $fillable = [
'name',
'type'
'type',
];
public function laws()
{
return $this->hasMany(Law::class);
}
public static function getType()
{
return [
'hagigi' => 'حقیقی',
'kifari' => 'کیفری'
'kifari' => 'کیفری',
];
}
}

View File

@@ -9,7 +9,7 @@ class Chapter extends Model
{
use HasFactory;
protected $fillable = ['title', 'number', 'section_id', 'book_id', 'volum_id', 'law_id','division_id'];
protected $fillable = ['title', 'number', 'section_id', 'book_id', 'volum_id', 'law_id', 'division_id'];
protected $hidden = ['created_at', 'updated_at'];
@@ -28,7 +28,6 @@ class Chapter extends Model
return $this->hasMany(Gate::class);
}
public function branch()
{
return $this->hasMany(Branch::class);

View File

@@ -11,7 +11,6 @@ class Division extends Model
protected $fillable = ['title', 'number', 'book_id', 'volum_id', 'law_id'];
public function sections()
{
return $this->hasMany(Section::class);
@@ -47,7 +46,6 @@ class Division extends Model
return $this->hasMany(Art::class);
}
public function gates()
{
return $this->hasMany(Gate::class);
@@ -67,5 +65,4 @@ class Division extends Model
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->limit(3)->get();
}
}

View File

@@ -11,7 +11,7 @@ class Folder extends Model
protected $fillable = [
'user_id',
'name'
'name',
];
public function arts()

View File

@@ -11,11 +11,11 @@ class FolderArt extends Model
protected $fillable = [
'folder_id',
'art_id'
'art_id',
];
public function arts()
{
return $this->belongsTo(Art::class,'art_id');
return $this->belongsTo(Art::class, 'art_id');
}
}

View File

@@ -9,7 +9,7 @@ class Gate extends Model
{
use HasFactory;
protected $fillable = ['title', 'number', 'part_id', 'chapter_id', 'section_id', 'book_id', 'volum_id', 'law_id','division_id'];
protected $fillable = ['title', 'number', 'part_id', 'chapter_id', 'section_id', 'book_id', 'volum_id', 'law_id', 'division_id'];
protected $hidden = ['created_at', 'updated_at'];
@@ -18,7 +18,6 @@ class Gate extends Model
return $this->hasMany(Branch::class);
}
public function art()
{
return $this->hasMany(Art::class);
@@ -38,6 +37,4 @@ class Gate extends Model
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->limit(3)->get();
}
}

View File

@@ -15,7 +15,7 @@ class JudicialPrecedent extends Model
'subject',
'full_text',
'issuing_authority',
'category_id'
'category_id',
];
protected $hidden = ['created_at', 'updated_at'];

View File

@@ -9,11 +9,10 @@ class Law extends Model
{
use HasFactory;
protected $fillable = ['title', 'is_locked', 'category_id', 'price','image'];
protected $fillable = ['title', 'is_locked', 'category_id', 'price', 'image'];
protected $hidden = ['created_at', 'updated_at'];
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
@@ -81,6 +80,6 @@ class Law extends Model
public function getImageAttribute($value)
{
return $value ? secure_asset('images/' . $value) : null;
return $value ? secure_asset('images/'.$value) : null;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class LegalOpinion extends Model
{
use HasFactory;
protected $fillable = [
'opinion_number',
'opinion_date',
'subject',
'full_text',
'issuing_authority',
'category_id',
];
protected $hidden = ['created_at', 'updated_at'];
public function arts()
{
return $this->belongsToMany(Art::class, 'art_legal_opinion');
}
public function category()
{
return $this->belongsTo(LegalOpinionCategory::class, 'category_id');
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class LegalOpinionCategory extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function legalOpinions()
{
return $this->hasMany(LegalOpinion::class, 'category_id');
}
}

View File

@@ -11,7 +11,7 @@ class LikeArt extends Model
protected $fillable = [
'user_id',
'art_id'
'art_id',
];
public function art()

View File

@@ -11,6 +11,6 @@ class LikeSection extends Model
protected $fillable = [
'section_id',
'user_id'
'user_id',
];
}

View File

@@ -13,6 +13,6 @@ class Note extends Model
'user_id',
'art_id',
'note',
'color_code'
'color_code',
];
}

View File

@@ -16,7 +16,6 @@ class Order extends Model
'transaction_id',
];
public function user()
{
return $this->belongsTo(User::class);
@@ -26,7 +25,7 @@ class Order extends Model
{
return [
'paid' => 'پرداخت شده',
'unpaid' => 'پرداخت نشده'
'unpaid' => 'پرداخت نشده',
];
}
}

View File

@@ -9,11 +9,10 @@ class Part extends Model
{
use HasFactory;
protected $fillable = ['title', 'number', 'chapter_id', 'section_id', 'book_id', 'volum_id', 'law_id','division_id'];
protected $fillable = ['title', 'number', 'chapter_id', 'section_id', 'book_id', 'volum_id', 'law_id', 'division_id'];
protected $hidden = ['created_at', 'updated_at'];
public function gates()
{
return $this->hasMany(Gate::class);
@@ -34,7 +33,6 @@ class Part extends Model
return self::where('title', 'LIKE', "%{$searchTerm}%")->get();
}
public static function searchLimit($searchTerm)
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->limit(3)->get();

View File

@@ -11,10 +11,9 @@ class RecentArt extends Model
protected $fillable = [
'user_id',
'law_id'
'law_id',
];
public function law()
{
return $this->belongsTo(Law::class);

View File

@@ -9,7 +9,7 @@ class Section extends Model
{
use HasFactory;
protected $fillable = ['title', 'number', 'book_id', 'volum_id', 'law_id','division_id'];
protected $fillable = ['title', 'number', 'book_id', 'volum_id', 'law_id', 'division_id'];
protected $hidden = ['created_at', 'updated_at'];
@@ -48,16 +48,13 @@ class Section extends Model
return $this->hasMany(Art::class);
}
public static function search($searchTerm)
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->get();
}
public static function searchLimit($searchTerm)
{
return self::where('title', 'LIKE', "%{$searchTerm}%")->limit(3)->get();
}
}

View File

@@ -16,7 +16,7 @@ class SubscribePlan extends Model
'is_active',
'is_free',
'type',
'transaction'
'transaction',
];
public function users()

View File

@@ -11,7 +11,7 @@ class Suggestion extends Model
protected $fillable = [
'user_id',
'text'
'text',
];
public function user()

View File

@@ -15,12 +15,16 @@ class UserSubscriber extends Model
'expired_at',
'subscription_id',
'purchase_token',
'is_free'
'market_provider',
'product_id',
'purchased_at',
'last_verified_at',
'is_free',
];
public function subscribe()
{
return $this->belongsTo(SubscribePlan::class,'subscribe_plan_id');
return $this->belongsTo(SubscribePlan::class, 'subscribe_plan_id');
}
public function user()
@@ -35,5 +39,7 @@ class UserSubscriber extends Model
protected $casts = [
'expired_at' => 'datetime',
'purchased_at' => 'datetime',
'last_verified_at' => 'datetime',
];
}

View File

@@ -14,10 +14,9 @@ class Version extends Model
'number',
'log',
'force_update',
'type'
'type',
];
protected $hidden = [
'created_at',
'updated_at',

View File

@@ -15,12 +15,14 @@ class Volum extends Model
public function law()
{
return $this->belongsTo(Law::class);
return $this->belongsTo(Law::class);
}
public function book()
{
return $this->hasMany(Book::class);
}
public function sections()
{
return $this->hasMany(Section::class);

View File

@@ -0,0 +1,117 @@
<?php
namespace App\Services;
use App\Models\UserSubscriber;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class AppMarketPurchaseVerifier
{
public function verifyBazaarSubscription(string $subscriptionId, string $purchaseToken): ?Carbon
{
$packageName = config('services.app_markets.package_name');
$url = "https://pardakht.cafebazaar.ir/devapi/v2/api/applications/{$packageName}/subscriptions/{$subscriptionId}/purchases/{$purchaseToken}";
$response = Http::timeout(3)->connectTimeout(2)->withHeaders([
'CAFEBAZAAR-PISHKHAN-API-SECRET' => config('services.app_markets.bazaar_secret'),
])->get($url);
if (! $response->successful()) {
Log::error('Failed to verify Bazaar subscription', [
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
$validUntil = $response->json('validUntilTimestampMsec');
if (! $validUntil || $validUntil < now()->timestamp * 1000) {
return null;
}
return Carbon::createFromTimestampMs($validUntil);
}
public function refreshBazaarSubscriber(UserSubscriber $subscriber): bool
{
if (! $subscriber->subscription_id || ! $subscriber->purchase_token) {
return false;
}
$expiredAt = $this->verifyBazaarSubscription($subscriber->subscription_id, $subscriber->purchase_token);
if (! $expiredAt) {
$subscriber->update(['expired_at' => now()]);
return false;
}
$subscriber->update([
'expired_at' => $expiredAt,
'last_verified_at' => now(),
]);
return true;
}
public function verifyMyketProduct(string $skuId, string $token): ?array
{
$packageName = config('services.app_markets.package_name');
$url = "https://developer.myket.ir/api/partners/applications/{$packageName}/purchases/products/{$skuId}/verify";
$response = Http::timeout(3)->connectTimeout(2)->withHeaders([
'X-Access-Token' => config('services.app_markets.myket_access_token'),
])->post($url, [
'tokenId' => $token,
]);
if (! $response->successful()) {
Log::error('Failed to verify Myket purchase', [
'status' => $response->status(),
'body' => $response->body(),
]);
return null;
}
$data = $response->json();
if (($data['purchaseState'] ?? null) !== 0 || empty($data['purchaseTime'])) {
return null;
}
return [
'data' => $data,
'purchased_at' => Carbon::createFromTimestampMs($data['purchaseTime']),
];
}
public function refreshMyketSubscriber(UserSubscriber $subscriber): bool
{
if (! $subscriber->product_id || ! $subscriber->purchase_token || ! $subscriber->subscribe) {
return false;
}
$purchase = $this->verifyMyketProduct($subscriber->product_id, $subscriber->purchase_token);
if (! $purchase) {
$subscriber->update(['expired_at' => now()]);
return false;
}
$expiredAt = $purchase['purchased_at']->copy()->addDays($subscriber->subscribe->expired_day);
$subscriber->update([
'purchased_at' => $purchase['purchased_at'],
'expired_at' => $expiredAt,
'last_verified_at' => now(),
]);
return $expiredAt->greaterThanOrEqualTo(now());
}
}

View File

@@ -15,7 +15,7 @@ return [
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie','images/*'],
'paths' => ['api/*', 'sanctum/csrf-cookie', 'images/*'],
'allowed_methods' => ['*'],

View File

@@ -131,8 +131,8 @@ return [
'apiPaymentUrl' => 'https://napi.jibit.ir/ppg/v3',
'apiKey' => '',
'apiSecret' => '',
// You can change the token storage path in Laravel like this
// 'tokenStoragePath' => function_exists('storage_path') ? storage_path('jibit/') : 'jibit/'
// You can change the token storage path in Laravel like this
// 'tokenStoragePath' => function_exists('storage_path') ? storage_path('jibit/') : 'jibit/'
'tokenStoragePath' => 'jibit/',
'callbackUrl' => 'http://yoursite.com/path/to',
'description' => 'payment using jibit',
@@ -248,9 +248,9 @@ return [
'PaymentIdentity' => '',
'MultiIdentityRows' => [
[
"IbanNumber" => '', // Sheba number (with IR)
"Amount" => 0,
"PaymentIdentity" => '',
'IbanNumber' => '', // Sheba number (with IR)
'Amount' => 0,
'PaymentIdentity' => '',
],
],
'description' => 'payment using sadad',
@@ -414,13 +414,13 @@ return [
'base_url' => 'https://escrow-api.toman.ir/api/v1',
'shop_slug' => '',
'auth_code' => '',
'data' => ''
'data' => '',
],
'bitpay' => [
'apiPurchaseUrl' => 'http://bitpay.ir/payment/gateway-send',
'apiPaymentUrl' => 'http://bitpay.ir/payment/gateway-{id_get}-get',
'apiVerificationUrl' => 'http://bitpay.ir/payment/gateway-result-second',
'callbackUrl' => env('APP_URL') . '/payment/callback',
'callbackUrl' => env('APP_URL').'/payment/callback',
'api_token' => '066fd-d622e-690a9-be618-ddf02bc6059bbbd67c317bb340d1',
'description' => 'payment using Bitpay',
'currency' => 'R', //Can be R, T (Rial, Toman)
@@ -487,5 +487,5 @@ return [
'toman' => \Shetabit\Multipay\Drivers\Toman\Toman::class,
'bitpay' => \Shetabit\Multipay\Drivers\Bitpay\Bitpay::class,
'minipay' => \Shetabit\Multipay\Drivers\Minipay\Minipay::class,
]
],
];

View File

@@ -31,4 +31,11 @@ return [
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'app_markets' => [
'package_name' => env('APP_MARKET_PACKAGE_NAME', 'com.razzaghi.lawbook.android'),
'myket_access_token' => env('MYKET_ACCESS_TOKEN', 'd9f9207b-72c9-438e-9ff1-0b44e24b2612'),
'myket_public_key' => env('MYKET_PUBLIC_KEY', 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCg3ZcL+tvifbjvSbo1ZKbG0Zw7PwVEtkiP9yCwpn6J9pxs53ZO5dqWDc2u8pewPPFxXbi/sUrbdpuia+l2raSO+8ncp5loA8r/dCRww/qjtWmcXhqGEZWfb9dsh8VduNVjBBva1EcePL63L3PbLgnj+ty/gLd03o+H+yOJbFc/dwIDAQAB'),
'bazaar_secret' => env('BAZAAR_API_SECRET', 'eyJhbGciOiJIUzI1NiIsImtpZCI6ImFuY2llbnQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJuYXNoZXItcGlzaGtoYW4tYXBpIiwiaWF0IjoxNzQwMjQ3NTMzLCJleHAiOjQ4OTM4NDc1MzMsImFwaV9hZ2VudF9pZCI6MzQ2NX0.UCrr3IHxCqn77ckxfnaubrsyCfrhPm18gJgyg1qNqwA'),
],
];

View File

@@ -12,7 +12,7 @@ return new class extends Migration
public function up(): void
{
Schema::table('versions', function (Blueprint $table) {
$table->enum('type',['web','ios','android'])->after('code')->default('web');
$table->enum('type', ['web', 'ios', 'android'])->after('code')->default('web');
});
}

View File

@@ -19,12 +19,10 @@ return new class extends Migration
$table->foreignId('division_id')->after('number')->nullable();
});
Schema::table('parts', function (Blueprint $table) {
$table->foreignId('division_id')->after('number')->nullable();
});
Schema::table('gates', function (Blueprint $table) {
$table->foreignId('division_id')->after('number')->nullable();
});

View File

@@ -11,8 +11,7 @@ return new class extends Migration
*/
public function up(): void
{
if(!Schema::hasTable('like_sections'))
{
if (! Schema::hasTable('like_sections')) {
Schema::create('like_sections', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id');

View File

@@ -11,8 +11,7 @@ return new class extends Migration
*/
public function up(): void
{
if(!Schema::hasTable('like_art'))
{
if (! Schema::hasTable('like_art')) {
Schema::create('like_art', function (Blueprint $table) {
$table->id();
$table->foreignId('art_id');

View File

@@ -11,7 +11,7 @@ return new class extends Migration
*/
public function up(): void
{
if (!Schema::hasTable('notes')) {
if (! Schema::hasTable('notes')) {
Schema::create('notes', function (Blueprint $table) {
$table->id();

View File

@@ -15,7 +15,7 @@ return new class extends Migration
$table->id();
$table->foreignId('user_id');
$table->BigInteger('price');
$table->enum('status' , ['unpaid' , 'paid' , 'canceled']);
$table->enum('status', ['unpaid', 'paid', 'canceled']);
$table->string('transaction_id');
$table->timestamps();
});

View File

@@ -14,7 +14,7 @@ return new class extends Migration
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->enum('type',['hagigi','kifari']);
$table->enum('type', ['hagigi', 'kifari']);
$table->timestamps();
});
}

View File

@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('legal_opinion_categories', function (Blueprint $table) {
$table->id();
$table->string('name')->unique()->comment('نام دسته‌بندی');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('legal_opinion_categories');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('legal_opinions', function (Blueprint $table) {
$table->id();
$table->string('opinion_number')->comment('شماره نظریه');
$table->date('opinion_date')->nullable()->comment('تاریخ نظریه');
$table->string('subject', 1000)->nullable()->comment('موضوع استعلام یا نظریه');
$table->longText('full_text')->comment('متن کامل نظریه و استعلام');
$table->string('issuing_authority')->nullable()->comment('مرجع صدور');
$table->foreignId('category_id')->constrained('legal_opinion_categories')->onDelete('cascade')->comment('شناسه دسته‌بندی');
$table->timestamps();
$table->unique(['opinion_number', 'category_id'], 'unique_opinion_category');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('legal_opinions');
}
};

View File

@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('art_legal_opinion', function (Blueprint $table) {
$table->id();
$table->foreignId('art_id')->constrained('art')->onDelete('cascade');
$table->foreignId('legal_opinion_id')->constrained('legal_opinions')->onDelete('cascade');
$table->timestamps();
$table->unique(['art_id', 'legal_opinion_id']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('art_legal_opinion');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('user_subscribers', function (Blueprint $table) {
$table->string('market_provider')->nullable()->after('purchase_token');
$table->string('product_id')->nullable()->after('market_provider');
$table->timestamp('purchased_at')->nullable()->after('product_id');
$table->timestamp('last_verified_at')->nullable()->after('purchased_at');
});
}
public function down(): void
{
Schema::table('user_subscribers', function (Blueprint $table) {
$table->dropColumn([
'market_provider',
'1',
'purchased_at',
'last_verified_at',
]);
});
}
};

View File

@@ -0,0 +1,128 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
DB::statement('SET FOREIGN_KEY_CHECKS=0');
Schema::create('bylaw_legal_authorities', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->enum('authority_type', ['executive', 'judicial', 'legislative', 'administrative', 'other']);
$table->text('description')->nullable();
$table->timestamps();
});
Schema::create('bylaw_subject_categories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->string('name');
$table->string('slug')->unique();
$table->integer('sort_order')->default(0);
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('bylaw_subject_categories')->nullOnDelete();
});
Schema::create('bylaw_documents', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 1000);
$table->unsignedInteger('category_id')->nullable();
$table->unsignedInteger('approval_authority_id')->nullable();
$table->date('approval_date')->nullable();
$table->unsignedInteger('promulgation_authority_id')->nullable();
$table->date('promulgation_date')->nullable();
$table->string('promulgation_number', 100)->nullable();
$table->string('official_gazette_number', 100)->nullable();
$table->date('official_gazette_date')->nullable();
$table->date('execution_date')->nullable();
$table->enum('bylaw_type', ['executive', 'delegated', 'independent']);
$table->enum('global_status', ['valid', 'explicitly_repealed', 'implicitly_repealed', 'annulled', 'expired', 'draft'])->default('valid');
$table->string('pdf_file_path', 500)->nullable();
$table->boolean('is_published')->default(true);
$table->text('description')->nullable();
$table->timestamps();
$table->foreign('category_id')->references('id')->on('bylaw_subject_categories')->nullOnDelete();
$table->foreign('approval_authority_id')->references('id')->on('bylaw_legal_authorities')->nullOnDelete();
$table->foreign('promulgation_authority_id')->references('id')->on('bylaw_legal_authorities')->nullOnDelete();
$table->index(['approval_date', 'promulgation_date'], 'idx_bylaw_dates');
$table->index('global_status', 'idx_bylaw_status');
});
Schema::create('bylaw_node_types', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->unique();
$table->integer('hierarchy_level');
$table->timestamps();
});
Schema::create('bylaw_nodes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('document_id');
$table->unsignedBigInteger('parent_id')->nullable();
$table->unsignedInteger('node_type_id');
$table->string('node_identifier', 50)->nullable();
$table->string('title', 500)->nullable();
$table->longText('node_content')->nullable();
$table->integer('sort_order')->default(0);
$table->date('valid_from')->nullable();
$table->date('valid_to')->nullable();
$table->enum('node_status', ['valid', 'repealed', 'annulled', 'amended', 'suspended'])->default('valid');
$table->timestamps();
$table->foreign('document_id')->references('id')->on('bylaw_documents')->cascadeOnDelete();
$table->foreign('parent_id')->references('id')->on('bylaw_nodes')->cascadeOnDelete();
$table->foreign('node_type_id')->references('id')->on('bylaw_node_types')->restrictOnDelete();
$table->index(['document_id', 'parent_id'], 'idx_node_tree');
$table->index(['node_status', 'valid_from', 'valid_to'], 'idx_node_temporal');
});
Schema::table('bylaw_nodes', function (Blueprint $table) {
$table->fullText(['node_content', 'title'], 'ft_idx_content');
});
Schema::create('bylaw_codification_links', function (Blueprint $table) {
$table->bigIncrements('id');
$table->enum('source_entity_type', ['bylaw_node', 'bylaw_doc', 'law_doc', 'court_verdict', 'advisory_opinion']);
$table->unsignedBigInteger('source_entity_id');
$table->enum('target_entity_type', ['bylaw_node', 'bylaw_doc', 'law_doc', 'court_verdict', 'advisory_opinion']);
$table->unsignedBigInteger('target_entity_id');
$table->enum('link_type', ['repeals_explicitly', 'repeals_implicitly', 'annuls_entirely', 'annuls_partially', 'amends', 'adds_to', 'interprets', 'is_executive_bylaw_of']);
$table->date('effective_date')->nullable();
$table->text('justification')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->unique(['source_entity_type', 'source_entity_id', 'target_entity_type', 'target_entity_id', 'link_type'], 'idx_unique_link');
$table->index(['target_entity_type', 'target_entity_id'], 'idx_target_search');
});
DB::table('bylaw_node_types')->insertOrIgnore([
['id' => 1, 'name' => 'متن کامل آیین‌نامه', 'hierarchy_level' => 1, 'created_at' => now(), 'updated_at' => now()],
]);
DB::table('bylaw_subject_categories')->insertOrIgnore([
['id' => 9, 'name' => 'آیین نامه ها', 'slug' => 'bylaws', 'sort_order' => 0, 'created_at' => now(), 'updated_at' => now()],
]);
DB::statement('SET FOREIGN_KEY_CHECKS=1');
}
public function down(): void
{
DB::statement('SET FOREIGN_KEY_CHECKS=0');
Schema::dropIfExists('bylaw_codification_links');
Schema::dropIfExists('bylaw_nodes');
Schema::dropIfExists('bylaw_node_types');
Schema::dropIfExists('bylaw_documents');
Schema::dropIfExists('bylaw_subject_categories');
Schema::dropIfExists('bylaw_legal_authorities');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
}
};

Some files were not shown because too many files have changed in this diff Show More