DONE: feedback module, use permission name for notification

This commit is contained in:
ISMAIL MASSERAN
2026-07-14 12:02:37 +08:00
parent 324b7facf1
commit 52ffd3393a
60 changed files with 3083 additions and 26 deletions
View File
+5
View File
@@ -0,0 +1,5 @@
<?php
return [
'name' => 'Feedback',
];
@@ -0,0 +1,54 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
// Create ENUM types for PostgreSQL
DB::statement("CREATE TYPE feedback_type_enum AS ENUM ('bug', 'feature_request', 'general_feedback', 'ui_issue', 'performance_issue')");
DB::statement("CREATE TYPE feedback_priority_enum AS ENUM ('low', 'medium', 'high', 'critical')");
DB::statement("CREATE TYPE feedback_status_enum AS ENUM ('open', 'in_progress', 'resolved', 'closed', 'rejected')");
Schema::create('feedback', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('user_id')->nullable()->constrained('users')->nullOnDelete();
$table->string('title');
$table->text('description');
$table->string('page_url')->nullable(); // URL where the issue occurred
$table->json('browser_info')->nullable(); // Browser, OS, screen resolution etc.
$table->text('steps_to_reproduce')->nullable(); // Steps to reproduce the issue
$table->text('expected_behavior')->nullable(); // What should happen
$table->text('actual_behavior')->nullable(); // What actually happened
$table->text('additional_notes')->nullable(); // Any additional information
$table->foreignUuid('assigned_to')->nullable()->constrained('users')->nullOnDelete();
$table->text('admin_notes')->nullable(); // Internal notes for admins
$table->timestamp('resolved_at')->nullable();
$table->timestamps();
$table->softDeletes();
});
// Add ENUM columns
DB::statement("ALTER TABLE feedback ADD COLUMN type feedback_type_enum NOT NULL DEFAULT 'general_feedback'");
DB::statement("ALTER TABLE feedback ADD COLUMN priority feedback_priority_enum NOT NULL DEFAULT 'medium'");
DB::statement("ALTER TABLE feedback ADD COLUMN status feedback_status_enum NOT NULL DEFAULT 'open'");
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('feedback');
DB::statement("DROP TYPE IF EXISTS feedback_type_enum");
DB::statement("DROP TYPE IF EXISTS feedback_priority_enum");
DB::statement("DROP TYPE IF EXISTS feedback_status_enum");
}
};
@@ -0,0 +1,16 @@
<?php
namespace Modules\Feedback\Database\Seeders;
use Illuminate\Database\Seeder;
class FeedbackDatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// $this->call([]);
}
}
View File
+119
View File
@@ -0,0 +1,119 @@
<?php
namespace Modules\Feedback\Entities;
use App\Traits\HasDocuments;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;
use Modules\Auth\Entities\User;
class Feedback extends Model
{
use HasDocuments, HasUuids, SoftDeletes, LogsActivity;
public const IMAGE_DOCUMENT_TYPE = 'image';
public const VIDEO_DOCUMENT_TYPE = 'video';
protected $table = 'feedback';
protected $fillable = [
'user_id',
'type',
'title',
'description',
'page_url',
'browser_info',
'steps_to_reproduce',
'expected_behavior',
'actual_behavior',
'additional_notes',
'priority',
'status',
'assigned_to',
'admin_notes',
'resolved_at',
];
protected $casts = [
'browser_info' => 'array',
'resolved_at' => 'datetime',
];
public function getActivitylogOptions(): LogOptions
{
return LogOptions::defaults()
->logAll()
->logOnlyDirty();
}
/**
* Get the user who submitted the feedback
*/
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
/**
* Get the admin assigned to handle this feedback
*/
public function assignedUser()
{
return $this->belongsTo(User::class, 'assigned_to');
}
public function images(): MorphMany
{
return $this->documents()->where('type', self::IMAGE_DOCUMENT_TYPE);
}
public function videos(): MorphMany
{
return $this->documents()->where('type', self::VIDEO_DOCUMENT_TYPE);
}
/**
* Scope for filtering by type
*/
public function scopeOfType($query, $type)
{
return $query->where('type', $type);
}
/**
* Scope for filtering by status
*/
public function scopeOfStatus($query, $status)
{
return $query->where('status', $status);
}
/**
* Scope for filtering by priority
*/
public function scopeOfPriority($query, $priority)
{
return $query->where('priority', $priority);
}
/**
* Scope for open feedback
*/
public function scopeOpen($query)
{
return $query->whereIn('status', ['open', 'in_progress']);
}
/**
* Scope for resolved feedback
*/
public function scopeResolved($query)
{
return $query->whereIn('status', ['resolved', 'closed']);
}
}
@@ -0,0 +1,339 @@
<?php
namespace Modules\Feedback\Http\Controllers;
use App\Http\Controllers\BaseCrudController;
use App\Models\Document;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Modules\Feedback\Entities\Feedback;
use Modules\Feedback\Http\Requests\FeedbackRequest;
use Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface;
use Modules\Feedback\Transformers\FeedbackResource;
use Modules\Feedback\Notifications\FeedbackNotification;
use Modules\Auth\Entities\User;
use Laravel\Sanctum\PersonalAccessToken;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class FeedbackController extends BaseCrudController
{
protected $modelClass = Feedback::class;
protected $resourceClass = FeedbackResource::class;
protected $requestClass = FeedbackRequest::class;
protected $resourceName = 'maklum balas';
protected $resourceNamePlural = 'maklum balas';
public function __construct(FeedbackRepositoryInterface $repository)
{
parent::__construct($repository);
}
/**
* Override getIndexData to handle filters
*/
protected function getIndexData(Request $request, int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc')
{
// Extract filter parameters from request
$filters = [
'type' => $request->get('type'),
'status' => $request->get('status'),
'priority' => $request->get('priority'),
];
// Always try paginated methods first when perPage is specified
if ($perPage > 0) {
if (method_exists($this->repository, 'getAllWithRelationsPaginated')) {
return $this->repository->getAllWithRelationsPaginated($perPage, $search, $sortBy, $sortOrder, $filters);
}
if (method_exists($this->repository, 'getAllPaginated')) {
return $this->repository->getAllPaginated($perPage, $search, $sortBy, $sortOrder, $filters);
}
}
// Fallback to non-paginated methods
if (method_exists($this->repository, 'getAllWithRelations')) {
return $this->repository->getAllWithRelations($search, $sortBy, $sortOrder);
}
return $this->repository->all($search, $sortBy, $sortOrder);
}
/**
* Store a newly created resource in storage (public access)
*/
public function store(Request $request): JsonResponse
{
// Skip authorization for public feedback submission
try {
$validated = $this->validateRequest($request);
$data = $this->prepareStoreData($validated);
$item = $this->repository->create($data);
$this->uploadAttachments($item, $request);
// Load relationships
$item->load(['user', 'documents']);
// Send notification to admins
$this->notifyAdminsForNewFeedback($item);
return response()->json([
'success' => true,
'data' => new $this->resourceClass($item),
'message' => 'Maklum balas berjaya dihantar. Terima kasih!',
], 201);
} catch (Exception $e) {
Log::error("Error creating {$this->resourceName}: ".$e->getMessage());
return $this->errorResponse($this->getErrorMessage('store').': '.$e->getMessage(), 500);
}
}
/**
* Prepare data for store method
*/
protected function prepareStoreData(array $validated): array
{
$data = $validated;
// Check if user is authenticated by looking for the Authorization header
$authHeader = request()->header('Authorization');
if ($authHeader && str_starts_with($authHeader, 'Bearer ')) {
// Try to authenticate the user manually
$token = str_replace('Bearer ', '', $authHeader);
$personalAccessToken = PersonalAccessToken::findToken($token);
if ($personalAccessToken) {
$data['user_id'] = $personalAccessToken->tokenable_id;
} else {
$data['user_id'] = null;
}
} else {
// User is not authenticated
$data['user_id'] = null;
}
$data['browser_info'] = $this->getBrowserInfo(request());
unset($data['images'], $data['videos']);
return $data;
}
/**
* Upload image and video attachments via HasDocuments.
*/
protected function uploadAttachments(Feedback $feedback, Request $request): void
{
if ($request->hasFile('images')) {
foreach ($request->file('images') as $image) {
$feedback->uploadDocument($image, Feedback::IMAGE_DOCUMENT_TYPE);
}
}
if ($request->hasFile('videos')) {
foreach ($request->file('videos') as $video) {
$feedback->uploadDocument($video, Feedback::VIDEO_DOCUMENT_TYPE);
}
}
}
/**
* Prepare data for update method
*/
protected function prepareUpdateData(array $validated, $feedback): array
{
$data = $validated;
unset($data['images'], $data['videos']);
// Set resolved_at timestamp when status changes to resolved
if (isset($data['status']) && $data['status'] === 'resolved') {
$data['resolved_at'] = now();
} elseif (isset($data['status']) && $data['status'] !== 'resolved') {
$data['resolved_at'] = null;
}
return $data;
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id): JsonResponse
{
$this->authorize('update', $this->modelClass);
try {
$item = $this->repository->findById($id);
if (! $item) {
return $this->errorResponse($this->getNotFoundMessage(), 404);
}
$validated = $this->validateRequest($request);
$data = $this->prepareUpdateData($validated, $item);
$item->update($data);
$item->load(['user', 'assignedUser', 'documents']);
return response()->json([
'success' => true,
'data' => new $this->resourceClass($item),
'message' => $this->getSuccessMessage('update'),
]);
} catch (Exception $e) {
Log::error("Error updating {$this->resourceName}: ".$e->getMessage());
return $this->errorResponse($this->getErrorMessage('update').': '.$e->getMessage(), 500);
}
}
/**
* Load relations for show method
*/
protected function loadShowRelations($item)
{
return $item->load(['user', 'assignedUser', 'documents']);
}
/**
* Check dependencies before deletion
*/
protected function checkDependencies($feedback): ?\Illuminate\Http\JsonResponse
{
foreach ($feedback->documents as $document) {
$feedback->deleteDocument($document->id);
}
return null;
}
/**
* Stream a feedback attachment inline (image/video preview).
*/
public function serveDocument(string $id, string $documentId): BinaryFileResponse
{
$this->authorize('view', $this->modelClass);
$feedback = Feedback::findOrFail($id);
$document = $feedback->documents()->findOrFail($documentId);
$disk = Storage::disk(Document::STORAGE_DISK);
if (! $disk->exists($document->path)) {
abort(404, 'File not found');
}
return response()->file($disk->path($document->path), [
'Content-Type' => $document->mime_type ?? 'application/octet-stream',
'Content-Disposition' => 'inline; filename="'.$document->name.'"',
]);
}
/**
* Get feedback statistics
*/
public function statistics(): JsonResponse
{
$stats = [
'total' => Feedback::count(),
'open' => Feedback::open()->count(),
'resolved' => Feedback::resolved()->count(),
'by_type' => Feedback::selectRaw('type, COUNT(*) as count')
->groupBy('type')
->pluck('count', 'type'),
'by_priority' => Feedback::selectRaw('priority, COUNT(*) as count')
->groupBy('priority')
->pluck('count', 'priority'),
'by_status' => Feedback::selectRaw('status, COUNT(*) as count')
->groupBy('status')
->pluck('count', 'status'),
];
return response()->json([
'success' => true,
'data' => $stats
]);
}
/**
* Get user's own feedback
*/
public function myFeedback(Request $request): JsonResponse
{
$query = Feedback::where('user_id', auth()->id())
->with(['assignedUser', 'documents'])
->orderBy('created_at', 'desc');
// Apply filters
if ($request->has('status') && $request->status) {
$query->ofStatus($request->status);
}
if ($request->has('type') && $request->type) {
$query->ofType($request->type);
}
$perPage = $request->get('per_page', 15);
$feedback = $query->paginate($perPage);
return response()->json([
'success' => true,
'data' => FeedbackResource::collection($feedback->items()),
'meta' => [
'current_page' => $feedback->currentPage(),
'last_page' => $feedback->lastPage(),
'per_page' => $feedback->perPage(),
'total' => $feedback->total(),
]
]);
}
/**
* Get browser information from request
*/
private function getBrowserInfo(Request $request): array
{
return [
'user_agent' => $request->userAgent(),
'ip_address' => $request->ip(),
'referer' => $request->header('referer'),
'accept_language' => $request->header('accept-language'),
'screen_resolution' => $request->input('screen_resolution'),
'viewport_size' => $request->input('viewport_size'),
'timezone' => $request->input('timezone'),
];
}
/**
* Notify admins about new feedback submission
*/
private function notifyAdminsForNewFeedback(Feedback $feedback): void
{
try {
$adminRoles = ['PENTADBIR', 'PS 2 KJC', 'PS 2 ALAT'];
// Get users with specific roles plus admins (PENTADBIR and DEVELOPER)
$adminUsers = $this->getUsersWithRolesAndAdmins($adminRoles);
$sender = auth()->user() ?? $feedback->user; // Use current user as sender, or feedback submitter if no auth
foreach ($adminUsers as $admin) {
try {
$admin->notify(new FeedbackNotification($feedback, $sender));
} catch (Exception $e) {
Log::error('Failed to send feedback notification: '.$e->getMessage());
}
}
} catch (Exception $e) {
Log::error('Failed to notify admins for new feedback: '.$e->getMessage());
}
}
}
@@ -0,0 +1,83 @@
<?php
namespace Modules\Feedback\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FeedbackRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
$rules = [
'type' => 'required|in:bug,feature_request,general_feedback,ui_issue,performance_issue',
'title' => 'required|string|max:255',
'description' => 'required|string',
'priority' => 'required|in:low,medium,high,critical',
'page_url' => 'nullable|url',
'steps_to_reproduce' => 'nullable|string',
'expected_behavior' => 'nullable|string',
'actual_behavior' => 'nullable|string',
'additional_notes' => 'nullable|string',
'images' => 'nullable|array',
'images.*' => 'file|mimes:jpeg,png,jpg,gif,webp|max:10240', // 10MB max
'videos' => 'nullable|array',
'videos.*' => 'file|mimes:mp4,mov,webm|max:51200', // 50MB max
];
// For update operations, add admin-specific fields
if ($this->isMethod('PUT') || $this->isMethod('PATCH')) {
$rules = [
'type' => 'sometimes|in:bug,feature_request,general_feedback,ui_issue,performance_issue',
'title' => 'sometimes|string|max:255',
'description' => 'sometimes|string',
'priority' => 'sometimes|in:low,medium,high,critical',
'page_url' => 'nullable|url',
'steps_to_reproduce' => 'nullable|string',
'expected_behavior' => 'nullable|string',
'actual_behavior' => 'nullable|string',
'additional_notes' => 'nullable|string',
'status' => 'sometimes|in:open,in_progress,resolved,closed,rejected',
'assigned_to' => 'nullable|exists:users,id',
'admin_notes' => 'nullable|string',
];
}
return $rules;
}
/**
* Get custom messages for validator errors.
*/
public function messages(): array
{
return [
'type.required' => 'Jenis maklum balas diperlukan.',
'type.in' => 'Jenis maklum balas tidak sah.',
'title.required' => 'Tajuk diperlukan.',
'title.max' => 'Tajuk tidak boleh melebihi 255 aksara.',
'description.required' => 'Penerangan diperlukan.',
'priority.required' => 'Keutamaan diperlukan.',
'priority.in' => 'Keutamaan tidak sah.',
'page_url.url' => 'URL halaman tidak sah.',
'images.*.mimes' => 'Format imej mestilah jpeg, png, jpg, gif atau webp.',
'images.*.max' => 'Saiz imej tidak boleh melebihi 10MB.',
'videos.*.mimes' => 'Format video mestilah mp4, mov atau webm.',
'videos.*.max' => 'Saiz video tidak boleh melebihi 50MB.',
'status.in' => 'Status tidak sah.',
'assigned_to.exists' => 'Pengguna yang ditugaskan tidak wujud.',
];
}
}
View File
@@ -0,0 +1,66 @@
<?php
namespace Modules\Feedback\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Modules\Feedback\Entities\Feedback;
use Modules\Auth\Entities\User;
class FeedbackNotification extends Notification
{
use Queueable;
protected $feedback;
protected $sender;
/**
* Create a new notification instance.
*/
public function __construct(Feedback $feedback, User $sender = null)
{
$this->feedback = $feedback;
$this->sender = $sender;
}
/**
* Get the notification's delivery channels.
*/
public function via($notifiable): array
{
return ['database'];
}
/**
* Get the array representation of the notification.
*/
public function toArray($notifiable): array
{
return [
'feedback_id' => $this->feedback->id,
'sender_id' => $this->sender ? $this->sender->id : null,
'type' => 'feedback_submitted',
'message' => $this->getNotificationMessage(),
'feedback_title' => $this->feedback->title ?? 'Unknown',
'feedback_type' => $this->feedback->type ?? 'Unknown',
'feedback_priority' => $this->feedback->priority ?? 'normal',
'user_name' => $this->feedback->user ? $this->feedback->user->name : 'Anonymous',
'user_email' => $this->feedback->user ? $this->feedback->user->email : null,
];
}
/**
* Get notification message
*/
private function getNotificationMessage(): string
{
$userName = $this->feedback->user ? $this->feedback->user->name : 'Pengguna tanpa nama';
$feedbackTitle = $this->feedback->title ?? 'Unknown';
$feedbackType = $this->feedback->type ?? 'Unknown';
$feedbackPriority = $this->feedback->priority ?? 'normal';
$feedbackId = $this->feedback->id;
return "Maklum balas baru telah diterima. ID: {$feedbackId}, Tajuk: {$feedbackTitle}, Jenis: {$feedbackType}, Keutamaan: {$feedbackPriority}, Pengguna: {$userName}";
}
}
@@ -0,0 +1,59 @@
<?php
namespace Modules\Feedback\Policies;
use Illuminate\Auth\Access\HandlesAuthorization;
use Modules\Feedback\Entities\Feedback;
class FeedbackPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*/
public function viewAny($user): bool
{
return $user->hasPermissionTo('lihat maklum balas'); // Adjust based on your authorization logic
}
/**
* Determine whether the user can view the model.
*/
public function view($user, ?Feedback $feedback = null): bool
{
return $user->hasPermissionTo('lihat maklum balas'); // Adjust based on your authorization logic
}
/**
* Determine whether the user can create models.
*/
public function create($user): bool
{
return true;
}
/**
* Determine whether the user can update the model.
*/
public function update($user, ?Feedback $feedback = null): bool
{
return $user->hasPermissionTo('kemaskini maklum balas'); // Adjust based on your authorization logic
}
/**
* Determine whether the user can delete any model.
*/
public function deleteAny($user): bool
{
return $user->hasPermissionTo('padam maklum balas'); // Adjust based on your authorization logic
}
/**
* Determine whether the user can delete the model.
*/
public function delete($user, ?Feedback $feedback = null): bool
{
return $user->hasPermissionTo('padam maklum balas'); // Adjust based on your authorization logic
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\Feedback\Providers;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
/**
* The event handler mappings for the application.
*
* @var array<string, array<int, string>>
*/
protected $listen = [];
/**
* Indicates if events should be discovered.
*
* @var bool
*/
protected static $shouldDiscoverEvents = true;
/**
* Configure the proper event listeners for email verification.
*/
protected function configureEmailVerification(): void {}
}
@@ -0,0 +1,160 @@
<?php
namespace Modules\Feedback\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;
use Nwidart\Modules\Traits\PathNamespace;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
class FeedbackServiceProvider extends ServiceProvider
{
use PathNamespace;
protected string $name = 'Feedback';
protected string $nameLower = 'feedback';
/**
* Boot the application events.
*/
public function boot(): void
{
$this->registerCommands();
$this->registerCommandSchedules();
$this->registerTranslations();
$this->registerConfig();
$this->registerViews();
$this->loadMigrationsFrom(module_path($this->name, 'Database/Migrations'));
}
/**
* Register the service provider.
*/
public function register(): void
{
$this->app->register(EventServiceProvider::class);
$this->app->register(RouteServiceProvider::class);
// Register repository binding
$this->app->bind(
\Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface::class,
\Modules\Feedback\Repositories\FeedbackRepository::class
);
}
/**
* Register commands in the format of Command::class
*/
protected function registerCommands(): void
{
// $this->commands([]);
}
/**
* Register command Schedules.
*/
protected function registerCommandSchedules(): void
{
// $this->app->booted(function () {
// $schedule = $this->app->make(Schedule::class);
// $schedule->command('inspire')->hourly();
// });
}
/**
* Register translations.
*/
public function registerTranslations(): void
{
$langPath = resource_path('lang/modules/'.$this->nameLower);
if (is_dir($langPath)) {
$this->loadTranslationsFrom($langPath, $this->nameLower);
$this->loadJsonTranslationsFrom($langPath);
} else {
$this->loadTranslationsFrom(module_path($this->name, 'Lang'), $this->nameLower);
$this->loadJsonTranslationsFrom(module_path($this->name, 'Lang'));
}
}
/**
* Register config.
*/
protected function registerConfig(): void
{
$configPath = module_path($this->name, config('modules.paths.generator.config.path'));
if (is_dir($configPath)) {
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($configPath));
foreach ($iterator as $file) {
if ($file->isFile() && $file->getExtension() === 'php') {
$config = str_replace($configPath.DIRECTORY_SEPARATOR, '', $file->getPathname());
$config_key = str_replace([DIRECTORY_SEPARATOR, '.php'], ['.', ''], $config);
$segments = explode('.', $this->nameLower.'.'.$config_key);
// Remove duplicated adjacent segments
$normalized = [];
foreach ($segments as $segment) {
if (end($normalized) !== $segment) {
$normalized[] = $segment;
}
}
$key = ($config === 'config.php') ? $this->nameLower : implode('.', $normalized);
$this->publishes([$file->getPathname() => config_path($config)], 'config');
$this->merge_config_from($file->getPathname(), $key);
}
}
}
}
/**
* Merge config from the given path recursively.
*/
protected function merge_config_from(string $path, string $key): void
{
$existing = config($key, []);
$module_config = require $path;
config([$key => array_replace_recursive($existing, $module_config)]);
}
/**
* Register views.
*/
public function registerViews(): void
{
$viewPath = resource_path('views/modules/'.$this->nameLower);
$sourcePath = module_path($this->name, 'Resources/Views');
$this->publishes([$sourcePath => $viewPath], ['views', $this->nameLower.'-module-views']);
$this->loadViewsFrom(array_merge($this->getPublishableViewPaths(), [$sourcePath]), $this->nameLower);
Blade::componentNamespace(config('modules.namespace').'\\' . $this->name . '\\View\\Components', $this->nameLower);
}
/**
* Get the services provided by the provider.
*/
public function provides(): array
{
return [];
}
private function getPublishableViewPaths(): array
{
$paths = [];
foreach (config('view.paths') as $path) {
if (is_dir($path.'/modules/'.$this->nameLower)) {
$paths[] = $path.'/modules/'.$this->nameLower;
}
}
return $paths;
}
}
@@ -0,0 +1,39 @@
<?php
namespace Modules\Feedback\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
protected string $name = 'Feedback';
/**
* Called before routes are registered.
*
* Register any model bindings or pattern based filters.
*/
public function boot(): void
{
parent::boot();
}
/**
* Define the routes for the application.
*/
public function map(): void
{
$this->mapApiRoutes();
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*/
protected function mapApiRoutes(): void
{
Route::middleware('api')->group(module_path($this->name, '/Routes/api.php'));
}
}
@@ -0,0 +1,44 @@
<?php
namespace Modules\Feedback\Repositories\Contracts;
use Illuminate\Database\Eloquent\Collection;
use Modules\Feedback\Entities\Feedback;
interface FeedbackRepositoryInterface
{
/**
* Get all feedback with pagination and search
*/
public function getAllPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = []);
/**
* Get all feedback with their relationships and pagination with search
*/
public function getAllWithRelationsPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = []);
/**
* Get all feedback with their relationships and search
*/
public function getAllWithRelations(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection;
/**
* Create a new feedback
*/
public function create(array $data): Feedback;
/**
* Find feedback by ID
*/
public function findById(string $id): ?Feedback;
/**
* Delete feedback (soft delete)
*/
public function delete(string $id): bool;
/**
* Get all feedback
*/
public function all(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection;
}
@@ -0,0 +1,149 @@
<?php
namespace Modules\Feedback\Repositories;
use Illuminate\Database\Eloquent\Collection;
use Modules\Feedback\Entities\Feedback;
use Modules\Feedback\Repositories\Contracts\FeedbackRepositoryInterface;
class FeedbackRepository implements FeedbackRepositoryInterface
{
/**
* Get all feedback with pagination and search
*/
public function getAllPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = [])
{
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
if (!empty($search)) {
$query->where(function ($q) use ($search) {
$q->where('title', 'ILIKE', "%{$search}%")
->orWhere('description', 'ILIKE', "%{$search}%")
->orWhereHas('user', function ($userQuery) use ($search) {
$userQuery->where('name', 'ILIKE', "%{$search}%")
->orWhere('email', 'ILIKE', "%{$search}%");
});
});
}
// Apply filters
if (!empty($filters['type'])) {
$query->where('type', $filters['type']);
}
if (!empty($filters['status'])) {
$query->where('status', $filters['status']);
}
if (!empty($filters['priority'])) {
$query->where('priority', $filters['priority']);
}
return $query->paginate($perPage);
}
/**
* Get all feedback with their relationships and pagination with search
*/
public function getAllWithRelationsPaginated(int $perPage = 10, string $search = '', string $sortBy = 'id', string $sortOrder = 'asc', array $filters = [])
{
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
if (!empty($search)) {
$query->where(function ($q) use ($search) {
$q->where('title', 'ILIKE', "%{$search}%")
->orWhere('description', 'ILIKE', "%{$search}%")
->orWhereHas('user', function ($userQuery) use ($search) {
$userQuery->where('name', 'ILIKE', "%{$search}%")
->orWhere('email', 'ILIKE', "%{$search}%");
});
});
}
// Apply filters
if (!empty($filters['type'])) {
$query->where('type', $filters['type']);
}
if (!empty($filters['status'])) {
$query->where('status', $filters['status']);
}
if (!empty($filters['priority'])) {
$query->where('priority', $filters['priority']);
}
return $query->paginate($perPage);
}
/**
* Get all feedback with their relationships and search
*/
public function getAllWithRelations(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection
{
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
if (!empty($search)) {
$query->where(function ($q) use ($search) {
$q->where('title', 'ILIKE', "%{$search}%")
->orWhere('description', 'ILIKE', "%{$search}%")
->orWhereHas('user', function ($userQuery) use ($search) {
$userQuery->where('name', 'ILIKE', "%{$search}%")
->orWhere('email', 'ILIKE', "%{$search}%");
});
});
}
return $query->get();
}
/**
* Create a new feedback
*/
public function create(array $data): Feedback
{
return Feedback::create($data);
}
/**
* Find feedback by ID
*/
public function findById(string $id): ?Feedback
{
return Feedback::with(['user', 'assignedUser', 'documents'])->find($id);
}
/**
* Delete feedback (soft delete)
*/
public function delete(string $id): bool
{
$feedback = Feedback::find($id);
if ($feedback) {
return $feedback->delete();
}
return false;
}
/**
* Get all feedback
*/
public function all(string $search = '', string $sortBy = 'id', string $sortOrder = 'asc'): Collection
{
$query = Feedback::with(['user', 'assignedUser', 'documents'])->orderBy($sortBy, $sortOrder);
if (!empty($search)) {
$query->where(function ($q) use ($search) {
$q->where('title', 'ILIKE', "%{$search}%")
->orWhere('description', 'ILIKE', "%{$search}%")
->orWhereHas('user', function ($userQuery) use ($search) {
$userQuery->where('name', 'ILIKE', "%{$search}%")
->orWhere('email', 'ILIKE', "%{$search}%");
});
});
}
return $query->get();
}
}
View File
+20
View File
@@ -0,0 +1,20 @@
<?php
use Illuminate\Support\Facades\Route;
use Modules\Feedback\Http\Controllers\FeedbackController;
// Public feedback submission (no authentication required)
Route::post('/v1/feedback', [FeedbackController::class, 'store'])->name('feedback.store');
// Authenticated feedback routes
Route::middleware(['auth:sanctum'])->prefix('v1')->group(function () {
Route::get('/feedback', [FeedbackController::class, 'index'])->name('feedback.index');
Route::get('/feedback/{id}', [FeedbackController::class, 'show'])->name('feedback.show');
Route::put('/feedback/{id}', [FeedbackController::class, 'update'])->name('feedback.update');
Route::patch('/feedback/{id}', [FeedbackController::class, 'update'])->name('feedback.patch');
Route::delete('/feedback/{id}', [FeedbackController::class, 'destroy'])->name('feedback.destroy');
Route::get('/feedback-statistics', [FeedbackController::class, 'statistics'])->name('feedback.statistics');
Route::get('/my-feedback', [FeedbackController::class, 'myFeedback'])->name('feedback.my');
Route::get('/feedback/{id}/documents/{documentId}/download', [FeedbackController::class, 'serveDocument'])
->name('feedback.download-document');
});
@@ -0,0 +1,79 @@
<?php
namespace Modules\Feedback\Transformers;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Feedback\Entities\Feedback;
class FeedbackResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'type' => $this->type,
'title' => $this->title,
'description' => $this->description,
'priority' => $this->priority,
'status' => $this->status,
'page_url' => $this->page_url,
'browser_info' => $this->browser_info,
'images' => $this->whenLoaded('documents', function () {
return $this->documents
->where('type', Feedback::IMAGE_DOCUMENT_TYPE)
->values()
->map(fn ($document) => $this->formatDocument($document));
}),
'videos' => $this->whenLoaded('documents', function () {
return $this->documents
->where('type', Feedback::VIDEO_DOCUMENT_TYPE)
->values()
->map(fn ($document) => $this->formatDocument($document));
}),
'steps_to_reproduce' => $this->steps_to_reproduce,
'expected_behavior' => $this->expected_behavior,
'actual_behavior' => $this->actual_behavior,
'additional_notes' => $this->additional_notes,
'admin_notes' => $this->admin_notes,
'resolved_at' => $this->resolved_at,
'user' => $this->whenLoaded('user', function () {
return [
'id' => $this->user->id,
'name' => $this->user->name,
'email' => $this->user->email,
'army_number' => $this->user->army_number,
];
}),
'assigned_user' => $this->whenLoaded('assignedUser', function () {
return [
'id' => $this->assignedUser->id,
'name' => $this->assignedUser->name,
'email' => $this->assignedUser->email,
];
}),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
protected function formatDocument($document): array
{
return [
'id' => $document->id,
'name' => $document->name,
'mime_type' => $document->mime_type,
'file_size' => $document->file_size,
'type' => $document->type,
'url' => url(route('feedback.download-document', [
'id' => $this->id,
'documentId' => $document->id,
])),
];
}
}
+30
View File
@@ -0,0 +1,30 @@
{
"name": "nwidart/feedback",
"description": "",
"authors": [
{
"name": "Nicolas Widart",
"email": "n.widart@gmail.com"
}
],
"extra": {
"laravel": {
"providers": [],
"aliases": {
}
}
},
"autoload": {
"psr-4": {
"Modules\\Feedback\\": "App",
"Modules\\Feedback\\Database\\Factories\\": "database/factories/",
"Modules\\Feedback\\Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Modules\\Feedback\\Tests\\": "tests/"
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "Feedback",
"alias": "feedback",
"description": "",
"keywords": [],
"priority": 0,
"providers": [
"Modules\\Feedback\\Providers\\FeedbackServiceProvider",
"Modules\\Feedback\\Providers\\RouteServiceProvider"
],
"files": []
}
+15
View File
@@ -0,0 +1,15 @@
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"axios": "^1.1.2",
"laravel-vite-plugin": "^0.7.5",
"sass": "^1.69.5",
"postcss": "^8.3.7",
"vite": "^4.0.0"
}
}