diff --git a/app/Console/Commands/DeleteUnusedImages.php b/app/Console/Commands/DeleteUnusedImages.php index 754958f7..745f6dbd 100644 --- a/app/Console/Commands/DeleteUnusedImages.php +++ b/app/Console/Commands/DeleteUnusedImages.php @@ -7,7 +7,6 @@ use App\Models\ForumPost; use App\Models\Notice; use App\Models\Resource; -use App\Models\ResourceChangeRequest; use App\Models\SupportTicket; use App\Models\User; use Illuminate\Console\Command; @@ -46,20 +45,25 @@ public function handle(): void ->toArray() ); - // Resource files (notes, images, videos — all stored under resources/) - // Also protects pending change requests awaiting moderation review - $activeResourceFiles = Resource::whereNotNull('file_path')->pluck('file_path')->toArray(); - $pendingChangeRequestFiles = ResourceChangeRequest::where('status', 'pending') - ->whereNotNull('payload') - ->get() - ->pluck('payload.file_path') - ->filter() - ->values() - ->toArray(); + // Resource files (items stored under resources/) + $rawItems = DB::table('resources') + ->whereNotNull('items') + ->pluck('items'); + + $activeResourceFiles = []; + foreach ($rawItems as $json) { + $items = is_array($json) ? $json : (json_decode($json, true) ?: []); + foreach ($items as $item) { + $source = $item['source'] ?? null; + if ($source && ! str_starts_with($source, 'http://') && ! str_starts_with($source, 'https://')) { + $activeResourceFiles[] = $source; + } + } + } $this->cleanDirectory( 'resources', - array_values(array_unique(array_merge($activeResourceFiles, $pendingChangeRequestFiles))) + array_values(array_unique($activeResourceFiles)) ); // Forum post images @@ -94,9 +98,19 @@ protected function cleanDirectory(string $directory, array $usedFiles): void $files = Storage::allFiles($directory); $deleted = 0; + $oneDayAgo = now()->subDay()->timestamp; foreach ($files as $file) { if (! in_array($file, $usedFiles, true)) { + // Skip newly uploaded files (e.g. uploaded within last 24h) to avoid race conditions with unsubmitted forms + try { + if (Storage::lastModified($file) > $oneDayAgo) { + continue; + } + } catch (\Throwable) { + // ignore if storage does not support lastModified + } + $this->line("Unused: {$file}"); if (! $this->option('dry-run')) { diff --git a/app/Http/Controllers/Admin/NodeController.php b/app/Http/Controllers/Admin/NodeController.php index 51e2672d..e78702cd 100644 --- a/app/Http/Controllers/Admin/NodeController.php +++ b/app/Http/Controllers/Admin/NodeController.php @@ -8,7 +8,6 @@ use App\Models\Node; use App\Models\Subject; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Str; use Inertia\Inertia; @@ -26,8 +25,6 @@ public function show(Subject $subject, $path = null) 'subject' => $subject, 'nodes' => $nodes, 'resources' => [], - 'pending_creates' => [], - 'rejected_creates' => [], 'breadcrumb' => [], ]); } @@ -50,33 +47,15 @@ public function show(Subject $subject, $path = null) } } - $pendingCreates = $node->pendingCreateRequests() - ->with('user:id,name,username') - ->get(); - - $rejectedCreates = $node->rejectedCreateRequests() - ->where('user_id', Auth::id()) - ->with(['user:id,name,username', 'reviewer:id,name,username']) - ->latest('reviewed_at') - ->take(10) - ->get(); - $resources = $node->resources() - ->with([ - 'pendingChangeRequest.user:id,name,username', - 'latestRejectedChangeRequest' => function ($query) { - $query->where('user_id', Auth::id()) - ->with('reviewer:id,name,username'); - }, - ]) + ->where('status', 'approved') + ->with(['user:id,name,username']) ->get(); return Inertia::render('admin/Node', [ 'subject' => $subject, 'nodes' => $node->children, 'resources' => $resources, - 'pending_creates' => $pendingCreates, - 'rejected_creates' => $rejectedCreates, 'parent' => $node->append('is_effectively_frozen'), 'breadcrumb' => $node->breadcrumb(), ]); diff --git a/app/Http/Controllers/Admin/ResourceController.php b/app/Http/Controllers/Admin/ResourceController.php index 72a2798d..27451c28 100644 --- a/app/Http/Controllers/Admin/ResourceController.php +++ b/app/Http/Controllers/Admin/ResourceController.php @@ -3,92 +3,140 @@ namespace App\Http\Controllers\Admin; use App\Http\Controllers\ResourceController as BaseResourceController; -use App\Http\Requests\Resource\UpdateResourceRequest; -use App\Models\Node; use App\Models\Resource; -use App\Models\ResourceChangeRequest; +use App\Notifications\ResourceModerationNotification; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; +use Inertia\Inertia; class ResourceController extends BaseResourceController { - public function update(UpdateResourceRequest $request, Resource $resource) + public function moderationIndex(Request $request) { - $validated = $request->validated(); - - $isModerator = $request->user()->can('moderate resources'); - - if (! $isModerator) { - $this->ensureCanSubmit(1); + $status = $request->query('status', 'pending'); + if (! in_array($status, ['pending', 'approved', 'rejected', 'all'])) { + $status = 'pending'; } - if ($request->hasFile('file')) { - if ($isModerator && $resource->file_path) { - Storage::delete($resource->file_path); - } - $validated['file_path'] = $request->file('file')->store("resources/{$validated['resource_type']}s"); - } + $counts = Resource::selectRaw('status, count(*) as total') + ->groupBy('status') + ->pluck('total', 'status'); - if ($isModerator) { - $resource->update($validated); + $query = Resource::query() + ->with([ + 'user:id,name,username,image_path', + 'node.subject', + ]) + ->latest('id'); - return back()->with('success', 'Resource updated successfully.'); + if ($status !== 'all') { + $query->where('status', $status); } - ResourceChangeRequest::recordUpdate( - Auth::id(), - $resource, - $validated - ); + $resources = $query->paginate(20)->withQueryString(); - return back()->with('success', 'Resource update submitted for moderation.'); + $resources->getCollection()->each(function ($res) { + $res->node?->append('breadcrumb'); + }); + + return Inertia::render('admin/moderation/Resources', [ + 'resources' => $resources, + 'currentStatus' => $status, + 'counts' => [ + 'all' => (int) $counts->sum(), + 'pending' => (int) $counts->get('pending', 0), + 'approved' => (int) $counts->get('approved', 0), + 'rejected' => (int) $counts->get('rejected', 0), + ], + ]); } - public function destroy(Resource $resource) + public function approve(Request $request) { - if (Auth::user()?->can('moderate resources')) { - if ($resource->file_path) { - Storage::delete($resource->file_path); - } - $resource->delete(); - - return redirect()->back()->with('success', 'Resource deleted successfully.'); - } + $validated = $request->validate([ + 'ids' => ['required', 'array', 'min:1'], + 'ids.*' => ['integer', 'exists:resources,id'], + ]); - $this->ensureCanSubmit(1); + $resources = Resource::whereIn('id', $validated['ids']) + ->where('status', '!=', 'approved') + ->with('user') + ->get(); + + DB::transaction(function () use ($resources) { + foreach ($resources as $res) { + $res->update([ + 'status' => 'approved', + 'reviewed_by' => Auth::id(), + 'reviewed_at' => now(), + ]); + + if ($res->user) { + ResourceModerationNotification::sendTo($res->user, $res, 'approved'); + } + } + }); - ResourceChangeRequest::recordDelete(Auth::id(), $resource); + $count = $resources->count(); + $message = $count === 1 + ? 'Resource approved and published successfully.' + : "{$count} resources approved and published successfully."; - return redirect()->back()->with('success', 'Resource deletion request submitted for moderation.'); + return back()->with('success', $message); } - public function bulkRename(Request $request, Node $node) + public function reject(Request $request) { - if ($node->isEffectivelyFrozen()) { - abort(403, 'This folder is frozen and cannot be modified.'); - } - $validated = $request->validate([ - 'prefix' => ['required', 'string', 'max:100'], - 'start_number' => ['nullable', 'integer', 'min:0'], + 'ids' => ['required', 'array', 'min:1'], + 'ids.*' => ['integer', 'exists:resources,id'], + 'admin_note' => ['nullable', 'string', 'max:500'], ]); - $rawPrefix = trim($validated['prefix']); - $cleanPrefix = rtrim($rawPrefix, ' -'); - $startNumber = (int) ($validated['start_number'] ?? 1); + $resources = Resource::whereIn('id', $validated['ids']) + ->where('status', '!=', 'rejected') + ->with('user') + ->get(); + + $adminNote = $validated['admin_note'] ?? null; + + DB::transaction(function () use ($resources, $adminNote) { + foreach ($resources as $res) { + $res->update([ + 'status' => 'rejected', + 'admin_note' => $adminNote, + 'reviewed_by' => Auth::id(), + 'reviewed_at' => now(), + ]); + + if ($res->user) { + ResourceModerationNotification::sendTo($res->user, $res, 'rejected', $adminNote); + } + } + }); - $resources = $node->resources()->orderBy('id')->get(); + $count = $resources->count(); + $message = $count === 1 + ? 'Resource rejected.' + : "{$count} resources rejected."; - DB::transaction(function () use ($resources, $cleanPrefix, $startNumber) { - foreach ($resources as $index => $resource) { - $number = str_pad((string) ($startNumber + $index), 2, '0', STR_PAD_LEFT); - $title = $cleanPrefix !== '' ? "{$cleanPrefix} - {$number}" : $number; - $resource->update(['title' => $title]); + return back()->with('success', $message); + } + + public function destroy(Resource $resource) + { + // Clean up stored items in S3/R2 + foreach ($resource->items as $item) { + $source = is_array($item) ? ($item['source'] ?? '') : ($item->source ?? ''); + if ($source && ! str_starts_with($source, 'http://') && ! str_starts_with($source, 'https://')) { + Storage::disk('s3')->delete($source); } - }); + } + + $resource->delete(); - return back()->with('success', "Renamed {$resources->count()} resources successfully."); + return redirect()->back()->with('success', 'Resource deleted successfully.'); } } diff --git a/app/Http/Controllers/Admin/ResourceModerationController.php b/app/Http/Controllers/Admin/ResourceModerationController.php deleted file mode 100644 index 898d2c78..00000000 --- a/app/Http/Controllers/Admin/ResourceModerationController.php +++ /dev/null @@ -1,191 +0,0 @@ -query('status', 'pending'); - - $query = ResourceChangeRequest::with([ - 'user:id,name,username,image_path', - 'resource', - 'node.subject', - 'reviewer:id,name,username', - ]); - - if (in_array($status, ['pending', 'approved', 'rejected'])) { - $query->where('status', $status); - } - - $requests = $query->latest() - ->simplePaginate(15) - ->withQueryString(); - - $requests->getCollection()->each(function ($req) { - $req->node?->append('breadcrumb'); - }); - - $counts = [ - 'pending' => ResourceChangeRequest::where('status', 'pending')->count(), - 'approved' => ResourceChangeRequest::where('status', 'approved')->count(), - 'rejected' => ResourceChangeRequest::where('status', 'rejected')->count(), - ]; - - return Inertia::render('admin/moderation/Resources', [ - 'requests' => $requests, - 'counts' => $counts, - 'filters' => [ - 'status' => $status, - ], - ]); - } - - public function approve(Request $request) - { - $validated = $request->validate([ - 'ids' => ['required', 'array', 'min:1'], - 'ids.*' => ['integer', 'exists:resource_change_requests,id'], - ]); - - $changeRequests = ResourceChangeRequest::whereIn('id', $validated['ids']) - ->where('status', 'pending') - ->with(['resource', 'user', 'node.subject']) - ->get(); - - if ($changeRequests->isEmpty()) { - return back()->with('error', 'Selected requests have already been reviewed.'); - } - - $filesToDelete = []; - - DB::transaction(function () use ($changeRequests, &$filesToDelete) { - $reviewerId = Auth::id(); - $now = now(); - - foreach ($changeRequests as $changeRequest) { - if ($changeRequest->action_type === 'create') { - $payload = $changeRequest->payload ?? []; - $payload['node_id'] = $changeRequest->node_id; - $payload['user_id'] = $changeRequest->user_id; - - $resource = Resource::create($payload); - $changeRequest->resource_id = $resource->id; - } elseif ($changeRequest->action_type === 'update') { - $resource = $changeRequest->resource; - - if ($resource) { - $newFilePath = $changeRequest->payload['file_path'] ?? null; - if ($newFilePath && $resource->file_path && $newFilePath !== $resource->file_path) { - $filesToDelete[] = $resource->file_path; - } - - $resource->update($changeRequest->payload); - } - } elseif ($changeRequest->action_type === 'delete') { - $resource = $changeRequest->resource; - - if ($resource) { - if ($resource->file_path) { - $filesToDelete[] = $resource->file_path; - } - $resource->delete(); - } - } - - $changeRequest->update([ - 'status' => 'approved', - 'reviewed_by' => $reviewerId, - 'reviewed_at' => $now, - ]); - } - }); - - foreach ($filesToDelete as $filePath) { - Storage::delete($filePath); - } - - $changeRequests->groupBy('user_id')->each(function ($userRequests) { - $user = $userRequests->first()->user; - if ($user) { - $user->notify(new ResourceModerationNotification( - $userRequests->first(), - 'approved', - null, - $userRequests->count() - )); - } - }); - - $count = $changeRequests->count(); - $message = $count === 1 - ? 'Resource request approved successfully.' - : "{$count} resource requests approved successfully."; - - return back()->with('success', $message); - } - - public function reject(Request $request) - { - $validated = $request->validate([ - 'ids' => ['required', 'array', 'min:1'], - 'ids.*' => ['integer', 'exists:resource_change_requests,id'], - 'rejection_reason' => ['nullable', 'string', 'max:500'], - ]); - - $changeRequests = ResourceChangeRequest::whereIn('id', $validated['ids']) - ->where('status', 'pending') - ->with(['resource', 'user', 'node.subject']) - ->get(); - - if ($changeRequests->isEmpty()) { - return back()->with('error', 'Selected requests have already been reviewed.'); - } - - $reason = $validated['rejection_reason'] ?? null; - - DB::transaction(function () use ($changeRequests, $reason) { - $reviewerId = Auth::id(); - $now = now(); - - foreach ($changeRequests as $item) { - $item->update([ - 'status' => 'rejected', - 'rejection_reason' => $reason, - 'reviewed_by' => $reviewerId, - 'reviewed_at' => $now, - ]); - } - }); - - $changeRequests->groupBy('user_id')->each(function ($userRequests) use ($reason) { - $user = $userRequests->first()->user; - if ($user) { - $user->notify(new ResourceModerationNotification( - $userRequests->first(), - 'rejected', - $reason, - $userRequests->count() - )); - } - }); - - $count = $changeRequests->count(); - $message = $count === 1 - ? 'Resource change request rejected.' - : "{$count} resource requests rejected."; - - return back()->with('success', $message); - } -} diff --git a/app/Http/Controllers/ForumController.php b/app/Http/Controllers/ForumController.php index 9b5ccba7..d7e2d06d 100644 --- a/app/Http/Controllers/ForumController.php +++ b/app/Http/Controllers/ForumController.php @@ -151,7 +151,8 @@ public function show(Request $request, ForumPost $post): Response ->where('voteable_id', $post->id) ->where('value', 1) ->with('user:id,name,username,image_path,institution,is_verified') - ->latest() + ->latest('id') + ->take(20) ->get() ->pluck('user') ->filter() diff --git a/app/Http/Controllers/NodeController.php b/app/Http/Controllers/NodeController.php index f5e5bea6..1598eb71 100644 --- a/app/Http/Controllers/NodeController.php +++ b/app/Http/Controllers/NodeController.php @@ -4,8 +4,6 @@ use App\Models\Node; use App\Models\Subject; -use App\Notifications\NodeVoteNotification; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Inertia\Inertia; @@ -38,30 +36,41 @@ public function show(Subject $subject, $path) $nodes = Cache::remember("node_children_{$node->id}", now()->addDay(), function () use ($node) { return Node::where('parent_id', $node->id) - ->withCount(['children', 'resources', 'upvotes', 'downvotes']) - ->orderByRaw('(upvotes_count - downvotes_count) DESC') + ->withCount(['children', 'resources' => function ($q) { + $q->where('status', 'approved'); + }]) ->orderBy('sort_order') + ->orderBy('name') ->get(['id', 'name', 'slug'])->toArray(); }); - $resources = Cache::remember("node_resources_{$node->id}", now()->addDay(), function () use ($node) { - return $node->resources()->get()->toArray(); - }); - - $upvotesCount = $node->upvotes()->count(); - $downvotesCount = $node->downvotes()->count(); - $userVote = auth()->check() - ? $node->votes()->where('user_id', auth()->id())->value('type') - : null; - - $upvoters = $node->upvotes() - ->with('user:id,name,username,image_path,institution,is_verified') - ->latest('id') - ->limit(50) - ->get() - ->pluck('user') - ->filter() - ->values(); + $resources = []; + + if (empty($nodes)) { + $resources = Cache::remember("node_resources_{$node->id}", now()->addDay(), function () use ($node) { + return $node->resources() + ->where('status', 'approved') + ->with('user:id,name,username') + ->orderByDesc('vote_score') + ->latest('id') + ->get() + ->toArray(); + }); + + if ($userId = auth()->id()) { + $unapproved = $node->resources() + ->where('user_id', $userId) + ->whereIn('status', ['pending', 'rejected']) + ->with('user:id,name,username') + ->latest('id') + ->get() + ->toArray(); + + if (! empty($unapproved)) { + $resources = array_merge($unapproved, $resources); + } + } + } return Inertia::render('Node', [ 'subject' => $subject, @@ -74,44 +83,6 @@ public function show(Subject $subject, $path) 'nodes' => $nodes, 'breadcrumb' => $node->breadcrumb(), 'resources' => $resources, - 'upvotesCount' => $upvotesCount, - 'downvotesCount' => $downvotesCount, - 'userVote' => $userVote, - 'upvoters' => $upvoters, ]); } - - public function vote(Request $request, Node $node) - { - $validated = $request->validate([ - 'type' => ['required', 'in:up,down'], - ]); - - $user = auth()->user(); - $existing = $node->votes()->where('user_id', $user->id)->first(); - $isFirstTimeUpvote = false; - - if ($existing) { - if ($existing->type === $validated['type']) { - $existing->delete(); - } else { - $existing->update(['type' => $validated['type']]); - } - } else { - $node->votes()->create([ - 'user_id' => $user->id, - 'type' => $validated['type'], - ]); - - if ($validated['type'] === 'up') { - $isFirstTimeUpvote = true; - } - } - - if ($isFirstTimeUpvote && $node->user_id && $node->user_id !== $user->id) { - NodeVoteNotification::sendTo($node->user, $node, $user); - } - - return back(); - } } diff --git a/app/Http/Controllers/ResourceController.php b/app/Http/Controllers/ResourceController.php index 98f0f460..da0c1991 100644 --- a/app/Http/Controllers/ResourceController.php +++ b/app/Http/Controllers/ResourceController.php @@ -2,17 +2,19 @@ namespace App\Http\Controllers; -use App\Http\Requests\Resource\BulkImageStoreRequest; -use App\Http\Requests\Resource\BulkVideoStoreRequest; use App\Http\Requests\Resource\StoreResourceRequest; -use App\Models\Node; +use App\Http\Requests\Resource\UpdateResourceRequest; use App\Models\Resource; -use App\Models\ResourceChangeRequest; -use App\Models\ResourceCompletion; +use App\Models\ResourceVote; +use App\Notifications\ResourceVoteNotification; +use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Str; use Illuminate\Validation\ValidationException; use Inertia\Inertia; @@ -20,78 +22,140 @@ class ResourceController extends Controller { public function show($id) { - $data = Cache::rememberForever("resource_{$id}", function () use ($id) { - $resource = Resource::with(['user', 'node.subject'])->findOrFail($id); - - $previousResourceId = Resource::where('node_id', $resource->node_id) - ->where('id', '<', $resource->id) - ->orderByDesc('id') - ->value('id'); - - $nextResourceId = Resource::where('node_id', $resource->node_id) - ->where('id', '>', $resource->id) - ->orderBy('id') - ->value('id'); - - return [ - 'resource' => $resource->toArray(), - 'subject' => $resource->node?->subject?->toArray(), - 'previousResourceId' => $previousResourceId, - 'nextResourceId' => $nextResourceId, - ]; - }); + $resource = Resource::with(['user:id,name,username,image_path', 'node.subject'])->findOrFail($id); + + $user = auth()->user(); + $isModerator = $user?->can('moderate resources'); + $isOwner = $user && $user->id === $resource->user_id; + + if ($resource->status !== 'approved' && ! $isModerator && ! $isOwner) { + abort(404); + } - $isCompleted = auth()->check() - ? ResourceCompletion::where('resource_id', $id)->where('user_id', auth()->id())->exists() - : false; + $node = $resource->node; - $completionsCount = ResourceCompletion::where('resource_id', $id)->count(); + $userVote = auth()->check() + ? ResourceVote::where('resource_id', $id)->where('user_id', auth()->id())->value('value') + : null; - $completers = ResourceCompletion::where('resource_id', $id) - ->with(['user:id,name,username,image_path,institution,is_verified']) - ->latest() - ->take(10) + $upvoters = ResourceVote::where('resource_id', $id) + ->where('value', 1) + ->with('user:id,name,username,image_path,institution,is_verified') + ->latest('id') + ->take(20) ->get() ->pluck('user') ->filter() ->values(); - $node = Node::find($data['resource']['node_id']); - - return Inertia::render('Resource', array_merge($data, [ + return Inertia::render('Resource', [ + 'resource' => $resource->toArray(), + 'subject' => $resource->node?->subject?->toArray(), 'breadcrumb' => $node ? $node->breadcrumb() : [], - 'isCompleted' => $isCompleted, - 'completionsCount' => $completionsCount, - 'completers' => $completers, - ])); + 'userVote' => $userVote, + 'upvoters' => $upvoters, + 'can_moderate' => (bool) $isModerator, + 'is_owner' => (bool) $isOwner, + ]); } - public function toggleComplete(Resource $resource) + public function vote(Request $request, Resource $resource) { $user = auth()->user(); - $existing = $resource->completions()->where('user_id', $user->id)->first(); + if ($user && $user->isBanned()) { + $bannedUntilFormatted = $user->banned_until->diffForHumans(); + + if ($request->wantsJson()) { + return response()->json([ + 'error' => "You are temporarily suspended from community participation until {$user->banned_until->toDateTimeString()} ({$bannedUntilFormatted}).", + ], 403); + } - if ($existing) { - $existing->delete(); - } else { - $resource->completions()->create(['user_id' => $user->id]); + return back()->with('error', "You are temporarily suspended from community participation until {$user->banned_until->toDateTimeString()} ({$bannedUntilFormatted})."); + } + + abort_if($resource->status !== 'approved', 404); + + $validated = $request->validate([ + 'value' => ['required', 'in:1,-1'], + ]); + + $value = (int) $validated['value']; + $userId = auth()->id(); + $isFirstTimeUpvote = false; + + DB::transaction(function () use ($resource, $userId, $value, &$isFirstTimeUpvote) { + $lockedResource = Resource::where('id', $resource->id)->lockForUpdate()->first(); + if (! $lockedResource) { + return; + } + + $existing = ResourceVote::where('resource_id', $lockedResource->id) + ->where('user_id', $userId) + ->lockForUpdate() + ->first(); + + if ($existing) { + if ($existing->value === $value) { + $existing->delete(); + } else { + $existing->update(['value' => $value]); + } + } else { + ResourceVote::create([ + 'resource_id' => $lockedResource->id, + 'user_id' => $userId, + 'value' => $value, + ]); + + if ($value === 1) { + $isFirstTimeUpvote = true; + } + } + + $upvotes = (int) ResourceVote::where('resource_id', $lockedResource->id)->where('value', 1)->count(); + $downvotes = (int) ResourceVote::where('resource_id', $lockedResource->id)->where('value', -1)->count(); + + $lockedResource->update([ + 'upvotes_count' => $upvotes, + 'downvotes_count' => $downvotes, + 'vote_score' => $upvotes - $downvotes, + ]); + }); + + if ($isFirstTimeUpvote && $resource->user_id && $resource->user_id !== $userId) { + $resource->loadMissing('user'); + if ($resource->user) { + ResourceVoteNotification::sendTo($resource->user, $resource, $user); + } + } + + Cache::forget("resource_{$resource->id}"); + Cache::forget("node_resources_{$resource->node_id}"); + + if ($request->wantsJson()) { + $refreshed = $resource->fresh(); + $currentUserVote = ResourceVote::where('resource_id', $resource->id) + ->where('user_id', $userId) + ->value('value'); + + return response()->json([ + 'success' => true, + 'vote_score' => $refreshed->vote_score, + 'upvotes_count' => $refreshed->upvotes_count, + 'downvotes_count' => $refreshed->downvotes_count, + 'user_vote' => $currentUserVote, + ]); } return back(); } - /** - * Determine maximum allowed pending submissions for the user. - * Verified users: 100, Unverified users: 30. - */ public function getMaxPendingSubmissions(): int { - return Auth::user()?->is_verified ? 100 : 30; + return Auth::user()?->is_verified ? 50 : 20; } - /** - * Check if user is eligible to submit (account age) and within pending change requests quota. - */ public function ensureCanSubmit(int $incomingCount = 1): void { $user = Auth::user(); @@ -106,16 +170,10 @@ public function ensureCanSubmit(int $incomingCount = 1): void ]); } - if ($user?->created_at && $user->created_at->diffInHours(now()) < 24) { - throw ValidationException::withMessages([ - 'account_age' => 'আপনার অ্যাকাউন্টটি নতুন। স্প্যাম রোধে অ্যাকাউন্ট তৈরির ২৪ ঘণ্টা পর রিসোর্স আপলোড করা যাবে।', - ]); - } - $userId = Auth::id(); $maxLimit = $this->getMaxPendingSubmissions(); - $currentPending = ResourceChangeRequest::where('user_id', $userId) + $currentPending = Resource::where('user_id', $userId) ->where('status', 'pending') ->count(); @@ -126,100 +184,145 @@ public function ensureCanSubmit(int $incomingCount = 1): void } } - public function store(StoreResourceRequest $request) + public function generateUploadUrl(Request $request) { - $validated = $request->validated(); - $isModerator = $request->user()->can('moderate resources'); - - if (! $isModerator) { + try { $this->ensureCanSubmit(1); + } catch (ValidationException $e) { + return response()->json([ + 'message' => collect($e->errors())->flatten()->first(), + 'errors' => $e->errors(), + ], 422); } - if ($request->hasFile('file')) { - $validated['file_path'] = $request->file('file')->store("resources/{$validated['resource_type']}s"); + $validated = $request->validate([ + 'files' => ['required', 'array', 'min:1', 'max:50'], + 'files.*.content_type' => ['required', 'string', 'in:image/jpeg,image/png,image/webp'], + 'files.*.size' => ['required', 'integer', 'min:1', 'max:5242880'], + ]); + + $userId = auth()->id(); + $results = []; + + foreach ($validated['files'] as $fileData) { + $extension = match ($fileData['content_type']) { + 'image/jpeg' => 'jpg', + 'image/png' => 'png', + 'image/webp' => 'webp', + }; + + $key = "resources/notes/{$userId}/".(string) Str::uuid().'.'.$extension; + $signed = Storage::disk('s3')->temporaryUploadUrl( + $key, + now()->addMinutes(15), + ['ContentType' => $fileData['content_type']] + ); + + $results[] = [ + 'key' => $key, + 'upload_url' => is_array($signed) ? $signed['url'] : $signed, + ]; } - if ($isModerator) { - $validated['user_id'] = Auth::id(); - Resource::create($validated); + return response()->json(['urls' => $results]); + } - return back()->with('success', 'Resource created successfully.'); + public function fetchPlaylist(Request $request) + { + $validator = Validator::make($request->all(), [ + 'playlist_url' => ['required', 'url'], + ]); + + if ($validator->fails()) { + return response()->json([ + 'message' => 'সঠিক ইউটিউব প্লেলিস্টের লিংক দিন।', + 'errors' => $validator->errors(), + ], 422); } - ResourceChangeRequest::recordCreate( - Auth::id(), - (int) $validated['node_id'], - $validated - ); + $items = $this->resolveYoutubePlaylist($validator->validated()['playlist_url']); + + if (empty($items)) { + return response()->json([ + 'error' => 'Unable to fetch videos. Please provide a valid, public YouTube playlist URL.', + ], 422); + } - return redirect()->route('submissions.index')->with('success', 'Resource submitted for moderation.'); + return response()->json(['items' => $items]); } - public function storeBulkImages(BulkImageStoreRequest $request) + public function store(StoreResourceRequest $request) { + $this->ensureCanSubmit(1); + $validated = $request->validated(); - $filesCount = count($request->file('files') ?? []); $isModerator = $request->user()->can('moderate resources'); + $status = $isModerator ? 'approved' : 'pending'; + + Resource::create([ + 'node_id' => $validated['node_id'], + 'user_id' => Auth::id(), + 'resource_type' => $validated['resource_type'], + 'title' => $validated['title'], + 'description' => $validated['description'] ?? null, + 'thumbnail' => $this->computeThumbnailFromItems($validated['items']), + 'items' => $validated['items'], + 'status' => $status, + 'reviewed_by' => $isModerator ? Auth::id() : null, + 'reviewed_at' => $isModerator ? now() : null, + ]); + + $typeName = ucfirst($validated['resource_type']); + $message = $isModerator + ? "{$typeName} created and published successfully." + : "{$typeName} submitted successfully and is awaiting review."; + + return back()->with('success', $message); + } - if (! $isModerator) { - $this->ensureCanSubmit($filesCount); + public function update(UpdateResourceRequest $request, Resource $resource) + { + $user = Auth::user(); + if ($user?->isBanned()) { + $bannedUntilFormatted = $user->banned_until->diffForHumans(); + throw ValidationException::withMessages([ + 'banned' => "আপনি সাময়িকভাবে ব্যান রয়েছেন ({$bannedUntilFormatted} পর্যন্ত)। এই সময়ে কোনো রিসোর্স পরিবর্তন করা যাবে না।", + ]); } - $userId = Auth::id(); - $nodeId = (int) $validated['node_id']; - - DB::transaction(function () use ($request, $validated, $userId, $nodeId, $isModerator) { - $content = $validated['content'] ?? null; + $validated = $request->validated(); - foreach ($request->file('files') as $index => $file) { - $filePath = $file->store('resources/images'); - $title = $validated['custom_titles'][$index]; + $updateData = [ + 'title' => $validated['title'], + 'description' => $validated['description'] ?? null, + 'resource_type' => $validated['resource_type'], + 'thumbnail' => $this->computeThumbnailFromItems($validated['items']), + 'items' => $validated['items'], + ]; + + // If an approved resource is edited by someone without 'edit resources', return it to pending for re-review + $canEditDirectly = $user && $user->can('edit resources'); + if (! $canEditDirectly && $resource->status === 'approved') { + $updateData['status'] = 'pending'; + $updateData['reviewed_by'] = null; + $updateData['reviewed_at'] = null; + } - if ($isModerator) { - Resource::create([ - 'user_id' => $userId, - 'node_id' => $nodeId, - 'title' => $title, - 'content' => $content, - 'resource_type' => 'image', - 'file_path' => $filePath, - ]); - } else { - ResourceChangeRequest::recordCreate($userId, $nodeId, [ - 'title' => $title, - 'content' => $content, - 'resource_type' => 'image', - 'file_path' => $filePath, - ]); - } - } - }); + $resource->update($updateData); - if ($isModerator) { - return back()->with('success', 'Images uploaded successfully.'); - } + Cache::forget("resource_{$resource->id}"); + Cache::forget("node_resources_{$resource->node_id}"); - return redirect()->route('submissions.index')->with('success', 'Images submitted for moderation.'); + return back()->with('success', 'রিসোর্স সফলভাবে আপডেট করা হয়েছে।'); } - public function storeBulkVideos(BulkVideoStoreRequest $request) + private function resolveYoutubePlaylist(string $url): array { - $validated = $request->validated(); - $isModerator = $request->user()->can('moderate resources'); - - if (! $isModerator) { - $this->ensureCanSubmit(1); - } - - $playlistUrl = $validated['playlist_url']; - - // Extract playlist ID - parse_str(parse_url($playlistUrl, PHP_URL_QUERY), $query); - + parse_str(parse_url($url, PHP_URL_QUERY) ?? '', $query); $playlistId = $query['list'] ?? null; - if (! $playlistId) { - return back()->with('error', 'Invalid Youtube URL'); + if (! $playlistId || ! config('services.youtube.key')) { + return []; } $videos = []; @@ -235,82 +338,49 @@ public function storeBulkVideos(BulkVideoStoreRequest $request) ]); if (! $response->successful()) { - return back()->with('error', 'Unable to fetch youtube url'); + break; } $data = $response->json(); + foreach ($data['items'] ?? [] as $item) { + $videoId = $item['snippet']['resourceId']['videoId'] ?? null; + $title = $item['snippet']['title'] ?? null; - foreach ($data['items'] as $item) { - $videos[] = [ - 'title' => $item['snippet']['title'], - 'video_id' => $item['snippet']['resourceId']['videoId'], - 'position' => $item['snippet']['position'], - ]; - } - - if (! $isModerator && count($videos) >= $this->getMaxPendingSubmissions()) { - break; + if ($videoId && $title !== 'Private video' && $title !== 'Deleted video') { + $videos[] = [ + 'format' => 'video', + 'title' => $title, + 'source' => "https://www.youtube.com/watch?v={$videoId}", + ]; + } } $pageToken = $data['nextPageToken'] ?? null; - } while ($pageToken); + } while ($pageToken && count($videos) < 100); - if (! empty($validated['is_reversed'])) { - $videos = array_reverse($videos); - } + return $videos; + } - // Apply naming strategy - foreach ($videos as $index => &$video) { - if ($validated['naming_strategy'] === 'youtube') { - $video['title'] = $video['title']; - } else { - $number = str_pad( - ($validated['start_number'] ?? 1) + $index, - 2, - '0', - STR_PAD_LEFT - ); - - $prefix = trim($validated['naming_prefix'] ?? ''); - $video['title'] = $prefix !== '' ? "{$prefix} - {$number}" : $number; - } + private function computeThumbnailFromItems(array $items): ?string + { + $first = $items[0] ?? null; + if (! $first) { + return null; } - $userId = Auth::id(); - $nodeId = (int) $validated['node_id']; - $videosCount = count($videos); - $isModerator = $request->user()->can('moderate resources'); + $format = $first['format'] ?? null; + $source = $first['source'] ?? null; - if (! $isModerator) { - $this->ensureCanSubmit($videosCount); + if ($format === 'image' && $source) { + return $source; } - DB::transaction(function () use ($videos, $userId, $nodeId, $isModerator) { - foreach ($videos as $video) { - $finalUrl = "https://www.youtube.com/watch?v={$video['video_id']}"; - - if ($isModerator) { - Resource::create([ - 'user_id' => $userId, - 'node_id' => $nodeId, - 'title' => $video['title'], - 'resource_type' => 'video', - 'external_url' => $finalUrl, - ]); - } else { - ResourceChangeRequest::recordCreate($userId, $nodeId, [ - 'title' => $video['title'], - 'resource_type' => 'video', - 'external_url' => $finalUrl, - ]); - } + if ($format === 'video' && $source) { + if (preg_match('/(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=|shorts\/))([\w-]{11})/', $source, $matches)) { + return "https://img.youtube.com/vi/{$matches[1]}/hqdefault.jpg"; } - }); - - if ($isModerator) { - return back()->with('success', 'YouTube playlist imported successfully.'); } - return redirect()->route('submissions.index')->with('success', 'YouTube playlist imported and submitted for moderation.'); + return null; } } diff --git a/app/Http/Controllers/SubjectController.php b/app/Http/Controllers/SubjectController.php index a4a1cd84..8e38fdbe 100644 --- a/app/Http/Controllers/SubjectController.php +++ b/app/Http/Controllers/SubjectController.php @@ -7,6 +7,7 @@ use App\Models\ForumVote; use App\Models\Node; use App\Models\Notice; +use App\Models\Resource; use App\Models\Subject; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; @@ -82,6 +83,26 @@ public function index(Request $request, $course) } } + $trendingNotes = Cache::remember("home_page_trending_notes_{$course}", now()->addMinutes(2), function () use ($course) { + return Resource::query() + ->where('status', 'approved') + ->whereNotNull('items') + ->whereJsonLength('items', '>', 0) + ->whereHas('node.subject', function ($query) use ($course) { + $query->where('course', $course); + }) + ->with([ + 'user:id,name,username,image_path,institution,is_verified', + 'node:id,name,slug,subject_id', + 'node.subject:id,name,course,slug', + ]) + ->orderByDesc('vote_score') + ->latest('id') + ->limit(4) + ->get() + ->toArray(); + }); + $notice = Cache::rememberForever('home_page_notice', function () { return Notice::activeForDisplay()?->toArray(); }); @@ -91,6 +112,7 @@ public function index(Request $request, $course) 'current_group' => $group, 'featured_blogs' => $featuredBlogs, 'trending_posts' => $trendingPosts, + 'trending_notes' => $trendingNotes, 'notice' => $notice, ]); } @@ -104,7 +126,9 @@ public function show(Subject $subject) $nodes = Cache::rememberForever("subject_page_{$subject->id}", function () use ($subject) { return Node::where('subject_id', $subject->id) ->whereNull('parent_id') - ->withCount(['children', 'resources', 'upvotes', 'downvotes']) + ->withCount(['children', 'resources' => function ($q) { + $q->where('status', 'approved'); + }]) ->orderBy('sort_order') ->get(['id', 'name', 'slug'])->toArray(); }); @@ -115,10 +139,6 @@ public function show(Subject $subject) 'nodes' => $nodes, 'breadcrumb' => [], 'resources' => [], - 'upvotesCount' => 0, - 'downvotesCount' => 0, - 'userVote' => null, - 'upvoters' => [], ]); } } diff --git a/app/Http/Controllers/SubmissionController.php b/app/Http/Controllers/SubmissionController.php index 59517998..34b674ed 100644 --- a/app/Http/Controllers/SubmissionController.php +++ b/app/Http/Controllers/SubmissionController.php @@ -2,7 +2,7 @@ namespace App\Http\Controllers; -use App\Models\ResourceChangeRequest; +use App\Models\Resource; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Inertia\Inertia; @@ -13,8 +13,8 @@ public function index(Request $request) { $user = Auth::user(); - $maxLimit = $user->is_verified ? 100 : 30; - $counts = ResourceChangeRequest::where('user_id', $user->id) + $maxLimit = $user->is_verified ? 50 : 20; + $counts = Resource::where('user_id', $user->id) ->selectRaw('status, count(*) as total') ->groupBy('status') ->pluck('total', 'status'); @@ -25,8 +25,8 @@ public function index(Request $request) $totalCount = (int) $counts->sum(); $status = $request->query('status'); - $query = ResourceChangeRequest::where('user_id', $user->id) - ->with(['resource', 'node.subject']) + $query = Resource::where('user_id', $user->id) + ->with(['node.subject']) ->latest(); if ($status && in_array($status, ['pending', 'approved', 'rejected'])) { diff --git a/app/Http/Controllers/UserProfileController.php b/app/Http/Controllers/UserProfileController.php index e219951c..f7419a8c 100644 --- a/app/Http/Controllers/UserProfileController.php +++ b/app/Http/Controllers/UserProfileController.php @@ -4,12 +4,9 @@ use App\Http\Controllers\Admin\PeerSettingsController; use App\Models\AppSetting; -use App\Models\BlogComment; -use App\Models\BlogReaction; use App\Models\DailyStudyLog; use App\Models\ForumAnswer; use App\Models\ForumPost; -use App\Models\Node; use App\Models\NodeCompletion; use App\Models\Resource; use App\Models\Subject; @@ -148,120 +145,13 @@ public function show(string $username) ->take(5) ->get(); - // Recent Community Activities - $recentForumPosts = ForumPost::where('user_id', $user->id) - ->approved() - ->latest('id') - ->take(3) - ->get() - ->map(fn ($post) => [ - 'type' => 'forum_post', - 'title' => $post->title, - 'subtitle' => strtoupper($post->curriculum).' Forum Question', - 'url' => "/forum/questions/{$post->slug}", - 'created_at' => $post->created_at?->diffForHumans(), - 'timestamp' => $post->created_at?->timestamp ?? 0, - ]); - - $recentForumAnswers = ForumAnswer::where('user_id', $user->id) - ->whereHas('post', fn ($q) => $q->approved()) - ->with('post:id,title,slug') - ->latest('id') - ->take(3) - ->get() - ->map(fn ($ans) => [ - 'type' => 'forum_answer', - 'title' => $ans->post?->title ?? 'Forum Question', - 'content' => $ans->body, - 'url' => $ans->post ? "/forum/questions/{$ans->post->slug}" : null, - 'created_at' => $ans->created_at?->diffForHumans(), - 'timestamp' => $ans->created_at?->timestamp ?? 0, - ]) - ->filter(fn ($item) => $item['url'] !== null); - - $recentFolders = Node::where('user_id', $user->id) - ->with([ - 'subject:id,name,slug', - 'parent:id,name,slug', - 'parent.parent:id,name,slug', - ]) + $notes = Resource::where('user_id', $user->id) + ->when(! $isOwner, fn ($q) => $q->where('status', 'approved')) + ->with(['node:id,name,slug,subject_id', 'node.subject:id,name,course,slug']) + ->orderByDesc('vote_score') ->latest('id') - ->take(3) - ->get() - ->map(function ($node) { - $url = $this->buildNodeUrl($node); - - return [ - 'type' => 'folder', - 'title' => $node->name, - 'subtitle' => $node->subject?->name.($node->parent ? ' · '.$node->parent->name : ''), - 'url' => $url, - 'created_at' => $node->created_at?->diffForHumans(), - 'timestamp' => $node->created_at?->timestamp ?? 0, - ]; - }) - ->filter() - ->values(); - - $recentUploads = Resource::where('user_id', $user->id) - ->with(['node:id,name,subject_id', 'node.subject:id,name']) - ->latest() - ->take(3) - ->get() - ->map(fn ($item) => [ - 'type' => 'upload', - 'title' => $item->title, - 'subtitle' => $item->node?->subject?->name.' · '.$item->node?->name, - 'resource_type' => $item->resource_type, - 'url' => "/resources/{$item->id}", - 'created_at' => $item->created_at?->diffForHumans(), - 'timestamp' => $item->created_at?->timestamp ?? 0, - ]); - - $recentReactions = BlogReaction::where('user_id', $user->id) - ->with('blog:id,title,slug') - ->latest() - ->take(3) - ->get() - ->map(fn ($item) => [ - 'type' => 'reaction', - 'title' => $item->blog?->title, - 'url' => $item->blog ? "/blogs/{$item->blog->slug}" : null, - 'created_at' => $item->created_at?->diffForHumans(), - 'timestamp' => $item->created_at?->timestamp ?? 0, - ]) - ->filter(fn ($item) => $item['title'] !== null); - - $recentComments = BlogComment::where('user_id', $user->id) - ->with('blog:id,title,slug') - ->latest() - ->take(3) - ->get() - ->map(fn ($item) => [ - 'type' => 'comment', - 'title' => $item->blog?->title, - 'content' => $item->content, - 'url' => $item->blog ? "/blogs/{$item->blog->slug}" : null, - 'created_at' => $item->created_at?->diffForHumans(), - 'timestamp' => $item->created_at?->timestamp ?? 0, - ]) - ->filter(fn ($item) => $item['title'] !== null); - - $recentAppreciations = UserAppreciation::where('appreciator_id', $user->id) - ->with('user:id,name,username') - ->latest('id') - ->take(3) - ->get() - ->map(fn ($item) => [ - 'type' => 'appreciation', - 'title' => $item->user?->name, - 'username' => $item->user?->username, - 'url' => $item->user ? "/u/{$item->user->username}" : null, - 'created_at' => $item->created_at?->diffForHumans(), - 'timestamp' => $item->created_at?->timestamp ?? 0, - ]) - ->filter(fn ($item) => $item['title'] !== null) - ->values(); + ->take(8) + ->get(); $syllabusProgress = $this->getSyllabusProgress($user); @@ -278,15 +168,7 @@ public function show(string $username) 'forumPosts' => $forumPosts, 'forumAnswers' => $forumAnswers, 'blogs' => $publishedBlogs, - 'recentActivities' => [ - 'forum_posts' => $recentForumPosts->values(), - 'forum_answers' => $recentForumAnswers->values(), - 'folders' => $recentFolders->values(), - 'uploads' => $recentUploads->values(), - 'reactions' => $recentReactions->values(), - 'comments' => $recentComments->values(), - 'appreciations' => $recentAppreciations->values(), - ], + 'notes' => $notes, 'suggestedUsers' => $suggestedUsers, 'pokeData' => $pokeData, 'studyHeatmap' => DailyStudyLog::getHeatmapAndStatsForUser($user), @@ -373,22 +255,6 @@ public function toggleAppreciate(User $user) return back(); } - private function buildNodeUrl(Node $node): ?string - { - if (! $node->subject) { - return null; - } - - $slugs = []; - $curr = $node; - while ($curr) { - array_unshift($slugs, $curr->slug); - $curr = $curr->parent; - } - - return '/'.$node->subject->slug.'/'.implode('/', $slugs); - } - private function getSyllabusProgress(User $user): array { $course = $user->curriculum ?: 'hsc'; diff --git a/app/Http/Requests/Resource/BulkImageStoreRequest.php b/app/Http/Requests/Resource/BulkImageStoreRequest.php deleted file mode 100644 index f539f7ae..00000000 --- a/app/Http/Requests/Resource/BulkImageStoreRequest.php +++ /dev/null @@ -1,37 +0,0 @@ -input('node_id')); - - return ! ($node?->isEffectivelyFrozen()); - } - - /** - * Get the validation rules that apply to the request. - * - * @return array|string> - */ - public function rules(): array - { - return [ - 'node_id' => 'required|exists:nodes,id', - 'custom_titles' => 'required|array|max:20', - 'custom_titles.*' => 'required|string|max:100', - 'files' => 'required|array|min:1|max:20', - 'files.*' => 'required|image|mimes:jpg,jpeg,png,webp|max:5120', - 'content' => 'nullable|string', - ]; - } -} diff --git a/app/Http/Requests/Resource/BulkVideoStoreRequest.php b/app/Http/Requests/Resource/BulkVideoStoreRequest.php deleted file mode 100644 index dac36bdf..00000000 --- a/app/Http/Requests/Resource/BulkVideoStoreRequest.php +++ /dev/null @@ -1,46 +0,0 @@ -input('node_id')); - - return ! ($node?->isEffectivelyFrozen()); - } - - /** - * Get the validation rules that apply to the request. - * - * @return array|string> - */ - public function rules(): array - { - return [ - 'playlist_url' => ['required', 'url'], - 'naming_strategy' => ['required', 'in:youtube,serial,prefix'], - 'start_number' => [ - 'nullable', - 'integer', - 'min:1', - 'required_if:naming_strategy,serial,prefix', - ], - 'naming_prefix' => [ - 'nullable', - 'string', - 'max:255', - ], - 'is_reversed' => ['nullable', 'boolean'], - 'node_id' => ['required', 'exists:nodes,id'], - ]; - } -} diff --git a/app/Http/Requests/Resource/ResourceValidationRules.php b/app/Http/Requests/Resource/ResourceValidationRules.php new file mode 100644 index 00000000..1f4650ad --- /dev/null +++ b/app/Http/Requests/Resource/ResourceValidationRules.php @@ -0,0 +1,63 @@ + 1) { + $validator->errors()->add('items', 'একটি রিসোর্সে একাধিক ফরম্যাট (ছবি, PDF, ভিডিও) একসাথে রাখা যাবে না।'); + + return; + } + + $format = $formats[0] ?? null; + + if ($format === 'image' && count($items) > 50) { + $validator->errors()->add('items', 'একটি রিসোর্সে সর্বোচ্চ ৫০টি ছবি যুক্ত করা যাবে।'); + + return; + } elseif ($format === 'video' && count($items) > 50) { + $validator->errors()->add('items', 'একটি প্লেলিস্ট/রিসোর্সে সর্বোচ্চ ৫০টি ভিডিও যুক্ত করা যাবে।'); + + return; + } elseif ($format === 'pdf' && count($items) > 5) { + $validator->errors()->add('items', 'একটি রিসোর্সে সর্বোচ্চ ৫টি PDF ডকুমেন্ট যুক্ত করা যাবে।'); + + return; + } + + if ($resourceType === 'video' && $format !== 'video') { + $validator->errors()->add('items', 'ভিডিও রিসোর্সে শুধুমাত্র ভিডিও লিংক থাকতে পারে।'); + } elseif ($resourceType !== 'video' && $format === 'video') { + $validator->errors()->add('items', 'নোট বা ডকুমেন্টে ভিডিও লিংক যুক্ত করা যাবে না।'); + } + + foreach ($items as $index => $item) { + $itemFormat = $item['format'] ?? null; + $source = $item['source'] ?? ''; + + if (in_array($itemFormat, ['pdf', 'video'], true)) { + if (! filter_var($source, FILTER_VALIDATE_URL) || (! str_starts_with($source, 'http://') && ! str_starts_with($source, 'https://'))) { + $validator->errors()->add("items.{$index}.source", 'PDF এবং ভিডিওর জন্য সঠিক URL লিঙ্ক প্রদান করতে হবে।'); + } + } elseif ($itemFormat === 'image') { + $isAllowedUpload = str_starts_with($source, 'resources/notes/') + && preg_match('#^resources/notes/([0-9a-zA-Z_-]+/)*[0-9a-zA-Z_.-]+\.(jpg|jpeg|png|webp)$#i', $source); + $isExternalUrl = (str_starts_with($source, 'http://') || str_starts_with($source, 'https://')) && filter_var($source, FILTER_VALIDATE_URL); + + if (! $isAllowedUpload && ! $isExternalUrl) { + $validator->errors()->add("items.{$index}.source", 'ছবির জন্য একটি সঠিক আপলোড কী বা লিঙ্ক প্রদান করতে হবে।'); + } + } + } + } +} diff --git a/app/Http/Requests/Resource/StoreResourceRequest.php b/app/Http/Requests/Resource/StoreResourceRequest.php index d35c4705..e0bade19 100644 --- a/app/Http/Requests/Resource/StoreResourceRequest.php +++ b/app/Http/Requests/Resource/StoreResourceRequest.php @@ -3,15 +3,10 @@ namespace App\Http\Requests\Resource; use App\Models\Node; -use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Validation\Rule; class StoreResourceRequest extends FormRequest { - /** - * Determine if the user is authorized to make this request. - */ public function authorize(): bool { $node = Node::find($this->input('node_id')); @@ -19,34 +14,25 @@ public function authorize(): bool return ! ($node?->isEffectivelyFrozen()); } - /** - * Get the validation rules that apply to the request. - * - * @return array|string> - */ public function rules(): array { return [ 'node_id' => ['required', 'integer', 'exists:nodes,id'], - 'resource_type' => ['required', 'in:note,pdf,image,video'], - 'title' => ['required', 'string', 'max:100', 'min:2'], - 'content' => ['nullable', 'string'], - - 'file' => [ - 'nullable', - 'file', - 'max:5120', - 'mimes:jpg,jpeg,png,webp', - Rule::requiredIf($this->resource_type === 'image'), - ], - - 'external_url' => [ - 'nullable', - - 'url', - 'max:2048', - Rule::requiredIf(in_array($this->resource_type, ['pdf', 'video'])), - ], + 'resource_type' => ['required', 'string', 'in:note,practical,marked_book,other,video'], + 'title' => ['required', 'string', 'max:255'], + 'description' => ['nullable', 'string'], + 'items' => ['required', 'array', 'min:1'], + 'items.*' => ['required', 'array'], + 'items.*.format' => ['required', 'in:image,pdf,video'], + 'items.*.source' => ['required', 'string'], + 'items.*.title' => ['nullable', 'string', 'max:255'], ]; } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + ResourceValidationRules::validateItems($validator, $this->input('items', []), $this->input('resource_type')); + }); + } } diff --git a/app/Http/Requests/Resource/UpdateResourceRequest.php b/app/Http/Requests/Resource/UpdateResourceRequest.php index 1498c7ac..edad01b3 100644 --- a/app/Http/Requests/Resource/UpdateResourceRequest.php +++ b/app/Http/Requests/Resource/UpdateResourceRequest.php @@ -2,56 +2,33 @@ namespace App\Http\Requests\Resource; -use App\Models\Node; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Validation\Rule; class UpdateResourceRequest extends FormRequest { public function authorize(): bool { - $resource = $this->route('resource'); - if ($resource?->node?->isEffectivelyFrozen()) { - return false; - } - - if ($this->has('node_id') && (int) $this->input('node_id') !== (int) $resource?->node_id) { - $targetNode = Node::find($this->input('node_id')); - if ($targetNode?->isEffectivelyFrozen()) { - return false; - } - } - return true; } public function rules(): array { return [ - 'node_id' => ['required', 'integer', 'exists:nodes,id'], - 'resource_type' => ['required', 'in:note,pdf,image,video'], - 'title' => ['required', 'string', 'max:100', 'min:2'], - 'content' => ['nullable', 'string'], - - 'file' => [ - 'nullable', - 'file', - 'max:5120', - 'mimes:jpg,jpeg,png,webp', - Rule::requiredIf( - $this->resource_type === 'image' - && ! $this->route('resource')->file_path - ), - ], - - 'external_url' => [ - 'nullable', - 'url', - 'max:2048', - Rule::requiredIf( - in_array($this->resource_type, ['pdf', 'video']) - ), - ], + 'title' => ['required', 'string', 'max:255'], + 'description' => ['nullable', 'string'], + 'resource_type' => ['required', 'string', 'in:note,practical,marked_book,other,video'], + 'items' => ['required', 'array', 'min:1'], + 'items.*' => ['required', 'array'], + 'items.*.format' => ['required', 'in:image,pdf,video'], + 'items.*.source' => ['required', 'string'], + 'items.*.title' => ['nullable', 'string', 'max:255'], ]; } + + public function withValidator($validator): void + { + $validator->after(function ($validator) { + ResourceValidationRules::validateItems($validator, $this->input('items', []), $this->input('resource_type')); + }); + } } diff --git a/app/Models/Node.php b/app/Models/Node.php index 2310a684..b4ddc57b 100644 --- a/app/Models/Node.php +++ b/app/Models/Node.php @@ -30,8 +30,6 @@ protected function casts(): array 'is_frozen' => 'boolean', 'children_count' => 'integer', 'resources_count' => 'integer', - 'upvotes_count' => 'integer', - 'downvotes_count' => 'integer', ]; } @@ -107,42 +105,8 @@ public function resources() return $this->hasMany(Resource::class); } - public function votes() - { - return $this->hasMany(NodeVote::class); - } - - public function upvotes() - { - return $this->hasMany(NodeVote::class)->where('type', 'up'); - } - - public function downvotes() - { - return $this->hasMany(NodeVote::class)->where('type', 'down'); - } - public function completions() { return $this->hasMany(NodeCompletion::class); } - - public function changeRequests() - { - return $this->hasMany(ResourceChangeRequest::class); - } - - public function pendingCreateRequests() - { - return $this->hasMany(ResourceChangeRequest::class) - ->where('action_type', 'create') - ->where('status', 'pending'); - } - - public function rejectedCreateRequests() - { - return $this->hasMany(ResourceChangeRequest::class) - ->where('action_type', 'create') - ->where('status', 'rejected'); - } } diff --git a/app/Models/NodeVote.php b/app/Models/NodeVote.php deleted file mode 100644 index a385a4ee..00000000 --- a/app/Models/NodeVote.php +++ /dev/null @@ -1,28 +0,0 @@ -belongsTo(Node::class); - } - - public function user(): BelongsTo - { - return $this->belongsTo(User::class); - } -} diff --git a/app/Models/Resource.php b/app/Models/Resource.php index 4ce31cf2..8437202b 100644 --- a/app/Models/Resource.php +++ b/app/Models/Resource.php @@ -3,6 +3,9 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Prunable; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\Storage; /** @@ -10,79 +13,116 @@ */ class Resource extends Model { + use Prunable; + protected $fillable = [ 'node_id', + 'user_id', 'resource_type', 'title', - 'content', - 'file_path', - 'external_url', - 'user_id', + 'description', + 'thumbnail', + 'items', + 'status', + 'admin_note', + 'reviewed_by', + 'reviewed_at', + 'vote_score', + 'upvotes_count', + 'downvotes_count', ]; protected $appends = [ - 'file_url', + 'items_count', ]; - protected static function booted(): void + protected function casts(): array { - static::deleting(function (Resource $resource) { - if ($resource->node?->isEffectivelyFrozen()) { - abort(403, 'Cannot delete resources from a frozen folder.'); - } - }); + return [ + 'items' => 'array', + 'vote_score' => 'integer', + 'upvotes_count' => 'integer', + 'downvotes_count' => 'integer', + 'reviewed_at' => 'datetime', + ]; } - public function getFileUrlAttribute(): ?string + public function getItemsAttribute($value): array { - if ($this->external_url) { - return $this->external_url; + if (empty($value)) { + return []; } - if ($this->file_path) { - return Storage::url($this->file_path); + $items = is_array($value) ? $value : (json_decode($value, true) ?: []); + + return array_values(array_map(function ($item) { + $source = $item['source'] ?? ''; + $url = (str_starts_with($source, 'http://') || str_starts_with($source, 'https://')) + ? $source + : ($source ? Storage::url($source) : ''); + + return array_merge($item, ['url' => $url]); + }, $items)); + } + + public function getThumbnailAttribute(?string $value): ?string + { + if (! $value) { + return null; } - return null; + return str_starts_with($value, 'http://') || str_starts_with($value, 'https://') + ? $value + : Storage::url($value); + } + + public function getItemsCountAttribute(): int + { + return count($this->items); } - // - public function node() + public function node(): BelongsTo { return $this->belongsTo(Node::class); } - public function user() + public function user(): BelongsTo { return $this->belongsTo(User::class); } - public function completions() + public function reviewer(): BelongsTo + { + return $this->belongsTo(User::class, 'reviewed_by'); + } + + public function scopeApproved($query) { - return $this->hasMany(ResourceCompletion::class); + return $query->where('status', 'approved'); } - public function changeRequests() + /** + * Get the prunable model query. + * Prunes rejected resources older than 15 days. + */ + public function prunable() { - return $this->hasMany(ResourceChangeRequest::class); + return static::where('status', 'rejected') + ->where('reviewed_at', '<=', now()->subDays(15)); } - public function pendingChangeRequest() + public function votes(): HasMany { - return $this->hasOne(ResourceChangeRequest::class)->where('status', 'pending'); + return $this->hasMany(ResourceVote::class); } - public function latestRejectedChangeRequest() + public function upvotes(): HasMany { - return $this->hasOne(ResourceChangeRequest::class) - ->where('status', 'rejected') - ->latestOfMany('reviewed_at'); + return $this->hasMany(ResourceVote::class)->where('value', 1); } - public function hasPendingChangeRequest(): bool + public function downvotes(): HasMany { - return $this->relationLoaded('pendingChangeRequest') - ? $this->pendingChangeRequest !== null - : $this->pendingChangeRequest()->exists(); + return $this->hasMany(ResourceVote::class)->where('value', -1); } } diff --git a/app/Models/ResourceChangeRequest.php b/app/Models/ResourceChangeRequest.php deleted file mode 100644 index a0197db7..00000000 --- a/app/Models/ResourceChangeRequest.php +++ /dev/null @@ -1,154 +0,0 @@ -where('reviewed_at', '<=', now()->subDays(15)); - } - - /** - * Clean up staged files when the change request is pruned. - */ - public function pruning(): void - { - if ($this->status === 'rejected') { - $stagedFile = $this->payload['file_path'] ?? null; - if ($stagedFile) { - Storage::delete($stagedFile); - } - } - } - - protected $casts = [ - 'payload' => 'array', - 'reviewed_at' => 'datetime', - ]; - - protected $appends = [ - 'staged_file_url', - ]; - - public function user(): BelongsTo - { - return $this->belongsTo(User::class); - } - - public function resource(): BelongsTo - { - return $this->belongsTo(Resource::class); - } - - public function node(): BelongsTo - { - return $this->belongsTo(Node::class); - } - - public function reviewer(): BelongsTo - { - return $this->belongsTo(User::class, 'reviewed_by'); - } - - public function getStagedFileUrlAttribute(): ?string - { - $filePath = $this->payload['file_path'] ?? null; - - if ($filePath) { - return Storage::url($filePath); - } - - return null; - } - - public function scopePending($query) - { - return $query->where('status', 'pending'); - } - - /** - * Sanitize and whitelist only valid resource attributes. - */ - public static function sanitizePayload(array $data): array - { - return [ - 'node_id' => $data['node_id'] ?? null, - 'resource_type' => $data['resource_type'] ?? null, - 'title' => $data['title'] ?? null, - 'content' => $data['content'] ?? null, - 'external_url' => $data['external_url'] ?? null, - 'file_path' => $data['file_path'] ?? null, - ]; - } - - public static function recordCreate(int $userId, int $nodeId, array $data): self - { - $data['node_id'] = $nodeId; - - return self::create([ - 'user_id' => $userId, - 'node_id' => $nodeId, - 'action_type' => 'create', - 'status' => 'pending', - 'payload' => self::sanitizePayload($data), - ]); - } - - public static function recordUpdate(int $userId, Resource $resource, array $data): self - { - if (! isset($data['file_path']) && $resource->file_path) { - $data['file_path'] = $resource->file_path; - } - - $payload = array_intersect_key( - self::sanitizePayload($data), - $data - ); - - return self::create([ - 'user_id' => $userId, - 'resource_id' => $resource->id, - 'node_id' => $payload['node_id'] ?? $resource->node_id, - 'action_type' => 'update', - 'status' => 'pending', - 'payload' => $payload, - ]); - } - - public static function recordDelete(int $userId, Resource $resource): self - { - return self::create([ - 'user_id' => $userId, - 'resource_id' => $resource->id, - 'node_id' => $resource->node_id, - 'action_type' => 'delete', - 'status' => 'pending', - 'payload' => null, - ]); - } -} diff --git a/app/Models/ResourceCompletion.php b/app/Models/ResourceVote.php similarity index 63% rename from app/Models/ResourceCompletion.php rename to app/Models/ResourceVote.php index 47d784c2..c2992d6e 100644 --- a/app/Models/ResourceCompletion.php +++ b/app/Models/ResourceVote.php @@ -2,16 +2,27 @@ namespace App\Models; +use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; -class ResourceCompletion extends Model +class ResourceVote extends Model { + use HasFactory; + protected $fillable = [ 'resource_id', 'user_id', + 'value', ]; + protected function casts(): array + { + return [ + 'value' => 'integer', + ]; + } + public function resource(): BelongsTo { return $this->belongsTo(Resource::class); diff --git a/app/Models/User.php b/app/Models/User.php index 99e9c875..d76d4835 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -160,24 +160,14 @@ public function blogs(): HasMany return $this->hasmany(Blog::class); } - public function resourceCompletions(): HasMany - { - return $this->hasMany(ResourceCompletion::class); - } - - public function completedResources() - { - return $this->belongsToMany(Resource::class, 'resource_completions'); - } - - public function nodeVotes(): HasMany + public function nodes(): HasMany { - return $this->hasMany(NodeVote::class); + return $this->hasMany(Node::class); } - public function nodes(): HasMany + public function resourceVotes(): HasMany { - return $this->hasMany(Node::class); + return $this->hasMany(ResourceVote::class); } public function appreciationsReceived(): HasMany diff --git a/app/Notifications/BlogReactionNotification.php b/app/Notifications/BlogReactionNotification.php index c5244948..be466312 100644 --- a/app/Notifications/BlogReactionNotification.php +++ b/app/Notifications/BlogReactionNotification.php @@ -7,7 +7,6 @@ use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; -use Illuminate\Support\Facades\Cache; class BlogReactionNotification extends Notification implements ShouldQueue { @@ -48,8 +47,6 @@ public static function sendTo(User $targetUser, Blog $blog, User $reactor, int $ 'data' => $data, 'created_at' => now(), ]); - - Cache::forever("user:{$targetUser->id}:has_unread_notifs", true); } else { $targetUser->notify(new self($blog, $reactor, $reactionsCount)); } diff --git a/app/Notifications/ForumVoteNotification.php b/app/Notifications/ForumVoteNotification.php index 2ec0f4ba..ef6e656a 100644 --- a/app/Notifications/ForumVoteNotification.php +++ b/app/Notifications/ForumVoteNotification.php @@ -8,7 +8,6 @@ use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; -use Illuminate\Support\Facades\Cache; class ForumVoteNotification extends Notification implements ShouldQueue { @@ -54,8 +53,6 @@ public static function sendTo(User $targetUser, ForumPost|ForumAnswer $item, Use 'data' => $data, 'created_at' => now(), ]); - - Cache::forever("user:{$targetUser->id}:has_unread_notifs", true); } else { $targetUser->notify(new self($item, $voter)); } diff --git a/app/Notifications/ResourceModerationNotification.php b/app/Notifications/ResourceModerationNotification.php index a3e72bfa..b4c9bf37 100644 --- a/app/Notifications/ResourceModerationNotification.php +++ b/app/Notifications/ResourceModerationNotification.php @@ -2,93 +2,91 @@ namespace App\Notifications; -use App\Models\ResourceChangeRequest; +use App\Models\Resource; +use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; +use Illuminate\Support\Facades\Auth; class ResourceModerationNotification extends Notification implements ShouldQueue { use Queueable; public function __construct( - public ResourceChangeRequest $changeRequest, + public Resource $resource, public string $status, public ?string $feedback = null, - public int $totalCount = 1, ) {} /** - * Get the notification's delivery channels. - * - * @return array + * Send or roll up a moderation notification to the target user. */ + public static function sendTo(User $targetUser, Resource $resource, string $status, ?string $feedback = null): void + { + if ($targetUser->id === Auth::id()) { + return; + } + + $unread = $targetUser->unreadNotifications() + ->where('type', self::class) + ->where('data->status', $status) + ->first(); + + if ($unread) { + $data = $unread->data; + $count = ($data['count'] ?? 1) + 1; + + $data['count'] = $count; + if ($status === 'approved') { + $data['title'] = 'Resource Submissions Approved'; + $data['message'] = "{$count} of your resource submissions were approved and are now live."; + } else { + $data['title'] = 'Resource Submissions Rejected'; + $data['message'] = $feedback + ? "{$count} resource submissions were rejected: {$feedback}" + : "{$count} of your resource submissions were rejected."; + } + + $unread->update([ + 'data' => $data, + 'created_at' => now(), + ]); + } else { + $targetUser->notify(new self($resource, $status, $feedback)); + } + } + public function via(object $notifiable): array { return ['database']; } - /** - * Get the array representation of the notification (Database in-app bell). - * - * @return array - */ public function toArray(object $notifiable): array { $url = $this->status === 'rejected' ? '/my-submissions?status=rejected' : '/my-submissions?status=approved'; - if ($this->totalCount > 1) { - $title = $this->status === 'rejected' - ? "{$this->totalCount} Resource Requests Rejected" - : "{$this->totalCount} Resource Requests Approved"; - - $message = $this->status === 'rejected' - ? ($this->feedback ? "{$this->totalCount} of your resource requests were rejected: {$this->feedback}" : "{$this->totalCount} of your resource requests were rejected.") - : "{$this->totalCount} of your resource requests were approved and are now live."; - - return [ - 'type' => 'resource_moderation', - 'status' => $this->status, - 'action_type' => 'batch', - 'title' => $title, - 'message' => $message, - 'url' => $url, - 'count' => $this->totalCount, - 'change_request_id' => $this->changeRequest->id, - 'node_id' => $this->changeRequest->node_id, - ]; - } - - $actionName = match ($this->changeRequest->action_type) { - 'create' => 'upload', - 'update' => 'edit', - 'delete' => 'deletion request', - default => 'request', - }; - - $resourceTitle = $this->changeRequest->payload['title'] - ?? $this->changeRequest->resource?->title - ?? 'Resource'; + $resourceTitle = $this->resource->title ?? 'Resource'; $title = $this->status === 'rejected' - ? 'Resource '.ucfirst($actionName).' Rejected' - : 'Resource '.ucfirst($actionName).' Approved'; + ? 'Resource Submission Rejected' + : 'Resource Submission Approved'; $message = $this->status === 'rejected' - ? ($this->feedback ? "\"{$resourceTitle}\": {$this->feedback}" : "Your {$actionName} for \"{$resourceTitle}\" was rejected.") - : "Your {$actionName} for \"{$resourceTitle}\" was approved and is now live."; + ? ($this->feedback ? "\"{$resourceTitle}\": {$this->feedback}" : "Your resource \"{$resourceTitle}\" was rejected.") + : "Your resource \"{$resourceTitle}\" was approved and is now live."; return [ 'type' => 'resource_moderation', 'status' => $this->status, - 'action_type' => $this->changeRequest->action_type, 'title' => $title, 'message' => $message, 'url' => $url, - 'change_request_id' => $this->changeRequest->id, - 'node_id' => $this->changeRequest->node_id, + 'resource_id' => $this->resource->id, + 'node_id' => $this->resource->node_id, + 'count' => 1, ]; } } diff --git a/app/Notifications/NodeVoteNotification.php b/app/Notifications/ResourceVoteNotification.php similarity index 52% rename from app/Notifications/NodeVoteNotification.php rename to app/Notifications/ResourceVoteNotification.php index 896c150a..b803ecb8 100644 --- a/app/Notifications/NodeVoteNotification.php +++ b/app/Notifications/ResourceVoteNotification.php @@ -2,35 +2,36 @@ namespace App\Notifications; -use App\Models\Node; +use App\Models\Resource; use App\Models\User; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; -use Illuminate\Support\Facades\Cache; -class NodeVoteNotification extends Notification implements ShouldQueue +class ResourceVoteNotification extends Notification implements ShouldQueue { use Queueable; public function __construct( - public Node $node, + public Resource $resource, public User $voter, ) {} /** - * Send or roll up a node vote notification to the node contributor. + * Send or roll up a resource vote notification to the author. */ - public static function sendTo(User $targetUser, Node $node, User $voter): void + public static function sendTo(User $targetUser, Resource $resource, User $voter): void { if ($targetUser->id === $voter->id) { return; } + $resourceId = $resource->id; + $unread = $targetUser->unreadNotifications() ->where('type', self::class) ->get() - ->first(fn ($n) => ($n->data['node_id'] ?? null) === $node->id); + ->first(fn ($n) => ($n->data['resource_id'] ?? null) === $resourceId); if ($unread) { $data = $unread->data; @@ -39,17 +40,15 @@ public static function sendTo(User $targetUser, Node $node, User $voter): void $othersText = $others === 1 ? '1 other person' : "{$others} other people"; $data['count'] = $count; - $data['title'] = "{$voter->name} and {$othersText} upvoted your folder"; - $data['message'] = "\"{$node->name}\""; + $data['title'] = "{$voter->name} and {$othersText} upvoted your resource"; + $data['message'] = "\"{$resource->title}\""; $unread->update([ 'data' => $data, 'created_at' => now(), ]); - - Cache::forever("user:{$targetUser->id}:has_unread_notifs", true); } else { - $targetUser->notify(new self($node, $voter)); + $targetUser->notify(new self($resource, $voter)); } } @@ -60,20 +59,12 @@ public function via(object $notifiable): array public function toArray(object $notifiable): array { - $subject = $this->node->subject; - if ($subject) { - $path = implode('/', array_column($this->node->breadcrumb(), 'slug')); - $url = url("/{$subject->slug}/{$path}"); - } else { - $url = url('/'); - } - return [ - 'type' => 'node_vote', - 'title' => "{$this->voter->name} upvoted your folder", - 'message' => "\"{$this->node->name}\"", - 'url' => $url, - 'node_id' => $this->node->id, + 'type' => 'resource_vote', + 'title' => "{$this->voter->name} upvoted your resource", + 'message' => "\"{$this->resource->title}\"", + 'url' => "/resources/{$this->resource->id}", + 'resource_id' => $this->resource->id, 'count' => 1, ]; } diff --git a/app/Notifications/UserAppreciationNotification.php b/app/Notifications/UserAppreciationNotification.php index 9d183125..803e7048 100644 --- a/app/Notifications/UserAppreciationNotification.php +++ b/app/Notifications/UserAppreciationNotification.php @@ -6,7 +6,6 @@ use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Notification; -use Illuminate\Support\Facades\Cache; class UserAppreciationNotification extends Notification implements ShouldQueue { @@ -45,8 +44,6 @@ public static function sendTo(User $targetUser, User $appreciator, int $totalApp 'data' => $data, 'created_at' => now(), ]); - - Cache::forever("user:{$targetUser->id}:has_unread_notifs", true); } else { $targetUser->notify(new self($appreciator, $totalAppreciations)); } diff --git a/app/Observers/NodeVoteObserver.php b/app/Observers/NodeVoteObserver.php deleted file mode 100644 index 843dfdef..00000000 --- a/app/Observers/NodeVoteObserver.php +++ /dev/null @@ -1,38 +0,0 @@ -clearVoteCache($nodeVote); - } - - public function updated(NodeVote $nodeVote): void - { - $this->clearVoteCache($nodeVote); - } - - public function deleted(NodeVote $nodeVote): void - { - $this->clearVoteCache($nodeVote); - } - - private function clearVoteCache(NodeVote $nodeVote): void - { - $node = $nodeVote->node; - if (! $node) { - return; - } - - if ($node->parent_id) { - Cache::forget("node_children_{$node->parent_id}"); - } else { - Cache::forget("subject_page_{$node->subject_id}"); - } - } -} diff --git a/app/Observers/ResourceObserver.php b/app/Observers/ResourceObserver.php index 88937b07..feb081dd 100644 --- a/app/Observers/ResourceObserver.php +++ b/app/Observers/ResourceObserver.php @@ -2,34 +2,23 @@ namespace App\Observers; -use App\Models\Node; use App\Models\Resource; use Illuminate\Support\Facades\Cache; class ResourceObserver { - public function creating(Resource $resource): void - { - if ($resource->node_id && $resource->user_id) { - $otherResourcesCount = Resource::where('node_id', $resource->node_id)->count(); - - if ($otherResourcesCount === 0) { - $node = Node::find($resource->node_id); - if ($node && $node->user_id !== $resource->user_id) { - $node->updateQuietly(['user_id' => $resource->user_id]); - } - } - } - } - public function saved(Resource $resource): void { - $this->clearCache($resource); + if ($resource->status === 'approved' || $resource->wasChanged('status')) { + $this->clearCache($resource); + } } public function deleted(Resource $resource): void { - $this->clearCache($resource); + if ($resource->status === 'approved') { + $this->clearCache($resource); + } } private function clearCache(Resource $resource): void @@ -37,11 +26,13 @@ private function clearCache(Resource $resource): void Cache::forget("resource_{$resource->id}"); Cache::forget("node_resources_{$resource->node_id}"); - $ids = Resource::where('node_id', $resource->node_id) - ->pluck('id'); - - foreach ($ids as $id) { - Cache::forget("resource_{$id}"); + $node = $resource->node; + if ($node) { + if ($node->parent_id) { + Cache::forget("node_children_{$node->parent_id}"); + } else { + Cache::forget("subject_page_{$node->subject_id}"); + } } } } diff --git a/app/Policies/ResourcePolicy.php b/app/Policies/ResourcePolicy.php index e2619879..5fc9d5eb 100644 --- a/app/Policies/ResourcePolicy.php +++ b/app/Policies/ResourcePolicy.php @@ -12,11 +12,15 @@ class ResourcePolicy */ public function update(User $user, Resource $resource): bool { - if ($resource->node?->isEffectivelyFrozen() || $resource->hasPendingChangeRequest()) { + if ($resource->node?->isEffectivelyFrozen()) { return false; } - return $user->id === $resource->user_id || $user->can('edit resources'); + if ($user->isBanned()) { + return false; + } + + return $user->can('edit resources') || $user->id === $resource->user_id; } /** @@ -24,10 +28,10 @@ public function update(User $user, Resource $resource): bool */ public function delete(User $user, Resource $resource): bool { - if ($resource->node?->isEffectivelyFrozen() || $resource->hasPendingChangeRequest()) { + if ($resource->node?->isEffectivelyFrozen()) { return false; } - return $user->id === $resource->user_id || $user->can('delete resources'); + return $user->can('delete resources'); } } diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 535c066c..32db6a3d 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -4,7 +4,6 @@ use App\Models\Blog; use App\Models\Node; -use App\Models\NodeVote; use App\Models\Notice; use App\Models\Product; use App\Models\Resource; @@ -12,7 +11,6 @@ use App\Models\User; use App\Observers\BlogObserver; use App\Observers\NodeObserver; -use App\Observers\NodeVoteObserver; use App\Observers\NoticeObserver; use App\Observers\ProductObserver; use App\Observers\ResourceObserver; @@ -45,15 +43,14 @@ public function boot(): void Blog::observe(BlogObserver::class); Node::observe(NodeObserver::class); - NodeVote::observe(NodeVoteObserver::class); Notice::observe(NoticeObserver::class); Product::observe(ProductObserver::class); Resource::observe(ResourceObserver::class); Subject::observe(SubjectObserver::class); User::observe(UserObserver::class); - DatabaseNotification::created(function (DatabaseNotification $notification) { - if ($notification->notifiable_type === User::class && $notification->notifiable_id) { + DatabaseNotification::saved(function (DatabaseNotification $notification) { + if ($notification->notifiable_type === User::class && $notification->notifiable_id && is_null($notification->read_at)) { Cache::forever("user:{$notification->notifiable_id}:has_unread_notifs", true); } }); diff --git a/database/migrations/2026_10_22_094417_drop_node_votes_table.php b/database/migrations/2026_10_22_094417_drop_node_votes_table.php new file mode 100644 index 00000000..44c07c79 --- /dev/null +++ b/database/migrations/2026_10_22_094417_drop_node_votes_table.php @@ -0,0 +1,37 @@ +where('type', 'App\Notifications\NodeVoteNotification') + ->delete(); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::create('node_votes', function (Blueprint $table) { + $table->id(); + $table->foreignId('node_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->enum('type', ['up', 'down']); + $table->timestamps(); + + $table->unique(['node_id', 'user_id']); + }); + } +}; diff --git a/database/migrations/2026_10_22_101342_update_resources_table.php b/database/migrations/2026_10_22_101342_update_resources_table.php new file mode 100644 index 00000000..1bbb542c --- /dev/null +++ b/database/migrations/2026_10_22_101342_update_resources_table.php @@ -0,0 +1,53 @@ +string('title', 255)->change(); + $table->renameColumn('content', 'description'); + $table->string('thumbnail', 2048)->nullable()->after('description'); + $table->json('items')->nullable()->after('thumbnail'); + $table->string('status', 20)->default('pending')->after('items'); + $table->text('admin_note')->nullable()->after('status'); + $table->foreignId('reviewed_by')->nullable()->after('admin_note')->constrained('users')->nullOnDelete(); + $table->timestamp('reviewed_at')->nullable()->after('reviewed_by'); + $table->dropColumn(['file_path', 'external_url']); + + $table->index(['status', 'created_at']); + }); + + if (DB::getDriverName() === 'mysql') { + DB::statement("ALTER TABLE resources MODIFY COLUMN resource_type VARCHAR(32) NOT NULL DEFAULT 'note'"); + } + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + if (DB::getDriverName() === 'mysql') { + DB::statement("ALTER TABLE resources MODIFY COLUMN resource_type ENUM('note', 'question', 'pdf', 'image', 'video') NOT NULL"); + } + + Schema::table('resources', function (Blueprint $table) { + $table->dropForeign(['reviewed_by']); + $table->dropIndex(['status', 'created_at']); + $table->dropColumn(['items', 'thumbnail', 'status', 'admin_note', 'reviewed_by', 'reviewed_at']); + $table->string('file_path', 255)->nullable(); + $table->text('external_url')->nullable(); + $table->renameColumn('description', 'content'); + $table->string('title', 100)->change(); + }); + } +}; diff --git a/database/migrations/2026_10_22_103134_drop_format_subfolders_from_nodes.php b/database/migrations/2026_10_22_103134_drop_format_subfolders_from_nodes.php new file mode 100644 index 00000000..33537d99 --- /dev/null +++ b/database/migrations/2026_10_22_103134_drop_format_subfolders_from_nodes.php @@ -0,0 +1,43 @@ +whereNotNull('parent_id') + ->where(function ($query) use ($formatSlugs, $formatNames) { + $query->whereIn('slug', $formatSlugs) + ->orWhereIn('name', $formatNames); + }) + ->delete(); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + // One-way cleanup migration: old dummy format subfolders are deprecated + } +}; diff --git a/database/migrations/2026_10_22_120500_drop_resource_completions_table.php b/database/migrations/2026_10_22_120500_drop_resource_completions_table.php new file mode 100644 index 00000000..d31cd4b1 --- /dev/null +++ b/database/migrations/2026_10_22_120500_drop_resource_completions_table.php @@ -0,0 +1,31 @@ +id(); + $table->foreignId('resource_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->timestamps(); + + $table->unique(['resource_id', 'user_id']); + }); + } +}; diff --git a/database/migrations/2026_10_22_121500_create_resource_votes_and_add_score_to_resources.php b/database/migrations/2026_10_22_121500_create_resource_votes_and_add_score_to_resources.php new file mode 100644 index 00000000..78fe6a1f --- /dev/null +++ b/database/migrations/2026_10_22_121500_create_resource_votes_and_add_score_to_resources.php @@ -0,0 +1,43 @@ +integer('vote_score')->default(0)->index()->after('description'); + $table->unsignedInteger('upvotes_count')->default(0)->after('vote_score'); + $table->unsignedInteger('downvotes_count')->default(0)->after('upvotes_count'); + }); + + Schema::create('resource_votes', function (Blueprint $table) { + $table->id(); + $table->foreignId('resource_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->tinyInteger('value'); // 1 = upvote, -1 = downvote + $table->timestamps(); + + $table->unique(['resource_id', 'user_id']); + $table->index(['resource_id', 'value']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('resource_votes'); + + Schema::table('resources', function (Blueprint $table) { + $table->dropColumn(['vote_score', 'upvotes_count', 'downvotes_count']); + }); + } +}; diff --git a/database/migrations/2026_10_22_155000_drop_resource_change_requests_table.php b/database/migrations/2026_10_22_155000_drop_resource_change_requests_table.php new file mode 100644 index 00000000..01f4a677 --- /dev/null +++ b/database/migrations/2026_10_22_155000_drop_resource_change_requests_table.php @@ -0,0 +1,39 @@ +id(); + $table->foreignId('user_id')->constrained('users')->cascadeOnDelete(); + $table->foreignId('resource_id')->nullable()->constrained('resources')->cascadeOnDelete(); + $table->foreignId('node_id')->constrained('nodes')->cascadeOnDelete(); + + $table->enum('action_type', ['create', 'update', 'delete']); + $table->enum('status', ['pending', 'approved', 'rejected'])->default('pending'); + + $table->json('payload')->nullable(); + + $table->foreignId('reviewed_by')->nullable()->constrained('users')->nullOnDelete(); + $table->timestamp('reviewed_at')->nullable(); + $table->text('rejection_reason')->nullable(); + + $table->timestamps(); + + $table->index('status'); + $table->index(['resource_id', 'status']); + $table->index(['user_id', 'status']); + $table->index(['node_id', 'action_type', 'status']); + }); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php index bb549735..24e3a8bc 100644 --- a/database/seeders/DatabaseSeeder.php +++ b/database/seeders/DatabaseSeeder.php @@ -30,7 +30,6 @@ public function run(): void ReportSeeder::class, UserAppreciationSeeder::class, ChatSeeder::class, - ResourceChangeRequestSeeder::class, ]); Blog::factory()->count(10)->create(); } diff --git a/database/seeders/ResourceChangeRequestSeeder.php b/database/seeders/ResourceChangeRequestSeeder.php deleted file mode 100644 index dda33ca3..00000000 --- a/database/seeders/ResourceChangeRequestSeeder.php +++ /dev/null @@ -1,225 +0,0 @@ -first() ?? User::first(); - $contributor = User::where('id', '!=', $admin?->id)->first() ?? User::factory()->create(); - - $node = Node::has('subject')->first() ?? Node::first(); - if (! $node) { - $this->command->warn('No nodes available to seed change requests.'); - - return; - } - - // Fetch or create sample resources for update and delete requests - $noteResource = Resource::where('resource_type', 'note')->first() ?? Resource::create([ - 'node_id' => $node->id, - 'user_id' => $contributor->id, - 'resource_type' => 'note', - 'title' => 'Original Summary of Newton Mechanics', - 'content' => 'Newton second law states that F = dp/dt. When mass is constant, F = ma.', - ]); - - $pdfResource = Resource::where('resource_type', 'pdf')->first() ?? Resource::create([ - 'node_id' => $node->id, - 'user_id' => $contributor->id, - 'resource_type' => 'pdf', - 'title' => 'Calculus Formula Sheet 2024', - 'external_url' => 'https://example.com/calculus-formula-sheet.pdf', - ]); - - $videoResource = Resource::where('resource_type', 'video')->first() ?? Resource::create([ - 'node_id' => $node->id, - 'user_id' => $contributor->id, - 'resource_type' => 'video', - 'title' => 'Introduction to Organic Reactions', - 'external_url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', - ]); - - $deleteCandidateResource = Resource::whereNotIn('id', [$noteResource->id, $pdfResource->id, $videoResource->id])->first() ?? Resource::create([ - 'node_id' => $node->id, - 'user_id' => $contributor->id, - 'resource_type' => 'note', - 'title' => 'Outdated Exam Routine 2021', - 'content' => 'Routine for 2021 HSC batch. No longer relevant.', - ]); - - // 1. Pending CREATE Requests - // Note - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'note', - 'title' => 'Photosynthesis Light & Dark Reaction Summary Notes', - 'content' => "### Photosynthesis Key Points\n\n- **Light Dependent Phase**: Occurs in thylakoid membranes.\n- **Light Independent Phase (Calvin Cycle)**: Occurs in the stroma.\n- Key enzyme: RuBisCO.", - 'external_url' => null, - 'file_path' => null, - ], - ]); - - // PDF - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'pdf', - 'title' => 'Thermodynamics Formulas & Chapter Practice PDF', - 'content' => null, - 'external_url' => 'https://drive.google.com/file/d/1sample_pdf_drive_link/view', - 'file_path' => null, - ], - ]); - - // Video - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'video', - 'title' => 'Complete Matrices and Determinants Masterclass (Bangla)', - 'content' => null, - 'external_url' => 'https://www.youtube.com/watch?v=ScMzIvxBSi4', - 'file_path' => null, - ], - ]); - - // Image - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'image', - 'title' => 'Conic Sections - Hyperbola and Ellipse Geometric Diagram', - 'content' => null, - 'external_url' => null, - 'file_path' => 'resources/images/sample-conic-diagram.png', - ], - ]); - - // 2. Pending UPDATE Requests - // Note update - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'resource_id' => $noteResource->id, - 'node_id' => $noteResource->node_id, - 'action_type' => 'update', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $noteResource->node_id, - 'resource_type' => 'note', - 'title' => 'Newtonian Mechanics - Comprehensive Derivations & Solved Problems', - 'content' => "### Comprehensive Newtonian Mechanics\n\n1. Momentum conservation: m1*u1 + m2*u2 = m1*v1 + m2*v2\n2. Friction: f_k = mu_k * N\n3. Centripetal Force: F_c = m * v^2 / r", - 'external_url' => null, - 'file_path' => null, - ], - ]); - - // PDF update - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'resource_id' => $pdfResource->id, - 'node_id' => $pdfResource->node_id, - 'action_type' => 'update', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $pdfResource->node_id, - 'resource_type' => 'pdf', - 'title' => 'Calculus Formula Sheet 2026 (Updated with Integration Rules)', - 'content' => null, - 'external_url' => 'https://example.com/calculus-formula-sheet-2026-revised.pdf', - 'file_path' => null, - ], - ]); - - // Video update - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'resource_id' => $videoResource->id, - 'node_id' => $videoResource->node_id, - 'action_type' => 'update', - 'status' => 'pending', - 'payload' => [ - 'node_id' => $videoResource->node_id, - 'resource_type' => 'video', - 'title' => 'Organic Chemistry - Electrophilic Aromatic Substitution (HD Remastered)', - 'content' => null, - 'external_url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', - 'file_path' => null, - ], - ]); - - // 3. Pending DELETE Request - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'resource_id' => $deleteCandidateResource->id, - 'node_id' => $deleteCandidateResource->node_id, - 'action_type' => 'delete', - 'status' => 'pending', - 'payload' => null, - ]); - - // 4. APPROVED Request (history check) - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'approved', - 'reviewed_by' => $admin?->id, - 'reviewed_at' => now()->subDay(), - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'pdf', - 'title' => 'HSC English 1st Paper Flowchart and Summary Guidelines', - 'content' => null, - 'external_url' => 'https://example.com/english-1st-paper-guide.pdf', - 'file_path' => null, - ], - ]); - - // 5. REJECTED Request (history check) - ResourceChangeRequest::create([ - 'user_id' => $contributor->id, - 'node_id' => $node->id, - 'action_type' => 'create', - 'status' => 'rejected', - 'reviewed_by' => $admin?->id, - 'reviewed_at' => now()->subHours(6), - 'rejection_reason' => 'The provided Google Drive link requires permission to view. Please set link sharing to "Anyone with the link can view" and resubmit.', - 'payload' => [ - 'node_id' => $node->id, - 'resource_type' => 'pdf', - 'title' => 'Inaccessible Question Bank PDF', - 'content' => null, - 'external_url' => 'https://drive.google.com/file/d/private-file-id/view', - 'file_path' => null, - ], - ]); - } -} diff --git a/database/seeders/ResourceSeeder.php b/database/seeders/ResourceSeeder.php index 745fb343..f5b103fe 100644 --- a/database/seeders/ResourceSeeder.php +++ b/database/seeders/ResourceSeeder.php @@ -2,63 +2,172 @@ namespace Database\Seeders; +use App\Models\Node; +use App\Models\Resource; +use App\Models\User; use Illuminate\Database\Seeder; -use Illuminate\Support\Facades\DB; class ResourceSeeder extends Seeder { public function run(): void { - $nodes = DB::table('nodes')->get(); + $user = User::first() ?? User::factory()->create(); - foreach ($nodes as $node) { + // Scan real image files from storage if available + $imageDir = storage_path('app/public/resources/images'); + $availableImages = []; + if (is_dir($imageDir)) { + $files = scandir($imageDir); + $availableImages = array_values(array_filter($files, fn ($f) => str_ends_with($f, '.jpg') || str_ends_with($f, '.png') || str_ends_with($f, '.webp') + )); + } - DB::table('resources')->insert([ - [ - 'node_id' => $node->id, - 'user_id' => 1, - 'resource_type' => 'note', - 'title' => $node->name.' - অধ্যায়ভিত্তিক নোট', - 'content' => $node->name.' অধ্যায়ের গুরুত্বপূর্ণ তত্ত্ব, সূত্র ও আলোচনা।', - 'file_path' => null, - 'external_url' => null, - 'created_at' => now(), - 'updated_at' => now(), - ], - [ - 'node_id' => $node->id, - 'user_id' => 1, - 'resource_type' => 'pdf', - 'title' => $node->name.' - PDF হ্যান্ডনোট', - 'content' => null, - 'file_path' => null, - 'external_url' => 'https://www.africau.edu/images/default/sample.pdf', - 'created_at' => now(), - 'updated_at' => now(), + // Fallback placeholder images if none on disk + if (empty($availableImages)) { + $availableImages = [ + 'sample1.jpg', + 'sample2.jpg', + 'sample3.jpg', + 'sample4.jpg', + ]; + } + + // Real educational YouTube lecture URLs + $youtubeUrls = [ + 'https://www.youtube.com/watch?v=lnnYO482hhg', + 'https://www.youtube.com/watch?v=1fRPMrIBgUk', + 'https://www.youtube.com/watch?v=vXsBw4zz5MQ', + 'https://www.youtube.com/watch?v=pzAeyWKWSs0', + 'https://www.youtube.com/watch?v=aXs8t1j9SwY', + 'https://www.youtube.com/watch?v=FijbFpRurag', + 'https://www.youtube.com/watch?v=45tM4SLSwCY', + 'https://www.youtube.com/watch?v=quiNSYM51fA', + ]; + + // Sample PDF URLs (including real Google Drive previewable PDF links) + $pdfUrls = [ + 'https://drive.google.com/file/d/1L2_3I1liaXy5YlYBAHEEe1iU1eR7ppI2/view', + 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', + ]; + + // Pick leaf nodes (nodes without children) across various subjects + $leafNodes = Node::whereDoesntHave('children') + ->with('subject') + ->take(50) + ->get(); + + $imageIndex = 0; + $videoIndex = 0; + + foreach ($leafNodes as $node) { + $subjectName = $node->subject?->name ?? 'সাধারণ'; + + // 1. Multi-Page Scanned Handwritten Note (format = 'image') + $notePagesCount = rand(4, 8); + $noteItems = []; + for ($page = 1; $page <= $notePagesCount; $page++) { + $imageFile = $availableImages[$imageIndex % count($availableImages)]; + $imageIndex++; + + $noteItems[] = [ + 'format' => 'image', + 'title' => null, + 'source' => "resources/images/{$imageFile}", + ]; + } + + Resource::create([ + 'node_id' => $node->id, + 'user_id' => $user->id, + 'resource_type' => 'note', + 'title' => "{$node->name} সম্পূর্ণ অধ্যায়ভিত্তিক হ্যান্ডনোট", + 'description' => "{$subjectName} বিষয়ের '{$node->name}' অধ্যায়ের সকল গুরুত্বপূর্ণ সূত্র, নিয়ম ও বিস্তারিত সমাধানসহ সম্পূর্ণ হ্যান্ডনোট। পরীক্ষার আগে দ্রুত রিভিশনের জন্য সহায়ক।", + 'items' => $noteItems, + ]); + + // 2. Video Lecture Course (format = 'video') + $lectureCount = rand(3, 5); + $lectureTitles = [ + 'লেকচার ০১: প্রাথমিক ধারণা ও বেসিক আলোচনা', + 'লেকচার ০২: গাণিতিক সূত্রাবলি ও টাইপভিত্তিক সমস্যা', + 'লেকচার ০৩: জটিল সমস্যার সহজ সমাধান', + 'লেকচার ০৪: বোর্ড প্রশ্ন ও বিগত বছরের প্রশ্ন সমাধান', + 'লেকচার ০৫: এমসিকিউ শর্টকাট ও সুপার ট্রিকস', + ]; + + $videoItems = []; + for ($lec = 0; $lec < $lectureCount; $lec++) { + $videoUrl = $youtubeUrls[$videoIndex % count($youtubeUrls)]; + $videoIndex++; + + $videoItems[] = [ + 'format' => 'video', + 'title' => $lectureTitles[$lec] ?? 'লেকচার ০'.($lec + 1), + 'source' => $videoUrl, + ]; + } + + Resource::create([ + 'node_id' => $node->id, + 'user_id' => $user->id, + 'resource_type' => 'video', + 'title' => "{$node->name} পূর্ণাঙ্গ মাস্টারক্লাস ও কনসেপ্ট ক্লিয়ারিং", + 'description' => "অভিজ্ঞ শিক্ষক দ্বারা পরিচালিত '{$node->name}' অধ্যায়ের ধারাবাহিক ভিডিও লেকচার। টপিকভিত্তিক আলোচনা ও বোর্ড প্রশ্ন সমাধান কাভার করা হয়েছে।", + 'items' => $videoItems, + ]); + + // 3. Highlighted Textbook / Note in PDF Format (format = 'pdf') + $pdfUrl = $pdfUrls[array_rand($pdfUrls)]; + Resource::create([ + 'node_id' => $node->id, + 'user_id' => $user->id, + 'resource_type' => 'note', + 'title' => "{$node->name} দাগানো মূল বই ও গুরুত্বপূর্ণ পয়েন্ট (PDF)", + 'description' => 'বোর্ড পরীক্ষার জন্য সবচেয়ে গুরুত্বপূর্ণ লাইন এবং জ্ঞানমূলক ও অনুধাবনমূলক প্রশ্নের জন্য দাগানো পাঠ্যবই।', + 'items' => [ + [ + 'format' => 'pdf', + 'title' => 'দাগানো পাঠ্যবই (PDF)', + 'source' => $pdfUrl, + ], ], - [ + ]); + + // 4. Practical / Lab Notebook (format = 'pdf') + if ($node->id % 2 === 0) { + Resource::create([ 'node_id' => $node->id, - 'user_id' => 1, - 'resource_type' => 'image', - 'title' => $node->name.' - চিত্র', - 'content' => null, - 'file_path' => null, - 'external_url' => 'https://picsum.photos/1200/800?random='.$node->id, - 'created_at' => now(), - 'updated_at' => now(), - ], - [ + 'user_id' => $user->id, + 'resource_type' => 'practical', + 'title' => "{$node->name} ব্যবহারিক নোটবুক ও এক্সপেরিমেন্ট চিত্র", + 'description' => 'ল্যাব ক্লাসের জন্য সম্পূর্ণ ব্যবহারিক খাতা, এক্সপেরিমেন্ট ডেটা টেবিল ও সঠিক চিত্রাঙ্কনসহ সমাধান।', + 'items' => [ + [ + 'format' => 'pdf', + 'title' => 'ব্যবহারিক নির্দেশিকা ও ল্যাব শিট (PDF)', + 'source' => $pdfUrl, + ], + ], + ]); + } + + // 5. Other Resources (format = 'pdf') + if ($node->id % 3 === 0) { + Resource::create([ 'node_id' => $node->id, - 'user_id' => 1, - 'resource_type' => 'video', - 'title' => $node->name.' - ভিডিও লেকচার', - 'content' => null, - 'file_path' => null, - 'external_url' => 'https://www.youtube.com/embed/a3ICNMQW7Ok', - 'created_at' => now(), - 'updated_at' => now(), - ], - ]); + 'user_id' => $user->id, + 'resource_type' => 'other', + 'title' => "{$node->name} বিগত ৫ বছরের বোর্ড প্রশ্ন ব্যাংক ও সাজেশন", + 'description' => 'বিগত বছরের সকল বোর্ডের গুরুত্বপূর্ণ সৃজনশীল ও বহুনির্বাচনী প্রশ্নের সাজানো সংগ্রহ।', + 'items' => [ + [ + 'format' => 'pdf', + 'title' => 'প্রশ্নব্যাংক ও সাজেশন বুকলেট (PDF)', + 'source' => $pdfUrl, + ], + ], + ]); + } } } } diff --git a/docs/storage-cleanup.md b/docs/storage-cleanup.md index c0d9c9f2..46d54a2d 100644 --- a/docs/storage-cleanup.md +++ b/docs/storage-cleanup.md @@ -8,7 +8,7 @@ It scans four storage directories and cross-references them against the database | Storage Directory | Database Check | | ----------------- | ------------------------------------------------------------------------------ | -| `resources/` | `resources.file_path` & pending `resource_change_requests.payload['file_path']` | +| `resources/` | `resources.items` (non-HTTP paths only) | | `users/` | `users.image_path` | | `blogs/` | `blogs.featured_image_path` | | `notices/` | `notices.image` (non-HTTP paths only) | diff --git a/resources/js/components/AdUnit.vue b/resources/js/components/AdUnit.vue index de52a540..ad441fe9 100644 --- a/resources/js/components/AdUnit.vue +++ b/resources/js/components/AdUnit.vue @@ -262,32 +262,34 @@ const isDismissed = ref(false); target="_blank" rel="noopener noreferrer" aria-label="Sponsored course tile" - class="group relative flex touch-manipulation items-center justify-between overflow-hidden rounded-xl border border-dashed border-amber-300/90 bg-gradient-to-r from-amber-50/70 via-white to-orange-50/40 px-5 py-4.5 transition-all duration-200 hover:border-amber-400 hover:shadow-sm active:scale-[0.99] dark:border-amber-500/40 dark:from-amber-950/20 dark:via-gray-900 dark:to-gray-900" + class="group relative flex touch-manipulation flex-col items-start gap-2.5 overflow-hidden rounded-xl border border-dashed border-amber-300/90 bg-gradient-to-r from-amber-50/70 via-white to-orange-50/40 p-3.5 transition-all duration-200 hover:border-amber-400 hover:shadow-sm active:scale-[0.99] sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-5 sm:py-4.5 dark:border-amber-500/40 dark:from-amber-950/20 dark:via-gray-900 dark:to-gray-900" > -
+
- +
-
+

{{ title }}

{{ badgeText }}

{{ subtitle }}

@@ -295,7 +297,7 @@ const isDismissed = ref(false);
-
+