first init

This commit is contained in:
ISMAIL MASSERAN
2026-06-08 11:37:14 +08:00
commit 94ecbe5887
1058 changed files with 87732 additions and 0 deletions
@@ -0,0 +1,210 @@
<?php
namespace Modules\User\Http\Controllers;
use App\Http\Controllers\BaseCrudController;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Modules\Auth\Entities\User;
use Modules\User\Http\Requests\UserRequest;
use Modules\User\Repositories\Contracts\UserRepositoryInterface;
use Modules\User\Services\UserService;
use Modules\User\Transformers\UserResource;
use Modules\User\Transformers\UserListResource;
class UserController extends BaseCrudController
{
protected $modelClass = User::class;
protected $resourceClass = UserResource::class;
protected $requestClass = UserRequest::class;
protected $resourceName = 'user';
protected $resourceNamePlural = 'users';
public function __construct(
UserRepositoryInterface $repository,
protected UserService $userService
) {
parent::__construct($repository);
}
/**
* Prepare data for store method
*/
protected function prepareStoreData(array $validated): array
{
$validated['uuid'] = Str::uuid();
$validated['password'] = Hash::make('suteraselamanya');
return $validated;
}
/**
* Prepare data for update method
*/
protected function prepareUpdateData(array $validated, $user): array
{
unset($validated['uuid']);
if (! array_key_exists('email', $validated)) {
unset($validated['email']);
}
return $validated;
}
/**
* Check dependencies before deletion
*/
protected function checkDependencies($user): ?JsonResponse
{
return null;
}
public function assignRoles(Request $request, $id): JsonResponse
{
$request->validate([
'roles' => 'required|array',
'roles.*' => 'exists:roles,id,guard_name,api',
]);
$result = $this->userService->assignRoles($id, $request->roles);
if (isset($result['error'])) {
$status = $result['error'] === 'User not found.' ? 404 : 400;
return response()->json([
'success' => false,
'message' => $result['error'],
], $status);
}
return response()->json([
'success' => true,
'message' => 'Roles assigned successfully.',
'data' => (new UserResource($result['user']))->resolve(),
]);
}
public function updateProfile(Request $request): JsonResponse
{
$user = $request->user();
$validated = $request->validate([
'name' => 'sometimes|string|max:255',
'ic_number' => 'sometimes|string|max:255|unique:users,ic_number,'.$user->id,
'position' => 'sometimes|string|max:255',
'phone_number' => 'sometimes|string|max:255',
'image' => 'sometimes|image|mimes:jpeg,png,jpg,gif|max:2048',
'image_url' => 'sometimes|string|max:255',
]);
$user = $this->userService->updateProfile(
$user,
$validated,
$request->file('image')
);
return response()->json([
'success' => true,
'data' => new UserResource($user),
'message' => 'Profile updated successfully.',
]);
}
public function updatePassword(Request $request): JsonResponse
{
$user = $request->user();
$validated = $request->validate([
'current_password' => 'required|string',
'password' => 'required|string|min:8|confirmed',
]);
$result = $this->userService->updatePassword(
$user,
$validated['current_password'],
$validated['password']
);
if (isset($result['error'])) {
return response()->json([
'success' => false,
'message' => $result['error'],
], 400);
}
return response()->json([
'success' => true,
'message' => 'Password updated successfully.',
]);
}
public function index(Request $request): JsonResponse
{
$this->authorize('viewAny', $this->modelClass);
try {
$perPage = min((int) $request->get('per_page', 10), 500);
$items = $this->userService->getPaginatedList(
$perPage,
$request->get('search', ''),
$request->get('status', ''),
$request->get('sort_by', 'id'),
$request->get('sort_order', 'asc')
);
return response()->json([
'success' => true,
'data' => UserListResource::collection($items->items()),
'pagination' => [
'current_page' => $items->currentPage(),
'per_page' => $items->perPage(),
'total' => $items->total(),
'last_page' => $items->lastPage(),
'from' => $items->firstItem(),
'to' => $items->lastItem(),
'has_more_pages' => $items->hasMorePages(),
],
'message' => $this->getSuccessMessage('index'),
]);
} catch (Exception $e) {
Log::error("Error fetching {$this->resourceNamePlural}: ".$e->getMessage());
return $this->errorResponse($this->getErrorMessage('index'), 500);
}
}
public function show($id): JsonResponse
{
$this->authorize('view', $this->modelClass);
try {
$user = $this->userService->getUserWithRelations($id);
if (! $user) {
return response()->json([
'success' => false,
'message' => 'User not found.',
], 404);
}
return response()->json([
'success' => true,
'data' => new UserResource($user),
'message' => 'User retrieved successfully.',
]);
} catch (Exception $e) {
Log::error('Error fetching user: '.$e->getMessage());
return $this->errorResponse('Failed to retrieve user.', 500);
}
}
}
@@ -0,0 +1,110 @@
<?php
namespace Modules\User\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest 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
{
// Get the user ID from the route (with null check)
$userId = $this->route() ? $this->route('user') : null;
// Check if this is a create or update operation
$isCreate = $this->isMethod('POST');
$isUpdate = $this->isMethod('PUT') || $this->isMethod('PATCH');
// If this is not a POST, PUT, or PATCH request, return minimal rules
if (! $isCreate && ! $isUpdate) {
return [
'name' => 'nullable|string|max:255',
'email' => 'nullable|string|email|max:255',
'password' => 'nullable|string|min:8',
'ic_number' => 'nullable|string|max:255',
'position' => 'nullable|string|max:255',
'phone_number' => 'nullable|string|max:255',
'image_url' => 'nullable|string|max:255',
'status' => 'nullable|string',
];
}
// Build unique email validation rule
$emailUniqueRule = $userId ? 'unique:users,email,'.$userId : 'unique:users,email';
// If this is an update operation, make email and password optional
if ($isUpdate) {
return [
'name' => 'required|string|max:255',
// 'email' => [
// 'nullable',
// 'string',
// 'email',
// 'max:255',
// $emailUniqueRule,
// ],
'password' => 'nullable|string|min:8',
'ic_number' => 'required|string|max:255',
'position' => 'required|string|max:255',
'phone_number' => 'nullable|string|max:255',
'image_url' => 'nullable|string|max:255',
'status' => 'nullable|string',
];
}
// Default rules for create operations
return [
'name' => 'required|string|max:255',
'email' => [
'required',
'string',
'email',
'max:255',
$emailUniqueRule,
],
'password' => 'nullable|string|min:8',
'ic_number' => 'required|string|max:255',
'position' => 'required|string|max:255',
'phone_number' => 'nullable|string|max:255',
'image_url' => 'nullable|string|max:255',
'status' => 'required|string',
];
}
/**
* Get custom messages for validator errors.
*/
public function messages(): array
{
return [
'name.required' => 'Nama diperlukan.',
'name.max' => 'Nama tidak boleh melebihi 255 aksara.',
'email.required' => 'Email diperlukan.',
'email.email' => 'Email tidak sah.',
'email.max' => 'Email tidak boleh melebihi 255 aksara.',
'email.unique' => 'Email sudah wujud.',
'password.nullable' => 'Kata laluan diperlukan.',
'ic_number.required' => 'Nombor Kad Pengenalan diperlukan.',
'ic_number.max' => 'Nombor Kad Pengenalan tidak boleh melebihi 255 aksara.',
'position.required' => 'Posisi diperlukan.',
'position.max' => 'Posisi tidak boleh melebihi 255 aksara.',
'phone_number.max' => 'Nombor telefon tidak boleh melebihi 255 aksara.',
'image_url.max' => 'URL imej tidak boleh melebihi 255 aksara.',
'status.required' => 'Status diperlukan.',
'status.string' => 'Status aktif tidak sah.',
];
}
}