refactor: susun semula struktur folder — Laravel source ke src/

This commit is contained in:
Saufi
2026-05-19 15:58:35 +08:00
parent f052251b94
commit bf53c71b45
10806 changed files with 1385379 additions and 121 deletions

18
src/.editorconfig Normal file
View File

@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[{compose,docker-compose}.{yml,yaml}]
indent_size = 4

65
src/.env.example Normal file
View File

@@ -0,0 +1,65 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"

11
src/.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

31
src/.gitignore vendored Normal file
View File

@@ -0,0 +1,31 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.codex
/.cursor/
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/fonts-manifest.dev.json
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
# Application-specific storage (private files)
/storage/app/private/certificates/
/storage/app/private/imports/
/storage/app/public/qrcodes/

2
src/.npmrc Normal file
View File

@@ -0,0 +1,2 @@
ignore-scripts=true
audit=true

View File

@@ -0,0 +1,106 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Jobs\GenerateCertificateJob;
use App\Models\Certificate;
use App\Models\Program;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class CertificateController extends Controller
{
public function index(Program $program): View
{
$certificates = $program->certificates()
->with('participant')
->latest()
->paginate(50);
$stats = [
'total' => $program->certificates()->count(),
'generated' => $program->certificates()->whereIn('status', ['generated', 'emailed', 'downloaded'])->count(),
'pending' => $program->certificates()->where('status', 'pending')->count(),
'failed' => $program->certificates()->where('status', 'failed')->count(),
'emailed' => $program->certificates()->where('status', 'emailed')->count(),
];
return view('admin.programs.certificates.index', compact('program', 'certificates', 'stats'));
}
public function generateAll(Request $request, Program $program): RedirectResponse
{
$template = $program->certificateTemplate;
if (! $template) {
return back()->with('error', 'Template sijil belum ditetapkan untuk program ini.');
}
// Find all attended participants without certificates
$existingIds = $program->certificates()->pluck('participant_id')->toArray();
$attended = $program->attendances()
->whereNotIn('participant_id', $existingIds)
->get();
if ($attended->isEmpty() && $program->certificates()->count() === 0) {
return back()->with('error', 'Tiada peserta yang hadir untuk dijana sijil.');
}
$sequence = $program->certificates()->count();
$created = 0;
foreach ($attended as $attendance) {
$sequence++;
$cert = Certificate::firstOrCreate(
['program_id' => $program->id, 'participant_id' => $attendance->participant_id],
[
'certificate_template_id' => $template->id,
'certificate_no' => $this->buildCertNo($program, $sequence),
'status' => 'pending',
]
);
if ($cert->wasRecentlyCreated || $cert->status === 'failed') {
$cert->update(['certificate_template_id' => $template->id, 'status' => 'pending']);
GenerateCertificateJob::dispatch($cert);
$created++;
}
}
// Re-queue failed certificates
$failed = $program->certificates()->where('status', 'failed')->get();
foreach ($failed as $cert) {
$cert->update(['status' => 'pending', 'error_message' => null]);
GenerateCertificateJob::dispatch($cert);
$created++;
}
return back()->with('success', "Penjanaan sijil telah diantri untuk {$created} peserta.");
}
public function emailAll(Program $program): RedirectResponse
{
$toEmail = $program->certificates()
->whereIn('status', ['generated'])
->whereNull('emailed_at')
->count();
if ($toEmail === 0) {
return back()->with('error', 'Tiada sijil yang sedia untuk dihantar emel.');
}
// Dispatch email blast job — implemented in Fasa 8
\App\Jobs\SendCertificateEmailJob::dispatchBatch($program);
return back()->with('success', "Penghantaran emel sijil dijadualkan untuk {$toEmail} peserta.");
}
private function buildCertNo(Program $program, int $seq): string
{
$year = now()->format('Y');
$prefix = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $program->title), 0, 4));
return sprintf('%s/%s/%04d', $prefix ?: 'ECT', $year, $seq);
}
}

View File

@@ -0,0 +1,152 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\CertificateTemplate;
use App\Models\Program;
use App\Services\CertificateService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
class CertificateTemplateController extends Controller
{
public function show(Program $program): View
{
$template = $program->certificateTemplate;
return view('admin.programs.template.show', compact('program', 'template'));
}
public function store(Request $request, Program $program): RedirectResponse
{
$request->validate([
'template_image' => 'required|image|mimes:jpg,jpeg,png|max:10240',
]);
$file = $request->file('template_image');
$filename = $file->getClientOriginalName();
$path = $file->store('templates/' . $program->id, 'local');
// Deactivate previous templates
$program->certificateTemplates()->update(['is_active' => false]);
$program->certificateTemplates()->create([
'original_filename' => $filename,
'image_path' => $path,
'is_active' => true,
'uploaded_by' => auth()->id(),
'config_json' => $this->defaultConfig($file->getPath() . '/' . $file->getFilename()),
]);
return redirect()->route('admin.programs.template.show', $program)
->with('success', 'Template sijil berjaya dimuat naik. Konfigurasi kedudukan teks di bawah.');
}
public function updateConfig(Request $request, Program $program): RedirectResponse
{
$template = $program->certificateTemplate;
abort_if(! $template, 404);
$request->validate([
'fields' => 'required|array',
'fields.*.x' => 'required|integer|min:0',
'fields.*.y' => 'required|integer|min:0',
'fields.*.font_size' => 'required|integer|min:8|max:200',
'fields.*.ic_font_size' => 'nullable|integer|min:8|max:200',
'fields.*.font_color' => 'required|string|max:20',
'fields.*.align' => 'required|in:left,center,right',
]);
$config = $template->config_json ?? [];
$config['fields'] = array_merge($config['fields'] ?? [], $request->fields);
$template->update(['config_json' => $config]);
return redirect()->route('admin.programs.template.show', $program)
->with('success', 'Konfigurasi template berjaya dikemaskini.');
}
public function destroy(Program $program): RedirectResponse
{
$template = $program->certificateTemplate;
abort_if(! $template, 404);
Storage::disk('local')->delete($template->image_path);
$template->delete();
return redirect()->route('admin.programs.template.show', $program)
->with('success', 'Template sijil dipadam.');
}
public function preview(Program $program): Response
{
$template = $program->certificateTemplate;
abort_if(! $template, 404);
$content = Storage::disk('local')->get($template->image_path);
return response($content, 200, [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'inline',
'Cache-Control' => 'private, max-age=3600',
]);
}
public function testGenerate(Request $request, Program $program, CertificateService $service): \Illuminate\Http\Response|\Illuminate\Http\JsonResponse
{
$template = $program->certificateTemplate;
abort_if(! $template, 404);
$sampleName = $request->input('sample_name', 'NAMA PESERTA CONTOH');
$sampleNo = $request->input('sample_no', 'ECT/2025/0001');
// Bina override dari nilai form semasa (belum disimpan)
// Gabung dengan config tersimpan supaya font_file & valign kekal
$liveFields = null;
if ($request->has('fields') && is_array($request->input('fields'))) {
$saved = $template->config_json['fields'] ?? [];
$liveFields = [];
foreach ($request->input('fields') as $key => $cfg) {
$liveFields[$key] = array_merge($saved[$key] ?? [], array_filter($cfg, fn($v) => $v !== null && $v !== ''));
}
}
try {
$imageData = $service->generatePreview($template, $sampleName, $sampleNo, $liveFields);
} catch (\Throwable $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
return response($imageData, 200, [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'inline; filename="preview.jpg"',
]);
}
private function defaultConfig(string $imagePath): array
{
[$width, $height] = getimagesize($imagePath) + [0, 0, 0, 0];
$cx = (int) round(($width ?: 1600) / 2);
$cy = (int) round(($height ?: 1100) * 0.52);
return [
'width' => $width ?: 1600,
'height' => $height ?: 1100,
'fields' => [
'name' => [
'x' => $cx,
'y' => $cy,
'font_size' => 52,
'font_color' => '#1a3a6b',
'font_file' => 'DejaVuSans-Bold.ttf',
'align' => 'center',
'valign' => 'top',
],
],
];
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\Certificate;
use App\Models\EmailLog;
use App\Models\Participant;
use App\Models\Program;
use App\Models\QuestionnaireResponse;
class DashboardController extends Controller
{
public function index()
{
$stats = [
'total_programs' => Program::count(),
'active_programs' => Program::where('status', 'published')->count(),
'total_participants' => Participant::count(),
'total_attendances' => Attendance::count(),
'total_certificates' => Certificate::count(),
'generated_certs' => Certificate::whereIn('status', ['generated', 'emailed', 'downloaded'])->count(),
'downloaded_certs' => Certificate::where('status', 'downloaded')->count(),
'total_responses' => QuestionnaireResponse::count(),
'pending_emails' => EmailLog::where('status', 'pending')->count(),
];
$recentPrograms = Program::with('creator')
->latest()
->limit(5)
->get();
return view('admin.dashboard', compact('stats', 'recentPrograms'));
}
}

View File

@@ -0,0 +1,185 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Participant;
use App\Models\Program;
use App\Models\ProgramParticipant;
use App\Services\AuditLogService;
use App\Services\ParticipantImportService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use League\Csv\Writer;
use SplTempFileObject;
class ParticipantController extends Controller
{
public function index(Program $program, Request $request): View
{
$query = $program->programParticipants()
->with('participant')
->latest();
if ($request->filled('search')) {
$query->whereHas('participant', function ($q) use ($request) {
$q->where('name', 'like', '%' . $request->search . '%')
->orWhere('agency', 'like', '%' . $request->search . '%');
});
}
if ($request->filled('source')) {
$query->where('registration_source', $request->source);
}
if ($request->filled('status')) {
$query->where('status', $request->status);
}
$programParticipants = $query->paginate(20)->withQueryString();
$countRow = DB::table('program_participants')
->where('program_id', $program->id)
->selectRaw("COUNT(*) as total, SUM(is_pre_registered) as pre_registered, SUM(registration_source = 'walk_in') as walk_in, SUM(status = 'checked_in') as checked_in")
->first();
$counts = [
'total' => (int) ($countRow->total ?? 0),
'pre_registered' => (int) ($countRow->pre_registered ?? 0),
'walk_in' => (int) ($countRow->walk_in ?? 0),
'checked_in' => (int) ($countRow->checked_in ?? 0),
];
return view('admin.programs.participants.index', compact('program', 'programParticipants', 'counts'));
}
public function create(Program $program): View
{
return view('admin.programs.participants.create', compact('program'));
}
public function store(Program $program, Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'no_kp' => ['required', 'string', 'regex:/^\d{6}-?\d{2}-?\d{4}$|^\d{12}$/'],
'email' => ['nullable', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:20'],
'agency' => ['nullable', 'string', 'max:255'],
'session' => ['nullable', 'in:pagi,petang,full_day'],
]);
$noKp = preg_replace('/[^0-9]/', '', $request->no_kp);
// Check duplicate in this program
$existing = Participant::where('no_kp', $noKp)->first();
if ($existing && $program->programParticipants()->where('participant_id', $existing->id)->exists()) {
return back()->withInput()->with('error', 'Peserta dengan No. K/P ini sudah didaftarkan dalam program ini.');
}
DB::transaction(function () use ($program, $request, $noKp, $existing) {
$participant = $existing ?? Participant::create([
'name' => $request->name,
'no_kp' => $noKp,
'email' => $request->email,
'phone' => $request->phone,
'agency' => $request->agency,
'participant_type' => 'staff',
]);
$program->programParticipants()->create([
'participant_id' => $participant->id,
'registration_source' => 'admin_manual',
'is_pre_registered' => true,
'pre_registered_session'=> $request->session ?? $program->default_staff_session,
'status' => 'registered',
'registered_at' => now(),
]);
AuditLogService::log('participant.added', $participant);
});
return back()->with('success', 'Peserta berjaya ditambah.');
}
public function destroy(Program $program, ProgramParticipant $pp): RedirectResponse
{
if ($pp->program_id !== $program->id) {
abort(403);
}
if ($pp->attendance()->exists()) {
return back()->with('error', 'Peserta tidak boleh dikeluarkan kerana sudah ada rekod kehadiran.');
}
$pp->delete();
return back()->with('success', 'Peserta berjaya dikeluarkan daripada program.');
}
public function importForm(Program $program): View
{
return view('admin.programs.participants.import', compact('program'));
}
public function import(Program $program, Request $request, ParticipantImportService $importer): RedirectResponse
{
$request->validate([
'csv_file' => ['required', 'file', 'mimes:csv,txt', 'max:5120'],
'session' => ['nullable', 'in:pagi,petang,full_day'],
]);
$result = $importer->import(
$program,
$request->file('csv_file'),
$request->input('session', $program->default_staff_session)
);
AuditLogService::log('participant.imported', $program, [], [
'success' => $result['success'],
'duplicates' => $result['duplicates'],
'failed' => $result['failed'],
]);
return back()->with('import_result', $result);
}
public function export(Program $program): \Symfony\Component\HttpFoundation\StreamedResponse
{
$headers = [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="peserta_' . $program->uuid . '_' . now()->format('Ymd') . '.csv"',
];
return response()->stream(function () use ($program) {
$handle = fopen('php://output', 'w');
// UTF-8 BOM for Excel compatibility
fputs($handle, "\xEF\xBB\xBF");
fputcsv($handle, ['Nama', 'No K/P', 'Emel', 'Telefon', 'Agensi', 'Sesi', 'Sumber', 'Status', 'Tarikh Daftar']);
$program->programParticipants()
->with('participant')
->lazy()
->each(function ($pp) use ($handle) {
$p = $pp->participant;
fputcsv($handle, [
$p->name,
$p->no_kp,
$p->email,
$p->phone,
$p->agency,
$pp->pre_registered_session ?? '—',
$pp->registration_source,
$pp->status,
$pp->registered_at?->format('d/m/Y H:i') ?? '—',
]);
});
fclose($handle);
}, 200, $headers);
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;
class ProfileController extends Controller
{
public function show(): View
{
return view('admin.profile.show', ['user' => auth()->user()]);
}
public function updateEmail(Request $request): RedirectResponse
{
$validator = \Validator::make($request->all(), [
'current_password' => ['required', 'current_password'],
'email' => ['required', 'email', 'max:255', 'unique:users,email,' . auth()->id()],
], [
'current_password.current_password' => 'Kata laluan semasa tidak betul.',
'email.unique' => 'Alamat emel ini sudah digunakan.',
]);
if ($validator->fails()) {
return back()->withErrors($validator, 'email')->withInput();
}
auth()->user()->update(['email' => $request->email]);
return back()->with('email_success', 'Alamat emel berjaya dikemaskini.');
}
public function updatePassword(Request $request): RedirectResponse
{
$validator = \Validator::make($request->all(), [
'current_password' => ['required', 'current_password'],
'password' => ['required', 'confirmed', Password::min(8)],
], [
'current_password.current_password' => 'Kata laluan semasa tidak betul.',
'password.min' => 'Kata laluan baru mestilah sekurang-kurangnya 8 aksara.',
'password.confirmed' => 'Pengesahan kata laluan tidak sepadan.',
]);
if ($validator->fails()) {
return back()->withErrors($validator, 'password')->withInput();
}
auth()->user()->update(['password' => Hash::make($request->password)]);
Auth::login(auth()->user());
return back()->with('password_success', 'Kata laluan berjaya ditukar.');
}
}

View File

@@ -0,0 +1,165 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreProgramRequest;
use App\Http\Requests\Admin\UpdateProgramRequest;
use App\Models\Program;
use App\Services\AuditLogService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class ProgramController extends Controller
{
public function index(Request $request): View
{
$query = Program::with('creator')
->withCount(['attendances', 'programParticipants'])
->latest();
// Admin program hanya nampak program sendiri
if (auth()->user()->isAdminProgram()) {
$query->where('created_by', auth()->id());
}
if ($request->filled('search')) {
$query->where(function ($q) use ($request) {
$q->where('title', 'like', '%' . $request->search . '%')
->orWhere('organizer', 'like', '%' . $request->search . '%')
->orWhere('location', 'like', '%' . $request->search . '%');
});
}
if ($request->filled('status')) {
$query->where('status', $request->status);
}
$programs = $query->paginate(15)->withQueryString();
return view('admin.programs.index', compact('programs'));
}
public function create(): View
{
return view('admin.programs.create');
}
public function store(StoreProgramRequest $request): RedirectResponse
{
$program = Program::create([
...$request->validated(),
'created_by' => auth()->id(),
]);
AuditLogService::log('program.created', $program);
return redirect()
->route('admin.programs.show', $program)
->with('success', 'Program "' . $program->title . '" berjaya ditambah.');
}
public function show(Program $program): View
{
$this->authorize('view', $program);
$program->load([
'qrCode',
'certificateTemplate',
'questionnaire.questionnaireSet.questions',
]);
// Consolidate into 2 queries instead of 6 separate COUNTs
$ppStats = \DB::table('program_participants')
->where('program_id', $program->id)
->selectRaw("COUNT(*) as total, SUM(is_pre_registered) as pre_registered, SUM(registration_source = 'walk_in') as walk_in")
->first();
$certStats = \DB::table('certificates')
->where('program_id', $program->id)
->selectRaw("COUNT(*) as total, SUM(status IN ('generated','emailed','downloaded')) as cert_generated")
->first();
$stats = [
'total_participants' => (int) ($ppStats->total ?? 0),
'pre_registered' => (int) ($ppStats->pre_registered ?? 0),
'walk_in' => (int) ($ppStats->walk_in ?? 0),
'total_attendances' => $program->attendances()->count(),
'total_certificates' => (int) ($certStats->total ?? 0),
'generated_certificates' => (int) ($certStats->cert_generated ?? 0),
];
return view('admin.programs.show', compact('program', 'stats'));
}
public function edit(Program $program): View
{
$this->authorize('update', $program);
return view('admin.programs.edit', compact('program'));
}
public function update(UpdateProgramRequest $request, Program $program): RedirectResponse
{
$this->authorize('update', $program);
$old = $program->only([
'title', 'status', 'checkin_start_at', 'checkin_end_at',
'ecert_download_start_at', 'ecert_download_end_at',
]);
$program->update($request->validated());
AuditLogService::log('program.updated', $program, $old);
return redirect()
->route('admin.programs.show', $program)
->with('success', 'Maklumat program berjaya dikemas kini.');
}
public function destroy(Program $program): RedirectResponse
{
$this->authorize('delete', $program);
if ($program->attendances()->exists()) {
return back()->with('error', 'Program tidak boleh dipadam kerana sudah ada rekod kehadiran.');
}
$title = $program->title;
AuditLogService::log('program.deleted', $program);
$program->delete();
return redirect()
->route('admin.programs.index')
->with('success', 'Program "' . $title . '" berjaya dipadam.');
}
public function publish(Program $program): RedirectResponse
{
$this->authorize('update', $program);
if ($program->status !== 'draft') {
return back()->with('error', 'Hanya program berstatus Draf boleh diterbitkan.');
}
$program->update(['status' => 'published']);
AuditLogService::log('program.published', $program);
return back()->with('success', 'Program berjaya diterbitkan.');
}
public function close(Program $program): RedirectResponse
{
$this->authorize('update', $program);
if ($program->status !== 'published') {
return back()->with('error', 'Hanya program berstatus Diterbitkan boleh ditutup.');
}
$program->update(['status' => 'closed']);
AuditLogService::log('program.closed', $program);
return back()->with('success', 'Program berjaya ditutup.');
}
}

View File

@@ -0,0 +1,108 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Program;
use App\Models\ProgramQuestionnaire;
use App\Models\QuestionnaireSet;
use App\Services\AuditLogService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class ProgramQuestionnaireController extends Controller
{
public function show(Program $program): View
{
$pq = $program->questionnaire()->with('questionnaireSet.questions')->first();
$availableSets = QuestionnaireSet::where('status', 'published')
->withCount('questions')
->orderBy('title')
->get();
return view('admin.programs.questionnaire.show', compact('program', 'pq', 'availableSets'));
}
public function attach(Request $request, Program $program): RedirectResponse
{
$data = $request->validate([
'questionnaire_set_id' => 'required|exists:questionnaire_sets,id',
]);
if ($program->questionnaire()->exists()) {
return back()->with('error', 'Program ini sudah ada soalselidik dilampirkan. Tanggalkan dahulu sebelum lampir yang baru.');
}
$set = QuestionnaireSet::findOrFail($data['questionnaire_set_id']);
if ($set->status !== 'published') {
return back()->with('error', 'Hanya soalselidik yang diterbitkan boleh dilampirkan.');
}
ProgramQuestionnaire::create([
'program_id' => $program->id,
'questionnaire_set_id' => $set->id,
'is_confirmed' => false,
]);
return back()->with('success', 'Soalselidik berjaya dilampirkan. Sila sahkan sebelum program bermula.');
}
public function confirm(Request $request, Program $program): RedirectResponse
{
$pq = $program->questionnaire;
if (! $pq) {
return back()->with('error', 'Tiada soalselidik untuk disahkan.');
}
$pq->update([
'is_confirmed' => true,
'confirmed_at' => now(),
'confirmed_by' => auth()->id(),
]);
AuditLogService::log('questionnaire.confirmed', $pq, [], ['program_id' => $program->id, 'questionnaire_set_id' => $pq->questionnaire_set_id]);
return back()->with('success', 'Soalselidik telah disahkan untuk program ini.');
}
public function preview(Program $program): View|\Illuminate\Http\RedirectResponse
{
$pq = $program->questionnaire()->with('questionnaireSet')->first();
if (! $pq || ! $pq->questionnaireSet) {
return back()->with('error', 'Tiada soalselidik untuk dipratonton.');
}
$questions = $pq->questionnaireSet->questions()
->whereNull('parent_id')
->with(['children' => fn($q) => $q->orderBy('sort_order')])
->orderBy('sort_order')
->get();
return view('admin.programs.questionnaire.preview', compact('program', 'pq', 'questions'));
}
public function detach(Program $program): RedirectResponse
{
$pq = $program->questionnaire;
if (! $pq) {
return back()->with('error', 'Tiada soalselidik untuk ditanggalkan.');
}
if ($pq->is_confirmed) {
$hasResponses = \App\Models\QuestionnaireResponse::where('program_id', $program->id)->exists();
if ($hasResponses) {
return back()->with('error', 'Soalselidik tidak boleh ditanggalkan kerana sudah ada respons diterima.');
}
}
$pq->delete();
return back()->with('success', 'Soalselidik berjaya ditanggalkan.');
}
}

View File

@@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Program;
use App\Services\AuditLogService;
use App\Services\QrCodeService;
use Illuminate\Support\Str;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Response;
use Illuminate\View\View;
class QrCodeController extends Controller
{
public function __construct(private QrCodeService $qrCodeService) {}
public function show(Program $program): View
{
$qrCode = $program->qrCodes()->where('is_active', true)->latest()->first();
return view('admin.programs.qr', compact('program', 'qrCode'));
}
public function generate(Program $program): RedirectResponse
{
$qrCode = $this->qrCodeService->generateForProgram($program);
AuditLogService::log('qrcode.generated', $program);
return redirect()
->route('admin.programs.qr.show', $program)
->with('success', 'QR Code berjaya dijana.');
}
public function download(Program $program): Response|RedirectResponse
{
$qrCode = $program->qrCodes()->where('is_active', true)->latest()->first();
if (! $qrCode) {
return back()->with('error', 'QR Code belum dijana.');
}
$png = $this->qrCodeService->getRawPng($qrCode);
$filename = 'QR_' . Str::slug($program->title) . '_' . now()->format('Ymd') . '.png';
return response($png, 200, [
'Content-Type' => 'image/png',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
public function deactivate(Program $program): RedirectResponse
{
$program->qrCodes()->where('is_active', true)->update(['is_active' => false]);
AuditLogService::log('qrcode.deactivated', $program);
return back()->with('success', 'QR Code berjaya dinyahaktifkan.');
}
}

View File

@@ -0,0 +1,155 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\QuestionnaireQuestion;
use App\Models\QuestionnaireSet;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class QuestionController extends Controller
{
public function store(Request $request, QuestionnaireSet $set): RedirectResponse
{
if ($request->has('options')) {
$request->merge(['options' => array_values(array_filter($request->input('options', [])))]);
}
$data = $request->validate([
'question_text' => 'required|string|max:1000',
'question_type' => 'required|in:tajuk,rating,single_choice,multiple_choice,short_text,long_text',
'is_required' => 'boolean',
'parent_id' => 'nullable|integer|exists:questionnaire_questions,id',
'options' => 'nullable|array',
'options.*' => 'required|string|max:255',
'rating_labels' => 'nullable|array',
'rating_labels.*' => 'nullable|string|max:100',
]);
if ($data['question_type'] === 'rating') {
if (empty($data['parent_id'])) {
return back()->withErrors(['parent_id' => 'Soalan rating mesti diletakkan di bawah tajuk.'])->withInput();
}
$parent = QuestionnaireQuestion::find($data['parent_id']);
if (! $parent || $parent->question_type !== 'tajuk') {
return back()->withErrors(['parent_id' => 'Parent mesti jenis Tajuk.'])->withInput();
}
}
$needsOptions = in_array($data['question_type'], ['single_choice', 'multiple_choice']);
if ($needsOptions && empty($data['options'])) {
return back()->withErrors(['options' => 'Pilihan jawapan diperlukan untuk jenis soalan ini.'])->withInput();
}
$parentId = $data['question_type'] === 'rating' ? ($data['parent_id'] ?? null) : null;
$maxOrder = $set->questions()
->when($parentId,
fn($q) => $q->where('parent_id', $parentId),
fn($q) => $q->whereNull('parent_id')
)
->max('sort_order') ?? 0;
$ratingLabels = null;
if ($data['question_type'] === 'tajuk') {
$filtered = array_filter($data['rating_labels'] ?? [], fn($v) => $v !== null && $v !== '');
$ratingLabels = ! empty($filtered) ? $filtered : null;
}
$set->questions()->create([
'question_text' => $data['question_text'],
'question_type' => $data['question_type'],
'parent_id' => $parentId,
'is_required' => $data['question_type'] === 'tajuk' ? false : ($data['is_required'] ?? true),
'options_json' => $needsOptions ? array_values(array_filter($data['options'] ?? [])) : null,
'rating_labels' => $ratingLabels,
'sort_order' => $maxOrder + 1,
]);
return redirect()->route('admin.questionnaires.show', $set)
->with('success', 'Soalan berjaya ditambah.');
}
public function update(Request $request, QuestionnaireQuestion $question): RedirectResponse
{
if ($request->has('options')) {
$request->merge(['options' => array_values(array_filter($request->input('options', [])))]);
}
$data = $request->validate([
'question_text' => 'required|string|max:1000',
'question_type' => 'required|in:tajuk,rating,single_choice,multiple_choice,short_text,long_text',
'is_required' => 'boolean',
'parent_id' => 'nullable|integer|exists:questionnaire_questions,id',
'options' => 'nullable|array',
'options.*' => 'required|string|max:255',
'rating_labels' => 'nullable|array',
'rating_labels.*' => 'nullable|string|max:100',
]);
if ($data['question_type'] === 'rating') {
if (empty($data['parent_id'])) {
return back()->withErrors(['parent_id' => 'Soalan rating mesti diletakkan di bawah tajuk.'])->withInput();
}
$parent = QuestionnaireQuestion::find($data['parent_id']);
if (! $parent || $parent->question_type !== 'tajuk') {
return back()->withErrors(['parent_id' => 'Parent mesti jenis Tajuk.'])->withInput();
}
}
$needsOptions = in_array($data['question_type'], ['single_choice', 'multiple_choice']);
$parentId = $data['question_type'] === 'rating' ? ($data['parent_id'] ?? null) : null;
$ratingLabels = null;
if ($data['question_type'] === 'tajuk') {
$filtered = array_filter($data['rating_labels'] ?? [], fn($v) => $v !== null && $v !== '');
$ratingLabels = ! empty($filtered) ? $filtered : null;
}
$question->update([
'question_text' => $data['question_text'],
'question_type' => $data['question_type'],
'parent_id' => $parentId,
'is_required' => $data['question_type'] === 'tajuk' ? false : ($data['is_required'] ?? true),
'options_json' => $needsOptions ? array_values(array_filter($data['options'] ?? [])) : null,
'rating_labels' => $ratingLabels,
]);
return redirect()->route('admin.questionnaires.show', $question->questionnaire_set_id)
->with('success', 'Soalan berjaya dikemaskini.');
}
public function destroy(QuestionnaireQuestion $question): RedirectResponse
{
$setId = $question->questionnaire_set_id;
// Cascade-delete children if this is a tajuk (DB cascade handles it too, but be explicit)
if ($question->question_type === 'tajuk') {
$question->children()->delete();
}
$question->delete();
return redirect()->route('admin.questionnaires.show', $setId)
->with('success', 'Soalan berjaya dipadam.');
}
public function reorder(Request $request): JsonResponse
{
$data = $request->validate([
'order' => 'required|array',
'order.*' => 'integer|exists:questionnaire_questions,id',
'parent_id' => 'nullable|integer|exists:questionnaire_questions,id',
]);
foreach ($data['order'] as $sortOrder => $questionId) {
QuestionnaireQuestion::where('id', $questionId)
->update(['sort_order' => $sortOrder + 1]);
}
return response()->json(['ok' => true]);
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\QuestionnaireSet;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class QuestionnaireSetController extends Controller
{
public function index(Request $request): View
{
$query = QuestionnaireSet::withCount('questions')
->with('creator')
->latest();
if ($request->filled('q')) {
$query->where('title', 'like', '%' . $request->q . '%');
}
if ($request->filled('status')) {
$query->where('status', $request->status);
}
$sets = $query->paginate(20)->withQueryString();
return view('admin.questionnaires.index', compact('sets'));
}
public function create(): View
{
return view('admin.questionnaires.create');
}
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string|max:1000',
]);
$data['created_by'] = auth()->id();
$data['status'] = 'draft';
$set = QuestionnaireSet::create($data);
return redirect()->route('admin.questionnaires.show', $set)
->with('success', 'Set soalselidik berjaya dicipta.');
}
public function show(QuestionnaireSet $set): View
{
$set->load('creator');
$topLevel = $set->questions()
->whereNull('parent_id')
->with(['children' => fn($q) => $q->orderBy('sort_order')])
->orderBy('sort_order')
->get();
$totalCount = $set->questions()->count();
$usedInPrograms = $set->programs()->get();
return view('admin.questionnaires.show', compact('set', 'topLevel', 'totalCount', 'usedInPrograms'));
}
public function edit(QuestionnaireSet $set): View
{
return view('admin.questionnaires.edit', compact('set'));
}
public function update(Request $request, QuestionnaireSet $set): RedirectResponse
{
$data = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string|max:1000',
]);
$set->update($data);
return redirect()->route('admin.questionnaires.show', $set)
->with('success', 'Set soalselidik berjaya dikemaskini.');
}
public function destroy(QuestionnaireSet $set): RedirectResponse
{
$confirmed = $set->programQuestionnaires()->where('is_confirmed', true)->exists();
if ($confirmed) {
return back()->with('error', 'Soalselidik ini tidak boleh dipadam kerana sudah disahkan untuk program.');
}
$set->delete();
return redirect()->route('admin.questionnaires.index')
->with('success', 'Set soalselidik berjaya dipadam.');
}
public function publish(QuestionnaireSet $set): RedirectResponse
{
if ($set->questions()->count() === 0) {
return back()->with('error', 'Tambah sekurang-kurangnya satu soalan sebelum menerbitkan.');
}
$set->update(['status' => 'published']);
return back()->with('success', 'Set soalselidik diterbitkan.');
}
public function archive(QuestionnaireSet $set): RedirectResponse
{
$set->update(['status' => 'archived']);
return back()->with('success', 'Set soalselidik diarkibkan.');
}
}

View File

@@ -0,0 +1,136 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Program;
use App\Models\Attendance;
use App\Models\Certificate;
use App\Models\QuestionnaireAnswer;
use App\Models\QuestionnaireQuestion;
use App\Models\QuestionnaireResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;
class StatisticsController extends Controller
{
public function show(Program $program): View
{
$program->load(['questionnaire.questionnaireSet.questions']);
// Attendance by session
$bySession = $program->attendances()
->selectRaw('attendance_session, COUNT(*) as total')
->groupBy('attendance_session')
->pluck('total', 'attendance_session')
->toArray();
// Attendance by source
$bySource = $program->attendances()
->selectRaw('attendance_source, COUNT(*) as total')
->groupBy('attendance_source')
->pluck('total', 'attendance_source')
->toArray();
// Certificate status breakdown
$certStats = $program->certificates()
->selectRaw('status, COUNT(*) as total')
->groupBy('status')
->pluck('total', 'status')
->toArray();
// Response rate + question stats
$pq = $program->questionnaire;
$responseRate = null;
$questionStats = [];
$totalResponses = 0;
if ($pq && $pq->is_confirmed) {
$totalAttended = array_sum($bySession); // reuse already-fetched data
$totalResponses = QuestionnaireResponse::where('program_id', $program->id)->count();
$responseRate = $totalAttended > 0 ? round($totalResponses / $totalAttended * 100) : 0;
$questions = $pq->questionnaireSet->questions ?? collect();
// Load ALL answers in one query, group by question — avoids N+1
$allAnswers = QuestionnaireAnswer::whereIn('questionnaire_question_id', $questions->pluck('id'))
->get()
->groupBy('questionnaire_question_id');
foreach ($questions as $q) {
$answers = $allAnswers->get($q->id, collect());
if ($q->question_type === 'rating') {
$values = $answers->map(fn($a) => is_array($a->answer_value) ? (int) ($a->answer_value[0] ?? 0) : (int) $a->answer_value);
$questionStats[] = [
'id' => $q->id,
'text' => $q->question_text,
'type' => 'rating',
'average' => $values->count() > 0 ? round($values->avg(), 2) : null,
'count' => $values->count(),
];
} elseif (in_array($q->question_type, ['single_choice', 'multiple_choice'])) {
$counts = [];
foreach ($answers as $row) {
$items = is_array($row->answer_value) ? $row->answer_value : [$row->answer_value];
foreach ($items as $item) {
$counts[$item] = ($counts[$item] ?? 0) + 1;
}
}
$questionStats[] = [
'id' => $q->id,
'text' => $q->question_text,
'type' => $q->question_type,
'options' => $q->options_json ?? [],
'counts' => $counts,
'total' => $answers->count(),
];
}
}
}
// Reuse data already computed above — no extra queries
$summary = [
'total_attendances' => array_sum($bySession),
'pre_registered' => $bySource['pre_registered_staff'] ?? 0,
'walk_in' => $bySource['walk_in_external'] ?? 0,
'total_certificates' => array_sum($certStats),
'generated_certs' => ($certStats['generated'] ?? 0) + ($certStats['emailed'] ?? 0) + ($certStats['downloaded'] ?? 0),
'downloaded_certs' => $certStats['downloaded'] ?? 0,
'total_responses' => $totalResponses,
];
return view('admin.programs.statistics.show', compact(
'program', 'summary', 'bySession', 'bySource',
'certStats', 'responseRate', 'questionStats'
));
}
public function export(Program $program): Response
{
$rows = $program->attendances()
->with('participant')
->get()
->map(fn($a) => [
$a->participant->name,
$a->participant->agency ?: '',
$a->attendance_session,
$a->attendance_source,
$a->checked_in_at->format('d/m/Y H:i'),
]);
$csv = "\xEF\xBB\xBF";
$csv .= implode(',', ['Nama', 'Agensi', 'Sesi', 'Sumber', 'Masa Check-In']) . "\n";
foreach ($rows as $row) {
$csv .= implode(',', array_map(fn($v) => '"' . str_replace('"', '""', $v) . '"', $row)) . "\n";
}
$filename = 'statistik-' . str($program->title)->slug() . '-' . now()->format('Ymd') . '.csv';
return response($csv, 200, [
'Content-Type' => 'text/csv; charset=UTF-8',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Services\AuditLogService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;
class UserController extends Controller
{
public function index(): View
{
$users = User::withCount('programs')->latest()->paginate(20);
return view('admin.users.index', compact('users'));
}
public function create(): View
{
return view('admin.users.create');
}
public function store(Request $request): RedirectResponse
{
$data = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|email|max:255|unique:users,email',
'role' => 'required|in:super_admin,admin',
'password' => ['required', 'confirmed', Password::min(8)->mixedCase()->numbers()],
]);
$user = User::create($data);
AuditLogService::log('user.created', $user, [], ['email' => $user->email, 'role' => $user->role]);
return redirect()->route('admin.users.index')
->with('success', 'Pengguna "' . $user->name . '" berjaya ditambah.');
}
public function edit(User $user): View
{
return view('admin.users.edit', compact('user'));
}
public function update(Request $request, User $user): RedirectResponse
{
$rules = [
'name' => 'required|string|max:255',
'email' => 'required|email|max:255|unique:users,email,' . $user->id,
'role' => 'required|in:super_admin,admin',
];
if ($request->filled('password')) {
$rules['password'] = ['confirmed', Password::min(8)->mixedCase()->numbers()];
}
$data = $request->validate($rules);
if (! $request->filled('password')) {
unset($data['password']);
}
$old = $user->only(['name', 'email', 'role']);
$user->update($data);
AuditLogService::log('user.updated', $user, $old, $user->only(['name', 'email', 'role']));
return redirect()->route('admin.users.index')
->with('success', 'Maklumat pengguna "' . $user->name . '" berjaya dikemas kini.');
}
public function destroy(User $user): RedirectResponse
{
if ($user->id === auth()->id()) {
return back()->with('error', 'Anda tidak boleh padam akaun sendiri.');
}
$name = $user->name;
AuditLogService::log('user.deleted', $user);
$user->delete();
return redirect()->route('admin.users.index')
->with('success', 'Pengguna "' . $name . '" berjaya dipadam.');
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('admin.dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*/
public function show(): View
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('admin.dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('admin.dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*/
public function __invoke(Request $request): RedirectResponse|View
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('admin.dashboard', absolute: false))
: view('auth.verify-email');
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*/
public function create(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class PasswordController extends Controller
{
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validateWithBag('updatePassword', [
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('status', 'password-updated');
}
}

View File

@@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*/
public function create(): View
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('admin.dashboard', absolute: false));
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('admin.dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(route('admin.dashboard', absolute: false).'?verified=1');
}
}

View File

@@ -0,0 +1,10 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller
{
use AuthorizesRequests;
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): View
{
return view('profile.edit', [
'user' => $request->user(),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}

View File

@@ -0,0 +1,60 @@
<?php
namespace App\Http\Controllers\Public;
use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\Participant;
use App\Models\ProgramQrCode;
use Illuminate\Http\Request;
use Illuminate\View\View;
class AttendanceCheckController extends Controller
{
public function show(string $qr_token): View
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
abort_if($program->status !== 'published', 404);
return view('public.semak.show', compact('program', 'qrCode'));
}
public function check(string $qr_token, Request $request): View
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
$request->validate([
'no_kp' => ['required', 'digits:12'],
], [
'no_kp.required' => 'Sila masukkan No. Kad Pengenalan anda.',
'no_kp.digits' => 'No. Kad Pengenalan mestilah 12 digit tanpa sempang.',
]);
$noKp = preg_replace('/[^0-9]/', '', $request->no_kp);
$participant = Participant::where('no_kp', $noKp)->first();
if (! $participant) {
return view('public.semak.result', [
'program' => $program,
'qrCode' => $qrCode,
'found' => false,
'participant' => null,
'attendance' => null,
'certificate' => null,
]);
}
$attendance = $participant->attendanceForProgram($program->id);
$certificate = $attendance
? Certificate::where('program_id', $program->id)
->where('participant_id', $participant->id)
->first()
: null;
return view('public.semak.result', compact('program', 'qrCode', 'participant', 'attendance', 'certificate'))
->with('found', (bool) $attendance);
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers\Public;
use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\QuestionnaireResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
class CertificateController extends Controller
{
public function show(string $cert_token): View|RedirectResponse
{
$certificate = Certificate::where('token', $cert_token)
->with(['participant', 'program', 'template'])
->firstOrFail();
$program = $certificate->program;
$participant = $certificate->participant;
// Check questionnaire gate
$pq = $program->questionnaire()->first();
$needsQuestionnaire = $pq && $pq->is_confirmed;
$hasAnswered = false;
if ($needsQuestionnaire) {
$hasAnswered = QuestionnaireResponse::where('program_id', $program->id)
->where('participant_id', $participant->id)
->exists();
}
// Find active QR code for questionnaire redirect
$qrCode = $program->qrCode;
return view('public.certificate.show', compact(
'certificate', 'program', 'participant', 'pq',
'needsQuestionnaire', 'hasAnswered', 'qrCode'
));
}
public function download(string $cert_token): Response|RedirectResponse
{
$certificate = Certificate::where('token', $cert_token)
->with(['participant', 'program'])
->firstOrFail();
if (! $certificate->isGenerated()) {
return back()->with('error', 'Sijil belum sedia untuk dimuat turun.');
}
if (! $certificate->file_path || ! Storage::disk('local')->exists($certificate->file_path)) {
return back()->with('error', 'Fail sijil tidak dijumpai. Sila hubungi penganjur.');
}
// Check questionnaire gate
$program = $certificate->program;
$pq = $program->questionnaire()->first();
if ($pq && $pq->is_confirmed) {
$hasAnswered = QuestionnaireResponse::where('program_id', $program->id)
->where('participant_id', $certificate->participant_id)
->exists();
if (! $hasAnswered) {
$qrCode = $program->qrCode;
$redirectTo = $qrCode
? route('public.questionnaire.show', [$qrCode->token, $certificate->participant->uuid])
: back();
return redirect($redirectTo)->with('info', 'Sila jawab borang penilaian terlebih dahulu.');
}
}
$certificate->recordDownload();
$content = Storage::disk('local')->get($certificate->file_path);
$filename = 'Sijil-' . str($certificate->participant->name)->slug() . '.jpg';
return response($content, 200, [
'Content-Type' => 'image/jpeg',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
'Content-Length' => strlen($content),
]);
}
}

View File

@@ -0,0 +1,120 @@
<?php
namespace App\Http\Controllers\Public;
use App\Http\Controllers\Controller;
use App\Models\ProgramQrCode;
use App\Services\AttendanceService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class CheckinController extends Controller
{
public function __construct(private AttendanceService $attendanceService) {}
public function show(string $qr_token): View|RedirectResponse
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
if ($program->status !== 'published') {
return view('public.checkin.unavailable', compact('program', 'qrCode'))
->with('message', 'Program ini belum dibuka atau sudah ditutup.');
}
// If download period is active → redirect to attendance check page
if ($program->isDownloadOpen()) {
return redirect()->route('public.semak.show', $qr_token);
}
// Check-in not yet open
if ($program->checkin_start_at && now()->lt($program->checkin_start_at)) {
return view('public.checkin.unavailable', compact('program', 'qrCode'))
->with('message', 'Check-in belum dibuka. Mula pada ' . $program->checkin_start_at->format('d M Y, H:i'));
}
// Check-in already closed
if ($program->checkin_end_at && now()->gt($program->checkin_end_at)) {
return view('public.checkin.unavailable', compact('program', 'qrCode'))
->with('message', 'Tempoh check-in telah tamat.');
}
return view('public.checkin.show', compact('program', 'qrCode'));
}
public function staffCheckin(string $qr_token, Request $request): View|RedirectResponse
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
$request->validate([
'no_kp' => ['required', 'string', 'max:20'],
], [
'no_kp.required' => 'Sila masukkan No. Kad Pengenalan anda.',
]);
$result = $this->attendanceService->staffCheckin($program, $request->no_kp, $request);
return match ($result['status']) {
'success' => view('public.checkin.success', [
'program' => $program,
'participant' => $result['participant'],
'attendance' => $result['attendance'],
'qrCode' => $qrCode,
]),
'already_checked_in' => view('public.checkin.already', [
'program' => $program,
'participant' => $result['participant'],
'attendance' => $result['attendance'],
]),
'not_found' => back()->withInput()
->with('error', 'No. Kad Pengenalan tidak dijumpai dalam senarai peserta program ini.')
->with('show_external_option', $program->allow_walk_in),
'not_registered' => back()->withInput()
->with('error', 'No. Kad Pengenalan tidak dijumpai dalam senarai pra-daftar.')
->with('show_external_option', $program->allow_walk_in),
default => back()->with('error', 'Ralat tidak dijangka. Sila cuba lagi.'),
};
}
public function externalRegister(string $qr_token, Request $request): View|RedirectResponse
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
if (! $program->allow_walk_in) {
return back()->with('error', 'Pendaftaran orang luar tidak dibenarkan untuk program ini.');
}
$request->validate([
'name' => ['required', 'string', 'max:255'],
'no_kp' => ['required', 'digits:12'],
'email' => ['nullable', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:20'],
'agency' => ['nullable', 'string', 'max:255'],
], [
'name.required' => 'Sila masukkan nama penuh anda.',
'no_kp.required' => 'Sila masukkan No. Kad Pengenalan anda.',
'no_kp.digits' => 'No. Kad Pengenalan mestilah 12 digit tanpa sempang.',
'email.email' => 'Format emel tidak sah.',
]);
$result = $this->attendanceService->walkInRegister($program, $request->all(), $request);
return match ($result['status']) {
'success' => view('public.checkin.success', [
'program' => $program,
'participant' => $result['participant'],
'attendance' => $result['attendance'],
'qrCode' => $qrCode,
]),
'already_checked_in' => view('public.checkin.already', [
'program' => $program,
'participant' => $result['participant'],
'attendance' => $result['attendance'],
]),
default => back()->withInput()->with('error', 'Ralat sistem. Sila cuba lagi.'),
};
}
}

View File

@@ -0,0 +1,131 @@
<?php
namespace App\Http\Controllers\Public;
use App\Http\Controllers\Controller;
use App\Models\Participant;
use App\Models\ProgramQrCode;
use App\Models\QuestionnaireResponse;
use App\Models\QuestionnaireAnswer;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\View\View;
class QuestionnaireController extends Controller
{
public function show(string $qr_token, string $participant_uuid): View|RedirectResponse
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
$participant = Participant::where('uuid', $participant_uuid)->firstOrFail();
$pp = $program->programParticipants()->where('participant_id', $participant->id)->first();
abort_if(! $pp, 404);
$pq = $program->questionnaire()->with('questionnaireSet')->first();
if (! $pq || ! $pq->is_confirmed) {
return redirect()->route('public.semak.show', $qr_token);
}
if (QuestionnaireResponse::where('program_id', $program->id)->where('participant_id', $participant->id)->exists()) {
return view('public.questionnaire.already', compact('program', 'participant', 'qrCode'));
}
$questions = $this->loadHierarchical($pq);
return view('public.questionnaire.show', compact('program', 'participant', 'qrCode', 'pq', 'questions'));
}
public function submit(Request $request, string $qr_token, string $participant_uuid): View|RedirectResponse
{
$qrCode = ProgramQrCode::where('token', $qr_token)->where('is_active', true)->firstOrFail();
$program = $qrCode->program;
$participant = Participant::where('uuid', $participant_uuid)->firstOrFail();
$pp = $program->programParticipants()->where('participant_id', $participant->id)->first();
abort_if(! $pp, 404);
$pq = $program->questionnaire()->with('questionnaireSet')->first();
abort_if(! $pq || ! $pq->is_confirmed, 404);
if (QuestionnaireResponse::where('program_id', $program->id)->where('participant_id', $participant->id)->exists()) {
return view('public.questionnaire.already', compact('program', 'participant', 'qrCode'));
}
$questions = $this->loadHierarchical($pq);
$answerable = $this->flatten($questions);
$rules = [];
foreach ($answerable as $q) {
if ($q->question_type === 'multiple_choice') {
$rules['q_' . $q->id] = ($q->is_required ? 'required|' : 'nullable|') . 'array';
} else {
$rules['q_' . $q->id] = $q->is_required ? 'required' : 'nullable';
}
}
$request->validate($rules, ['q_*.required' => 'Soalan ini wajib dijawab.']);
$response = QuestionnaireResponse::create([
'program_id' => $program->id,
'participant_id' => $participant->id,
'questionnaire_set_id' => $pq->questionnaire_set_id,
'submitted_at' => now(),
'ip_address' => $request->ip(),
'user_agent' => substr($request->userAgent() ?? '', 0, 500),
]);
foreach ($answerable as $q) {
$raw = $request->input('q_' . $q->id);
if ($raw === null && ! $q->is_required) {
continue;
}
$value = match ($q->question_type) {
'multiple_choice' => (array) $raw,
'rating' => (int) $raw,
default => $raw,
};
QuestionnaireAnswer::create([
'questionnaire_response_id' => $response->id,
'questionnaire_question_id' => $q->id,
'answer_value' => $value,
]);
}
return view('public.questionnaire.thankyou', compact('program', 'participant', 'qrCode'));
}
// ── Helpers ──────────────────────────────────────────────────────────────
private function loadHierarchical($pq): Collection
{
return $pq->questionnaireSet->questions()
->whereNull('parent_id')
->with(['children' => fn($q) => $q->orderBy('sort_order')])
->orderBy('sort_order')
->get();
}
/** Return only answerable (non-tajuk) questions as a flat collection. */
private function flatten(Collection $topLevel): Collection
{
$out = collect();
foreach ($topLevel as $q) {
if ($q->question_type === 'tajuk') {
foreach ($q->children as $child) {
$out->push($child);
}
} else {
$out->push($q);
}
}
return $out;
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureIsAdmin
{
public function handle(Request $request, Closure $next): Response
{
$role = $request->user()?->role;
if (! in_array($role, ['super_admin', 'admin'])) {
abort(403, 'Akses ditolak.');
}
return $next($request);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureSuperAdmin
{
public function handle(Request $request, Closure $next): Response
{
if ($request->user()?->role !== 'super_admin') {
abort(403, 'Hanya Super Admin boleh mengakses bahagian ini.');
}
return $next($request);
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace App\Http\Requests\Admin;
use Illuminate\Foundation\Http\FormRequest;
class StoreProgramRequest extends FormRequest
{
public function authorize(): bool
{
return auth()->check();
}
public function rules(): array
{
return [
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:5000'],
'organizer' => ['required', 'string', 'max:255'],
'location' => ['required', 'string', 'max:500'],
'start_date' => ['required', 'date'],
'end_date' => ['required', 'date', 'gte:start_date'],
'checkin_start_at' => ['nullable', 'date'],
'checkin_end_at' => ['nullable', 'date', 'after_or_equal:checkin_start_at'],
'ecert_download_start_at' => ['nullable', 'date'],
'ecert_download_end_at' => ['nullable', 'date', 'after_or_equal:ecert_download_start_at'],
'allow_walk_in' => ['boolean'],
'default_staff_session' => ['nullable', 'in:pagi,petang,full_day'],
'default_external_session' => ['nullable', 'in:pagi,petang,full_day'],
];
}
public function attributes(): array
{
return [
'title' => 'nama program',
'organizer' => 'penganjur',
'location' => 'lokasi',
'start_date' => 'tarikh mula',
'end_date' => 'tarikh tamat',
'checkin_start_at' => 'masa mula check-in',
'checkin_end_at' => 'masa tamat check-in',
'ecert_download_start_at' => 'masa mula download sijil',
'ecert_download_end_at' => 'masa tamat download sijil',
'default_staff_session' => 'sesi default kakitangan',
'default_external_session' => 'sesi default peserta luar',
];
}
protected function prepareForValidation(): void
{
$this->merge([
'allow_walk_in' => $this->boolean('allow_walk_in'),
]);
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace App\Http\Requests\Admin;
class UpdateProgramRequest extends StoreProgramRequest
{
// Inherits all rules from StoreProgramRequest.
// Status changes handled via dedicated publish/close actions, not here.
}

View File

@@ -0,0 +1,86 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Jobs;
use App\Models\Certificate;
use App\Services\CertificateService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class GenerateCertificateJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 30;
public function __construct(public readonly Certificate $certificate) {}
public function handle(CertificateService $service): void
{
$this->certificate->refresh();
if ($this->certificate->status === 'generated') {
return;
}
$service->generate($this->certificate);
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace App\Jobs;
use App\Mail\CertificateReadyMail;
use App\Models\Certificate;
use App\Models\EmailLog;
use App\Models\Program;
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\Mail;
class SendCertificateEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $backoff = 60;
public function __construct(public readonly Certificate $certificate) {}
public function handle(): void
{
$cert = $this->certificate->refresh();
$cert->load(['participant', 'program']);
$email = $cert->participant->email;
if (! $email) {
return;
}
try {
Mail::to($email)->send(new CertificateReadyMail($cert));
$cert->update([
'status' => 'emailed',
'emailed_at' => now(),
]);
EmailLog::create([
'program_id' => $cert->program_id,
'participant_id' => $cert->participant_id,
'certificate_id' => $cert->id,
'recipient_email'=> $email,
'subject' => 'Sijil Digital Program — ' . $cert->program->title,
'email_type' => 'certificate_ready',
'status' => 'sent',
'sent_at' => now(),
]);
} catch (\Throwable $e) {
EmailLog::create([
'program_id' => $cert->program_id,
'participant_id' => $cert->participant_id,
'certificate_id' => $cert->id,
'recipient_email'=> $email,
'subject' => 'Sijil Digital Program — ' . $cert->program->title,
'email_type' => 'certificate_ready',
'status' => 'failed',
'error_message' => $e->getMessage(),
]);
throw $e;
}
}
public static function dispatchBatch(Program $program): void
{
$program->certificates()
->whereIn('status', ['generated'])
->whereNull('emailed_at')
->with('participant')
->each(function (Certificate $cert) {
if ($cert->participant->email) {
static::dispatch($cert);
}
});
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Mail;
use App\Models\Certificate;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
class CertificateReadyMail extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public readonly Certificate $certificate) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Sijil Digital Program — ' . $this->certificate->program->title,
);
}
public function content(): Content
{
return new Content(
view: 'emails.certificate-ready',
);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Attendance extends Model
{
protected $fillable = [
'program_id', 'participant_id', 'program_participant_id',
'attendance_source', 'attendance_session',
'checked_in_at', 'checked_in_ip', 'user_agent', 'notes',
];
protected function casts(): array
{
return ['checked_in_at' => 'datetime'];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
public function programParticipant()
{
return $this->belongsTo(ProgramParticipant::class);
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AuditLog extends Model
{
protected $fillable = [
'user_id', 'action', 'auditable_type', 'auditable_id',
'old_values', 'new_values', 'ip_address', 'user_agent',
];
protected function casts(): array
{
return [
'old_values' => 'array',
'new_values' => 'array',
];
}
public function user()
{
return $this->belongsTo(User::class);
}
public function auditable()
{
return $this->morphTo();
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Certificate extends Model
{
protected $fillable = [
'uuid', 'program_id', 'participant_id', 'certificate_template_id',
'certificate_no', 'file_path', 'token', 'status', 'error_message',
'generated_at', 'emailed_at', 'downloaded_at', 'download_count',
];
protected function casts(): array
{
return [
'generated_at' => 'datetime',
'emailed_at' => 'datetime',
'downloaded_at' => 'datetime',
'download_count' => 'integer',
];
}
protected static function boot(): void
{
parent::boot();
static::creating(function ($model) {
$model->uuid ??= (string) Str::uuid();
$model->token ??= Str::random(48);
});
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
public function template()
{
return $this->belongsTo(CertificateTemplate::class, 'certificate_template_id');
}
public function emailLogs()
{
return $this->hasMany(EmailLog::class);
}
public function isGenerated(): bool
{
return $this->status === 'generated' || $this->status === 'emailed' || $this->status === 'downloaded';
}
public function recordDownload(): void
{
$this->increment('download_count');
if (! $this->downloaded_at) {
$this->update(['downloaded_at' => now(), 'status' => 'downloaded']);
}
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CertificateTemplate extends Model
{
protected $fillable = [
'program_id', 'original_filename', 'image_path', 'config_json', 'is_active', 'uploaded_by',
];
protected function casts(): array
{
return [
'config_json' => 'array',
'is_active' => 'boolean',
];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function uploader()
{
return $this->belongsTo(User::class, 'uploaded_by');
}
public function certificates()
{
return $this->hasMany(Certificate::class);
}
public function getFieldConfig(string $field): ?array
{
return $this->config_json['fields'][$field] ?? null;
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class EmailLog extends Model
{
protected $fillable = [
'program_id', 'participant_id', 'certificate_id',
'recipient_email', 'subject', 'email_type', 'status', 'error_message', 'sent_at',
];
protected function casts(): array
{
return ['sent_at' => 'datetime'];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
public function certificate()
{
return $this->belongsTo(Certificate::class);
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Str;
class Participant extends Model
{
use HasFactory;
protected $fillable = [
'uuid', 'name', 'no_kp', 'email', 'phone', 'agency', 'participant_type',
];
protected static function boot(): void
{
parent::boot();
static::creating(fn($model) => $model->uuid ??= (string) Str::uuid());
}
public function programs()
{
return $this->belongsToMany(Program::class, 'program_participants')
->withPivot(['registration_source', 'is_pre_registered', 'pre_registered_session', 'status', 'registered_at'])
->withTimestamps();
}
public function programParticipants()
{
return $this->hasMany(ProgramParticipant::class);
}
public function attendances()
{
return $this->hasMany(Attendance::class);
}
public function certificates()
{
return $this->hasMany(Certificate::class);
}
public function questionnaireResponses()
{
return $this->hasMany(QuestionnaireResponse::class);
}
public function attendanceForProgram(int $programId): ?Attendance
{
return $this->attendances()->where('program_id', $programId)->first();
}
public function hasAnsweredQuestionnaire(int $programId, int $questionnaireSetId): bool
{
return $this->questionnaireResponses()
->where('program_id', $programId)
->where('questionnaire_set_id', $questionnaireSetId)
->exists();
}
}

122
src/app/Models/Program.php Normal file
View File

@@ -0,0 +1,122 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Str;
class Program extends Model
{
use HasFactory;
protected $fillable = [
'uuid', 'title', 'description', 'organizer', 'location',
'start_date', 'end_date',
'checkin_start_at', 'checkin_end_at',
'ecert_download_start_at', 'ecert_download_end_at',
'status', 'allow_walk_in',
'default_staff_session', 'default_external_session',
'created_by',
];
protected function casts(): array
{
return [
'start_date' => 'date',
'end_date' => 'date',
'checkin_start_at' => 'datetime',
'checkin_end_at' => 'datetime',
'ecert_download_start_at' => 'datetime',
'ecert_download_end_at' => 'datetime',
'allow_walk_in' => 'boolean',
];
}
protected static function boot(): void
{
parent::boot();
static::creating(fn($model) => $model->uuid ??= (string) Str::uuid());
}
public function getRouteKeyName(): string
{
return 'uuid';
}
public function creator()
{
return $this->belongsTo(User::class, 'created_by');
}
public function qrCode()
{
return $this->hasOne(ProgramQrCode::class)->where('is_active', true)->latestOfMany();
}
public function qrCodes()
{
return $this->hasMany(ProgramQrCode::class);
}
public function participants()
{
return $this->belongsToMany(Participant::class, 'program_participants')
->withPivot(['registration_source', 'is_pre_registered', 'pre_registered_session', 'status', 'registered_at'])
->withTimestamps();
}
public function programParticipants()
{
return $this->hasMany(ProgramParticipant::class);
}
public function attendances()
{
return $this->hasMany(Attendance::class);
}
public function certificateTemplate()
{
return $this->hasOne(CertificateTemplate::class)->where('is_active', true)->latestOfMany();
}
public function certificateTemplates()
{
return $this->hasMany(CertificateTemplate::class);
}
public function certificates()
{
return $this->hasMany(Certificate::class);
}
public function questionnaire()
{
return $this->hasOne(ProgramQuestionnaire::class);
}
public function questionnaireSets()
{
return $this->belongsToMany(QuestionnaireSet::class, 'program_questionnaires')
->withPivot(['is_confirmed', 'confirmed_at', 'confirmed_by'])
->withTimestamps();
}
public function isCheckinOpen(): bool
{
$now = now();
return $this->status === 'published'
&& $this->checkin_start_at
&& $now->between($this->checkin_start_at, $this->checkin_end_at ?? $now->addYear());
}
public function isDownloadOpen(): bool
{
$now = now();
return $this->status === 'published'
&& $this->ecert_download_start_at
&& $now->gte($this->ecert_download_start_at)
&& (! $this->ecert_download_end_at || $now->lte($this->ecert_download_end_at));
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProgramParticipant extends Model
{
protected $fillable = [
'program_id', 'participant_id',
'registration_source', 'is_pre_registered', 'pre_registered_session',
'status', 'registered_at',
];
protected function casts(): array
{
return [
'is_pre_registered' => 'boolean',
'registered_at' => 'datetime',
];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
public function attendance()
{
return $this->hasOne(Attendance::class);
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class ProgramQrCode extends Model
{
protected $fillable = ['program_id', 'token', 'qr_image_path', 'is_active'];
protected function casts(): array
{
return ['is_active' => 'boolean'];
}
protected static function boot(): void
{
parent::boot();
static::creating(fn($model) => $model->token ??= Str::random(48));
}
public function program()
{
return $this->belongsTo(Program::class);
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProgramQuestionnaire extends Model
{
protected $fillable = [
'program_id', 'questionnaire_set_id', 'is_confirmed', 'confirmed_at', 'confirmed_by',
];
protected function casts(): array
{
return [
'is_confirmed' => 'boolean',
'confirmed_at' => 'datetime',
];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function questionnaireSet()
{
return $this->belongsTo(QuestionnaireSet::class);
}
public function confirmedBy()
{
return $this->belongsTo(User::class, 'confirmed_by');
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class QuestionnaireAnswer extends Model
{
protected $fillable = [
'questionnaire_response_id', 'questionnaire_question_id', 'answer_value',
];
protected function casts(): array
{
return ['answer_value' => 'array'];
}
public function response()
{
return $this->belongsTo(QuestionnaireResponse::class, 'questionnaire_response_id');
}
public function question()
{
return $this->belongsTo(QuestionnaireQuestion::class, 'questionnaire_question_id');
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class QuestionnaireQuestion extends Model
{
protected $fillable = [
'questionnaire_set_id', 'parent_id', 'question_text', 'question_type',
'options_json', 'rating_labels', 'is_required', 'sort_order',
];
protected function casts(): array
{
return [
'options_json' => 'array',
'rating_labels' => 'array',
'is_required' => 'boolean',
'sort_order' => 'integer',
];
}
public function questionnaireSet()
{
return $this->belongsTo(QuestionnaireSet::class);
}
public function parent()
{
return $this->belongsTo(QuestionnaireQuestion::class, 'parent_id');
}
public function children()
{
return $this->hasMany(QuestionnaireQuestion::class, 'parent_id')->orderBy('sort_order');
}
public function answers()
{
return $this->hasMany(QuestionnaireAnswer::class);
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class QuestionnaireResponse extends Model
{
protected $fillable = [
'program_id', 'participant_id', 'questionnaire_set_id',
'submitted_at', 'ip_address', 'user_agent',
];
protected function casts(): array
{
return ['submitted_at' => 'datetime'];
}
public function program()
{
return $this->belongsTo(Program::class);
}
public function participant()
{
return $this->belongsTo(Participant::class);
}
public function questionnaireSet()
{
return $this->belongsTo(QuestionnaireSet::class);
}
public function answers()
{
return $this->hasMany(QuestionnaireAnswer::class);
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class QuestionnaireSet extends Model
{
use HasFactory;
protected $fillable = ['title', 'description', 'status', 'created_by'];
public function creator()
{
return $this->belongsTo(User::class, 'created_by');
}
public function questions()
{
return $this->hasMany(QuestionnaireQuestion::class)->orderBy('sort_order');
}
public function programs()
{
return $this->belongsToMany(Program::class, 'program_questionnaires')
->withPivot(['is_confirmed', 'confirmed_at', 'confirmed_by'])
->withTimestamps();
}
public function programQuestionnaires()
{
return $this->hasMany(ProgramQuestionnaire::class);
}
public function responses()
{
return $this->hasMany(QuestionnaireResponse::class);
}
}

50
src/app/Models/User.php Normal file
View File

@@ -0,0 +1,50 @@
<?php
namespace App\Models;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
protected $fillable = ['name', 'email', 'password', 'role'];
protected $hidden = ['password', 'remember_token'];
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
public function isSuperAdmin(): bool
{
return $this->role === 'super_admin';
}
public function isAdminProgram(): bool
{
return $this->role === 'admin';
}
public function canAccessProgram(Program $program): bool
{
return $this->isSuperAdmin() || $program->created_by === $this->id;
}
public function programs()
{
return $this->hasMany(Program::class, 'created_by');
}
public function auditLogs()
{
return $this->hasMany(AuditLog::class);
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace App\Policies;
use App\Models\Program;
use App\Models\User;
class ProgramPolicy
{
public function viewAny(User $user): bool
{
return true; // Both roles can see programs list (scoped per controller)
}
public function view(User $user, Program $program): bool
{
return $user->canAccessProgram($program);
}
public function create(User $user): bool
{
return true; // Both roles can create programs
}
public function update(User $user, Program $program): bool
{
return $user->canAccessProgram($program);
}
public function delete(User $user, Program $program): bool
{
return $user->canAccessProgram($program);
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace App\Providers;
use App\Models\Program;
use App\Policies\ProgramPolicy;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function register(): void {}
public function boot(): void
{
// Policies
Gate::policy(Program::class, ProgramPolicy::class);
// Bootstrap pagination
Paginator::useBootstrapFive();
// Rate limiters for public routes
RateLimiter::for('checkin', fn(Request $request) =>
Limit::perMinute(60)->by($request->ip())
);
RateLimiter::for('certificate', fn(Request $request) =>
Limit::perMinute(30)->by($request->ip())
);
// Force HTTPS in production
if (app()->environment('production')) {
URL::forceScheme('https');
}
}
}

View File

@@ -0,0 +1,123 @@
<?php
namespace App\Services;
use App\Models\Attendance;
use App\Models\Participant;
use App\Models\Program;
use App\Models\ProgramParticipant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AttendanceService
{
public function staffCheckin(Program $program, string $noKp, Request $request): array
{
$noKp = preg_replace('/[^0-9]/', '', $noKp);
// Find participant
$participant = Participant::where('no_kp', $noKp)->first();
if (! $participant) {
return ['status' => 'not_found'];
}
// Check if registered in this program
$pp = ProgramParticipant::where('program_id', $program->id)
->where('participant_id', $participant->id)
->first();
if (! $pp) {
return ['status' => 'not_registered', 'participant' => $participant];
}
// Already checked in
if (Attendance::where('program_id', $program->id)->where('participant_id', $participant->id)->exists()) {
$att = Attendance::where('program_id', $program->id)->where('participant_id', $participant->id)->first();
return ['status' => 'already_checked_in', 'participant' => $participant, 'attendance' => $att];
}
// Record attendance
$attendance = DB::transaction(function () use ($program, $participant, $pp, $request) {
$session = $pp->pre_registered_session ?? $program->default_staff_session ?? 'full_day';
$pp->update(['status' => 'checked_in']);
return Attendance::create([
'program_id' => $program->id,
'participant_id' => $participant->id,
'program_participant_id' => $pp->id,
'attendance_source' => 'pre_registered_staff',
'attendance_session' => $session,
'checked_in_at' => now(),
'checked_in_ip' => $request->ip(),
'user_agent' => substr($request->userAgent() ?? '', 0, 500),
]);
});
return ['status' => 'success', 'participant' => $participant, 'attendance' => $attendance];
}
public function walkInRegister(Program $program, array $data, Request $request): array
{
$noKp = preg_replace('/[^0-9]/', '', $data['no_kp']);
// Check duplicate in this program
$existing = Participant::where('no_kp', $noKp)->first();
if ($existing) {
$alreadyRegistered = ProgramParticipant::where('program_id', $program->id)
->where('participant_id', $existing->id)
->exists();
if ($alreadyRegistered) {
// Check if already attended
$att = Attendance::where('program_id', $program->id)
->where('participant_id', $existing->id)
->first();
if ($att) {
return ['status' => 'already_checked_in', 'participant' => $existing, 'attendance' => $att];
}
}
}
$result = DB::transaction(function () use ($program, $data, $noKp, $existing, $request) {
$participant = $existing ?? Participant::create([
'name' => $data['name'],
'no_kp' => $noKp,
'email' => $data['email'] ?: null,
'phone' => $data['phone'] ?: null,
'agency' => $data['agency'] ?: null,
'participant_type' => 'external',
]);
// Create program_participant if not exists
$pp = ProgramParticipant::firstOrCreate(
['program_id' => $program->id, 'participant_id' => $participant->id],
[
'registration_source' => 'walk_in',
'is_pre_registered' => false,
'pre_registered_session'=> $program->default_external_session,
'status' => 'registered',
'registered_at' => now(),
]
);
$session = $program->default_external_session ?? 'full_day';
$pp->update(['status' => 'checked_in']);
$attendance = Attendance::create([
'program_id' => $program->id,
'participant_id' => $participant->id,
'program_participant_id' => $pp->id,
'attendance_source' => 'walk_in_external',
'attendance_session' => $session,
'checked_in_at' => now(),
'checked_in_ip' => $request->ip(),
'user_agent' => substr($request->userAgent() ?? '', 0, 500),
]);
return ['status' => 'success', 'participant' => $participant, 'attendance' => $attendance];
});
return $result;
}
}

View File

@@ -0,0 +1,39 @@
<?php
namespace App\Services;
use App\Models\AuditLog;
use Illuminate\Database\Eloquent\Model;
class AuditLogService
{
public static function log(
string $action,
?Model $model = null,
array $oldValues = [],
array $newValues = []
): void {
try {
AuditLog::create([
'user_id' => auth()->id(),
'action' => $action,
'auditable_type' => $model ? get_class($model) : null,
'auditable_id' => $model?->getKey(),
'old_values' => self::redact($oldValues),
'new_values' => self::redact($newValues),
'ip_address' => request()->ip(),
'user_agent' => substr(request()->userAgent() ?? '', 0, 500),
]);
} catch (\Throwable) {
// Audit log failure must not break the main flow.
}
}
private static function redact(array $values): array
{
// Never log these sensitive fields.
$sensitive = ['no_kp', 'password', 'token', 'remember_token'];
return array_diff_key($values, array_flip($sensitive));
}
}

View File

@@ -0,0 +1,143 @@
<?php
namespace App\Services;
use App\Models\Certificate;
use App\Models\Program;
use App\Models\Participant;
use App\Models\CertificateTemplate;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\ImageManager;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\Encoders\JpegEncoder;
use Intervention\Image\Typography\FontFactory;
class CertificateService
{
private ImageManager $manager;
public function __construct()
{
$this->manager = new ImageManager(new Driver());
}
public function generate(Certificate $certificate): void
{
$certificate->update(['status' => 'generating']);
try {
$certificate->load(['participant', 'template', 'program']);
$template = $certificate->template;
if (! $template) {
throw new \RuntimeException('Template sijil tidak dijumpai.');
}
$templatePath = Storage::disk('local')->path($template->image_path);
if (! file_exists($templatePath)) {
throw new \RuntimeException('Fail template sijil tidak dijumpai di storage.');
}
$image = $this->manager->decodePath($templatePath);
$config = $template->config_json ?? [];
$fields = $config['fields'] ?? [];
if (isset($fields['name'])) {
$this->writeText($image, $certificate->participant->name, $fields['name']);
$this->writeIcBelow($image, $certificate->participant->no_kp, $fields['name']);
}
if (isset($fields['certificate_no']) && $certificate->certificate_no) {
$this->writeText($image, $certificate->certificate_no, $fields['certificate_no']);
}
$outputDir = 'certificates/' . $certificate->program_id;
$outputFile = $outputDir . '/' . $certificate->uuid . '.jpg';
Storage::disk('local')->makeDirectory($outputDir);
$image->encode(new JpegEncoder(90))
->save(Storage::disk('local')->path($outputFile));
$certificate->update([
'file_path' => $outputFile,
'status' => 'generated',
'generated_at' => now(),
'error_message'=> null,
]);
} catch (\Throwable $e) {
$certificate->update([
'status' => 'failed',
'error_message' => $e->getMessage(),
]);
}
}
public function generatePreview(CertificateTemplate $template, string $sampleName, string $sampleNo = '', ?array $overrideFields = null, string $sampleIc = '800808-08-8888'): string
{
$templatePath = Storage::disk('local')->path($template->image_path);
$image = $this->manager->decodePath($templatePath);
$fields = $overrideFields ?? ($template->config_json['fields'] ?? []);
if (isset($fields['name'])) {
$this->writeText($image, $sampleName, $fields['name']);
$this->writeIcBelow($image, $sampleIc, $fields['name']);
}
if (isset($fields['certificate_no'])) {
$this->writeText($image, $sampleNo ?: 'ECT/2025/0001', $fields['certificate_no']);
}
return $image->encode(new JpegEncoder(85))->toString();
}
// Tulis IC di bawah nama — auto-posisi Y, saiz font dari config atau fallback 70%
private function writeIcBelow(\Intervention\Image\Interfaces\ImageInterface $image, string $ic, array $nameCfg): void
{
$nameFontSize = (int) ($nameCfg['font_size'] ?? 48);
$icFontSize = isset($nameCfg['ic_font_size']) && (int) $nameCfg['ic_font_size'] > 0
? (int) $nameCfg['ic_font_size']
: (int) round($nameFontSize * 0.7);
$icY = (int) ($nameCfg['y'] ?? 0) + (int) round($nameFontSize * 1.5);
$this->writeText($image, $ic, array_merge($nameCfg, [
'font_size' => $icFontSize,
'y' => $icY,
'font_file' => $nameCfg['font_file'] ?? 'DejaVuSans.ttf',
]));
}
private function writeText(\Intervention\Image\Interfaces\ImageInterface $image, string $text, array $cfg): void
{
$fontFile = $this->resolveFontPath($cfg['font_file'] ?? 'DejaVuSans-Bold.ttf');
$fontSize = (int) ($cfg['font_size'] ?? 48);
$fontColor = (string)($cfg['font_color'] ?? '#000000');
$align = (string)($cfg['align'] ?? 'center');
$valign = (string)($cfg['valign'] ?? 'top');
$x = (int) ($cfg['x'] ?? 0);
$y = (int) ($cfg['y'] ?? 0);
$image->text($text, $x, $y, function (FontFactory $font) use ($fontFile, $fontSize, $fontColor, $align, $valign) {
$font->filename($fontFile);
$font->size($fontSize);
$font->color($fontColor);
$font->align($align, $valign); // v4: satu kaedah untuk horizontal + vertical
});
}
private function resolveFontPath(string $filename): string
{
$custom = resource_path('fonts/' . $filename);
if (file_exists($custom)) {
return $custom;
}
return resource_path('fonts/DejaVuSans-Bold.ttf');
}
public function buildCertificateNo(Program $program, Participant $participant, int $sequence): string
{
$year = now()->format('Y');
$prefix = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $program->title), 0, 4));
return sprintf('%s/%s/%04d', $prefix, $year, $sequence);
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace App\Services;
use App\Models\Participant;
use App\Models\Program;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use League\Csv\Reader;
class ParticipantImportService
{
public function import(Program $program, UploadedFile $file, ?string $defaultSession): array
{
$result = ['success' => 0, 'duplicates' => 0, 'failed' => 0, 'errors' => []];
$csv = Reader::createFromPath($file->getRealPath(), 'r');
$csv->setHeaderOffset(0);
// Strip UTF-8 BOM if present (Excel-exported CSV)
$csv->setOutputBOM('');
try {
$csv->addStreamFilter('convert.iconv.UTF-8/UTF-8');
} catch (\Throwable) {}
foreach ($csv->getRecords() as $rowNum => $row) {
$row = array_map('trim', $row);
// Normalise header keys (lowercase, strip BOM)
$row = array_combine(
array_map(fn($k) => strtolower(preg_replace('/[\x{FEFF}\s]/u', '', $k)), array_keys($row)),
array_values($row)
);
$data = [
'name' => $row['name'] ?? $row['nama'] ?? '',
'no_kp' => preg_replace('/[^0-9]/', '', $row['no_kp'] ?? $row['nokp'] ?? $row['ic'] ?? ''),
'email' => $row['email'] ?? $row['emel'] ?? null,
'phone' => $row['phone'] ?? $row['telefon'] ?? $row['phone'] ?? null,
'agency' => $row['agency'] ?? $row['agensi'] ?? $row['jabatan'] ?? null,
];
// Validate row
$validator = Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'no_kp' => ['required', 'digits:12'],
'email' => ['nullable', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:20'],
]);
if ($validator->fails()) {
$result['failed']++;
$result['errors'][] = 'Baris ' . ($rowNum + 2) . ': ' . implode(', ', $validator->errors()->all());
continue;
}
try {
DB::transaction(function () use ($program, $data, $defaultSession, &$result) {
// Find or create participant by no_kp
$participant = Participant::firstOrCreate(
['no_kp' => $data['no_kp']],
[
'name' => $data['name'],
'email' => $data['email'] ?: null,
'phone' => $data['phone'] ?: null,
'agency' => $data['agency'] ?: null,
'participant_type' => 'staff',
]
);
// Check duplicate in this program
$exists = $program->programParticipants()
->where('participant_id', $participant->id)
->exists();
if ($exists) {
$result['duplicates']++;
return;
}
$program->programParticipants()->create([
'participant_id' => $participant->id,
'registration_source' => 'import',
'is_pre_registered' => true,
'pre_registered_session' => $defaultSession,
'status' => 'registered',
'registered_at' => now(),
]);
$result['success']++;
});
} catch (\Throwable $e) {
$result['failed']++;
$result['errors'][] = 'Baris ' . ($rowNum + 2) . ': Ralat sistem — ' . $e->getMessage();
}
}
return $result;
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace App\Services;
use App\Models\Program;
use App\Models\ProgramQrCode;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
class QrCodeService
{
public function generateForProgram(Program $program): ProgramQrCode
{
$program->qrCodes()->where('is_active', true)->update(['is_active' => false]);
$token = Str::random(48);
$url = route('public.checkin.show', $token);
$path = 'qrcodes/' . $token . '.png';
Storage::disk('public')->makeDirectory('qrcodes');
$png = QrCode::format('png')
->size(400)
->margin(2)
->errorCorrection('H')
->generate($url);
Storage::disk('public')->put($path, $png);
return $program->qrCodes()->create([
'token' => $token,
'qr_image_path' => $path,
'is_active' => true,
]);
}
public function getPublicUrl(ProgramQrCode $qrCode): string
{
return Storage::disk('public')->url($qrCode->qr_image_path);
}
public function getRawPng(ProgramQrCode $qrCode): string
{
return Storage::disk('public')->get($qrCode->qr_image_path);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class AppLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.app');
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}

18
src/artisan Normal file
View File

@@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);

21
src/bootstrap/app.php Normal file
View File

@@ -0,0 +1,21 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'admin' => \App\Http\Middleware\EnsureIsAdmin::class,
'super_admin' => \App\Http\Middleware\EnsureSuperAdmin::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();

2
src/bootstrap/cache/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*
!.gitignore

View File

@@ -0,0 +1,7 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];

92
src/composer.json Normal file
View File

@@ -0,0 +1,92 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.3",
"barryvdh/laravel-dompdf": "^3.1",
"intervention/image": "^4.1",
"laravel/framework": "^13.8",
"laravel/tinker": "^3.0",
"league/csv": "^9.28",
"simplesoftwareio/simple-qrcode": "^4.2"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/boost": "^2.4",
"laravel/breeze": "^2.4",
"laravel/pail": "^1.2.5",
"laravel/pao": "^1.0.6",
"laravel/pint": "^1.27",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^12.5.12"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install --ignore-scripts",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi @no_additional_args",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

9526
src/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

126
src/config/app.php Normal file
View File

@@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];

117
src/config/auth.php Normal file
View File

@@ -0,0 +1,117 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];

130
src/config/cache.php Normal file
View File

@@ -0,0 +1,130 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "octane",
| "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
/*
|--------------------------------------------------------------------------
| Serializable Classes
|--------------------------------------------------------------------------
|
| This value determines the classes that can be unserialized from cache
| storage. By default, no PHP classes will be unserialized from your
| cache to prevent gadget chain attacks if your APP_KEY is leaked.
|
*/
'serializable_classes' => false,
];

184
src/config/database.php Normal file
View File

@@ -0,0 +1,184 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];

View File

@@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

132
src/config/logging.php Normal file
View File

@@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

118
src/config/mail.php Normal file
View File

@@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];

129
src/config/queue.php Normal file
View File

@@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];

38
src/config/services.php Normal file
View File

@@ -0,0 +1,38 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
];

233
src/config/session.php Normal file
View File

@@ -0,0 +1,233 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
/*
|--------------------------------------------------------------------------
| Session Serialization
|--------------------------------------------------------------------------
|
| This value controls the serialization strategy for session data, which
| is JSON by default. Setting this to "php" allows the storage of PHP
| objects in the session but can make an application vulnerable to
| "gadget chain" serialization attacks if the APP_KEY is leaked.
|
| Supported: "json", "php"
|
*/
'serialization' => 'json',
];

1
src/database/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
*.sqlite*

View File

@@ -0,0 +1,30 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProgramFactory extends Factory
{
public function definition(): array
{
return [
'title' => fake()->sentence(3),
'organizer' => fake()->company(),
'location' => fake()->city(),
'start_date' => now()->toDateString(),
'end_date' => now()->toDateString(),
'status' => 'draft',
'allow_walk_in' => true,
'default_staff_session' => 'pagi',
'default_external_session' => 'pagi',
'created_by' => User::factory(),
];
}
public function published(): static
{
return $this->state(fn () => ['status' => 'published']);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'role' => 'super_admin',
];
}
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
public function adminProgram(): static
{
return $this->state(fn (array $attributes) => ['role' => 'admin']);
}
public function nonAdmin(): static
{
// role='none' bukan dalam enum yang valid → EnsureIsAdmin returns 403
// SQLite tidak enforce enum constraint dalam tests
return $this->state(fn (array $attributes) => ['role' => 'none']);
}
}

View File

@@ -0,0 +1,50 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('is_admin')->default(true);
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};

View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->bigInteger('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->bigInteger('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};

View File

@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedSmallInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->string('connection');
$table->string('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
$table->index(['connection', 'queue', 'failed_at']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};

View File

@@ -0,0 +1,40 @@
<?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::create('programs', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('title');
$table->text('description')->nullable();
$table->string('organizer');
$table->string('location', 500);
$table->date('start_date');
$table->date('end_date');
$table->dateTime('checkin_start_at')->nullable();
$table->dateTime('checkin_end_at')->nullable();
$table->dateTime('ecert_download_start_at')->nullable();
$table->dateTime('ecert_download_end_at')->nullable();
$table->enum('status', ['draft', 'published', 'closed'])->default('draft');
$table->boolean('allow_walk_in')->default(true);
$table->enum('default_staff_session', ['pagi', 'petang', 'full_day'])->nullable();
$table->enum('default_external_session', ['pagi', 'petang', 'full_day'])->nullable();
$table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
$table->timestamps();
$table->index('status');
$table->index('uuid');
});
}
public function down(): void
{
Schema::dropIfExists('programs');
}
};

View File

@@ -0,0 +1,28 @@
<?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::create('program_qr_codes', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->string('token', 64)->unique();
$table->string('qr_image_path', 500)->nullable();
$table->boolean('is_active')->default(true);
$table->timestamps();
$table->index('token');
$table->index('program_id');
});
}
public function down(): void
{
Schema::dropIfExists('program_qr_codes');
}
};

View File

@@ -0,0 +1,32 @@
<?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::create('participants', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->string('name');
$table->string('no_kp', 20)->unique();
$table->string('email', 255)->nullable();
$table->string('phone', 20)->nullable();
$table->string('agency', 255)->nullable();
$table->enum('participant_type', ['staff', 'external'])->default('external');
$table->timestamps();
$table->index('no_kp');
$table->index('email');
$table->index('uuid');
});
}
public function down(): void
{
Schema::dropIfExists('participants');
}
};

View File

@@ -0,0 +1,33 @@
<?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::create('program_participants', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->foreignId('participant_id')->constrained('participants')->cascadeOnDelete();
$table->enum('registration_source', ['pre_registered', 'walk_in', 'admin_manual', 'import'])->default('admin_manual');
$table->boolean('is_pre_registered')->default(false);
$table->enum('pre_registered_session', ['pagi', 'petang', 'full_day'])->nullable();
$table->enum('status', ['registered', 'checked_in', 'cancelled'])->default('registered');
$table->timestamp('registered_at')->nullable();
$table->timestamps();
$table->unique(['program_id', 'participant_id']);
$table->index('program_id');
$table->index('participant_id');
$table->index('status');
});
}
public function down(): void
{
Schema::dropIfExists('program_participants');
}
};

View File

@@ -0,0 +1,36 @@
<?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::create('attendances', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->foreignId('participant_id')->constrained('participants')->cascadeOnDelete();
$table->foreignId('program_participant_id')->nullable()->constrained('program_participants')->nullOnDelete();
$table->enum('attendance_source', ['pre_registered_staff', 'walk_in_external', 'admin_manual']);
$table->enum('attendance_session', ['pagi', 'petang', 'full_day']);
$table->timestamp('checked_in_at');
$table->string('checked_in_ip', 45)->nullable();
$table->string('user_agent', 500)->nullable();
$table->string('notes', 500)->nullable();
$table->timestamps();
$table->unique(['program_id', 'participant_id']);
$table->index('program_id');
$table->index('participant_id');
$table->index('attendance_source');
$table->index('attendance_session');
});
}
public function down(): void
{
Schema::dropIfExists('attendances');
}
};

View File

@@ -0,0 +1,29 @@
<?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::create('certificate_templates', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->string('original_filename', 255);
$table->string('image_path', 500);
$table->json('config_json')->nullable();
$table->boolean('is_active')->default(true);
$table->foreignId('uploaded_by')->constrained('users');
$table->timestamps();
$table->index('program_id');
});
}
public function down(): void
{
Schema::dropIfExists('certificate_templates');
}
};

View File

@@ -0,0 +1,27 @@
<?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::create('questionnaire_sets', function (Blueprint $table) {
$table->id();
$table->string('title', 255);
$table->text('description')->nullable();
$table->enum('status', ['draft', 'published', 'archived'])->default('draft');
$table->foreignId('created_by')->constrained('users');
$table->timestamps();
$table->index('status');
});
}
public function down(): void
{
Schema::dropIfExists('questionnaire_sets');
}
};

View File

@@ -0,0 +1,29 @@
<?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::create('questionnaire_questions', function (Blueprint $table) {
$table->id();
$table->foreignId('questionnaire_set_id')->constrained('questionnaire_sets')->cascadeOnDelete();
$table->text('question_text');
$table->enum('question_type', ['rating', 'single_choice', 'multiple_choice', 'short_text', 'long_text']);
$table->json('options_json')->nullable();
$table->boolean('is_required')->default(true);
$table->unsignedInteger('sort_order')->default(0);
$table->timestamps();
$table->index(['questionnaire_set_id', 'sort_order']);
});
}
public function down(): void
{
Schema::dropIfExists('questionnaire_questions');
}
};

View File

@@ -0,0 +1,29 @@
<?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::create('program_questionnaires', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->foreignId('questionnaire_set_id')->constrained('questionnaire_sets');
$table->boolean('is_confirmed')->default(false);
$table->timestamp('confirmed_at')->nullable();
$table->foreignId('confirmed_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
$table->unique(['program_id', 'questionnaire_set_id']);
$table->index('program_id');
});
}
public function down(): void
{
Schema::dropIfExists('program_questionnaires');
}
};

View File

@@ -0,0 +1,40 @@
<?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::create('certificates', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->foreignId('participant_id')->constrained('participants')->cascadeOnDelete();
$table->foreignId('certificate_template_id')->nullable()->constrained('certificate_templates')->nullOnDelete();
$table->string('certificate_no', 100)->unique()->nullable();
$table->string('file_path', 500)->nullable();
$table->string('token', 64)->unique();
$table->enum('status', ['pending', 'generating', 'generated', 'emailed', 'failed'])->default('pending');
$table->text('error_message')->nullable();
$table->timestamp('generated_at')->nullable();
$table->timestamp('emailed_at')->nullable();
$table->timestamp('downloaded_at')->nullable();
$table->unsignedInteger('download_count')->default(0);
$table->timestamps();
$table->unique(['program_id', 'participant_id']);
$table->index('token');
$table->index('status');
$table->index('program_id');
$table->index('participant_id');
});
}
public function down(): void
{
Schema::dropIfExists('certificates');
}
};

View File

@@ -0,0 +1,31 @@
<?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::create('questionnaire_responses', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->constrained('programs')->cascadeOnDelete();
$table->foreignId('participant_id')->constrained('participants')->cascadeOnDelete();
$table->foreignId('questionnaire_set_id')->constrained('questionnaire_sets');
$table->timestamp('submitted_at');
$table->string('ip_address', 45)->nullable();
$table->string('user_agent', 500)->nullable();
$table->timestamps();
$table->unique(['program_id', 'participant_id', 'questionnaire_set_id'], 'unique_program_participant_questionnaire');
$table->index('program_id');
$table->index('participant_id');
});
}
public function down(): void
{
Schema::dropIfExists('questionnaire_responses');
}
};

View File

@@ -0,0 +1,27 @@
<?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::create('questionnaire_answers', function (Blueprint $table) {
$table->id();
$table->foreignId('questionnaire_response_id')->constrained('questionnaire_responses')->cascadeOnDelete();
$table->foreignId('questionnaire_question_id')->constrained('questionnaire_questions')->cascadeOnDelete();
$table->json('answer_value')->nullable();
$table->timestamps();
$table->index('questionnaire_response_id');
$table->index('questionnaire_question_id');
});
}
public function down(): void
{
Schema::dropIfExists('questionnaire_answers');
}
};

View File

@@ -0,0 +1,34 @@
<?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::create('email_logs', function (Blueprint $table) {
$table->id();
$table->foreignId('program_id')->nullable()->constrained('programs')->nullOnDelete();
$table->foreignId('participant_id')->nullable()->constrained('participants')->nullOnDelete();
$table->foreignId('certificate_id')->nullable()->constrained('certificates')->nullOnDelete();
$table->string('recipient_email', 255);
$table->string('subject', 500);
$table->enum('email_type', ['certificate_ready', 'reminder', 'test'])->default('certificate_ready');
$table->enum('status', ['pending', 'sent', 'failed'])->default('pending');
$table->text('error_message')->nullable();
$table->timestamp('sent_at')->nullable();
$table->timestamps();
$table->index('status');
$table->index('program_id');
$table->index('participant_id');
});
}
public function down(): void
{
Schema::dropIfExists('email_logs');
}
};

Some files were not shown because too many files have changed in this diff Show More