3 Commits

Author SHA1 Message Date
ismailmasseran 1e50e3d19f Merge pull request 'DONE: merge heir tab into profile tab, santize userIcNum and name, rename to malay, add stat card on user list' (#10) from feature/stat-card-on-users into main
Build Docker Image / build-backend (push) Successful in 54s
Build Docker Image / build-frontend (push) Successful in 20s
Reviewed-on: #10
2026-07-09 12:48:57 +08:00
ISMAIL MASSERAN af7f47bf71 DONE: merge heir tab into profile tab, santize userIcNum and name, rename to malay, add stat card on user list 2026-07-09 12:48:26 +08:00
ismailmasseran ebd3caecc6 DONE: use full name for date in letter, include password in email after membership is done, block ic_number to exclude - (#9)
Build Docker Image / build-backend (push) Successful in 44s
Build Docker Image / build-frontend (push) Successful in 18s
Co-authored-by: ISMAIL MASSERAN <topaz@ISMAILs-Macbook.local>
Reviewed-on: #9
2026-07-08 12:15:41 +08:00
41 changed files with 866 additions and 571 deletions
+2
View File
@@ -54,6 +54,7 @@ class User extends Authenticatable
'member_type', 'member_type',
'public_profile_token', 'public_profile_token',
'join_date', 'join_date',
'leave_date',
'birth_date', 'birth_date',
'birth_place', 'birth_place',
'onboarding_completed_at', 'onboarding_completed_at',
@@ -136,6 +137,7 @@ class User extends Authenticatable
'member_type' => 'string', 'member_type' => 'string',
'public_profile_token_expires_at' => 'datetime', 'public_profile_token_expires_at' => 'datetime',
'join_date' => 'date', 'join_date' => 'date',
'leave_date' => 'date',
'birth_date' => 'date', 'birth_date' => 'date',
'birth_place' => 'string', 'birth_place' => 'string',
'onboarding_completed_at' => 'datetime', 'onboarding_completed_at' => 'datetime',
@@ -38,6 +38,7 @@ class UserResource extends JsonResource
'member_type' => $this->member_type, 'member_type' => $this->member_type,
'public_profile_token' => $this->public_profile_token, 'public_profile_token' => $this->public_profile_token,
'join_date' => $this->join_date, 'join_date' => $this->join_date,
'leave_date' => $this->leave_date,
'birth_date' => $this->birth_date, 'birth_date' => $this->birth_date,
'birth_place' => $this->birth_place, 'birth_place' => $this->birth_place,
'onboarding_completed_at' => $this->onboarding_completed_at, 'onboarding_completed_at' => $this->onboarding_completed_at,
@@ -19,6 +19,7 @@ class MembershipApplicationPassedNotification extends Notification implements Sh
public function __construct( public function __construct(
public MembershipApplication $application, public MembershipApplication $application,
public Document $resultLetter, public Document $resultLetter,
public ?string $plainPassword = null,
) {} ) {}
/** /**
@@ -40,6 +41,8 @@ class MembershipApplicationPassedNotification extends Notification implements Sh
data: [ data: [
'application' => $this->application, 'application' => $this->application,
'applicant' => $applicant, 'applicant' => $applicant,
'plainPassword' => $this->plainPassword,
'loginUrl' => rtrim(config('user.frontend_url'), '/'),
], ],
)->attach( )->attach(
Storage::disk(Document::STORAGE_DISK)->path($this->resultLetter->path), Storage::disk(Document::STORAGE_DISK)->path($this->resultLetter->path),
@@ -9,6 +9,15 @@ Permohonan keahlian anda (**{{ $application->application_number }}**) **dilulusk
Surat keputusan rasmi dilampirkan dalam e-mel ini. Surat keputusan rasmi dilampirkan dalam e-mel ini.
@if ($plainPassword)
Akaun portal anda telah didaftarkan. Maklumat log masuk adalah seperti berikut:
- **E-mel:** {{ $applicant->email }}
- **Kata laluan:** {{ $plainPassword }}
Sila log masuk di [{{ $loginUrl }}]({{ $loginUrl }}) dan tukar kata laluan anda selepas log masuk kali pertama.
@endif
Terima kasih atas minat anda. Untuk sebarang pertanyaan, sila hubungi pejabat koperasi. Terima kasih atas minat anda. Untuk sebarang pertanyaan, sila hubungi pejabat koperasi.
@include('emails.partials.footer') @include('emails.partials.footer')
@@ -274,15 +274,18 @@ class MembershipApplicationService
} }
return DB::transaction(function () use ($application, $boardMeetingReference, $boardMeetingDate) { return DB::transaction(function () use ($application, $boardMeetingReference, $boardMeetingDate) {
$plainPassword = null;
if ($application->board_result === BoardResult::Pass->value && ! $application->user_id) { if ($application->board_result === BoardResult::Pass->value && ! $application->user_id) {
$user = $this->createMemberFromApplication($application); $member = $this->createMemberFromApplication($application);
$application->update(['user_id' => $user->id]); $application->update(['user_id' => $member['user']->id]);
$plainPassword = $member['plainPassword'];
$application->refresh(); $application->refresh();
} }
$resultLetter = $this->storeResultLetter($application, $boardMeetingReference, $boardMeetingDate); $resultLetter = $this->storeResultLetter($application, $boardMeetingReference, $boardMeetingDate);
$this->sendResultNotification($application, $resultLetter); $this->sendResultNotification($application, $resultLetter, $plainPassword);
$application->update([ $application->update([
'status' => ApplicationStatus::Completed, 'status' => ApplicationStatus::Completed,
@@ -438,7 +441,7 @@ class MembershipApplicationService
'application' => $application, 'application' => $application,
'applicant' => $applicant, 'applicant' => $applicant,
'boardMeetingReference' => $boardMeetingReference, 'boardMeetingReference' => $boardMeetingReference,
'boardMeetingDate' => Carbon::parse($boardMeetingDate)->translatedFormat('d M Y'), 'boardMeetingDate' => Carbon::parse($boardMeetingDate)->translatedFormat('d F Y'),
'isPassed' => $isPassed, 'isPassed' => $isPassed,
'letterSubject' => $isPassed 'letterSubject' => $isPassed
? 'KELULUSAN PERMOHONAN MENJADI ANGGOTA KOPERASI PERMODALAN KELANTAN BERHAD (KoPKB)' ? 'KELULUSAN PERMOHONAN MENJADI ANGGOTA KOPERASI PERMODALAN KELANTAN BERHAD (KoPKB)'
@@ -447,7 +450,10 @@ class MembershipApplicationService
]; ];
} }
protected function createMemberFromApplication(MembershipApplication $application): User /**
* @return array{user: User, plainPassword: string}
*/
protected function createMemberFromApplication(MembershipApplication $application): array
{ {
$application->loadMissing(['applicant', 'heirs']); $application->loadMissing(['applicant', 'heirs']);
$applicant = $application->applicant; $applicant = $application->applicant;
@@ -458,10 +464,12 @@ class MembershipApplicationService
]); ]);
} }
$plainPassword = Str::password(16);
$user = User::create([ $user = User::create([
'name' => $applicant->name, 'name' => $applicant->name,
'email' => $applicant->email, 'email' => $applicant->email,
'password' => Hash::make(Str::password(16)), 'password' => Hash::make($plainPassword),
'ic_number' => $applicant->ic_number, 'ic_number' => $applicant->ic_number,
'phone_number' => $applicant->phone_number, 'phone_number' => $applicant->phone_number,
'position' => $applicant->current_position, 'position' => $applicant->current_position,
@@ -507,7 +515,10 @@ class MembershipApplicationService
app(EmailVerificationOtpService::class)->send($user); app(EmailVerificationOtpService::class)->send($user);
return $user; return [
'user' => $user,
'plainPassword' => $plainPassword,
];
} }
public function lookupMemberByIcNumber(string $icNumber): ?User public function lookupMemberByIcNumber(string $icNumber): ?User
@@ -532,12 +543,15 @@ class MembershipApplicationService
->notify(new MembershipApplicationSubmittedNotification($application)); ->notify(new MembershipApplicationSubmittedNotification($application));
} }
protected function sendResultNotification(MembershipApplication $application, Document $resultLetter): void protected function sendResultNotification(
{ MembershipApplication $application,
Document $resultLetter,
?string $plainPassword = null,
): void {
$application->loadMissing('applicant'); $application->loadMissing('applicant');
$notification = $application->board_result === BoardResult::Pass->value $notification = $application->board_result === BoardResult::Pass->value
? new MembershipApplicationPassedNotification($application, $resultLetter) ? new MembershipApplicationPassedNotification($application, $resultLetter, $plainPassword)
: new MembershipApplicationFailedNotification($application, $resultLetter); : new MembershipApplicationFailedNotification($application, $resultLetter);
Notification::route('mail', $application->applicant->email)->notify($notification); Notification::route('mail', $application->applicant->email)->notify($notification);
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->date('leave_date')->nullable()->after('join_date');
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('leave_date');
});
}
};
@@ -44,7 +44,7 @@ class UserController extends BaseCrudController
$validated['uuid'] = Str::uuid(); $validated['uuid'] = Str::uuid();
$validated['password'] = Hash::make('suteraselamanya'); $validated['password'] = Hash::make('suteraselamanya');
return $validated; return $this->applyLeaveDateForStatus($validated);
} }
/** /**
@@ -58,6 +58,25 @@ class UserController extends BaseCrudController
unset($validated['email']); unset($validated['email']);
} }
return $this->applyLeaveDateForStatus($validated, $user);
}
/**
* Set or clear leave_date based on membership status transitions.
*/
protected function applyLeaveDateForStatus(array $validated, ?User $user = null): array
{
$newStatus = $validated['status'] ?? $user?->status;
$currentStatus = $user?->status;
if ($newStatus === 'inactive') {
if ($currentStatus !== 'inactive') {
$validated['leave_date'] = $validated['leave_date'] ?? now()->toDateString();
}
} elseif (in_array($newStatus, ['active', 'pending'], true)) {
$validated['leave_date'] = null;
}
return $validated; return $validated;
} }
@@ -171,13 +190,27 @@ class UserController extends BaseCrudController
$this->authorize('viewAny', $this->modelClass); $this->authorize('viewAny', $this->modelClass);
try { try {
$request->validate([
'join_date_from' => 'nullable|date',
'join_date_to' => 'nullable|date',
'leave_date_from' => 'nullable|date',
'leave_date_to' => 'nullable|date',
]);
$perPage = min((int) $request->get('per_page', 10), 500); $perPage = min((int) $request->get('per_page', 10), 500);
$dateFilters = array_filter([
'join_date_from' => $request->get('join_date_from'),
'join_date_to' => $request->get('join_date_to'),
'leave_date_from' => $request->get('leave_date_from'),
'leave_date_to' => $request->get('leave_date_to'),
]);
$items = $this->userService->getPaginatedList( $items = $this->userService->getPaginatedList(
$perPage, $perPage,
$request->get('search', ''), $request->get('search', ''),
$request->get('status', ''), $request->get('status', ''),
$request->get('sort_by', 'id'), $request->get('sort_by', 'id'),
$request->get('sort_order', 'asc') $request->get('sort_order', 'asc'),
$dateFilters
); );
return response()->json([ return response()->json([
@@ -236,6 +269,43 @@ class UserController extends BaseCrudController
} }
} }
public function stats(Request $request): JsonResponse
{
$this->authorize('viewAny', $this->modelClass);
try {
$request->validate([
'join_date_from' => 'nullable|date',
'join_date_to' => 'nullable|date',
'leave_date_from' => 'nullable|date',
'leave_date_to' => 'nullable|date',
]);
$dateFilters = array_filter([
'join_date_from' => $request->get('join_date_from'),
'join_date_to' => $request->get('join_date_to'),
'leave_date_from' => $request->get('leave_date_from'),
'leave_date_to' => $request->get('leave_date_to'),
]);
$stats = $this->userService->getListStats(
$request->get('search', ''),
$request->get('status', ''),
$dateFilters
);
return response()->json([
'success' => true,
'data' => $stats,
'message' => 'User stats retrieved successfully.',
]);
} catch (Exception $e) {
Log::error("Error fetching {$this->resourceNamePlural} stats: ".$e->getMessage());
return $this->errorResponse('Failed to retrieve user stats.', 500);
}
}
public function restore(string $id): JsonResponse public function restore(string $id): JsonResponse
{ {
$this->authorize('restore', $this->modelClass); $this->authorize('restore', $this->modelClass);
@@ -44,6 +44,7 @@ class UserRequest extends FormRequest
'member_number' => 'required|integer', 'member_number' => 'required|integer',
'member_type' => 'required|string|max:255', 'member_type' => 'required|string|max:255',
'join_date' => 'nullable|date', 'join_date' => 'nullable|date',
'leave_date' => 'nullable|date',
'birth_date' => 'nullable|date', 'birth_date' => 'nullable|date',
'birth_place' => 'nullable|string|max:255', 'birth_place' => 'nullable|string|max:255',
]; ];
@@ -74,6 +75,7 @@ class UserRequest extends FormRequest
'member_number' => 'required|integer', 'member_number' => 'required|integer',
'member_type' => 'required|string|max:255', 'member_type' => 'required|string|max:255',
'join_date' => 'nullable|date', 'join_date' => 'nullable|date',
'leave_date' => 'nullable|date',
'birth_date' => 'nullable|date', 'birth_date' => 'nullable|date',
'birth_place' => 'nullable|string|max:255', 'birth_place' => 'nullable|string|max:255',
]; ];
@@ -100,6 +102,7 @@ class UserRequest extends FormRequest
'member_number' => 'required|integer', 'member_number' => 'required|integer',
'member_type' => 'required|string|max:255', 'member_type' => 'required|string|max:255',
'join_date' => 'required|date', 'join_date' => 'required|date',
'leave_date' => 'nullable|date',
'birth_date' => 'required|date', 'birth_date' => 'required|date',
'birth_place' => 'required|string|max:255', 'birth_place' => 'required|string|max:255',
]; ];
@@ -136,6 +139,7 @@ class UserRequest extends FormRequest
'member_type.max' => 'Jenis anggota tidak boleh melebihi 255 aksara.', 'member_type.max' => 'Jenis anggota tidak boleh melebihi 255 aksara.',
'join_date.required' => 'Tarikh join diperlukan.', 'join_date.required' => 'Tarikh join diperlukan.',
'join_date.date' => 'Tarikh join tidak sah.', 'join_date.date' => 'Tarikh join tidak sah.',
'leave_date.date' => 'Tarikh berhenti tidak sah.',
'birth_date.required' => 'Tarikh lahir diperlukan.', 'birth_date.required' => 'Tarikh lahir diperlukan.',
'birth_date.date' => 'Tarikh lahir tidak sah.', 'birth_date.date' => 'Tarikh lahir tidak sah.',
'birth_place.required' => 'Tempat lahir diperlukan.', 'birth_place.required' => 'Tempat lahir diperlukan.',
@@ -20,7 +20,8 @@ interface UserRepositoryInterface
string $search = '', string $search = '',
string $status = '', string $status = '',
string $sortBy = 'name', string $sortBy = 'name',
string $sortOrder = 'asc' string $sortOrder = 'asc',
array $dateFilters = []
); );
/** /**
@@ -54,6 +55,17 @@ interface UserRepositoryInterface
string $sortOrder = 'desc' string $sortOrder = 'desc'
); );
/**
* Get stats for the Users list (filtered).
*
* @return array{total: int, joined_this_month: int}
*/
public function getListStats(
string $search = '',
string $status = '',
array $dateFilters = []
): array;
/** /**
* Find soft-deleted User by ID * Find soft-deleted User by ID
*/ */
@@ -3,6 +3,7 @@
namespace Modules\User\Repositories; namespace Modules\User\Repositories;
use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Carbon;
use Modules\Auth\Entities\User; use Modules\Auth\Entities\User;
use Modules\User\Repositories\Contracts\UserRepositoryInterface; use Modules\User\Repositories\Contracts\UserRepositoryInterface;
@@ -26,6 +27,25 @@ class UserRepository implements UserRepositoryInterface
}); });
} }
private function applyDateRangeFilters($query, array $dateFilters): void
{
if (! empty($dateFilters['join_date_from'])) {
$query->whereDate('join_date', '>=', $dateFilters['join_date_from']);
}
if (! empty($dateFilters['join_date_to'])) {
$query->whereDate('join_date', '<=', $dateFilters['join_date_to']);
}
if (! empty($dateFilters['leave_date_from'])) {
$query->whereDate('leave_date', '>=', $dateFilters['leave_date_from']);
}
if (! empty($dateFilters['leave_date_to'])) {
$query->whereDate('leave_date', '<=', $dateFilters['leave_date_to']);
}
}
/** /**
* Get all Users with pagination and search * Get all Users with pagination and search
*/ */
@@ -46,7 +66,8 @@ class UserRepository implements UserRepositoryInterface
string $search = '', string $search = '',
string $status = '', string $status = '',
string $sortBy = 'name', string $sortBy = 'name',
string $sortOrder = 'asc' string $sortOrder = 'asc',
array $dateFilters = []
) { ) {
$allowedSortColumns = [ $allowedSortColumns = [
'id', 'id',
@@ -55,6 +76,8 @@ class UserRepository implements UserRepositoryInterface
'position', 'position',
'status', 'status',
'member_number', 'member_number',
'join_date',
'leave_date',
'created_at', 'created_at',
'deleted_at', 'deleted_at',
]; ];
@@ -63,7 +86,18 @@ class UserRepository implements UserRepositoryInterface
$query = User::excludeDevelopersUnlessDeveloper() $query = User::excludeDevelopersUnlessDeveloper()
->with([ ->with([
'roles:id,name,guard_name' 'roles:id,name,guard_name',
'employments' => function ($q) {
$q->select([
'id',
'user_id',
'company_name',
'is_current',
'start_date',
])
->orderByDesc('is_current')
->orderByDesc('start_date');
},
]) ])
->orderBy($sortBy, $sortOrder); ->orderBy($sortBy, $sortOrder);
@@ -73,6 +107,8 @@ class UserRepository implements UserRepositoryInterface
$query->where('status', $status); $query->where('status', $status);
} }
$this->applyDateRangeFilters($query, $dateFilters);
return $query->paginate($perPage); return $query->paginate($perPage);
} }
@@ -93,6 +129,8 @@ class UserRepository implements UserRepositoryInterface
'position', 'position',
'status', 'status',
'member_number', 'member_number',
'join_date',
'leave_date',
'created_at', 'created_at',
'deleted_at', 'deleted_at',
]; ];
@@ -103,6 +141,17 @@ class UserRepository implements UserRepositoryInterface
->excludeDevelopersUnlessDeveloper() ->excludeDevelopersUnlessDeveloper()
->with([ ->with([
'roles:id,name,guard_name', 'roles:id,name,guard_name',
'employments' => function ($q) {
$q->select([
'id',
'user_id',
'company_name',
'is_current',
'start_date',
])
->orderByDesc('is_current')
->orderByDesc('start_date');
},
]) ])
->orderBy($sortBy, $sortOrder); ->orderBy($sortBy, $sortOrder);
@@ -115,6 +164,36 @@ class UserRepository implements UserRepositoryInterface
return $query->paginate($perPage); return $query->paginate($perPage);
} }
public function getListStats(
string $search = '',
string $status = '',
array $dateFilters = []
): array {
$baseQuery = User::excludeDevelopersUnlessDeveloper();
$this->applySearch($baseQuery, $search);
if (! empty($status)) {
$baseQuery->where('status', $status);
}
$this->applyDateRangeFilters($baseQuery, $dateFilters);
$total = (int) (clone $baseQuery)->count();
$monthStart = Carbon::now()->startOfMonth()->toDateString();
$monthEnd = Carbon::now()->endOfMonth()->toDateString();
$joinedThisMonth = (int) (clone $baseQuery)
->whereDate('join_date', '>=', $monthStart)
->whereDate('join_date', '<=', $monthEnd)
->count();
return [
'total' => $total,
'joined_this_month' => $joinedThisMonth,
];
}
/** /**
* Get all Users with their relationships and search * Get all Users with their relationships and search
*/ */
+1
View File
@@ -19,6 +19,7 @@ Route::prefix('v1/public')->group(function () {
Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () { Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () {
Route::get('users/deleted', [UserController::class, 'deletedIndex'])->name('users.deleted.index'); Route::get('users/deleted', [UserController::class, 'deletedIndex'])->name('users.deleted.index');
Route::get('users/stats', [UserController::class, 'stats'])->name('users.stats');
Route::post('users/{id}/restore', [UserController::class, 'restore'])->name('users.restore'); Route::post('users/{id}/restore', [UserController::class, 'restore'])->name('users.restore');
Route::apiResource('users', UserController::class)->names('user'); Route::apiResource('users', UserController::class)->names('user');
Route::apiResource('addresses', AddressController::class)->names('address'); Route::apiResource('addresses', AddressController::class)->names('address');
+12 -2
View File
@@ -21,14 +21,16 @@ class UserService
string $search, string $search,
string $status, string $status,
string $sortBy, string $sortBy,
string $sortOrder string $sortOrder,
array $dateFilters = []
): LengthAwarePaginator { ): LengthAwarePaginator {
return $this->repository->getAllWithRelationsPaginated( return $this->repository->getAllWithRelationsPaginated(
$perPage, $perPage,
$search, $search,
$status, $status,
$sortBy, $sortBy,
$sortOrder $sortOrder,
$dateFilters
); );
} }
@@ -48,6 +50,14 @@ class UserService
); );
} }
/**
* @return array{total: int, joined_this_month: int}
*/
public function getListStats(string $search, string $status, array $dateFilters = []): array
{
return $this->repository->getListStats($search, $status, $dateFilters);
}
public function restoreUser(string $id): ?User public function restoreUser(string $id): ?User
{ {
if (! $this->repository->restore($id)) { if (! $this->repository->restore($id)) {
@@ -5,6 +5,7 @@ namespace Modules\User\Transformers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Storage;
use Modules\User\Transformers\EmploymentResource;
class UserListResource extends JsonResource class UserListResource extends JsonResource
{ {
@@ -25,11 +26,13 @@ class UserListResource extends JsonResource
'member_number' => $this->member_number, 'member_number' => $this->member_number,
'member_type' => $this->member_type, 'member_type' => $this->member_type,
'join_date' => $this->join_date, 'join_date' => $this->join_date,
'leave_date' => $this->leave_date,
'birth_date' => $this->birth_date, 'birth_date' => $this->birth_date,
'birth_place' => $this->birth_place, 'birth_place' => $this->birth_place,
'created_at' => $this->created_at, 'created_at' => $this->created_at,
'updated_at' => $this->updated_at, 'updated_at' => $this->updated_at,
'deleted_at' => $this->deleted_at, 'deleted_at' => $this->deleted_at,
'employments' => EmploymentResource::collection($this->whenLoaded('employments')),
'roles' => $this->roles->map(function ($role) { 'roles' => $this->roles->map(function ($role) {
return [ return [
'id' => $role->id, 'id' => $role->id,
@@ -1,56 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Modules\KJCReport\Entities\KJCReport;
use Modules\KJCReport\Jobs\GenerateTeamWeeklyReports;
use Modules\Unit\Entities\Unit;
use Modules\Auth\Entities\User;
class AutoGenerateWeeklyReportForUnit extends Command
{
protected $signature = 'kjc:auto-generate-weekly-report
{unit : Unit name to generate reports for (e.g. "Jabatan Arah RAJD")}
{--force : Force generation even if reports already exist}';
protected $description = 'Auto-generate weekly KJC reports for a specific unit';
public function handle(): int
{
$unitName = $this->argument('unit');
$unit = Unit::where('name', $unitName)->first();
if (! $unit) {
$this->error("Unit '{$unitName}' not found.");
return 1;
}
$month = strtolower(now()->format('F'));
$week = (int) ceil(now()->day / 7);
if (! $this->option('force')) {
$existingReports = KJCReport::where('unit_id', $unit->id)
->where('report_type', 'weekly')
->where('report_month', $month)
->where('report_week', $week)
->exists();
if ($existingReports) {
$this->info("Reports for {$unitName} - {$month} week {$week} already exist. Skipping.");
return 0;
}
}
$user = User::where('unit_id', $unit->id)->first();
GenerateTeamWeeklyReports::dispatch($unit->id, $month, $week, $user?->id);
$this->info("✓ Queued weekly report generation for {$unitName} - {$month} week {$week}");
return 0;
}
}
@@ -1,68 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CaptureKJCHistoricalDataJob;
use App\Services\KJCHistoricalDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;
class TriggerKJCHistoricalDataCapture extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'kjc:historical:trigger
{--month= : Month to capture (1-12)}
{--year= : Year to capture (YYYY)}
{--queue : Dispatch to queue instead of running immediately}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Manually trigger KJC historical data capture';
/**
* Execute the console command.
*/
public function handle()
{
$month = $this->option('month');
$year = $this->option('year');
$useQueue = $this->option('queue');
// If no month/year provided, use previous month
if (! $month || ! $year) {
$lastMonth = Carbon::now()->subMonth();
$month = $month ?: $lastMonth->format('m');
$year = $year ?: $lastMonth->format('Y');
}
$this->info("Triggering KJC historical data capture for {$month}/{$year}...");
try {
if ($useQueue) {
// Dispatch to queue
CaptureKJCHistoricalDataJob::dispatch($month, $year);
$this->info('✓ KJC historical data capture job dispatched to queue');
$this->info('You can monitor the job in Horizon dashboard');
} else {
// Run immediately
$job = new CaptureKJCHistoricalDataJob($month, $year);
$job->handle(app(KJCHistoricalDataService::class));
$this->info('✓ KJC historical data capture completed immediately');
}
} catch (\Exception $e) {
$this->error('Error: '.$e->getMessage());
return 1;
}
return 0;
}
}
@@ -1,55 +0,0 @@
<?php
namespace App\Console\Commands;
use App\Jobs\CapturePKJHistoricalDataJob;
use App\Services\PKJHistoricalDataService;
use Carbon\Carbon;
use Illuminate\Console\Command;
class TriggerPKJHistoricalDataCapture extends Command
{
protected $signature = 'pkj:historical:trigger
{--month= : Month to capture (1-12)}
{--year= : Year to capture (YYYY)}
{--queue : Dispatch to queue instead of running immediately}';
protected $description = 'Manually trigger PKJ historical data capture';
public function handle()
{
$month = $this->option('month');
$year = $this->option('year');
$useQueue = $this->option('queue');
// If no month/year provided, use previous month
if (! $month || ! $year) {
$lastMonth = Carbon::now()->subMonth();
$month = $month ?: $lastMonth->format('m');
$year = $year ?: $lastMonth->format('Y');
}
$this->info("Triggering PKJ historical data capture for {$month}/{$year}...");
try {
if ($useQueue) {
// Dispatch to queue
CapturePKJHistoricalDataJob::dispatch($month, $year);
$this->info('✓ PKJ historical data capture job dispatched to queue');
$this->info('You can monitor the job in Horizon dashboard');
} else {
// Run immediately
$job = new CapturePKJHistoricalDataJob($month, $year);
$job->handle(app(PKJHistoricalDataService::class));
$this->info('✓ PKJ historical data capture completed immediately');
}
} catch (\Exception $e) {
$this->error('Error: '.$e->getMessage());
return 1;
}
return 0;
}
}
@@ -113,8 +113,6 @@ abstract class BaseCrudController extends Controller
$item = $this->repository->create($data); $item = $this->repository->create($data);
ActivityLogger::log("Created {$this->resourceName}: {$this->getItemName($item)}", $item);
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'data' => new $this->resourceClass($item), 'data' => new $this->resourceClass($item),
@@ -175,8 +173,6 @@ abstract class BaseCrudController extends Controller
$item->update($data); $item->update($data);
ActivityLogger::log("Updated {$this->resourceName}: {$this->getItemName($item)}", $item);
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'data' => new $this->resourceClass($item), 'data' => new $this->resourceClass($item),
@@ -221,8 +217,6 @@ abstract class BaseCrudController extends Controller
$this->repository->delete($id); $this->repository->delete($id);
ActivityLogger::log("Deleted {$this->resourceName}: {$this->getItemName($item)}", $item);
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'message' => $this->getSuccessMessage('destroy'), 'message' => $this->getSuccessMessage('destroy'),
-102
View File
@@ -1,102 +0,0 @@
<?php
namespace App\Jobs;
use App\Services\KJCHistoricalDataService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CaptureKJCHistoricalDataJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 300; // 5 minutes timeout
public $tries = 3; // Retry 3 times if failed
public $backoff = 60; // Wait 60 seconds between retries
protected $month;
protected $year;
/**
* Create a new job instance.
*/
public function __construct($month = null, $year = null)
{
$this->month = $month;
$this->year = $year;
// Set queue name for Horizon monitoring
$this->onQueue('kjc-historical-data');
}
/**
* Execute the job.
*/
public function handle(KJCHistoricalDataService $kjcHistoricalService)
{
try {
Log::info('Starting KJC historical data capture job', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
$success = $kjcHistoricalService->captureMonthlySnapshots($this->month, $this->year);
if ($success) {
Log::info('KJC historical data capture job completed successfully', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
} else {
Log::error('KJC historical data capture job failed', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
throw new \Exception('KJC historical data capture failed');
}
} catch (\Exception $e) {
Log::error('KJC historical data capture job exception', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception)
{
Log::error('KJC historical data capture job failed permanently', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
'error' => $exception->getMessage(),
]);
}
/**
* Get the tags that should be assigned to the job.
*/
public function tags()
{
return ['kjc-historical-data', "month-{$this->month}", "year-{$this->year}"];
}
}
-102
View File
@@ -1,102 +0,0 @@
<?php
namespace App\Jobs;
use App\Services\PKJHistoricalDataService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class CapturePKJHistoricalDataJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 300; // 5 minutes timeout
public $tries = 3; // Retry 3 times if failed
public $backoff = 60; // Wait 60 seconds between retries
protected $month;
protected $year;
/**
* Create a new job instance.
*/
public function __construct($month = null, $year = null)
{
$this->month = $month;
$this->year = $year;
// Set queue name for Horizon monitoring
$this->onQueue('pkj-historical-data');
}
/**
* Execute the job.
*/
public function handle(PKJHistoricalDataService $historicalService)
{
try {
Log::info('Starting PKJ historical data capture job', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
$success = $historicalService->captureMonthlySnapshots($this->month, $this->year);
if ($success) {
Log::info('PKJ historical data capture job completed successfully', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
} else {
Log::error('PKJ historical data capture job failed', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
]);
throw new \Exception('PKJ historical data capture failed');
}
} catch (\Exception $e) {
Log::error('PKJ historical data capture job exception', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception)
{
Log::error('PKJ historical data capture job failed permanently', [
'month' => $this->month,
'year' => $this->year,
'job_id' => $this->job ? $this->job->getJobId() : 'manual-execution',
'error' => $exception->getMessage(),
]);
}
/**
* Get the tags that should be assigned to the job.
*/
public function tags()
{
return ['pkj-historical-data', "month-{$this->month}", "year-{$this->year}"];
}
}
+1 -21
View File
@@ -3,27 +3,7 @@
use Illuminate\Foundation\Inspiring; use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule; use Illuminate\Support\Facades\Schedule;
use App\Jobs\CaptureKJCHistoricalDataJob;
use App\Jobs\CapturePKJHistoricalDataJob;
Artisan::command('inspire', function () { Artisan::command('inspire', function () {
$this->comment(Inspiring::quote()); $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote'); })->purpose('Display an inspiring quote');
// Schedule KJC Historical Data Capture to run monthly on the 1st day at 2:00 AM
Schedule::job(new CaptureKJCHistoricalDataJob())
->monthlyOn(1, '02:00')
->withoutOverlapping()
->name('kjc-historical-data-capture');
// Schedule PKJ Historical Data Capture to run monthly on the 1st day at 2:30 AM
Schedule::job(new CapturePKJHistoricalDataJob())
->monthlyOn(1, '02:30')
->withoutOverlapping()
->name('pkj-historical-data-capture');
// Auto-generate weekly KJC reports for Jabatan Arah RAJD every Monday at 3:00 AM
Schedule::command('kjc:auto-generate-weekly-report "Jabatan Arah RAJD"')
->weeklyOn(1, '03:00') // Monday at 3:00 AM
->withoutOverlapping()
->name('kjc-auto-weekly-report');
+13 -1
View File
@@ -100,6 +100,8 @@ const props = withDefaults(defineProps<{
currentSort?: SortConfig[]; currentSort?: SortConfig[];
exportable?: boolean; exportable?: boolean;
exportFileName?: string; exportFileName?: string;
/** Title shown at the top of exported PDF documents. */
exportPdfTitle?: string;
/** When true, table body scrolls inside a max-height box instead of growing the page. */ /** When true, table body scrolls inside a max-height box instead of growing the page. */
scrollable?: boolean; scrollable?: boolean;
/** Max height of the scrollable table area (CSS value). */ /** Max height of the scrollable table area (CSS value). */
@@ -622,12 +624,22 @@ const exportToPDF = () => {
else if (colCount > 8) fontSize = 7; else if (colCount > 8) fontSize = 7;
const cellPadding = colCount > 8 ? 4 : 8; const cellPadding = colCount > 8 ? 4 : 8;
let tableStartY = 20;
if (props.exportPdfTitle?.trim()) {
doc.setFontSize(14);
doc.text(props.exportPdfTitle.trim(), doc.internal.pageSize.getWidth() / 2, 28, {
align: 'center',
});
tableStartY = 48;
}
const tableOptions: Parameters<typeof autoTable>[1] = { const tableOptions: Parameters<typeof autoTable>[1] = {
head: [headers], head: [headers],
body: data, body: data,
startY: tableStartY,
styles: { fontSize, cellPadding }, styles: { fontSize, cellPadding },
headStyles: { fillColor: [66, 139, 202] }, headStyles: { fillColor: [66, 139, 202] },
margin: { top: 20 }, margin: { top: tableStartY },
}; };
// For wide tables: let table use natural column widths and split across pages // For wide tables: let table use natural column widths and split across pages
+2 -2
View File
@@ -86,9 +86,9 @@ export function useRoleSwitcher() {
toast: true, toast: true,
position: 'top-end', position: 'top-end',
icon: 'success', icon: 'success',
title: res.message || 'Peranan telah ditukar.', title: res.message,
showConfirmButton: false, showConfirmButton: false,
timer: 3000, timer: 500,
}) })
await router.push(resolvePostLoginRoute(res.redirect_path)) await router.push(resolvePostLoginRoute(res.redirect_path))
+2 -2
View File
@@ -117,7 +117,7 @@ const appVersion = import.meta.env.VITE_APP_VERSION
<Input v-model="email" class="box block min-w-full px-5 py-6 xl:min-w-md" type="email" <Input v-model="email" class="box block min-w-full px-5 py-6 xl:min-w-md" type="email"
placeholder="Email" autocomplete="email" required /> placeholder="Email" autocomplete="email" required />
<PasswordInput v-model="password" class="box block min-w-full px-5 py-6 xl:min-w-md" <PasswordInput v-model="password" class="box block min-w-full px-5 py-6 xl:min-w-md"
placeholder="Password" autocomplete="current-password" required /> placeholder="Kata Laluan" autocomplete="current-password" required />
<div class="flex text-xs sm:text-sm"> <div class="flex text-xs sm:text-sm">
<div class="mr-auto flex-row items-center"> <div class="mr-auto flex-row items-center">
<CheckboxRoot :checked="remember" @checked-change="({ checked }) => (remember = checked === true)"> <CheckboxRoot :checked="remember" @checked-change="({ checked }) => (remember = checked === true)">
@@ -127,7 +127,7 @@ const appVersion = import.meta.env.VITE_APP_VERSION
</div> </div>
<button type="button" class="opacity-70 hover:opacity-100" <button type="button" class="opacity-70 hover:opacity-100"
@click="router.push({ name: 'forgot-password' })"> @click="router.push({ name: 'forgot-password' })">
Lupa Password? Lupa Kata Laluan?
</button> </button>
</div> </div>
<div class="mt-5 text-center xl:mt-10 xl:text-left"> <div class="mt-5 text-center xl:mt-10 xl:text-left">
+14 -4
View File
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert' import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { PasswordInput } from '@/components/ui/password-input' import { PasswordInput } from '@/components/ui/password-input'
import { getRegisterErrorMessage, register } from '@/modules/auth' import { getRegisterErrorMessage, register } from '@/modules/auth'
import { sanitizeIcNumberInput, sanitizeNameInput } from '@/utils/form-input.utils'
import illustrationUrl from '@/assets/images/logo.svg' import illustrationUrl from '@/assets/images/logo.svg'
const router = useRouter() const router = useRouter()
@@ -21,6 +22,14 @@ const termsAccepted = ref(false)
const loading = ref(false) const loading = ref(false)
const errorMessage = ref('') const errorMessage = ref('')
const handleNameInput = () => {
name.value = sanitizeNameInput(name.value)
}
const handleIcNumberInput = () => {
icNumber.value = sanitizeIcNumberInput(icNumber.value)
}
const handleRegister = async () => { const handleRegister = async () => {
if (!termsAccepted.value) { if (!termsAccepted.value) {
errorMessage.value = 'Sila bersetuju dengan Dasar Privasi dan Terma dan Syarat.' errorMessage.value = 'Sila bersetuju dengan Dasar Privasi dan Terma dan Syarat.'
@@ -90,15 +99,16 @@ const handleRegister = async () => {
<form class="mt-8 flex flex-col gap-5" @submit.prevent="handleRegister"> <form class="mt-8 flex flex-col gap-5" @submit.prevent="handleRegister">
<Input v-model="name" class="box block min-w-full px-5 py-6 xl:min-w-md" type="text" <Input v-model="name" class="box block min-w-full px-5 py-6 xl:min-w-md" type="text"
placeholder="Nama Penuh" autocomplete="name" required /> placeholder="Nama Penuh" autocomplete="name" required @input="handleNameInput" />
<Input v-model="email" class="box block min-w-full px-5 py-6 xl:min-w-md" type="email" <Input v-model="email" class="box block min-w-full px-5 py-6 xl:min-w-md" type="email"
placeholder="Email" autocomplete="email" required /> placeholder="Email" autocomplete="email" required />
<Input v-model="icNumber" class="box block min-w-full px-5 py-6 xl:min-w-md" type="text" <Input v-model="icNumber" class="box block min-w-full px-5 py-6 xl:min-w-md" type="text"
placeholder="No. Kad Pengenalan" required /> inputmode="numeric" maxlength="15" placeholder="Contoh: 900101011234" required
@input="handleIcNumberInput" />
<PasswordInput v-model="password" class="box block min-w-full px-5 py-6 xl:min-w-md" type="password" <PasswordInput v-model="password" class="box block min-w-full px-5 py-6 xl:min-w-md" type="password"
placeholder="Password" autocomplete="new-password" minlength="8" required /> placeholder="Kata Laluan" autocomplete="new-password" minlength="8" required />
<PasswordInput v-model="passwordConfirmation" class="box block min-w-full px-5 py-6 xl:min-w-md" <PasswordInput v-model="passwordConfirmation" class="box block min-w-full px-5 py-6 xl:min-w-md"
placeholder="Sahkan Password" autocomplete="new-password" minlength="8" required /> placeholder="Sahkan Kata Laluan" autocomplete="new-password" minlength="8" required />
<div class="flex text-xs sm:text-sm"> <div class="flex text-xs sm:text-sm">
<CheckboxRoot :checked="termsAccepted" <CheckboxRoot :checked="termsAccepted"
@@ -59,7 +59,7 @@ const availableModules = computed(() => [
visible: hasPermission('lihat aktiviti'), visible: hasPermission('lihat aktiviti'),
}, },
{ {
title: 'Senarai Pengguna', title: 'Senarai Daftar Anggota',
description: 'Pantau dan urus akaun pengguna sistem.', description: 'Pantau dan urus akaun pengguna sistem.',
route: 'list-users', route: 'list-users',
icon: 'Users' as Icon, icon: 'Users' as Icon,
@@ -22,6 +22,7 @@ import { AlertRoot, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Lucide } from '@/components/ui/lucide' import { Lucide } from '@/components/ui/lucide'
import { getApiErrorMessage, getApiValidationErrors } from '@/core/utils/getApiErrorMessage' import { getApiErrorMessage, getApiValidationErrors } from '@/core/utils/getApiErrorMessage'
import { submitMembershipApplication, lookupMemberByIcNumber } from '../services/membership-application.service' import { submitMembershipApplication, lookupMemberByIcNumber } from '../services/membership-application.service'
import { sanitizeIcNumberInput, sanitizeNameInput } from '@/utils/form-input.utils'
import type { import type {
MembershipApplicationFormState, MembershipApplicationFormState,
MembershipApplicationHeirForm, MembershipApplicationHeirForm,
@@ -37,7 +38,7 @@ const MIN_FEE_MONTHLY_CONTRIBUTION = 30
const steps = [ const steps = [
{ id: 1, label: 'Maklumat Peribadi' }, { id: 1, label: 'Maklumat Peribadi' },
{ id: 2, label: 'Hubungan & Alamat' }, { id: 2, label: 'No. Telefon & Alamat' },
{ id: 3, label: 'Maklumat Pekerjaan' }, { id: 3, label: 'Maklumat Pekerjaan' },
{ id: 4, label: 'Maklumat Penama' }, { id: 4, label: 'Maklumat Penama' },
{ id: 5, label: 'Dokumen & Hantar' }, { id: 5, label: 'Dokumen & Hantar' },
@@ -79,15 +80,15 @@ const RELATIONSHIP_OPTIONS: SelectOption[] = [
// TODO: replace with API lookup // TODO: replace with API lookup
const EMPLOYERS = [ const EMPLOYERS = [
{ {
name: 'INFRA QUEST SDN BHD', name: 'Infra Quest Sdn. Bhd. (IQSB)',
address: 'Lot 1045, Jalan Dato Lundang, 15200 Kota Bharu, Kelantan', address: 'Lot 1045, Jalan Dato Lundang, 15200 Kota Bharu, Kelantan',
}, },
{ {
name: 'Permodalan Kelantan Berhad', name: 'Permodalan Kelantan Berhad (PKB)',
address: 'Permodalan Kelantan Berhad, Tingkat 4, Wisma Permodalan Kelantan Berhad, Jalan Maju, 15000 Kota Bharu Kelantan', address: 'Permodalan Kelantan Berhad, Tingkat 4, Wisma Permodalan Kelantan Berhad, Jalan Maju, 15000 Kota Bharu Kelantan',
}, },
{ {
name: 'Koperasi Permodalan Kelantan Berhad', name: 'Koperasi Permodalan Kelantan Berhad (KOPKB)',
address: 'Lot Pt 448, Tingkat 1,Jalan Kuala Krai, Batu 3, Wakaf Che Yeh, 15150 Kota Bharu, Kelantan.', address: 'Lot Pt 448, Tingkat 1,Jalan Kuala Krai, Batu 3, Wakaf Che Yeh, 15150 Kota Bharu, Kelantan.',
}, },
{ {
@@ -221,9 +222,34 @@ function clearReference(role: 'proposer' | 'supporter') {
} }
function handleReferenceIcInput(role: 'proposer' | 'supporter') { function handleReferenceIcInput(role: 'proposer' | 'supporter') {
form.references[role].ic_number = sanitizeIcNumberInput(form.references[role].ic_number)
clearReference(role) clearReference(role)
} }
function handleApplicantNameInput() {
form.applicant.name = sanitizeNameInput(form.applicant.name)
delete fieldErrors['applicant.name']
}
function handleApplicantIcInput() {
form.applicant.ic_number = sanitizeIcNumberInput(form.applicant.ic_number)
delete fieldErrors['applicant.ic_number']
}
function handleHeirNameInput(index: number) {
const heir = form.heirs[index]
if (!heir) return
heir.name = sanitizeNameInput(heir.name)
delete fieldErrors[`heirs.${index}.name`]
}
function handleHeirIcInput(index: number) {
const heir = form.heirs[index]
if (!heir) return
heir.ic_number = sanitizeIcNumberInput(heir.ic_number)
delete fieldErrors[`heirs.${index}.ic_number`]
}
async function lookupReference(role: 'proposer' | 'supporter') { async function lookupReference(role: 'proposer' | 'supporter') {
const reference = form.references[role] const reference = form.references[role]
const icNumber = reference.ic_number.trim() const icNumber = reference.ic_number.trim()
@@ -608,7 +634,7 @@ function stepLabelClass(stepId: number) {
<template v-if="currentStep === 1"> <template v-if="currentStep === 1">
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel for="name">Nama Penuh</FieldLabel> <FieldLabel for="name">Nama Penuh</FieldLabel>
<Input id="name" v-model="form.applicant.name" type="text" /> <Input id="name" v-model="form.applicant.name" type="text" @input="handleApplicantNameInput" />
<FieldError v-if="fieldErrors['applicant.name']">{{ fieldErrors['applicant.name'] }}</FieldError> <FieldError v-if="fieldErrors['applicant.name']">{{ fieldErrors['applicant.name'] }}</FieldError>
</Field> </Field>
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
@@ -618,7 +644,8 @@ function stepLabelClass(stepId: number) {
</Field> </Field>
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel for="ic_number">No. Kad Pengenalan</FieldLabel> <FieldLabel for="ic_number">No. Kad Pengenalan</FieldLabel>
<Input id="ic_number" v-model="form.applicant.ic_number" type="text" /> <Input id="ic_number" v-model="form.applicant.ic_number" type="text" inputmode="numeric" maxlength="15"
placeholder="Contoh: 900101011234" @input="handleApplicantIcInput" />
<FieldError v-if="fieldErrors['applicant.ic_number']">{{ fieldErrors['applicant.ic_number'] }} <FieldError v-if="fieldErrors['applicant.ic_number']">{{ fieldErrors['applicant.ic_number'] }}
</FieldError> </FieldError>
</Field> </Field>
@@ -793,14 +820,16 @@ function stepLabelClass(stepId: number) {
<div class="grid grid-cols-12 gap-4"> <div class="grid grid-cols-12 gap-4">
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel :for="`heir-name-${index}`">Nama</FieldLabel> <FieldLabel :for="`heir-name-${index}`">Nama</FieldLabel>
<Input :id="`heir-name-${index}`" v-model="heir.name" type="text" /> <Input :id="`heir-name-${index}`" v-model="heir.name" type="text"
@input="handleHeirNameInput(index)" />
<FieldError v-if="fieldErrors[`heirs.${index}.name`]"> <FieldError v-if="fieldErrors[`heirs.${index}.name`]">
{{ fieldErrors[`heirs.${index}.name`] }} {{ fieldErrors[`heirs.${index}.name`] }}
</FieldError> </FieldError>
</Field> </Field>
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel :for="`heir-ic-${index}`">No. Kad Pengenalan</FieldLabel> <FieldLabel :for="`heir-ic-${index}`">No. Kad Pengenalan</FieldLabel>
<Input :id="`heir-ic-${index}`" v-model="heir.ic_number" type="text" /> <Input :id="`heir-ic-${index}`" v-model="heir.ic_number" type="text" inputmode="numeric"
maxlength="15" placeholder="Contoh: 900101011234" @input="handleHeirIcInput(index)" />
<FieldError v-if="fieldErrors[`heirs.${index}.ic_number`]"> <FieldError v-if="fieldErrors[`heirs.${index}.ic_number`]">
{{ fieldErrors[`heirs.${index}.ic_number`] }} {{ fieldErrors[`heirs.${index}.ic_number`] }}
</FieldError> </FieldError>
@@ -857,8 +886,9 @@ function stepLabelClass(stepId: number) {
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel for="proposer_ic_number">No. KP Pencadang</FieldLabel> <FieldLabel for="proposer_ic_number">No. KP Pencadang</FieldLabel>
<Input id="proposer_ic_number" v-model="form.references.proposer.ic_number" type="text" <Input id="proposer_ic_number" v-model="form.references.proposer.ic_number" type="text"
placeholder="Contoh: 900101011234" :disabled="referenceLookupLoading.proposer" inputmode="numeric" maxlength="12" placeholder="Contoh: 900101011234"
@input="handleReferenceIcInput('proposer')" @blur="lookupReference('proposer')" /> :disabled="referenceLookupLoading.proposer" @input="handleReferenceIcInput('proposer')"
@blur="lookupReference('proposer')" />
<p v-if="form.references.proposer.name" class="mt-1 text-sm text-success"> <p v-if="form.references.proposer.name" class="mt-1 text-sm text-success">
{{ form.references.proposer.name }} {{ form.references.proposer.name }}
</p> </p>
@@ -870,8 +900,9 @@ function stepLabelClass(stepId: number) {
<Field class="col-span-12 sm:col-span-6"> <Field class="col-span-12 sm:col-span-6">
<FieldLabel for="supporter_ic_number">No. KP Penyokong</FieldLabel> <FieldLabel for="supporter_ic_number">No. KP Penyokong</FieldLabel>
<Input id="supporter_ic_number" v-model="form.references.supporter.ic_number" type="text" <Input id="supporter_ic_number" v-model="form.references.supporter.ic_number" type="text"
placeholder="Contoh: 850505055678" :disabled="referenceLookupLoading.supporter" inputmode="numeric" maxlength="12" placeholder="Contoh: 850505055678"
@input="handleReferenceIcInput('supporter')" @blur="lookupReference('supporter')" /> :disabled="referenceLookupLoading.supporter" @input="handleReferenceIcInput('supporter')"
@blur="lookupReference('supporter')" />
<p v-if="form.references.supporter.name" class="mt-1 text-sm text-success"> <p v-if="form.references.supporter.name" class="mt-1 text-sm text-success">
{{ form.references.supporter.name }} {{ form.references.supporter.name }}
</p> </p>
@@ -907,7 +938,7 @@ function stepLabelClass(stepId: number) {
<Input id="employer_letter" type="file" accept=".pdf,.jpg,.jpeg,.png" <Input id="employer_letter" type="file" accept=".pdf,.jpg,.jpeg,.png"
@change="handleFileChange('employer_letter', $event)" /> @change="handleFileChange('employer_letter', $event)" />
<FieldError v-if="fieldErrors['documents.employer_letter']">{{ fieldErrors['documents.employer_letter'] <FieldError v-if="fieldErrors['documents.employer_letter']">{{ fieldErrors['documents.employer_letter']
}}</FieldError> }}</FieldError>
</Field> </Field>
<div class="col-span-12 mt-2 rounded-lg border border-foreground/10 bg-foreground/5 p-4"> <div class="col-span-12 mt-2 rounded-lg border border-foreground/10 bg-foreground/5 p-4">
@@ -65,6 +65,8 @@ const DOCUMENT_TYPE_LABELS: Record<string, string> = {
[RESULT_LETTER_DOCUMENT_TYPE]: 'Surat Keputusan', [RESULT_LETTER_DOCUMENT_TYPE]: 'Surat Keputusan',
} }
const BOARD_MEETING_REFERENCE_PREFIX = 'Mesyuarat Lembaga Bil.'
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
const { hasPermission } = usePermissions() const { hasPermission } = usePermissions()
@@ -430,8 +432,10 @@ async function confirmPendingAction() {
}) })
boardRemarks.value = '' boardRemarks.value = ''
} else { } else {
const boardMeetingReferenceValue = `${BOARD_MEETING_REFERENCE_PREFIX} ${boardMeetingReference.value.trim()}`
response = await completeMembershipApplication(applicationId.value, { response = await completeMembershipApplication(applicationId.value, {
board_meeting_reference: boardMeetingReference.value.trim(), board_meeting_reference: boardMeetingReferenceValue,
board_meeting_date: boardMeetingDate.value, board_meeting_date: boardMeetingDate.value,
}) })
} }
@@ -1013,9 +1017,15 @@ onUnmounted(() => {
<div class="mt-2 opacity-70">{{ confirmDialogDescription }}</div> <div class="mt-2 opacity-70">{{ confirmDialogDescription }}</div>
<Field v-if="pendingAction?.type === 'complete'" class="mt-5 text-left"> <Field v-if="pendingAction?.type === 'complete'" class="mt-5 text-left">
<FieldLabel for="detail-board-meeting-reference">Rujukan Mesyuarat Lembaga</FieldLabel> <FieldLabel for="detail-board-meeting-reference">Rujukan Mesyuarat Lembaga</FieldLabel>
<Input id="detail-board-meeting-reference" v-model="boardMeetingReference" type="text" <div class="flex">
placeholder="Contoh: Mesyuarat Lembaga Bil. 3/2026" :disabled="completeSubmitting" <span
@input="boardMeetingReferenceError = null" /> class="inline-flex items-center rounded-l-lg border border-r-0 border-foreground/10 bg-foreground/5 px-3 text-sm opacity-80">
{{ BOARD_MEETING_REFERENCE_PREFIX }}
</span>
<Input id="detail-board-meeting-reference" v-model="boardMeetingReference" type="text"
class="rounded-l-none" placeholder="Contoh: 3/2026" :disabled="completeSubmitting"
@input="boardMeetingReferenceError = null" />
</div>
<FieldError v-if="boardMeetingReferenceError">{{ boardMeetingReferenceError }}</FieldError> <FieldError v-if="boardMeetingReferenceError">{{ boardMeetingReferenceError }}</FieldError>
</Field> </Field>
<Field v-if="pendingAction?.type === 'complete'" class="mt-4 text-left"> <Field v-if="pendingAction?.type === 'complete'" class="mt-4 text-left">
@@ -61,6 +61,8 @@ export type ApplicantDocumentUploadType = (typeof APPLICANT_DOCUMENT_UPLOAD_TYPE
export type AdminDocumentUploadType = (typeof ADMIN_DOCUMENT_UPLOAD_TYPES)[number] export type AdminDocumentUploadType = (typeof ADMIN_DOCUMENT_UPLOAD_TYPES)[number]
export type DocumentUploadType = ApplicantDocumentUploadType | AdminDocumentUploadType export type DocumentUploadType = ApplicantDocumentUploadType | AdminDocumentUploadType
export { sanitizeIcNumberInput } from '@/utils/form-input.utils'
export function createSelectCollection(options: SelectOption[]) { export function createSelectCollection(options: SelectOption[]) {
return select.collection({ return select.collection({
items: options, items: options,
@@ -168,11 +170,11 @@ export function detailToFormState(detail: MembershipApplicationDetail): Membersh
}, },
heirs: detail.heirs.length heirs: detail.heirs.length
? detail.heirs.map((heir) => ({ ? detail.heirs.map((heir) => ({
name: toFormString(heir.name), name: toFormString(heir.name),
ic_number: toFormString(heir.ic_number), ic_number: toFormString(heir.ic_number),
relationship: toFormString(heir.relationship), relationship: toFormString(heir.relationship),
phone_number: toFormString(heir.phone_number), phone_number: toFormString(heir.phone_number),
})) }))
: [createEmptyHeir()], : [createEmptyHeir()],
references: { references: {
proposer: { proposer: {
@@ -15,7 +15,6 @@ import MemberDigitalCard from '../components/MemberDigitalCard.vue'
import ProfileTab from './ProfileTab.vue' import ProfileTab from './ProfileTab.vue'
import EmploymentTab from './EmploymentTab.vue' import EmploymentTab from './EmploymentTab.vue'
import BankDetailTab from './BankDetailTab.vue' import BankDetailTab from './BankDetailTab.vue'
import HeirTab from './HeirTab.vue'
import ChangePasswordTab from './ChangePasswordTab.vue' import ChangePasswordTab from './ChangePasswordTab.vue'
const authStore = useAuthStore() const authStore = useAuthStore()
@@ -263,12 +262,6 @@ onMounted(async () => {
<Lucide class="size-4 shrink-0 md:mr-2" icon="Banknote" /> <Lucide class="size-4 shrink-0 md:mr-2" icon="Banknote" />
<span class="hidden md:inline">Bank</span> <span class="hidden md:inline">Bank</span>
</TabsTrigger> </TabsTrigger>
<TabsTrigger
class="inline-flex min-w-0 flex-1 items-center justify-center whitespace-nowrap px-2 sm:px-3 md:text-sm"
value="6" aria-label="Penama">
<Lucide class="size-4 shrink-0 md:mr-2" icon="Users" />
<span class="hidden md:inline">Penama</span>
</TabsTrigger>
<TabsTrigger <TabsTrigger
class="inline-flex min-w-0 flex-1 items-center justify-center whitespace-nowrap px-2 sm:px-3 md:text-sm" class="inline-flex min-w-0 flex-1 items-center justify-center whitespace-nowrap px-2 sm:px-3 md:text-sm"
value="2" aria-label="Kata Laluan"> value="2" aria-label="Kata Laluan">
@@ -294,10 +287,6 @@ onMounted(async () => {
<TabsContent value="2" class="mt-8"> <TabsContent value="2" class="mt-8">
<ChangePasswordTab embedded /> <ChangePasswordTab embedded />
</TabsContent> </TabsContent>
<!-- Penama -->
<TabsContent value="6" class="mt-8">
<HeirTab embedded />
</TabsContent>
</TabsRoot> </TabsRoot>
</div> </div>
</template> </template>
+16 -2
View File
@@ -20,6 +20,7 @@ import {
SelectItemText, SelectItemText,
} from '@/components/ui/select' } from '@/components/ui/select'
import { getApiErrorMessage, getApiValidationErrors } from '@/core/utils/getApiErrorMessage' import { getApiErrorMessage, getApiValidationErrors } from '@/core/utils/getApiErrorMessage'
import { sanitizeIcNumberInput, sanitizeNameInput } from '@/utils/form-input.utils'
import { import {
createAddress, createAddress,
deleteAddress, deleteAddress,
@@ -29,6 +30,7 @@ import {
import { updateProfile } from '@/modules/profile/services/profile.service' import { updateProfile } from '@/modules/profile/services/profile.service'
import type { Address, AddressPayload } from '@/modules/profile/types/address.types' import type { Address, AddressPayload } from '@/modules/profile/types/address.types'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import HeirTab from './HeirTab.vue'
defineProps<{ defineProps<{
embedded?: boolean embedded?: boolean
@@ -159,6 +161,14 @@ const stateValue = ref<string[]>([])
const addressTypeInitial = ref<string[]>([]) const addressTypeInitial = ref<string[]>([])
const stateInitial = ref<string[]>([]) const stateInitial = ref<string[]>([])
function handleNameInput() {
form.name = sanitizeNameInput(form.name)
}
function handleIcNumberInput() {
form.ic_number = sanitizeIcNumberInput(form.ic_number)
}
function clearProfileFieldError(field: ProfileFieldKey) { function clearProfileFieldError(field: ProfileFieldKey) {
delete profileErrors[field] delete profileErrors[field]
} }
@@ -569,7 +579,8 @@ onMounted(async () => {
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<Field> <Field>
<FieldLabel for="profile-name">Nama</FieldLabel> <FieldLabel for="profile-name">Nama</FieldLabel>
<Input id="profile-name" v-model="form.name" type="text" placeholder="Nama penuh" required /> <Input id="profile-name" v-model="form.name" type="text" placeholder="Nama penuh" required
@input="handleNameInput" />
</Field> </Field>
<Field> <Field>
<FieldLabel for="profile-email">E-mel</FieldLabel> <FieldLabel for="profile-email">E-mel</FieldLabel>
@@ -577,7 +588,8 @@ onMounted(async () => {
</Field> </Field>
<Field> <Field>
<FieldLabel for="profile-ic">No. Kad Pengenalan</FieldLabel> <FieldLabel for="profile-ic">No. Kad Pengenalan</FieldLabel>
<Input id="profile-ic" v-model="form.ic_number" type="text" placeholder="No. kad pengenalan" /> <Input id="profile-ic" v-model="form.ic_number" type="text" inputmode="numeric" maxlength="15"
placeholder="Contoh: 900101011234" @input="handleIcNumberInput" />
</Field> </Field>
<Field> <Field>
<FieldLabel for="profile-phone">No. Telefon</FieldLabel> <FieldLabel for="profile-phone">No. Telefon</FieldLabel>
@@ -817,5 +829,7 @@ onMounted(async () => {
</form> </form>
</div> </div>
</Box> </Box>
<HeirTab embedded />
</div> </div>
</template> </template>
+71 -2
View File
@@ -1,23 +1,43 @@
import { onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import debounce from 'lodash/debounce' import debounce from 'lodash/debounce'
import type { SortConfig } from '@/components/ui/usage/DataTable.vue' import type { SortConfig } from '@/components/ui/usage/DataTable.vue'
import { useApiPagination } from '@/composables/useApiPagination' import { useApiPagination } from '@/composables/useApiPagination'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage' import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { listUsers } from '../services/user.service' import { getUserStats, listUsers } from '../services/user.service'
import type { UserListItem } from '../types/user.types' import type { UserListItem } from '../types/user.types'
export function useUserList() { export function useUserList() {
const users = ref<UserListItem[]>([]) const users = ref<UserListItem[]>([])
const loading = ref(false) const loading = ref(false)
const statsLoading = ref(false)
const error = ref<string | null>(null) const error = ref<string | null>(null)
const statsError = ref<string | null>(null)
const search = ref('') const search = ref('')
const statusFilter = ref('') const statusFilter = ref('')
const joinDateFrom = ref('')
const joinDateTo = ref('')
const leaveDateFrom = ref('')
const leaveDateTo = ref('')
const sortBy = ref<SortConfig[]>([{ key: 'name', order: 'asc' }]) const sortBy = ref<SortConfig[]>([{ key: 'name', order: 'asc' }])
const page = ref(1) const page = ref(1)
const itemsPerPage = ref(10) const itemsPerPage = ref(10)
const stats = ref<{ total: number; joined_this_month: number }>({ total: 0, joined_this_month: 0 })
const { pagination, applyPagination } = useApiPagination({ per_page: 10 }) const { pagination, applyPagination } = useApiPagination({ per_page: 10 })
const hasJoinDateFilters = computed(() => Boolean(joinDateFrom.value || joinDateTo.value))
const hasLeaveDateFilters = computed(() => Boolean(leaveDateFrom.value || leaveDateTo.value))
function clearJoinDateFilters() {
joinDateFrom.value = ''
joinDateTo.value = ''
}
function clearLeaveDateFilters() {
leaveDateFrom.value = ''
leaveDateTo.value = ''
}
async function fetchUsers(requestPage = page.value) { async function fetchUsers(requestPage = page.value) {
loading.value = true loading.value = true
error.value = null error.value = null
@@ -31,16 +51,45 @@ export function useUserList() {
sort_order: activeSort?.order ?? 'asc', sort_order: activeSort?.order ?? 'asc',
search: search.value.trim() || undefined, search: search.value.trim() || undefined,
status: statusFilter.value.trim() || undefined, status: statusFilter.value.trim() || undefined,
join_date_from: joinDateFrom.value || undefined,
join_date_to: joinDateTo.value || undefined,
leave_date_from: leaveDateFrom.value || undefined,
leave_date_to: leaveDateTo.value || undefined,
}) })
users.value = data.data users.value = data.data
applyPagination(data.pagination) applyPagination(data.pagination)
page.value = data.pagination.current_page page.value = data.pagination.current_page
} catch (err) {
error.value = getApiErrorMessage(err, 'Gagal memuatkan senarai pengguna.')
} finally { } finally {
loading.value = false loading.value = false
} }
} }
async function fetchStats() {
statsLoading.value = true
statsError.value = null
try {
const res = await getUserStats({
search: search.value.trim() || undefined,
status: statusFilter.value.trim() || undefined,
join_date_from: joinDateFrom.value || undefined,
join_date_to: joinDateTo.value || undefined,
leave_date_from: leaveDateFrom.value || undefined,
leave_date_to: leaveDateTo.value || undefined,
})
stats.value = res.data
} catch (err) {
statsError.value = getApiErrorMessage(err, 'Gagal memuatkan statistik pengguna.')
stats.value = { total: 0, joined_this_month: 0 }
} finally {
statsLoading.value = false
}
}
function handleSortUpdate(value: SortConfig[]) { function handleSortUpdate(value: SortConfig[]) {
sortBy.value = value sortBy.value = value
fetchUsers(1) fetchUsers(1)
@@ -48,6 +97,7 @@ export function useUserList() {
const debouncedSearch = debounce(() => { const debouncedSearch = debounce(() => {
fetchUsers(1) fetchUsers(1)
fetchStats()
}, 400) }, 400)
watch(search, () => { watch(search, () => {
@@ -56,6 +106,12 @@ export function useUserList() {
watch(statusFilter, () => { watch(statusFilter, () => {
fetchUsers(1) fetchUsers(1)
fetchStats()
})
watch([joinDateFrom, joinDateTo, leaveDateFrom, leaveDateTo], () => {
fetchUsers(1)
fetchStats()
}) })
watch(page, (nextPage, previousPage) => { watch(page, (nextPage, previousPage) => {
@@ -72,19 +128,32 @@ export function useUserList() {
onMounted(() => { onMounted(() => {
fetchUsers(1) fetchUsers(1)
fetchStats()
}) })
return { return {
users, users,
loading, loading,
stats,
statsLoading,
statsError,
error, error,
search, search,
statusFilter, statusFilter,
joinDateFrom,
joinDateTo,
leaveDateFrom,
leaveDateTo,
hasJoinDateFilters,
hasLeaveDateFilters,
clearJoinDateFilters,
clearLeaveDateFilters,
sortBy, sortBy,
page, page,
itemsPerPage, itemsPerPage,
pagination, pagination,
handleSortUpdate, handleSortUpdate,
fetchUsers, fetchUsers,
fetchStats,
} }
} }
+1 -1
View File
@@ -4,7 +4,7 @@ export const userMenu: Menu[] = [
{ {
icon: 'Users', icon: 'Users',
route_name: 'list-users', route_name: 'list-users',
title: 'Senarai Pengguna', title: 'Senarai Daftar Anggota',
permission: 'lihat pengguna', permission: 'lihat pengguna',
}, },
] ]
+14 -1
View File
@@ -19,6 +19,7 @@ import {
SelectItemText, SelectItemText,
} from '@/components/ui/select' } from '@/components/ui/select'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage' import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { sanitizeIcNumberInput, sanitizeNameInput } from '@/utils/form-input.utils'
import { createUser } from '../services/user.service' import { createUser } from '../services/user.service'
type SelectOption = { label: string; value: string } type SelectOption = { label: string; value: string }
@@ -105,6 +106,14 @@ const form = reactive({
birth_place: '', birth_place: '',
}) })
function handleNameInput() {
form.name = sanitizeNameInput(form.name)
}
function handleIcNumberInput() {
form.ic_number = sanitizeIcNumberInput(form.ic_number)
}
function requireSelectValue(label: string | undefined, fieldName: string): string { function requireSelectValue(label: string | undefined, fieldName: string): string {
if (!label) { if (!label) {
throw new Error(`${fieldName} diperlukan.`) throw new Error(`${fieldName} diperlukan.`)
@@ -201,6 +210,7 @@ const formDisabled = computed(() => saving.value)
placeholder="Nama penuh" placeholder="Nama penuh"
:disabled="formDisabled" :disabled="formDisabled"
required required
@input="handleNameInput"
/> />
</Field> </Field>
@@ -226,9 +236,12 @@ const formDisabled = computed(() => saving.value)
v-model="form.ic_number" v-model="form.ic_number"
class="w-full" class="w-full"
type="text" type="text"
placeholder="Nombor kad pengenalan" inputmode="numeric"
maxlength="15"
placeholder="Contoh: 900101011234"
:disabled="formDisabled" :disabled="formDisabled"
required required
@input="handleIcNumberInput"
/> />
</Field> </Field>
+39 -4
View File
@@ -1,6 +1,7 @@
<script lang="ts" setup> <script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue' import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import * as select from '@zag-js/select' import * as select from '@zag-js/select'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert' import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Box } from '@/components/ui/box' import { Box } from '@/components/ui/box'
@@ -19,6 +20,7 @@ import {
SelectItemText, SelectItemText,
} from '@/components/ui/select' } from '@/components/ui/select'
import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage' import { getApiErrorMessage } from '@/core/utils/getApiErrorMessage'
import { sanitizeIcNumberInput, sanitizeNameInput } from '@/utils/form-input.utils'
import { getUser, updateUser } from '../services/user.service' import { getUser, updateUser } from '../services/user.service'
type SelectOption = { label: string; value: string } type SelectOption = { label: string; value: string }
@@ -115,10 +117,19 @@ const form = reactive({
phone_number: '', phone_number: '',
member_number: '', member_number: '',
join_date: '', join_date: '',
leave_date: '',
birth_date: '', birth_date: '',
birth_place: '', birth_place: '',
}) })
function handleNameInput() {
form.name = sanitizeNameInput(form.name)
}
function handleIcNumberInput() {
form.ic_number = sanitizeIcNumberInput(form.ic_number)
}
function toDateInputValue(value: string | null | undefined): string { function toDateInputValue(value: string | null | undefined): string {
if (!value) return '' if (!value) return ''
return value.slice(0, 10) return value.slice(0, 10)
@@ -132,6 +143,7 @@ function syncFormFromUser(user: Awaited<ReturnType<typeof getUser>>['data']) {
form.phone_number = user.phone_number ?? '' form.phone_number = user.phone_number ?? ''
form.member_number = user.member_number != null ? String(user.member_number) : '' form.member_number = user.member_number != null ? String(user.member_number) : ''
form.join_date = toDateInputValue(user.join_date) form.join_date = toDateInputValue(user.join_date)
form.leave_date = toDateInputValue(user.leave_date)
form.birth_date = toDateInputValue(user.birth_date) form.birth_date = toDateInputValue(user.birth_date)
form.birth_place = user.birth_place ?? '' form.birth_place = user.birth_place ?? ''
statusValue.value = apiValueToLabel(STATUS_OPTIONS, user.status ?? 'active') statusValue.value = apiValueToLabel(STATUS_OPTIONS, user.status ?? 'active')
@@ -159,6 +171,17 @@ async function fetchUser() {
} }
} }
const selectedStatus = computed(
() => labelToApiValue(STATUS_OPTIONS, statusValue.value[0]) ?? 'active',
)
const isInactiveStatus = computed(() => selectedStatus.value === 'inactive')
watch(selectedStatus, (newStatus, oldStatus) => {
if (newStatus === 'inactive' && oldStatus !== 'inactive' && !form.leave_date) {
form.leave_date = dayjs().format('YYYY-MM-DD')
}
})
async function handleSubmit() { async function handleSubmit() {
saving.value = true saving.value = true
error.value = null error.value = null
@@ -176,6 +199,7 @@ async function handleSubmit() {
member_number: form.member_number ? Number(form.member_number) : null, member_number: form.member_number ? Number(form.member_number) : null,
member_type: labelToApiValue(MEMBER_TYPE_OPTIONS, memberTypeValue.value[0]), member_type: labelToApiValue(MEMBER_TYPE_OPTIONS, memberTypeValue.value[0]),
join_date: form.join_date || null, join_date: form.join_date || null,
leave_date: isInactiveStatus.value ? form.leave_date || null : null,
birth_date: form.birth_date || null, birth_date: form.birth_date || null,
birth_place: form.birth_place.trim() || null, birth_place: form.birth_place.trim() || null,
}) })
@@ -224,7 +248,7 @@ onMounted(() => {
<Field> <Field>
<FieldLabel for="user-name">Nama</FieldLabel> <FieldLabel for="user-name">Nama</FieldLabel>
<Input id="user-name" v-model="form.name" class="w-full" type="text" placeholder="Nama penuh" <Input id="user-name" v-model="form.name" class="w-full" type="text" placeholder="Nama penuh"
:disabled="formDisabled" required /> :disabled="formDisabled" required @input="handleNameInput" />
</Field> </Field>
<Field> <Field>
@@ -236,8 +260,8 @@ onMounted(() => {
<div class="grid grid-cols-1 gap-4 md:grid-cols-2"> <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<Field> <Field>
<FieldLabel for="user-ic">Nombor Kad Pengenalan</FieldLabel> <FieldLabel for="user-ic">Nombor Kad Pengenalan</FieldLabel>
<Input id="user-ic" v-model="form.ic_number" class="w-full" type="text" placeholder="Nombor kad pengenalan" <Input id="user-ic" v-model="form.ic_number" class="w-full" type="text" inputmode="numeric" maxlength="15"
:disabled="formDisabled" required /> placeholder="Contoh: 900101011234" :disabled="formDisabled" required @input="handleIcNumberInput" />
</Field> </Field>
<Field> <Field>
@@ -351,6 +375,17 @@ onMounted(() => {
<Input id="user-join-date" v-model="form.join_date" class="w-full" type="date" :disabled="formDisabled" /> <Input id="user-join-date" v-model="form.join_date" class="w-full" type="date" :disabled="formDisabled" />
</Field> </Field>
<Field v-if="isInactiveStatus">
<FieldLabel for="user-leave-date">Tarikh Berhenti Menjadi Anggota</FieldLabel>
<Input
id="user-leave-date"
v-model="form.leave_date"
class="w-full"
type="date"
:disabled="formDisabled"
/>
</Field>
<Field> <Field>
<FieldLabel for="user-birth-date">Tarikh Lahir</FieldLabel> <FieldLabel for="user-birth-date">Tarikh Lahir</FieldLabel>
<Input id="user-birth-date" v-model="form.birth_date" class="w-full" type="date" :disabled="formDisabled" /> <Input id="user-birth-date" v-model="form.birth_date" class="w-full" type="date" :disabled="formDisabled" />
-38
View File
@@ -1,38 +0,0 @@
<script lang="ts" setup>
import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box'
import type { UserDetail } from '../types/user.types'
defineProps<{
user: UserDetail
embedded?: boolean
}>()
</script>
<template>
<div :class="embedded ? '' : 'mt-5'">
<Box raised="single" class="p-6">
<div class="mb-6">
<h3 class="text-lg font-semibold text-slate-900">Penama</h3>
<p class="mt-1 text-sm text-slate-500">Senarai penama pengguna.</p>
</div>
<div v-if="user.heirs?.length" class="space-y-3">
<div v-for="heir in user.heirs" :key="heir.id" class="rounded-lg border border-foreground/10 p-4">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium text-slate-900">{{ heir.name }}</span>
<Badge v-if="heir.is_primary" class="bg-green-500 text-white">Utama</Badge>
<Badge look="outline">{{ heir.relationship }}</Badge>
</div>
<p class="mt-1 text-sm text-slate-500">{{ heir.ic_number }}</p>
<p class="mt-1 text-sm text-slate-500">{{ heir.phone_number }}</p>
<p class="mt-1 text-sm text-slate-700">{{ heir.address }}</p>
</div>
</div>
<div v-else class="rounded-lg border border-dashed border-foreground/15 p-6 text-center text-sm text-slate-500">
Tiada penama direkodkan.
</div>
</Box>
</div>
</template>
+234 -11
View File
@@ -1,12 +1,19 @@
<script lang="ts" setup> <script lang="ts" setup>
import { onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import debounce from 'lodash/debounce' import debounce from 'lodash/debounce'
import { Search, HatGlasses, SquarePen, Trash2, Eye, Shield, RotateCcw } from '@lucide/vue' import { Search, HatGlasses, SquarePen, Trash2, Eye, Shield, RotateCcw } from '@lucide/vue'
import { Badge } from '@/components/ui/badge' import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import {
AccordionRoot,
AccordionItem,
AccordionTrigger,
AccordionContent,
} from '@/components/ui/accordion'
import { CheckboxRoot, CheckboxControl, CheckboxLabel } from '@/components/ui/checkbox' import { CheckboxRoot, CheckboxControl, CheckboxLabel } from '@/components/ui/checkbox'
import { DialogRoot, DialogContent, DialogCloseTrigger } from '@/components/ui/dialog' import { DialogRoot, DialogContent, DialogCloseTrigger } from '@/components/ui/dialog'
import { Lucide } from '@/components/ui/lucide' import { Lucide } from '@/components/ui/lucide'
@@ -36,9 +43,9 @@ type StatusFilterChip = {
const STATUS_FILTER_CHIPS: StatusFilterChip[] = [ const STATUS_FILTER_CHIPS: StatusFilterChip[] = [
{ label: 'Semua', value: '', variant: 'ghost' }, { label: 'Semua', value: '', variant: 'ghost' },
{ label: 'Active', value: 'active', variant: 'success' }, { label: 'Aktif', value: 'active', variant: 'success' },
{ label: 'Inactive', value: 'inactive', variant: 'danger' }, { label: 'Tidak Aktif', value: 'inactive', variant: 'danger' },
{ label: 'Pending', value: 'pending', variant: 'pending' }, { label: 'Menunggu', value: 'pending', variant: 'pending' },
] ]
const router = useRouter() const router = useRouter()
@@ -78,6 +85,70 @@ function formatUserRoles(roles: UserRole[] | undefined): string {
return roles?.map((role) => role.name).join(', ') || '-' return roles?.map((role) => role.name).join(', ') || '-'
} }
type QuickDatePreset = {
label: string
getRange: () => { from: string; to: string }
}
function formatDateInput(value: dayjs.Dayjs) {
return value.format('YYYY-MM-DD')
}
const QUICK_DATE_PRESETS: QuickDatePreset[] = [
{
label: 'Bulan ini',
getRange: () => ({
from: formatDateInput(dayjs().startOf('month')),
to: formatDateInput(dayjs().endOf('month')),
}),
},
{
label: 'Bulan lepas',
getRange: () => {
const prev = dayjs().subtract(1, 'month')
return {
from: formatDateInput(prev.startOf('month')),
to: formatDateInput(prev.endOf('month')),
}
},
},
{
label: 'Tahun ini',
getRange: () => ({
from: formatDateInput(dayjs().startOf('year')),
to: formatDateInput(dayjs().endOf('year')),
}),
},
]
function applyJoinDatePreset(preset: QuickDatePreset) {
const { from, to } = preset.getRange()
joinDateFrom.value = from
joinDateTo.value = to
}
function applyLeaveDatePreset(preset: QuickDatePreset) {
const { from, to } = preset.getRange()
leaveDateFrom.value = from
leaveDateTo.value = to
}
function getUserCompanyName(
item: Pick<UserListItem, 'company_name' | 'employments'>,
): string {
if (item.company_name) return item.company_name
const employments = item.employments ?? []
const current = employments.find((employment) => employment.is_current)
return (current ?? employments[0])?.company_name ?? '-'
}
const totalUsersLabel = computed(() => {
const value = stats.value.total || pagination.value.total
return value.toLocaleString()
})
const joinedThisMonthCountLabel = computed(() => stats.value.joined_this_month.toLocaleString())
function statusBadgeVariant(status: string) { function statusBadgeVariant(status: string) {
if (status === 'active') return 'success' if (status === 'active') return 'success'
if (status === 'inactive') return 'danger' if (status === 'inactive') return 'danger'
@@ -97,6 +168,11 @@ function formatDeletedAt(value: string | null | undefined): string {
return dayjs(value).format('DD MMM YYYY, HH:mm') return dayjs(value).format('DD MMM YYYY, HH:mm')
} }
function formatUserDate(value: string | null | undefined): string {
if (!value) return '-'
return dayjs(value).format('DD MMM YYYY')
}
function openDeleteConfirmation(user: UserListItem) { function openDeleteConfirmation(user: UserListItem) {
userToDelete.value = user userToDelete.value = user
deleteError.value = null deleteError.value = null
@@ -217,9 +293,27 @@ async function confirmRestore() {
const headers: TableHeader[] = [ const headers: TableHeader[] = [
{ title: 'Bil.', key: '#', sortable: false }, { title: 'Bil.', key: '#', sortable: false },
{ title: 'Name', key: 'name', sortable: true }, { title: 'Name', key: 'name', sortable: true },
{ title: 'Emel', key: 'email', sortable: true }, { title: 'Jenis Anggota', key: 'member_type', sortable: true },
{
title: 'Unit',
key: 'company_name',
sortable: false,
exportValue: (item) => getUserCompanyName(item),
},
{ title: 'Jawatan', key: 'position', sortable: true }, { title: 'Jawatan', key: 'position', sortable: true },
{ title: 'No. Anggota', key: 'member_number', sortable: true, align: 'center' }, { title: 'No. Anggota', key: 'member_number', sortable: true, align: 'center' },
{
title: 'Tarikh Menjadi Anggota',
key: 'join_date',
sortable: true,
exportValue: (item) => formatUserDate(item.join_date),
},
{
title: 'Tarikh Berhenti',
key: 'leave_date',
sortable: true,
exportValue: (item) => formatUserDate(item.leave_date),
},
{ {
title: 'Peranan', title: 'Peranan',
key: 'roles', key: 'roles',
@@ -230,10 +324,16 @@ const headers: TableHeader[] = [
{ title: 'Tindakan', key: 'actions', sortable: false }, { title: 'Tindakan', key: 'actions', sortable: false },
] ]
// deleted users table headers
const deletedHeaders: TableHeader[] = [ const deletedHeaders: TableHeader[] = [
{ title: 'Bil.', key: '#', sortable: false }, { title: 'Bil.', key: '#', sortable: false },
{ title: 'Name', key: 'name', sortable: true }, { title: 'Name', key: 'name', sortable: true },
{ title: 'Emel', key: 'email', sortable: true }, {
title: 'Unit',
key: 'company_name',
sortable: false,
exportValue: (item) => getUserCompanyName(item),
},
{ title: 'Jawatan', key: 'position', sortable: true }, { title: 'Jawatan', key: 'position', sortable: true },
{ title: 'No. Anggota', key: 'member_number', sortable: true, align: 'center' }, { title: 'No. Anggota', key: 'member_number', sortable: true, align: 'center' },
{ {
@@ -250,9 +350,20 @@ const deletedHeaders: TableHeader[] = [
const { const {
users, users,
loading, loading,
stats,
statsLoading,
statsError,
error, error,
search, search,
statusFilter, statusFilter,
joinDateFrom,
joinDateTo,
leaveDateFrom,
leaveDateTo,
hasJoinDateFilters,
hasLeaveDateFilters,
clearJoinDateFilters,
clearLeaveDateFilters,
sortBy, sortBy,
page, page,
itemsPerPage, itemsPerPage,
@@ -306,17 +417,105 @@ onMounted(() => {
<template> <template>
<div class="w-full space-y-6"> <div class="w-full space-y-6">
<div> <div>
<h2 class="text-lg font-medium">Senarai Pengguna</h2> <h2 class="text-lg font-medium">Senarai Daftar Anggota</h2>
<p class="mt-1 text-sm opacity-70">Urus dan semak pengguna koperasi.</p> <p class="mt-1 text-sm opacity-70">Urus dan semak anggota koperasi.</p>
</div> </div>
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<Box class="p-5">
<div class="flex items-start justify-between gap-4">
<div>
<div class="text-sm font-medium opacity-70">Jumlah Anggota</div>
<div class="mt-2 text-3xl font-semibold tabular-nums">{{ totalUsersLabel }}</div>
<div class="mt-1 text-xs opacity-60">Mengikut carian & penapis semasa</div>
</div>
<div class="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
<Lucide icon="Users" class="size-5" />
</div>
</div>
</Box>
<Box class="p-5">
<div class="flex items-start justify-between gap-4">
<div>
<div class="text-sm font-medium opacity-70">Baru Sertai</div>
<div class="mt-2 text-3xl font-semibold tabular-nums">{{ joinedThisMonthCountLabel }}</div>
<div class="mt-1 text-xs opacity-60">Bulan ini (semua rekod)</div>
<div v-if="statsError" class="mt-1 text-xs text-danger">{{ statsError }}</div>
</div>
<div class="flex size-10 items-center justify-center rounded-xl bg-primary/10 text-primary">
<Lucide icon="UserPlus" class="size-5" />
</div>
</div>
</Box>
</div>
<AlertRoot v-if="error" class="mt-6" variant="danger"> <AlertRoot v-if="error" class="mt-6" variant="danger">
<AlertTitle>Error</AlertTitle> <AlertTitle>Error</AlertTitle>
<AlertDescription>{{ error }}</AlertDescription> <AlertDescription>{{ error }}</AlertDescription>
</AlertRoot> </AlertRoot>
<AccordionRoot class="w-full" variant="boxed">
<AccordionItem raised="single" value="date-filters">
<AccordionTrigger>Penapis Tarikh</AccordionTrigger>
<AccordionContent>
<div class="flex flex-col gap-3">
<div class="rounded-lg border border-foreground/10 p-3">
<div class="flex flex-wrap items-end gap-3">
<div class="flex min-w-[16rem] flex-1 flex-col gap-1.5">
<span class="text-sm font-medium">Tarikh Menjadi Anggota</span>
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm opacity-70">Pantas:</span>
<Badge v-for="preset in QUICK_DATE_PRESETS" :key="`join-${preset.label}`" variant="ghost"
look="outline" role="button" tabindex="0" @click="applyJoinDatePreset(preset)"
@keydown.enter="applyJoinDatePreset(preset)">
{{ preset.label }}
</Badge>
</div>
<div class="flex items-center gap-2">
<Input v-model="joinDateFrom" type="date" aria-label="Tarikh menjadi anggota dari" />
<span class="text-sm opacity-50"></span>
<Input v-model="joinDateTo" type="date" aria-label="Tarikh menjadi anggota hingga" />
</div>
</div>
<Button v-if="hasJoinDateFilters" type="button" variant="ghost" look="outline"
@click="clearJoinDateFilters">
Reset
</Button>
</div>
</div>
<div class="rounded-lg border border-foreground/10 p-3">
<div class="flex flex-wrap items-end gap-3">
<div class="flex min-w-[16rem] flex-1 flex-col gap-1.5">
<span class="text-sm font-medium">Tarikh Berhenti</span>
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm opacity-70">Pantas:</span>
<Badge v-for="preset in QUICK_DATE_PRESETS" :key="`leave-${preset.label}`" variant="ghost"
look="outline" role="button" tabindex="0" @click="applyLeaveDatePreset(preset)"
@keydown.enter="applyLeaveDatePreset(preset)">
{{ preset.label }}
</Badge>
</div>
<div class="flex items-center gap-2">
<Input v-model="leaveDateFrom" type="date" aria-label="Tarikh berhenti dari" />
<span class="text-sm opacity-50"></span>
<Input v-model="leaveDateTo" type="date" aria-label="Tarikh berhenti hingga" />
</div>
</div>
<Button v-if="hasLeaveDateFilters" type="button" variant="ghost" look="outline"
@click="clearLeaveDateFilters">
Reset
</Button>
</div>
</div>
</div>
</AccordionContent>
</AccordionItem>
</AccordionRoot>
<DataTable :headers="headers" :items="users" :loading="loading" :pagination="pagination" :current-sort="sortBy" <DataTable :headers="headers" :items="users" :loading="loading" :pagination="pagination" :current-sort="sortBy"
show-pagination exportable export-file-name="users" v-model:page="page" v-model:items-per-page="itemsPerPage" show-pagination exportable export-file-name="users" export-pdf-title="Senarai Daftar Anggota" v-model:page="page"
@update:sort-by="handleSortUpdate"> v-model:items-per-page="itemsPerPage" @update:sort-by="handleSortUpdate">
<template #toolbar> <template #toolbar>
<div class="flex w-full flex-col gap-3"> <div class="flex w-full flex-col gap-3">
<div class="flex w-full flex-wrap items-center gap-3"> <div class="flex w-full flex-wrap items-center gap-3">
@@ -324,7 +523,7 @@ onMounted(() => {
<Search <Search
class="pointer-events-none absolute top-1/2 left-3 z-10 size-4 -translate-y-1/2 text-foreground/50" class="pointer-events-none absolute top-1/2 left-3 z-10 size-4 -translate-y-1/2 text-foreground/50"
aria-hidden="true" /> aria-hidden="true" />
<Input v-model="search" type="search" placeholder="Search name, email, IC, phone, role..." <Input v-model="search" type="search" placeholder="Cari nama, email, no. anggota, jawatan..."
class="w-full pl-9" aria-label="Search users" /> class="w-full pl-9" aria-label="Search users" />
</div> </div>
<Button v-if="hasPermission('daftar pengguna baru')" type="button" variant="primary" look="outline" <Button v-if="hasPermission('daftar pengguna baru')" type="button" variant="primary" look="outline"
@@ -361,6 +560,14 @@ onMounted(() => {
<span class="lowercase">{{ item.email }}</span> <span class="lowercase">{{ item.email }}</span>
</template> </template>
<template #item.member_type="{ item }">
<span class="capitalize">{{ item.member_type }}</span>
</template>
<template #item.company_name="{ item }">
<span>{{ getUserCompanyName(item) }}</span>
</template>
<template #item.roles="{ item }"> <template #item.roles="{ item }">
{{ formatUserRoles(item.roles) }} {{ formatUserRoles(item.roles) }}
</template> </template>
@@ -369,6 +576,14 @@ onMounted(() => {
<span class="text-center">{{ item.member_number }}</span> <span class="text-center">{{ item.member_number }}</span>
</template> </template>
<template #item.join_date="{ item }">
{{ formatUserDate(item.join_date) }}
</template>
<template #item.leave_date="{ item }">
{{ formatUserDate(item.leave_date) }}
</template>
<!-- centre align status --> <!-- centre align status -->
<template #item.status="{ item }"> <template #item.status="{ item }">
<Badge :variant="statusBadgeVariant(item.status)" class="capitalize text-center"> <Badge :variant="statusBadgeVariant(item.status)" class="capitalize text-center">
@@ -440,6 +655,14 @@ onMounted(() => {
<span class="lowercase">{{ item.email }}</span> <span class="lowercase">{{ item.email }}</span>
</template> </template>
<template #item.member_type="{ item }">
<span class="uppercase">{{ item.member_type }}</span>
</template>
<template #item.company_name="{ item }">
<span>{{ getUserCompanyName(item) }}</span>
</template>
<template #item.roles="{ item }"> <template #item.roles="{ item }">
{{ formatUserRoles(item.roles) }} {{ formatUserRoles(item.roles) }}
</template> </template>
@@ -107,6 +107,10 @@ function formatAddressLine(address: Address) {
<FieldLabel for="view-user-join-date">Tarikh Sertai</FieldLabel> <FieldLabel for="view-user-join-date">Tarikh Sertai</FieldLabel>
<Input id="view-user-join-date" :model-value="formatDate(user.join_date)" type="text" disabled /> <Input id="view-user-join-date" :model-value="formatDate(user.join_date)" type="text" disabled />
</Field> </Field>
<Field v-if="user.status === 'inactive' || user.leave_date">
<FieldLabel for="view-user-leave-date">Tarikh Berhenti Menjadi Anggota</FieldLabel>
<Input id="view-user-leave-date" :model-value="formatDate(user.leave_date)" type="text" disabled />
</Field>
<Field> <Field>
<FieldLabel for="view-user-birth-date">Tarikh Lahir</FieldLabel> <FieldLabel for="view-user-birth-date">Tarikh Lahir</FieldLabel>
<Input id="view-user-birth-date" :model-value="formatDate(user.birth_date)" type="text" disabled /> <Input id="view-user-birth-date" :model-value="formatDate(user.birth_date)" type="text" disabled />
@@ -149,5 +153,32 @@ function formatAddressLine(address: Address) {
Tiada alamat direkodkan. Tiada alamat direkodkan.
</div> </div>
</Box> </Box>
<Box raised="single" class="p-6">
<div class="mb-6">
<h3 class="text-lg font-semibold text-slate-900">Penama</h3>
<p class="mt-1 text-sm text-slate-500">Senarai penama pengguna.</p>
</div>
<div v-if="user.heirs?.length" class="space-y-3">
<div v-for="heir in user.heirs" :key="heir.id" class="rounded-lg border border-foreground/10 p-4">
<div class="flex flex-wrap items-center gap-2">
<span class="font-medium text-slate-900">{{ heir.name }}</span>
<Badge v-if="heir.is_primary" class="bg-green-500 text-white">Utama</Badge>
<Badge look="outline">{{ heir.relationship }}</Badge>
</div>
<p class="mt-1 text-sm text-slate-500">{{ heir.ic_number }}</p>
<p class="mt-1 text-sm text-slate-500">{{ heir.phone_number }}</p>
<p class="mt-1 text-sm text-slate-700">{{ heir.address }}</p>
</div>
</div>
<div
v-else
class="rounded-lg border border-dashed border-foreground/15 p-6 text-center text-sm text-slate-500"
>
Tiada penama direkodkan.
</div>
</Box>
</div> </div>
</template> </template>
+75 -42
View File
@@ -2,6 +2,7 @@
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert' import { AlertRoot, AlertTitle, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Box } from '@/components/ui/box' import { Box } from '@/components/ui/box'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { TabsRoot, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' import { TabsRoot, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
@@ -13,7 +14,6 @@ import type { UserDetail } from '../types/user.types'
import UserProfileTab from './UserProfileTab.vue' import UserProfileTab from './UserProfileTab.vue'
import UserEmploymentTab from './UserEmploymentTab.vue' import UserEmploymentTab from './UserEmploymentTab.vue'
import UserBankDetailTab from './UserBankDetailTab.vue' import UserBankDetailTab from './UserBankDetailTab.vue'
import UserHeirTab from './UserHeirTab.vue'
const router = useRouter() const router = useRouter()
const route = useRoute() const route = useRoute()
@@ -29,15 +29,41 @@ const displayValue = (value: string | number | null | undefined) => {
return String(value).trim() || '-' return String(value).trim() || '-'
} }
const STATUS_LABELS: Record<string, string> = {
active: 'Aktif',
pending: 'Menunggu',
inactive: 'Tidak Aktif',
}
const statusLabel = computed(() => { const statusLabel = computed(() => {
const status = user.value?.status const status = user.value?.status
if (!status) return '-' if (!status) return '-'
return status.charAt(0).toUpperCase() + status.slice(1) return STATUS_LABELS[status] ?? status.charAt(0).toUpperCase() + status.slice(1)
}) })
const roleNames = computed(() => const statusBadgeVariant = computed(() => {
user.value?.roles?.map((role) => role.name).join(', ') || '-', const status = user.value?.status
) if (status === 'active') return 'success' as const
if (status === 'pending') return 'pending' as const
return 'secondary' as const
})
const companyName = computed(() => {
const employments = user.value?.employments ?? []
const currentEmployment = employments.find((employment) => employment.is_current)
return currentEmployment?.company_name ?? employments[0]?.company_name ?? null
})
function formatDateLabel(value: string | null | undefined): string {
if (!value) return '-'
const date = new Date(value)
if (Number.isNaN(date.getTime())) return value
return new Intl.DateTimeFormat('ms-MY', {
day: 'numeric',
month: 'short',
year: 'numeric',
}).format(date)
}
const avatarFallback = computed(() => { const avatarFallback = computed(() => {
const name = user.value?.name?.trim() const name = user.value?.name?.trim()
@@ -82,53 +108,66 @@ onMounted(() => {
<TabsRoot v-else-if="user" defaultValue="1"> <TabsRoot v-else-if="user" defaultValue="1">
<Box raised="single" class="mt-5 p-0"> <Box raised="single" class="mt-5 p-0">
<div class="flex flex-col border-b border-foreground/15 p-5 lg:flex-row"> <div class="flex flex-col border-b border-foreground/15 lg:flex-row">
<div class="flex flex-1 items-center justify-center px-5 lg:justify-start"> <!-- Identity -->
<div class="flex flex-1 items-center justify-center p-5 lg:justify-start">
<AvatarRoot class="size-20 border-5 bg-background rounded-full sm:size-24 lg:size-32"> <AvatarRoot class="size-20 border-5 bg-background rounded-full sm:size-24 lg:size-32">
<AvatarFallback>{{ avatarFallback }}</AvatarFallback> <AvatarFallback>{{ avatarFallback }}</AvatarFallback>
<AvatarImage v-if="user.image_url" :src="user.image_url" :alt="user.name" /> <AvatarImage v-if="user.image_url" :src="user.image_url" :alt="user.name" />
</AvatarRoot> </AvatarRoot>
<div class="ml-5"> <div class="ml-5 min-w-0">
<div class="w-24 truncate text-lg font-medium sm:w-40 sm:whitespace-normal"> <div class="truncate text-lg font-medium sm:whitespace-normal">
{{ displayValue(user.name) }} {{ displayValue(user.name) }}
</div> </div>
<div class="opacity-70">{{ roleNames }}</div> <div v-if="user.member_type"
class="mt-1 truncate text-sm capitalize opacity-70 sm:whitespace-normal">
{{ displayValue(user.member_type) }}
</div>
<div class="mt-3 flex flex-wrap items-center gap-2">
<Badge :variant="statusBadgeVariant">{{ statusLabel }}</Badge>
<Badge v-if="user.member_number" look="outline" variant="secondary">
No. {{ user.member_number }}
</Badge>
</div>
</div> </div>
</div> </div>
<div
class="mt-6 flex-1 border-t border-l border-r border-foreground/15 px-5 pt-5 lg:mt-0 lg:border-t-0 lg:pt-0"> <!-- Contact & membership -->
<div class="text-center font-medium lg:mt-3 lg:text-left">Maklumat Hubungan</div> <div class="flex-1 border-t border-foreground/15 p-5 lg:border-t-0 lg:border-l">
<div class="mt-4 flex flex-col items-center justify-center lg:items-start"> <div class="text-center font-medium lg:text-left">Maklumat Hubungan</div>
<div class="mt-4 flex flex-col items-center lg:items-start">
<div class="flex items-center truncate sm:whitespace-normal"> <div class="flex items-center truncate sm:whitespace-normal">
<Lucide class="mr-2 size-4" icon="Mail" /> <Lucide class="mr-2 size-4 shrink-0" icon="Mail" />
{{ displayValue(user.email) }} {{ displayValue(user.email) }}
</div> </div>
<div class="mt-3 flex items-center truncate sm:whitespace-normal"> <div class="mt-3 flex items-center truncate sm:whitespace-normal">
<Lucide class="mr-2 size-4" icon="Phone" /> <Lucide class="mr-2 size-4 shrink-0" icon="Phone" />
{{ displayValue(user.phone_number) }} {{ displayValue(user.phone_number) }}
</div> </div>
<div class="mt-3 flex items-center truncate sm:whitespace-normal"> <div class="mt-3 flex items-center truncate sm:whitespace-normal">
<Lucide class="mr-2 size-4" icon="IdCard" /> <Lucide class="mr-2 size-4 shrink-0" icon="IdCard" />
{{ displayValue(user.ic_number) }} {{ displayValue(user.ic_number) }}
</div> </div>
</div> </div>
</div>
<div <div class="mt-6 grid grid-cols-2 gap-4 sm:grid-cols-3">
class="mt-6 flex flex-1 items-center justify-center border-t border-foreground/15 px-5 pt-5 lg:mt-0 lg:border-0 lg:pt-0"> <div class="text-center lg:text-left">
<div class="grid grid-cols-3 gap-5"> <div class="truncate text-base font-medium">
<div class="text-center"> {{ displayValue(user.position) }}
<div class="truncate text-xl font-medium">{{ user.roles?.length ?? 0 }}</div>
<div class="opacity-70">Peranan</div>
</div>
<div class="text-center">
<div class="text-xl font-medium">{{ statusLabel }}</div>
<div class="opacity-70">Status</div>
</div>
<div class="text-center">
<div class="truncate text-xl font-medium capitalize">
{{ displayValue(user.member_type) }}
</div> </div>
<div class="opacity-70">Jenis Anggota</div> <div class="text-xs opacity-70">Jawatan</div>
</div>
<div class="text-center lg:text-left">
<div class="truncate text-base font-medium">
{{ displayValue(companyName) }}
</div>
<div class="text-xs opacity-70">Unit</div>
</div>
<div class="col-span-2 text-center sm:col-span-1 lg:text-left">
<div class="truncate text-base font-medium">
{{ formatDateLabel(user.join_date) }}
</div>
<div class="text-xs opacity-70">Tarikh Sertai</div>
</div> </div>
</div> </div>
</div> </div>
@@ -136,18 +175,15 @@ onMounted(() => {
<div class="px-5 py-4"> <div class="px-5 py-4">
<TabsList class="mb-0 w-full flex justify-between"> <TabsList class="mb-0 w-full flex justify-between">
<TabsTrigger class="inline-flex w-1/4 items-center justify-center" value="1"> <TabsTrigger class="inline-flex w-1/3 items-center justify-center" value="1">
<Lucide class="mr-2 size-4" icon="User" /> Profil <Lucide class="mr-2 size-4" icon="User" /> Profil
</TabsTrigger> </TabsTrigger>
<TabsTrigger class="inline-flex w-1/4 items-center justify-center" value="5"> <TabsTrigger class="inline-flex w-1/3 items-center justify-center" value="5">
<Lucide class="mr-2 size-4" icon="Briefcase" /> Pekerjaan <Lucide class="mr-2 size-4" icon="Briefcase" /> Pekerjaan
</TabsTrigger> </TabsTrigger>
<TabsTrigger class="inline-flex w-1/4 items-center justify-center" value="3"> <TabsTrigger class="inline-flex w-1/3 items-center justify-center" value="3">
<Lucide class="mr-2 size-4" icon="Banknote" /> Bank <Lucide class="mr-2 size-4" icon="Banknote" /> Bank
</TabsTrigger> </TabsTrigger>
<TabsTrigger class="inline-flex w-1/4 items-center justify-center" value="6">
<Lucide class="mr-2 size-4" icon="Users" /> Penama
</TabsTrigger>
</TabsList> </TabsList>
</div> </div>
</Box> </Box>
@@ -161,9 +197,6 @@ onMounted(() => {
<TabsContent value="3" class="mt-8"> <TabsContent value="3" class="mt-8">
<UserBankDetailTab :user="user" embedded /> <UserBankDetailTab :user="user" embedded />
</TabsContent> </TabsContent>
<TabsContent value="6" class="mt-8">
<UserHeirTab :user="user" embedded />
</TabsContent>
</TabsRoot> </TabsRoot>
</div> </div>
</template> </template>
@@ -15,6 +15,15 @@ type UserApiResponse = {
message?: string message?: string
} }
type UserStatsApiResponse = {
success: boolean
data: {
total: number
joined_this_month: number
}
message?: string
}
export async function listUsers( export async function listUsers(
params: ListUsersParams, params: ListUsersParams,
): Promise<PaginatedApiResponse<UserListItem>> { ): Promise<PaginatedApiResponse<UserListItem>> {
@@ -29,6 +38,20 @@ export async function listUsers(
return data return data
} }
export async function getUserStats(
params: Omit<ListUsersParams, 'page' | 'per_page' | 'sort_by' | 'sort_order'>,
): Promise<UserStatsApiResponse> {
const { data } = await api.get<UserStatsApiResponse>('/v1/users/stats', {
params,
})
if (!data.success) {
throw new Error(data.message ?? 'Failed to load user stats')
}
return data
}
export async function listDeletedUsers( export async function listDeletedUsers(
params: ListDeletedUsersParams, params: ListDeletedUsersParams,
): Promise<PaginatedApiResponse<UserListItem>> { ): Promise<PaginatedApiResponse<UserListItem>> {
+10
View File
@@ -20,12 +20,16 @@ export interface UserListItem {
email: string email: string
ic_number: string ic_number: string
position: string position: string
company_name?: string | null
employments?: Employment[]
phone_number: string phone_number: string
image_url: string | null image_url: string | null
status: string status: string
deleted_at?: string | null deleted_at?: string | null
roles: UserRole[] roles: UserRole[]
member_number?: number | null member_number?: number | null
join_date?: string | null
leave_date?: string | null
} }
export interface UserDetail { export interface UserDetail {
@@ -42,6 +46,7 @@ export interface UserDetail {
member_number: number | null member_number: number | null
member_type: string | null member_type: string | null
join_date: string | null join_date: string | null
leave_date: string | null
birth_date: string | null birth_date: string | null
birth_place: string | null birth_place: string | null
roles: UserRole[] roles: UserRole[]
@@ -62,6 +67,7 @@ export interface UpdateUserPayload {
member_number?: number | null member_number?: number | null
member_type?: string | null member_type?: string | null
join_date?: string | null join_date?: string | null
leave_date?: string | null
birth_date?: string | null birth_date?: string | null
birth_place?: string | null birth_place?: string | null
} }
@@ -89,6 +95,10 @@ export interface ListUsersParams {
sort_order: string sort_order: string
search?: string search?: string
status?: string status?: string
join_date_from?: string
join_date_to?: string
leave_date_from?: string
leave_date_to?: string
} }
export interface ListDeletedUsersParams { export interface ListDeletedUsersParams {
+7
View File
@@ -0,0 +1,7 @@
export function sanitizeIcNumberInput(value: string): string {
return value.replace(/\D/g, '')
}
export function sanitizeNameInput(value: string): string {
return value.toUpperCase()
}