DONE: digital card with profile display: WIP: membership condition on letter, is_first_time column in users table

This commit is contained in:
ISMAIL MASSERAN
2026-07-06 09:43:58 +08:00
parent 61345e9cf0
commit ac8f00175a
34 changed files with 1662 additions and 99 deletions
+50
View File
@@ -8,6 +8,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Activitylog\LogOptions;
use Spatie\Activitylog\Traits\LogsActivity;
@@ -51,6 +52,7 @@ class User extends Authenticatable
'marriage_status',
'member_number',
'member_type',
'public_profile_token',
'join_date',
'birth_date',
'birth_place',
@@ -67,8 +69,55 @@ class User extends Authenticatable
'two_factor_secret',
'two_factor_recovery_codes',
'two_factor_confirmed_at',
'public_profile_token',
];
protected static function booted(): void
{
static::creating(function (User $user) {
$expiryDays = self::publicProfileTokenTtlDays();
if (empty($user->public_profile_token)) {
$user->public_profile_token = Str::random(48);
}
if (empty($user->public_profile_token_expires_at)) {
$user->public_profile_token_expires_at = now()->addDays($expiryDays);
}
});
}
public static function publicProfileTokenTtlDays(): int
{
return (int) config('user.public_profile_token_ttl_days', 90);
}
public function isPublicProfileTokenExpired(): bool
{
return $this->public_profile_token_expires_at !== null
&& $this->public_profile_token_expires_at->isPast();
}
public function ensurePublicProfileToken(): string
{
$expiryDays = self::publicProfileTokenTtlDays();
if (blank($this->public_profile_token) || $this->isPublicProfileTokenExpired()) {
$this->forceFill([
'public_profile_token' => Str::random(48),
'public_profile_token_expires_at' => now()->addDays($expiryDays),
])->save();
return $this->public_profile_token;
}
$this->forceFill([
'public_profile_token_expires_at' => now()->addDays($expiryDays),
])->save();
return $this->public_profile_token;
}
/**
* Get the attributes that should be cast.
*
@@ -84,6 +133,7 @@ class User extends Authenticatable
'marriage_status' => 'string',
'member_number' => 'integer',
'member_type' => 'string',
'public_profile_token_expires_at' => 'datetime',
'join_date' => 'date',
'birth_date' => 'date',
'birth_place' => 'string',
@@ -24,6 +24,7 @@ class SessionController extends Controller
], 401);
}
$user->ensurePublicProfileToken();
$user->load(['roles.permissions']);
return response()->json([
@@ -12,6 +12,8 @@ class AuthSessionService
{
public function createAuthResponse(User $user, string $message, int $status = 200): JsonResponse
{
$user->ensurePublicProfileToken();
if (config('app.env') !== 'local') {
$user->tokens()->delete();
}
@@ -36,6 +36,7 @@ class UserResource extends JsonResource
'marriage_status' => $this->marriage_status,
'member_number' => $this->member_number,
'member_type' => $this->member_type,
'public_profile_token' => $this->public_profile_token,
'join_date' => $this->join_date,
'birth_date' => $this->birth_date,
'birth_place' => $this->birth_place,
+3
View File
@@ -2,4 +2,7 @@
return [
'name' => 'User',
'public_profile_token_ttl_days' => (int) env('PUBLIC_PROFILE_TOKEN_TTL_DAYS', 90),
'frontend_url' => rtrim(env('FRONTEND_URL', env('APP_URL', 'http://localhost')), '/'),
'digital_card_logo_path' => env('DIGITAL_CARD_LOGO_PATH', public_path('images/logo/logo-kopkb.svg')),
];
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Modules\Auth\Entities\User;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('public_profile_token', 64)->nullable()->unique()->after('member_type');
});
User::withTrashed()
->whereNull('public_profile_token')
->cursor()
->each(function (User $user) {
$user->forceFill([
'public_profile_token' => Str::random(48),
])->saveQuietly();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropUnique(['public_profile_token']);
$table->dropColumn('public_profile_token');
});
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Modules\Auth\Entities\User;
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->timestamp('public_profile_token_expires_at')->nullable()->after('public_profile_token');
});
$expiryDays = (int) config('user.public_profile_token_ttl_days', 90);
User::withTrashed()
->whereNotNull('public_profile_token')
->whereNull('public_profile_token_expires_at')
->cursor()
->each(function (User $user) use ($expiryDays) {
$user->forceFill([
'public_profile_token_expires_at' => now()->addDays($expiryDays),
])->saveQuietly();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('public_profile_token_expires_at');
});
}
};
@@ -0,0 +1,61 @@
<?php
namespace Modules\User\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Modules\User\Services\MemberDigitalCardService;
use Symfony\Component\HttpFoundation\Response;
class MemberDigitalCardController extends Controller
{
public function __construct(
protected MemberDigitalCardService $memberDigitalCardService
) {}
public function download(Request $request): Response|JsonResponse
{
$validated = $request->validate([
'side' => 'sometimes|in:depan,belakang',
]);
$user = $request->user();
$side = $validated['side'] ?? 'depan';
if ($user->status !== 'active') {
return response()->json([
'success' => false,
'message' => 'Kad digital hanya tersedia untuk anggota aktif.',
'code' => 'digital_card_inactive',
'data' => null,
], 403);
}
try {
$png = $this->memberDigitalCardService->renderPng($user, $side);
$memberNumber = $user->member_number ?: 'anggota';
$filename = sprintf('kad-digital-%s-%s.png', $memberNumber, $side);
return response($png, Response::HTTP_OK, [
'Content-Type' => 'image/png',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
'Cache-Control' => 'no-store, private',
]);
} catch (\Throwable $exception) {
Log::error('Failed to render member digital card.', [
'user_id' => $user->id,
'side' => $side,
'message' => $exception->getMessage(),
]);
return response()->json([
'success' => false,
'message' => 'Gagal menjana kad digital. Sila cuba lagi.',
'code' => 'digital_card_render_failed',
'data' => null,
], 500);
}
}
}
@@ -0,0 +1,37 @@
<?php
namespace Modules\User\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Modules\User\Services\PublicMemberProfileService;
use Modules\User\Transformers\PublicMemberProfileResource;
class PublicMemberProfileController extends Controller
{
public function __construct(
protected PublicMemberProfileService $publicMemberProfileService
) {}
public function show(string $token): JsonResponse
{
$member = $this->publicMemberProfileService->findMemberByToken($token);
if (! $member) {
return response()->json([
'success' => false,
'message' => 'Anggota tidak dijumpai atau tidak sah.',
'code' => 'public_profile_not_found',
'data' => null,
], 404);
}
$member = $this->publicMemberProfileService->loadVerifiableRelations($member);
return response()->json([
'success' => true,
'message' => 'Anggota disahkan.',
'data' => new PublicMemberProfileResource($member),
]);
}
}
@@ -5,6 +5,8 @@ namespace Modules\User\Providers;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Cache\RateLimiting\Limit;
use Modules\Auth\Entities\User;
use Modules\User\Policies\UserPolicy;
use Modules\User\Entities\Address;
@@ -34,6 +36,7 @@ class UserServiceProvider extends ServiceProvider
*/
public function boot(): void
{
$this->registerRateLimiters();
$this->registerCommands();
$this->registerCommandSchedules();
$this->registerTranslations();
@@ -96,6 +99,13 @@ class UserServiceProvider extends ServiceProvider
Gate::policy(Heir::class, HeirPolicy::class);
}
protected function registerRateLimiters(): void
{
RateLimiter::for('public-member-profile', function ($request) {
return Limit::perMinute(60)->by($request->ip());
});
}
/**
* Register commands in the format of Command::class
*/
@@ -0,0 +1,166 @@
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
width: 840px;
height: 540px;
overflow: hidden;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.card {
position: relative;
width: 840px;
height: 540px;
overflow: hidden;
border-radius: 16px;
color: #eff6ff;
background: linear-gradient(to bottom right, #1e3a8a, #1e40af, #2563eb);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
outline: 1px solid rgba(255, 255, 255, 0.2);
padding: 24px;
}
.orb-1 {
position: absolute;
right: -48px;
top: -48px;
width: 176px;
height: 176px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.1);
}
.orb-2 {
position: absolute;
bottom: -64px;
left: -40px;
width: 192px;
height: 192px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.05);
}
.content {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
flex-shrink: 0;
}
.logo {
height: 36px;
width: auto;
filter: brightness(0) invert(1);
}
.badge {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.18em;
opacity: 0.75;
text-align: right;
}
.main {
display: flex;
flex: 1;
min-height: 0;
align-items: center;
gap: 24px;
margin-top: 20px;
}
.qr-wrap {
flex-shrink: 0;
border-radius: 8px;
background: #ffffff;
padding: 12px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.qr-wrap img {
display: block;
width: 144px;
height: 144px;
}
.info {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
justify-content: center;
gap: 20px;
}
.info p {
font-size: 18px;
line-height: 1.375;
opacity: 0.85;
}
.label {
font-size: 14px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.1em;
opacity: 0.6;
}
.member-number {
margin-top: 2px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 36px;
font-weight: 600;
letter-spacing: 0.1em;
}
.footer {
flex-shrink: 0;
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid rgba(255, 255, 255, 0.15);
text-align: center;
}
.footer p {
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.2em;
opacity: 0.5;
}
</style>
</head>
<body>
<div class="card">
<div class="orb-1"></div>
<div class="orb-2"></div>
<div class="content">
<div class="header">
@if ($logoDataUri)
<img src="{{ $logoDataUri }}" alt="" class="logo">
@endif
<div class="badge">Belakang · Kod QR</div>
</div>
<div class="main">
<div class="qr-wrap">
<img src="{{ $qrDataUri }}" alt="Kod QR profil anggota">
</div>
<div class="info">
<p>Imbas untuk sahkan profil anggota MyKOPKB.</p>
<div>
<div class="label">No. Anggota</div>
<div class="member-number">{{ $memberNumber }}</div>
</div>
</div>
</div>
<div class="footer">
<p>Koperasi Permodalan Kelantan Berhad (KOPKB)</p>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,214 @@
<!DOCTYPE html>
<html lang="ms">
<head>
<meta charset="utf-8">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body {
width: 840px;
height: 540px;
overflow: hidden;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
.card {
position: relative;
width: 840px;
height: 540px;
overflow: hidden;
border-radius: 16px;
color: #eff6ff;
background: linear-gradient(to bottom right, #1e3a8a, #1e40af, #1d4ed8);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1);
outline: 1px solid rgba(255, 255, 255, 0.2);
padding: 32px;
}
.orb-1 {
position: absolute;
right: -40px;
top: -40px;
width: 192px;
height: 192px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.1);
}
.orb-2 {
position: absolute;
bottom: -48px;
left: -32px;
width: 208px;
height: 208px;
border-radius: 9999px;
background: rgba(255, 255, 255, 0.05);
}
.avatar {
position: absolute;
top: 50%;
right: 24px;
transform: translateY(-50%);
width: 112px;
height: 112px;
overflow: hidden;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.25);
background: rgba(255, 255, 255, 0.1);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
.avatar img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.avatar-fallback {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.15);
font-size: 18px;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.content {
position: relative;
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
}
.header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
flex-shrink: 0;
}
.logo {
height: 40px;
width: auto;
filter: brightness(0) invert(1);
}
.badge {
font-size: 14px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.2em;
opacity: 0.8;
text-align: right;
}
.main {
display: flex;
flex: 1;
min-height: 0;
flex-direction: column;
justify-content: center;
gap: 16px;
padding: 8px 0;
}
.label {
font-size: 14px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.1em;
opacity: 0.7;
}
.member-number {
margin-top: 2px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 48px;
font-weight: 600;
letter-spacing: 0.15em;
}
.company-block {
min-width: 0;
padding-right: 152px;
}
.company-value {
font-size: 20px;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.footer {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
flex-shrink: 0;
padding-top: 16px;
border-top: 1px solid rgba(255, 255, 255, 0.15);
}
.footer-name {
min-width: 0;
flex: 1;
font-size: 24px;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.footer-type {
flex-shrink: 0;
text-align: right;
font-size: 24px;
font-weight: 600;
}
.footer-sub {
margin-top: 2px;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 0.05em;
opacity: 0.6;
}
</style>
</head>
<body>
<div class="card">
<div class="orb-1"></div>
<div class="orb-2"></div>
<div class="avatar">
@if ($avatarDataUri)
<img src="{{ $avatarDataUri }}" alt="{{ $memberName }}">
@else
<div class="avatar-fallback">{{ $avatarInitials }}</div>
@endif
</div>
<div class="content">
<div class="header">
@if ($logoDataUri)
<img src="{{ $logoDataUri }}" alt="" class="logo">
@endif
<div class="badge">Kad Digital</div>
</div>
<div class="main">
<div>
<div class="label">No. Anggota</div>
<div class="member-number">{{ $memberNumber }}</div>
</div>
<div class="company-block">
<div class="label">Unit</div>
<div class="company-value">{{ $companyName }}</div>
</div>
</div>
<div class="footer">
<div>
<div class="footer-name">{{ $memberName }}</div>
<div class="footer-sub">Nama</div>
</div>
<div>
<div class="footer-type">{{ $memberType }}</div>
<div class="footer-sub">Jenis Anggota</div>
</div>
</div>
</div>
</div>
</body>
</html>
+10
View File
@@ -8,6 +8,14 @@ use Modules\User\Http\Controllers\EmploymentController;
use Modules\User\Http\Controllers\BankController;
use Modules\User\Http\Controllers\BankDetailController;
use Modules\User\Http\Controllers\HeirController;
use Modules\User\Http\Controllers\MemberDigitalCardController;
use Modules\User\Http\Controllers\PublicMemberProfileController;
Route::prefix('v1/public')->group(function () {
Route::middleware('throttle:public-member-profile')
->get('members/{token}', [PublicMemberProfileController::class, 'show'])
->name('user.public.member-profile');
});
Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(function () {
Route::get('users/deleted', [UserController::class, 'deletedIndex'])->name('users.deleted.index');
@@ -28,6 +36,8 @@ Route::middleware(['auth:sanctum', 'single.session'])->prefix('v1')->group(funct
// User profile management routes
Route::post('/profile', [UserController::class, 'updateProfile']);
Route::put('/profile/password', [UserController::class, 'updatePassword']);
Route::get('/profile/digital-card', [MemberDigitalCardController::class, 'download'])
->name('profile.digital-card.download');
// Impersonation routes
Route::get('/impersonate/take/{id}', [ImpersonateController::class, 'take'])->name('impersonate');
@@ -0,0 +1,141 @@
<?php
namespace Modules\User\Services;
use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\View;
use Modules\Auth\Entities\User;
use Spatie\Browsershot\Browsershot;
class MemberDigitalCardService
{
public const CARD_WIDTH = 840;
public const CARD_HEIGHT = 540;
public function renderPng(User $user, string $side): string
{
$view = $side === 'belakang'
? 'user::digital-card.back'
: 'user::digital-card.front';
$html = View::make($view, $this->prepareViewData($user))->render();
return $this->makeBrowsershot($html)->screenshot();
}
/**
* @return array<string, mixed>
*/
protected function prepareViewData(User $user): array
{
$user = app(PublicMemberProfileService::class)->loadVerifiableRelations($user);
$user->ensurePublicProfileToken();
$currentEmployment = $user->employments->firstWhere('is_current', true)
?? $user->employments->first();
$logoPath = config('user.digital_card_logo_path');
$profileUrl = rtrim(config('user.frontend_url'), '/').'/v/'.$user->public_profile_token;
return [
'memberNumber' => $this->displayCardValue($user->member_number),
'memberName' => $user->name ?: '-',
'memberType' => $this->displayCardValue($user->member_type),
'companyName' => $this->displayCardValue($currentEmployment?->company_name),
'avatarDataUri' => $this->resolveStorageDataUri($user->image_url),
'avatarInitials' => $this->avatarInitials($user->name),
'logoDataUri' => $this->resolveFileDataUri($logoPath),
'profileUrl' => $profileUrl,
'qrDataUri' => $this->generateQrDataUri($profileUrl),
];
}
protected function makeBrowsershot(string $html): Browsershot
{
$browsershot = Browsershot::html($html)
->setNodeModulePath(config('browsershot.node_module_path'))
->timeout(config('browsershot.timeout'))
->windowSize(self::CARD_WIDTH, self::CARD_HEIGHT)
->deviceScaleFactor(2)
->showBackground();
if ($nodeBinary = config('browsershot.node_binary')) {
$browsershot->setNodeBinary($nodeBinary);
}
if ($npmBinary = config('browsershot.npm_binary')) {
$browsershot->setNpmBinary($npmBinary);
}
if ($chromePath = config('browsershot.chrome_path')) {
$browsershot->setChromePath($chromePath);
}
if (config('browsershot.no_sandbox')) {
$browsershot->noSandbox();
}
return $browsershot;
}
protected function generateQrDataUri(string $content): string
{
$renderer = new ImageRenderer(
new RendererStyle(220, 1),
new SvgImageBackEnd
);
$writer = new Writer($renderer);
$svg = $writer->writeString($content);
return 'data:image/svg+xml;base64,'.base64_encode($svg);
}
protected function resolveFileDataUri(?string $path): ?string
{
if (empty($path) || ! file_exists($path)) {
return null;
}
$mime = mime_content_type($path) ?: 'image/svg+xml';
return 'data:'.$mime.';base64,'.base64_encode(file_get_contents($path));
}
protected function resolveStorageDataUri(?string $path): ?string
{
if (blank($path)) {
return null;
}
$fullPath = Storage::disk('public')->path($path);
return $this->resolveFileDataUri($fullPath);
}
protected function avatarInitials(?string $name): string
{
$trimmed = trim((string) $name);
if ($trimmed === '') {
return '--';
}
return strtoupper(mb_substr($trimmed, 0, 2));
}
protected function displayCardValue(mixed $value): string
{
if ($value === null || $value === '') {
return '-';
}
$trimmed = trim((string) $value);
return $trimmed !== '' ? $trimmed : '-';
}
}
@@ -0,0 +1,25 @@
<?php
namespace Modules\User\Services;
use Modules\Auth\Entities\User;
class PublicMemberProfileService
{
public function findMemberByToken(string $token): ?User
{
return User::query()
->where('public_profile_token', $token)
->where('status', 'active')
->first();
}
public function loadVerifiableRelations(User $member): User
{
$member->load(['employments' => function ($query) {
$query->orderByDesc('is_current')->orderByDesc('start_date');
}]);
return $member;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Modules\User\Transformers;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;
class PublicMemberProfileResource extends JsonResource
{
public function toArray(Request $request): array
{
$currentEmployment = $this->employments->firstWhere('is_current', true)
?? $this->employments->first();
return [
'name' => $this->name,
'member_number' => $this->member_number,
'member_type' => $this->member_type,
'status' => $this->status,
'image_url' => $this->image_url ? Storage::disk('public')->url($this->image_url) : null,
'company_name' => $currentEmployment?->company_name,
'verified_at' => now()->toIso8601String(),
];
}
}