Spaces:
Sleeping
Sleeping
Araihan413 commited on
Commit ·
b213d9c
0
Parent(s):
deploy: copy entire /app workspace to preserve pnpm symlinks
Browse files- .gitignore +57 -0
- Dockerfile +46 -0
- README.md +190 -0
- apps/api/package.json +31 -0
- apps/api/src/index.ts +85 -0
- apps/api/src/routes/auth.ts +90 -0
- apps/api/src/routes/questionSets.ts +185 -0
- apps/api/src/routes/questions.ts +129 -0
- apps/api/src/routes/rooms.ts +86 -0
- apps/api/src/socket/gameManager.ts +873 -0
- apps/api/src/supabaseAuth.ts +68 -0
- apps/api/tsconfig.json +12 -0
- package.json +14 -0
- packages/db/index.ts +13 -0
- packages/db/package.json +23 -0
- packages/db/prisma/presets/pai-kelas-10-genap.json +736 -0
- packages/db/prisma/schema.prisma +134 -0
- packages/db/prisma/seed.ts +68 -0
- packages/db/tsconfig.json +19 -0
- packages/types/package.json +13 -0
- packages/types/src/index.ts +46 -0
- pnpm-lock.yaml +0 -0
- pnpm-workspace.yaml +6 -0
- turbo.json +16 -0
.gitignore
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
| 2 |
+
|
| 3 |
+
# dependencies
|
| 4 |
+
node_modules
|
| 5 |
+
.pnp
|
| 6 |
+
.pnp.*
|
| 7 |
+
.yarn/*
|
| 8 |
+
!.yarn/patches
|
| 9 |
+
!.yarn/plugins
|
| 10 |
+
!.yarn/releases
|
| 11 |
+
!.yarn/versions
|
| 12 |
+
|
| 13 |
+
# testing
|
| 14 |
+
coverage
|
| 15 |
+
|
| 16 |
+
# next.js
|
| 17 |
+
.next/
|
| 18 |
+
out/
|
| 19 |
+
|
| 20 |
+
# production
|
| 21 |
+
/build
|
| 22 |
+
|
| 23 |
+
# misc
|
| 24 |
+
.DS_Store
|
| 25 |
+
*.pem
|
| 26 |
+
|
| 27 |
+
# debug
|
| 28 |
+
npm-debug.log*
|
| 29 |
+
yarn-debug.log*
|
| 30 |
+
yarn-error.log*
|
| 31 |
+
.pnpm-debug.log*
|
| 32 |
+
|
| 33 |
+
# env files (can opt-in for committing if needed)
|
| 34 |
+
.env*
|
| 35 |
+
|
| 36 |
+
# vercel
|
| 37 |
+
.vercel
|
| 38 |
+
|
| 39 |
+
# typescript
|
| 40 |
+
*.tsbuildinfo
|
| 41 |
+
next-env.d.ts
|
| 42 |
+
|
| 43 |
+
# ai agent
|
| 44 |
+
.gemini/
|
| 45 |
+
.agents/
|
| 46 |
+
.claude/
|
| 47 |
+
.qwen/
|
| 48 |
+
.windsurf/
|
| 49 |
+
PRD.md
|
| 50 |
+
AGENTS.md
|
| 51 |
+
CLAUDE.md
|
| 52 |
+
|
| 53 |
+
# local workspace/cache
|
| 54 |
+
.vscode/
|
| 55 |
+
.turbo/
|
| 56 |
+
dist/
|
| 57 |
+
|
Dockerfile
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ─── Base Stage ────────────────────────────────────────────────────────────────
|
| 2 |
+
FROM node:22-alpine AS base
|
| 3 |
+
ENV PNPM_HOME="/pnpm"
|
| 4 |
+
ENV PATH="$PNPM_HOME:$PNPM_HOME/bin:$PATH"
|
| 5 |
+
RUN corepack enable
|
| 6 |
+
RUN apk add --no-cache libc6-compat openssl
|
| 7 |
+
WORKDIR /app
|
| 8 |
+
|
| 9 |
+
# ─── Prune Stage (Turborepo Pruner) ───────────────────────────────────────────
|
| 10 |
+
FROM base AS pruner
|
| 11 |
+
RUN pnpm add -g turbo
|
| 12 |
+
COPY . .
|
| 13 |
+
# Isolasi paket api dan dependensinya (termasuk @repo/db, @repo/types)
|
| 14 |
+
RUN turbo prune api --docker --out-dir=out
|
| 15 |
+
|
| 16 |
+
# ─── Installer Stage (Install dependencies) ───────────────────────────────────
|
| 17 |
+
FROM base AS installer
|
| 18 |
+
# Salin package.json dan lockfile yang sudah di-prune untuk pnpm caching
|
| 19 |
+
COPY --from=pruner /app/out/json/ .
|
| 20 |
+
RUN pnpm install --frozen-lockfile
|
| 21 |
+
|
| 22 |
+
# ─── Builder Stage (Build source code) ────────────────────────────────────────
|
| 23 |
+
FROM base AS builder
|
| 24 |
+
# Salin node_modules hasil instalasi
|
| 25 |
+
COPY --from=installer /app/ .
|
| 26 |
+
# Salin source code yang sudah di-prune
|
| 27 |
+
COPY --from=pruner /app/out/full/ .
|
| 28 |
+
|
| 29 |
+
# Generate Prisma Client sebelum mem-build (penting untuk type safety dan Prisma import)
|
| 30 |
+
RUN pnpm --filter @repo/db db:generate
|
| 31 |
+
|
| 32 |
+
# Build Fastify backend
|
| 33 |
+
RUN pnpm --filter api build
|
| 34 |
+
|
| 35 |
+
# ─── Runner Stage (Production server) ─────────────────────────────────────────
|
| 36 |
+
FROM base AS runner
|
| 37 |
+
ENV NODE_ENV=production
|
| 38 |
+
ENV PORT=7860
|
| 39 |
+
|
| 40 |
+
# Salin seluruh workspace terkompilasi dari builder stage agar seluruh symlink pnpm tetap utuh
|
| 41 |
+
COPY --from=builder /app /app
|
| 42 |
+
|
| 43 |
+
EXPOSE 7860
|
| 44 |
+
|
| 45 |
+
# Jalankan backend API Fastify
|
| 46 |
+
CMD ["pnpm", "--filter", "api", "start"]
|
README.md
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: EduBoard API
|
| 3 |
+
emoji: 🎓
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# EduBoard PAI
|
| 12 |
+
|
| 13 |
+
EduBoard PAI adalah aplikasi **web game digital edukatif** yang mengadaptasi mekanisme board game (papan permainan, giliran, kartu soal, tantangan, skor) ke dalam format digital. Produk ini dirancang khusus untuk mendukung pembelajaran Pendidikan Agama Islam (PAI) untuk jenjang SMA.
|
| 14 |
+
|
| 15 |
+
Proyek ini dibangun menggunakan arsitektur **Monorepo (Turborepo)** dengan pemisahan antara frontend (Next.js) dan backend (Fastify + Socket.io), serta menggunakan Supabase sebagai layanan database.
|
| 16 |
+
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
## 🎯 Fitur Utama
|
| 20 |
+
|
| 21 |
+
- **Mode Guru & Siswa**: Guru dapat membuat ruang permainan (room), mengelola soal, memantau permainan, dan menilai jawaban secara real-time. Siswa dapat langsung bermain tanpa harus membuat akun.
|
| 22 |
+
- **Papan Permainan Real-time**: Papan permainan interaktif yang tersinkronisasi antar semua perangkat dalam room yang sama.
|
| 23 |
+
- **Kartu Pertanyaan**: Tiga tipe soal—Dasar (objektif), Tantangan (subjektif/lisan), dan Pemahaman (subjektif/tertulis).
|
| 24 |
+
- **Penilaian Langsung**: Guru dapat langsung memberi nilai (0-100) untuk pertanyaan tipe subjektif saat permainan berlangsung.
|
| 25 |
+
- **Bank Soal Terpusat**: Pengelolaan soal yang mudah melalui dashboard guru.
|
| 26 |
+
|
| 27 |
+
## 🛠️ Stack Teknologi
|
| 28 |
+
|
| 29 |
+
- **Monorepo**: Turborepo
|
| 30 |
+
- **Frontend (`apps/web`)**: Next.js 16+ (App Router), Tailwind CSS v4, Zustand, React Three Fiber (@react-three/drei), Framer Motion, Supabase Auth
|
| 31 |
+
- **Backend (`apps/api`)**: Fastify v4, Socket.io v4 (Real-time Engine), Zod
|
| 32 |
+
- **Database & ORM (`packages/db`)**: PostgreSQL 16+ (Supabase), Prisma v5
|
| 33 |
+
- **Package Manager**: pnpm
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## 📋 Syarat Sistem (Prerequisites)
|
| 38 |
+
|
| 39 |
+
Sebelum menjalankan proyek ini, pastikan Anda telah menginstal perangkat lunak berikut:
|
| 40 |
+
|
| 41 |
+
1. [Node.js](https://nodejs.org/en/) (v18.x atau lebih baru disarankan)
|
| 42 |
+
2. [pnpm](https://pnpm.io/installation) (v9.5.0 atau lebih baru) — *Ini adalah package manager utama yang digunakan di proyek ini.*
|
| 43 |
+
3. [Git](https://git-scm.com/)
|
| 44 |
+
4. Akun [Supabase](https://supabase.com/) (untuk pengaturan database secara cloud)
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
## 🚀 Cara Setup dan Menjalankan Proyek
|
| 49 |
+
|
| 50 |
+
### 1. Clone Repository
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
git clone git@github.com:Araihan413/EduBoard.git
|
| 54 |
+
cd EduBoard
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### 2. Install Dependensi
|
| 58 |
+
|
| 59 |
+
Gunakan `pnpm` untuk menginstal semua dependensi di seluruh workspace monorepo.
|
| 60 |
+
|
| 61 |
+
```bash
|
| 62 |
+
pnpm install
|
| 63 |
+
```
|
| 64 |
+
|
| 65 |
+
### 3. Konfigurasi Environment Variables
|
| 66 |
+
|
| 67 |
+
Karena proyek ini menggunakan struktur monorepo, Anda perlu menyiapkan beberapa file `.env` di lokasi yang berbeda. Silakan buat file-file berikut:
|
| 68 |
+
|
| 69 |
+
#### A. Root Directory (`/.env`)
|
| 70 |
+
Digunakan untuk konfigurasi global dan perintah Prisma dari root.
|
| 71 |
+
```env
|
| 72 |
+
DATABASE_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 73 |
+
DIRECT_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 74 |
+
NEXT_PUBLIC_SUPABASE_URL="https://[PROYEK].supabase.co"
|
| 75 |
+
NEXT_PUBLIC_SUPABASE_ANON_KEY="eyJhbGci..."
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
#### B. Frontend (`/apps/web/.env.local`)
|
| 79 |
+
Digunakan oleh Next.js untuk autentikasi, koneksi REST API, dan WebSocket.
|
| 80 |
+
```env
|
| 81 |
+
NEXT_PUBLIC_SUPABASE_URL="https://[PROYEK].supabase.co"
|
| 82 |
+
NEXT_PUBLIC_SUPABASE_ANON_KEY="eyJhbGci..."
|
| 83 |
+
NEXT_PUBLIC_API_URL="http://localhost:4000"
|
| 84 |
+
NEXT_PUBLIC_WS_URL="http://localhost:4000"
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
#### C. Backend (`/apps/api/.env`)
|
| 89 |
+
Digunakan oleh Fastify untuk koneksi database, keamanan JWT, dan konfigurasi CORS.
|
| 90 |
+
```env
|
| 91 |
+
DATABASE_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 92 |
+
DIRECT_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 93 |
+
NEXT_PUBLIC_SUPABASE_URL="https://[PROYEK].supabase.co"
|
| 94 |
+
NEXT_PUBLIC_SUPABASE_ANON_KEY="eyJhbGci..."
|
| 95 |
+
JWT_SECRET="string-acak-panjang-minimal-32-karakter"
|
| 96 |
+
PORT=4000
|
| 97 |
+
# Produksi: isi URL frontend. Kosongkan untuk dev (default localhost:3000)
|
| 98 |
+
CORS_ORIGIN=
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
#### D. Database Package (`/packages/db/.env`)
|
| 102 |
+
Wajib ada jika Anda ingin menjalankan perintah Prisma langsung di dalam folder `packages/db`.
|
| 103 |
+
```env
|
| 104 |
+
DATABASE_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 105 |
+
DIRECT_URL="postgresql://postgres.[PROYEK]:[PASSWORD]@..."
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
### 4. Konfigurasi Supabase & Google Auth
|
| 109 |
+
|
| 110 |
+
Aplikasi ini menggunakan **Google OAuth** untuk autentikasi Guru. Berikut langkah-langkah pengaturannya:
|
| 111 |
+
|
| 112 |
+
#### A. Google Cloud Console
|
| 113 |
+
1. Buka [Google Cloud Console](https://console.cloud.google.com/).
|
| 114 |
+
2. Buat proyek baru atau pilih proyek yang sudah ada.
|
| 115 |
+
3. Buka **APIs & Services > OAuth consent screen**. Pilih User Type **External**, lalu isi informasi aplikasi.
|
| 116 |
+
4. Buka **APIs & Services > Credentials**. Klik **Create Credentials > OAuth client ID**.
|
| 117 |
+
5. Pilih Application Type **Web application**.
|
| 118 |
+
6. Pada bagian **Authorized redirect URIs**, masukkan URL callback dari Supabase Anda (bisa didapatkan di langkah B.3 di bawah). Formatnya biasanya: `https://[PROYEK-ANDA].supabase.co/auth/v1/callback`.
|
| 119 |
+
7. Simpan, lalu catat **Client ID** dan **Client Secret**.
|
| 120 |
+
|
| 121 |
+
#### B. Dashboard Supabase
|
| 122 |
+
1. Buka dashboard proyek [Supabase](https://supabase.com/) Anda.
|
| 123 |
+
2. Pergi ke menu **Authentication > Providers > Google**.
|
| 124 |
+
3. Aktifkan (Enable) Google Provider.
|
| 125 |
+
4. Masukkan **Client ID** dan **Client Secret** yang Anda dapatkan dari Google Cloud Console tadi.
|
| 126 |
+
5. Pada menu **Authentication > URL Configuration**:
|
| 127 |
+
- **Site URL**: `http://localhost:3000` (untuk dev) atau domain produksi Anda.
|
| 128 |
+
- **Redirect URLs**: Tambahkan `http://localhost:3000/**` agar redirect setelah login berjalan lancar di lokal.
|
| 129 |
+
|
| 130 |
+
### 5. Setup Database (Prisma)
|
| 131 |
+
|
| 132 |
+
Karena skema database berada di dalam package tersendiri, Anda dapat menjalankan perintah Prisma melalui `pnpm` dari root atau masuk ke foldernya langsung:
|
| 133 |
+
|
| 134 |
+
```bash
|
| 135 |
+
# Opsi 1: Dari root menggunakan pnpm filter (Direkomendasikan)
|
| 136 |
+
pnpm --filter @repo/db db:push
|
| 137 |
+
pnpm --filter @repo/db db:generate
|
| 138 |
+
|
| 139 |
+
# Opsi 2: Masuk ke direktori package secara manual
|
| 140 |
+
cd packages/db
|
| 141 |
+
npx prisma db push
|
| 142 |
+
npx prisma generate
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
> [!IMPORTANT]
|
| 146 |
+
> Pastikan Anda menjalankan `db:generate` setidaknya sekali sebelum menjalankan server agar TypeScript dapat mengenali skema database terbaru.
|
| 147 |
+
|
| 148 |
+
### 6. Import Data Preset (Seeding)
|
| 149 |
+
|
| 150 |
+
Aplikasi ini dilengkapi dengan data soal preset (PAI Kelas X s.d XII). Untuk memasukkannya ke database, jalankan perintah berikut:
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
# Opsi 1: Dari root menggunakan pnpm filter (Direkomendasikan)
|
| 154 |
+
pnpm --filter @repo/db db:seed
|
| 155 |
+
|
| 156 |
+
# Opsi 2: Masuk ke direktori package secara manual
|
| 157 |
+
cd packages/db
|
| 158 |
+
npx prisma db seed
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
Proses ini akan membersihkan data lama dan memasukkan data soal baru dari folder `packages/db/prisma/presets` ke database Anda.
|
| 162 |
+
|
| 163 |
+
### 7. Jalankan Development Server
|
| 164 |
+
|
| 165 |
+
Jalankan semua aplikasi (frontend dan backend) secara serentak menggunakan Turborepo:
|
| 166 |
+
|
| 167 |
+
```bash
|
| 168 |
+
pnpm run dev
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
Secara default:
|
| 172 |
+
- **Frontend (Next.js)** akan berjalan di `http://localhost:3000`
|
| 173 |
+
- **Backend (Fastify/Socket.io)** akan berjalan di `http://localhost:4000`
|
| 174 |
+
|
| 175 |
+
---
|
| 176 |
+
|
| 177 |
+
## 📁 Struktur Proyek (Monorepo)
|
| 178 |
+
|
| 179 |
+
```text
|
| 180 |
+
eduboard-pai/ ← root (Turborepo)
|
| 181 |
+
├── apps/
|
| 182 |
+
│ ├── web/ ← Frontend (Next.js)
|
| 183 |
+
│ └── api/ ← Backend (Fastify + Socket.io)
|
| 184 |
+
├── packages/
|
| 185 |
+
│ ├── db/ ← Prisma schema & client
|
| 186 |
+
│ ├── types/ ← Shared TypeScript types & Zod schemas
|
| 187 |
+
│ └── config/ ← Shared configs (ESLint, Prettier, tsconfig)
|
| 188 |
+
└── package.json
|
| 189 |
+
```
|
| 190 |
+
|
apps/api/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "api",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "tsx watch src/index.ts",
|
| 7 |
+
"build": "tsc",
|
| 8 |
+
"start": "node dist/index.js",
|
| 9 |
+
"lint": "eslint src/"
|
| 10 |
+
},
|
| 11 |
+
"dependencies": {
|
| 12 |
+
"@fastify/cookie": "^9.3.1",
|
| 13 |
+
"@fastify/cors": "^8.5.0",
|
| 14 |
+
"@fastify/jwt": "^8.0.0",
|
| 15 |
+
"@repo/db": "workspace:*",
|
| 16 |
+
"@repo/types": "workspace:*",
|
| 17 |
+
"@supabase/supabase-js": "^2.104.1",
|
| 18 |
+
"bcryptjs": "^2.4.3",
|
| 19 |
+
"dotenv": "^17.4.2",
|
| 20 |
+
"fastify": "^4.26.2",
|
| 21 |
+
"fastify-type-provider-zod": "^1.1.9",
|
| 22 |
+
"socket.io": "^4.7.5",
|
| 23 |
+
"zod": "^3.23.4"
|
| 24 |
+
},
|
| 25 |
+
"devDependencies": {
|
| 26 |
+
"@types/bcryptjs": "^2.4.6",
|
| 27 |
+
"@types/node": "^20.12.7",
|
| 28 |
+
"tsx": "^4.7.2",
|
| 29 |
+
"typescript": "^5.4.5"
|
| 30 |
+
}
|
| 31 |
+
}
|
apps/api/src/index.ts
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import Fastify from "fastify";
|
| 2 |
+
import cors from "@fastify/cors";
|
| 3 |
+
import { Server } from "socket.io";
|
| 4 |
+
import { prisma } from "@repo/db";
|
| 5 |
+
import * as dotenv from "dotenv";
|
| 6 |
+
import * as path from "path";
|
| 7 |
+
|
| 8 |
+
import fastifyJwt from "@fastify/jwt";
|
| 9 |
+
import authRoutes from "./routes/auth";
|
| 10 |
+
import questionRoutes from "./routes/questions";
|
| 11 |
+
import roomRoutes from "./routes/rooms";
|
| 12 |
+
import { questionSetRoutes } from "./routes/questionSets";
|
| 13 |
+
import { handleSocketEvents } from "./socket/gameManager";
|
| 14 |
+
|
| 15 |
+
// ─── Load Environment Variables ───────────────────────────────────────────────
|
| 16 |
+
// Priority: apps/api/.env → root .env (fallback for local dev)
|
| 17 |
+
dotenv.config({ path: path.resolve(__dirname, "../.env") });
|
| 18 |
+
dotenv.config({ path: path.resolve(__dirname, "../../../.env") });
|
| 19 |
+
|
| 20 |
+
// ─── Validate Required Environment Variables ──────────────────────────────────
|
| 21 |
+
const jwtSecret = process.env.JWT_SECRET;
|
| 22 |
+
if (!jwtSecret) {
|
| 23 |
+
console.error(
|
| 24 |
+
"[FATAL] JWT_SECRET environment variable is not set. " +
|
| 25 |
+
"Generate one with: openssl rand -base64 32"
|
| 26 |
+
);
|
| 27 |
+
process.exit(1);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
const port = parseInt(process.env.PORT || "4000", 10);
|
| 31 |
+
|
| 32 |
+
// CORS_ORIGIN: comma-separated list of allowed origins for production.
|
| 33 |
+
// Example: "https://eduboard.vercel.app,https://www.eduboard.com"
|
| 34 |
+
// In development, defaults to localhost:3000.
|
| 35 |
+
const corsOrigins: string | string[] | boolean = process.env.CORS_ORIGIN
|
| 36 |
+
? process.env.CORS_ORIGIN.split(",").map((o) => o.trim())
|
| 37 |
+
: "http://localhost:3000";
|
| 38 |
+
|
| 39 |
+
// ─── Fastify Instance ─────────────────────────────────────────────────────────
|
| 40 |
+
const fastify = Fastify({ logger: true });
|
| 41 |
+
|
| 42 |
+
// Register Plugins
|
| 43 |
+
fastify.register(cors, {
|
| 44 |
+
origin: true,
|
| 45 |
+
credentials: true,
|
| 46 |
+
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
|
| 47 |
+
});
|
| 48 |
+
|
| 49 |
+
fastify.register(fastifyJwt, {
|
| 50 |
+
secret: jwtSecret,
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
fastify.get("/health", async () => {
|
| 54 |
+
return { status: "ok" };
|
| 55 |
+
});
|
| 56 |
+
|
| 57 |
+
fastify.register(authRoutes, { prefix: "/api/auth" });
|
| 58 |
+
fastify.register(questionRoutes, { prefix: "/api/questions" });
|
| 59 |
+
fastify.register(roomRoutes, { prefix: "/api/rooms" });
|
| 60 |
+
fastify.register(questionSetRoutes, { prefix: "/api/sets" });
|
| 61 |
+
|
| 62 |
+
const start = async () => {
|
| 63 |
+
try {
|
| 64 |
+
await fastify.listen({ port, host: "0.0.0.0" });
|
| 65 |
+
|
| 66 |
+
// Initialize Socket.io attached to Fastify's raw server
|
| 67 |
+
const io = new Server(fastify.server, {
|
| 68 |
+
cors: {
|
| 69 |
+
origin: corsOrigins,
|
| 70 |
+
methods: ["GET", "POST"],
|
| 71 |
+
},
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
io.on("connection", (socket) => {
|
| 75 |
+
handleSocketEvents(io, socket);
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
console.log(`Server and Socket.io started on port ${port}`);
|
| 79 |
+
} catch (err) {
|
| 80 |
+
fastify.log.error(err);
|
| 81 |
+
process.exit(1);
|
| 82 |
+
}
|
| 83 |
+
};
|
| 84 |
+
|
| 85 |
+
start();
|
apps/api/src/routes/auth.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { FastifyInstance } from "fastify";
|
| 2 |
+
import { z } from "zod";
|
| 3 |
+
import bcrypt from "bcryptjs";
|
| 4 |
+
import { prisma } from "@repo/db";
|
| 5 |
+
|
| 6 |
+
const LoginSchema = z.object({
|
| 7 |
+
email: z.string().email("Format email tidak valid"),
|
| 8 |
+
password: z.string().min(6, "Password minimal 6 karakter"),
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
const RegisterSchema = z.object({
|
| 12 |
+
email: z.string().email("Format email tidak valid"),
|
| 13 |
+
password: z.string().min(6, "Password minimal 6 karakter"),
|
| 14 |
+
name: z.string().min(2, "Nama minimal 2 karakter").max(50, "Nama terlalu panjang"),
|
| 15 |
+
});
|
| 16 |
+
|
| 17 |
+
export default async function authRoutes(fastify: FastifyInstance) {
|
| 18 |
+
// LOGIN
|
| 19 |
+
fastify.post("/login", async (request, reply) => {
|
| 20 |
+
try {
|
| 21 |
+
const { email, password } = LoginSchema.parse(request.body);
|
| 22 |
+
|
| 23 |
+
const user = await prisma.user.findUnique({ where: { email } });
|
| 24 |
+
if (!user) {
|
| 25 |
+
return reply.code(401).send({ error: "Email atau password salah" });
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
const match = await bcrypt.compare(password, user.passwordHash);
|
| 29 |
+
if (!match) {
|
| 30 |
+
return reply.code(401).send({ error: "Email atau password salah" });
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
const token = fastify.jwt.sign({ id: user.id, email: user.email });
|
| 34 |
+
|
| 35 |
+
return {
|
| 36 |
+
token,
|
| 37 |
+
user: {
|
| 38 |
+
id: user.id,
|
| 39 |
+
name: user.name,
|
| 40 |
+
email: user.email
|
| 41 |
+
}
|
| 42 |
+
};
|
| 43 |
+
} catch (err) {
|
| 44 |
+
if (err instanceof z.ZodError) {
|
| 45 |
+
return reply.code(400).send({ error: err.errors[0].message });
|
| 46 |
+
}
|
| 47 |
+
return reply.code(500).send({ error: "Terjadi kesalahan pada server" });
|
| 48 |
+
}
|
| 49 |
+
});
|
| 50 |
+
|
| 51 |
+
// REGISTER
|
| 52 |
+
fastify.post("/register", async (request, reply) => {
|
| 53 |
+
try {
|
| 54 |
+
const { email, password, name } = RegisterSchema.parse(request.body);
|
| 55 |
+
|
| 56 |
+
// Check if user exists
|
| 57 |
+
const existing = await prisma.user.findUnique({ where: { email } });
|
| 58 |
+
if (existing) {
|
| 59 |
+
return reply.code(400).send({ error: "Email sudah terdaftar" });
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
const passwordHash = await bcrypt.hash(password, 10);
|
| 63 |
+
const user = await prisma.user.create({
|
| 64 |
+
data: {
|
| 65 |
+
email,
|
| 66 |
+
passwordHash,
|
| 67 |
+
name
|
| 68 |
+
}
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
const token = fastify.jwt.sign({ id: user.id, email: user.email });
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
success: true,
|
| 75 |
+
token,
|
| 76 |
+
user: {
|
| 77 |
+
id: user.id,
|
| 78 |
+
name: user.name,
|
| 79 |
+
email: user.email
|
| 80 |
+
}
|
| 81 |
+
};
|
| 82 |
+
} catch (err) {
|
| 83 |
+
if (err instanceof z.ZodError) {
|
| 84 |
+
return reply.code(400).send({ error: err.errors[0].message });
|
| 85 |
+
}
|
| 86 |
+
console.error(err);
|
| 87 |
+
return reply.code(500).send({ error: "Gagal mendaftarkan akun" });
|
| 88 |
+
}
|
| 89 |
+
});
|
| 90 |
+
}
|
apps/api/src/routes/questionSets.ts
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { FastifyInstance } from "fastify";
|
| 2 |
+
import { prisma } from "@repo/db";
|
| 3 |
+
import { QuestionSchema } from "@repo/types";
|
| 4 |
+
import { verifySupabaseAuth } from "../supabaseAuth";
|
| 5 |
+
import { z } from "zod";
|
| 6 |
+
|
| 7 |
+
export async function questionSetRoutes(fastify: FastifyInstance) {
|
| 8 |
+
fastify.addHook("preHandler", verifySupabaseAuth);
|
| 9 |
+
|
| 10 |
+
// Get all question sets for the current teacher + presets
|
| 11 |
+
fastify.get("/", async (request, reply) => {
|
| 12 |
+
const userId = (request.user as any).id;
|
| 13 |
+
const { page = "1", limit = "12" } = request.query as { page?: string, limit?: string };
|
| 14 |
+
|
| 15 |
+
const p = parseInt(page);
|
| 16 |
+
const l = parseInt(limit);
|
| 17 |
+
const skip = (p - 1) * l;
|
| 18 |
+
|
| 19 |
+
const where = {
|
| 20 |
+
OR: [
|
| 21 |
+
{ guruId: userId },
|
| 22 |
+
{ isPreset: true }
|
| 23 |
+
]
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
const [sets, total] = await Promise.all([
|
| 27 |
+
prisma.questionSet.findMany({
|
| 28 |
+
where,
|
| 29 |
+
include: {
|
| 30 |
+
_count: {
|
| 31 |
+
select: { questions: true }
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
orderBy: { createdAt: 'desc' },
|
| 35 |
+
skip,
|
| 36 |
+
take: l
|
| 37 |
+
}),
|
| 38 |
+
prisma.questionSet.count({ where })
|
| 39 |
+
]);
|
| 40 |
+
|
| 41 |
+
return {
|
| 42 |
+
data: sets,
|
| 43 |
+
meta: {
|
| 44 |
+
total,
|
| 45 |
+
page: p,
|
| 46 |
+
limit: l,
|
| 47 |
+
totalPages: Math.ceil(total / l)
|
| 48 |
+
}
|
| 49 |
+
};
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
// Create a new question set
|
| 53 |
+
fastify.post("/", async (request, reply) => {
|
| 54 |
+
const userId = (request.user as any).id;
|
| 55 |
+
const { title, description } = request.body as any;
|
| 56 |
+
|
| 57 |
+
const set = await prisma.questionSet.create({
|
| 58 |
+
data: {
|
| 59 |
+
title,
|
| 60 |
+
description,
|
| 61 |
+
guruId: userId
|
| 62 |
+
}
|
| 63 |
+
});
|
| 64 |
+
return set;
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
// Get a specific set with its questions
|
| 68 |
+
fastify.get("/:id", async (request, reply) => {
|
| 69 |
+
const { id } = request.params as any;
|
| 70 |
+
const userId = (request.user as any).id;
|
| 71 |
+
|
| 72 |
+
const set = await prisma.questionSet.findFirst({
|
| 73 |
+
where: {
|
| 74 |
+
id,
|
| 75 |
+
OR: [
|
| 76 |
+
{ guruId: userId },
|
| 77 |
+
{ isPreset: true }
|
| 78 |
+
]
|
| 79 |
+
},
|
| 80 |
+
include: {
|
| 81 |
+
questions: true
|
| 82 |
+
}
|
| 83 |
+
});
|
| 84 |
+
|
| 85 |
+
if (!set) return reply.status(404).send({ message: "Paket soal tidak ditemukan" });
|
| 86 |
+
return set;
|
| 87 |
+
});
|
| 88 |
+
|
| 89 |
+
// Duplicate a preset into teacher's collection
|
| 90 |
+
fastify.post("/:id/duplicate", async (request, reply) => {
|
| 91 |
+
const { id } = request.params as any;
|
| 92 |
+
const userId = (request.user as any).id;
|
| 93 |
+
|
| 94 |
+
const sourceSet = await prisma.questionSet.findUnique({
|
| 95 |
+
where: { id },
|
| 96 |
+
include: { questions: true }
|
| 97 |
+
});
|
| 98 |
+
|
| 99 |
+
if (!sourceSet) return reply.status(404).send({ message: "Sumber paket tidak ditemukan" });
|
| 100 |
+
|
| 101 |
+
const newSet = await prisma.questionSet.create({
|
| 102 |
+
data: {
|
| 103 |
+
title: `${sourceSet.title} (Salinan)`,
|
| 104 |
+
description: sourceSet.description,
|
| 105 |
+
guruId: userId,
|
| 106 |
+
questions: {
|
| 107 |
+
create: sourceSet.questions.map(q => ({
|
| 108 |
+
type: q.type,
|
| 109 |
+
text: q.text,
|
| 110 |
+
options: q.options || undefined,
|
| 111 |
+
answerKey: q.answerKey,
|
| 112 |
+
points: q.points
|
| 113 |
+
}))
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
include: { questions: true }
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
return newSet;
|
| 120 |
+
});
|
| 121 |
+
|
| 122 |
+
// Delete a set
|
| 123 |
+
fastify.delete("/:id", async (request, reply) => {
|
| 124 |
+
const { id } = request.params as any;
|
| 125 |
+
const userId = (request.user as any).id;
|
| 126 |
+
|
| 127 |
+
const set = await prisma.questionSet.findFirst({
|
| 128 |
+
where: { id, guruId: userId }
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
if (!set) return reply.status(404).send({ message: "Paket tidak ditemukan atau Anda tidak memiliki akses" });
|
| 132 |
+
|
| 133 |
+
await prisma.questionSet.delete({ where: { id } });
|
| 134 |
+
return { success: true };
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
// Update a question set
|
| 138 |
+
fastify.put("/:id", async (request, reply) => {
|
| 139 |
+
const { id } = request.params as any;
|
| 140 |
+
const { title, description } = request.body as any;
|
| 141 |
+
const userId = (request.user as any).id;
|
| 142 |
+
|
| 143 |
+
const updated = await prisma.questionSet.update({
|
| 144 |
+
where: { id, guruId: userId },
|
| 145 |
+
data: { title, description }
|
| 146 |
+
});
|
| 147 |
+
|
| 148 |
+
return updated;
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
// Import questions to a set
|
| 152 |
+
fastify.post("/:id/import", async (request, reply) => {
|
| 153 |
+
const { id } = request.params as any;
|
| 154 |
+
const { questions } = request.body as any;
|
| 155 |
+
const userId = (request.user as any).id;
|
| 156 |
+
|
| 157 |
+
if (!Array.isArray(questions)) {
|
| 158 |
+
return reply.status(400).send({ error: "Invalid questions data" });
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
const set = await prisma.questionSet.findFirst({
|
| 162 |
+
where: { id, guruId: userId }
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
if (!set) return reply.status(404).send({ error: "Set not found" });
|
| 166 |
+
|
| 167 |
+
try {
|
| 168 |
+
const validatedQuestions = questions.map((q: any) => QuestionSchema.parse(q));
|
| 169 |
+
|
| 170 |
+
const created = await prisma.question.createMany({
|
| 171 |
+
data: validatedQuestions.map((q: any) => ({
|
| 172 |
+
...q,
|
| 173 |
+
setId: id
|
| 174 |
+
}))
|
| 175 |
+
});
|
| 176 |
+
|
| 177 |
+
return { success: true, count: created.count };
|
| 178 |
+
} catch (err) {
|
| 179 |
+
if (err instanceof z.ZodError) {
|
| 180 |
+
return reply.status(400).send({ error: "Beberapa soal tidak valid", details: err.errors });
|
| 181 |
+
}
|
| 182 |
+
return reply.status(500).send({ error: "Gagal mengimport soal" });
|
| 183 |
+
}
|
| 184 |
+
});
|
| 185 |
+
}
|
apps/api/src/routes/questions.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { FastifyInstance } from "fastify";
|
| 2 |
+
import { z } from "zod";
|
| 3 |
+
import { prisma, QuestionType } from "@repo/db";
|
| 4 |
+
import { QuestionSchema } from "@repo/types";
|
| 5 |
+
import { verifySupabaseAuth } from "../supabaseAuth";
|
| 6 |
+
|
| 7 |
+
export default async function questionRoutes(fastify: FastifyInstance) {
|
| 8 |
+
// GET Questions for a specific Set (PUBLIC for Students)
|
| 9 |
+
fastify.get("/", async (request, reply) => {
|
| 10 |
+
const { setId, page = "1", limit = "50" } = request.query as { setId: string, page?: string, limit?: string };
|
| 11 |
+
if (!setId) return reply.code(400).send({ error: "setId wajib disertakan" });
|
| 12 |
+
|
| 13 |
+
const p = parseInt(page);
|
| 14 |
+
const l = parseInt(limit);
|
| 15 |
+
const skip = (p - 1) * l;
|
| 16 |
+
|
| 17 |
+
const [questions, total] = await Promise.all([
|
| 18 |
+
prisma.question.findMany({
|
| 19 |
+
where: { setId },
|
| 20 |
+
orderBy: { createdAt: 'desc' },
|
| 21 |
+
skip,
|
| 22 |
+
take: l
|
| 23 |
+
}),
|
| 24 |
+
prisma.question.count({ where: { setId } })
|
| 25 |
+
]);
|
| 26 |
+
|
| 27 |
+
return {
|
| 28 |
+
data: questions,
|
| 29 |
+
meta: {
|
| 30 |
+
total,
|
| 31 |
+
page: p,
|
| 32 |
+
limit: l,
|
| 33 |
+
totalPages: Math.ceil(total / l)
|
| 34 |
+
}
|
| 35 |
+
};
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
// POST New Question into a Set (PROTECTED)
|
| 39 |
+
fastify.post("/", { onRequest: [verifySupabaseAuth] }, async (request, reply) => {
|
| 40 |
+
try {
|
| 41 |
+
const user = request.user as { id: string };
|
| 42 |
+
const { setId, ...dataRaw } = request.body as any;
|
| 43 |
+
const data = QuestionSchema.parse(dataRaw);
|
| 44 |
+
|
| 45 |
+
if (!setId) return reply.code(400).send({ error: "setId wajib disertakan" });
|
| 46 |
+
|
| 47 |
+
// Verify Set ownership
|
| 48 |
+
const set = await prisma.questionSet.findFirst({
|
| 49 |
+
where: { id: setId, guruId: user.id }
|
| 50 |
+
});
|
| 51 |
+
if (!set) return reply.code(403).send({ error: "Anda tidak memiliki akses ke paket ini" });
|
| 52 |
+
|
| 53 |
+
const q = await prisma.question.create({
|
| 54 |
+
data: {
|
| 55 |
+
setId,
|
| 56 |
+
type: data.type as QuestionType,
|
| 57 |
+
text: data.text,
|
| 58 |
+
options: data.options ?? [],
|
| 59 |
+
answerKey: data.answerKey,
|
| 60 |
+
points: data.points,
|
| 61 |
+
}
|
| 62 |
+
});
|
| 63 |
+
return q;
|
| 64 |
+
} catch (err) {
|
| 65 |
+
if (err instanceof z.ZodError) {
|
| 66 |
+
return reply.code(400).send({ error: err.errors[0].message });
|
| 67 |
+
}
|
| 68 |
+
return reply.code(500).send({ error: "Gagal menyimpan soal" });
|
| 69 |
+
}
|
| 70 |
+
});
|
| 71 |
+
|
| 72 |
+
// PUT Update Question (PROTECTED)
|
| 73 |
+
fastify.put("/:id", { onRequest: [verifySupabaseAuth] }, async (request, reply) => {
|
| 74 |
+
try {
|
| 75 |
+
const user = request.user as { id: string };
|
| 76 |
+
const { id } = request.params as { id: string };
|
| 77 |
+
const data = QuestionSchema.partial().parse(request.body);
|
| 78 |
+
|
| 79 |
+
// Verify ownership via Set
|
| 80 |
+
const existing = await prisma.question.findFirst({
|
| 81 |
+
where: {
|
| 82 |
+
id,
|
| 83 |
+
set: { guruId: user.id }
|
| 84 |
+
}
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
if (!existing) {
|
| 88 |
+
return reply.code(404).send({ error: "Soal tidak ditemukan atau Anda tidak memiliki akses" });
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
const q = await prisma.question.update({
|
| 92 |
+
where: { id },
|
| 93 |
+
data: {
|
| 94 |
+
type: data.type as QuestionType | undefined,
|
| 95 |
+
text: data.text,
|
| 96 |
+
options: data.options ?? [],
|
| 97 |
+
answerKey: data.answerKey,
|
| 98 |
+
points: data.points,
|
| 99 |
+
}
|
| 100 |
+
});
|
| 101 |
+
return q;
|
| 102 |
+
} catch (err) {
|
| 103 |
+
if (err instanceof z.ZodError) {
|
| 104 |
+
return reply.code(400).send({ error: err.errors[0].message });
|
| 105 |
+
}
|
| 106 |
+
return reply.code(500).send({ error: "Gagal memperbarui soal" });
|
| 107 |
+
}
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
// DELETE Question (PROTECTED)
|
| 111 |
+
fastify.delete("/:id", { onRequest: [verifySupabaseAuth] }, async (request, reply) => {
|
| 112 |
+
const user = request.user as { id: string };
|
| 113 |
+
const { id } = request.params as { id: string };
|
| 114 |
+
|
| 115 |
+
const existing = await prisma.question.findFirst({
|
| 116 |
+
where: {
|
| 117 |
+
id,
|
| 118 |
+
set: { guruId: user.id }
|
| 119 |
+
}
|
| 120 |
+
});
|
| 121 |
+
|
| 122 |
+
if (!existing) {
|
| 123 |
+
return reply.code(404).send({ error: "Soal tidak ditemukan atau Anda tidak memiliki akses" });
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
await prisma.question.delete({ where: { id } });
|
| 127 |
+
return { success: true };
|
| 128 |
+
});
|
| 129 |
+
}
|
apps/api/src/routes/rooms.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { FastifyInstance } from "fastify";
|
| 2 |
+
import { z } from "zod";
|
| 3 |
+
import { prisma, RoomStatus } from "@repo/db";
|
| 4 |
+
import { CreateRoomSchema } from "@repo/types";
|
| 5 |
+
|
| 6 |
+
import { verifySupabaseAuth } from "../supabaseAuth";
|
| 7 |
+
|
| 8 |
+
export default async function roomRoutes(fastify: FastifyInstance) {
|
| 9 |
+
// Protected Routes - Only for authenticated Teachers
|
| 10 |
+
// MUST be registered BEFORE the dynamic /:code route
|
| 11 |
+
fastify.register(async (protectedRoutes) => {
|
| 12 |
+
protectedRoutes.addHook("onRequest", verifySupabaseAuth);
|
| 13 |
+
|
| 14 |
+
// GET All Room History (Sessions) for the Teacher
|
| 15 |
+
protectedRoutes.get("/history", async (request, reply) => {
|
| 16 |
+
const user = request.user as { id: string };
|
| 17 |
+
|
| 18 |
+
const rooms = await prisma.room.findMany({
|
| 19 |
+
where: {
|
| 20 |
+
guruId: user.id,
|
| 21 |
+
status: 'ENDED'
|
| 22 |
+
},
|
| 23 |
+
include: {
|
| 24 |
+
groups: { orderBy: { score: 'desc' } },
|
| 25 |
+
session: true
|
| 26 |
+
},
|
| 27 |
+
orderBy: { createdAt: 'desc' }
|
| 28 |
+
});
|
| 29 |
+
|
| 30 |
+
return rooms;
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
// POST Create New Room
|
| 34 |
+
protectedRoutes.post("/", async (request, reply) => {
|
| 35 |
+
try {
|
| 36 |
+
const user = request.user as { id: string };
|
| 37 |
+
const config = CreateRoomSchema.parse(request.body);
|
| 38 |
+
|
| 39 |
+
let code = "";
|
| 40 |
+
let isUnique = false;
|
| 41 |
+
while (!isUnique) {
|
| 42 |
+
code = Math.random().toString(36).substring(2, 8).toUpperCase();
|
| 43 |
+
const existing = await prisma.room.findUnique({ where: { code } });
|
| 44 |
+
if (!existing) isUnique = true;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
const room = await prisma.room.create({
|
| 48 |
+
data: {
|
| 49 |
+
code,
|
| 50 |
+
guruId: user.id,
|
| 51 |
+
status: 'LOBBY',
|
| 52 |
+
durationMinutes: config.durationMinutes,
|
| 53 |
+
turnDurationDasar: config.turnDurationDasar,
|
| 54 |
+
turnDurationTantangan: config.turnDurationTantangan,
|
| 55 |
+
turnDurationPemahaman: config.turnDurationPemahaman,
|
| 56 |
+
maxGroups: config.maxGroups,
|
| 57 |
+
questionSetId: (request.body as any).questionSetId || null
|
| 58 |
+
}
|
| 59 |
+
});
|
| 60 |
+
|
| 61 |
+
return room;
|
| 62 |
+
} catch (err) {
|
| 63 |
+
if (err instanceof z.ZodError) {
|
| 64 |
+
return reply.code(400).send({ error: err.errors[0].message });
|
| 65 |
+
}
|
| 66 |
+
return reply.code(500).send({ error: "Gagal membuat ruang" });
|
| 67 |
+
}
|
| 68 |
+
});
|
| 69 |
+
});
|
| 70 |
+
|
| 71 |
+
// GET Room by Code - PUBLIC (For Students joining, no auth required)
|
| 72 |
+
// Registered AFTER protected routes so /history is matched first
|
| 73 |
+
fastify.get("/:code", async (request, reply) => {
|
| 74 |
+
const { code } = request.params as { code: string };
|
| 75 |
+
const room = await prisma.room.findUnique({
|
| 76 |
+
where: { code },
|
| 77 |
+
include: { groups: true, session: true }
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
if (!room) {
|
| 81 |
+
return reply.code(404).send({ error: "Ruang tidak ditemukan" });
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
return room;
|
| 85 |
+
});
|
| 86 |
+
}
|
apps/api/src/socket/gameManager.ts
ADDED
|
@@ -0,0 +1,873 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Server, Socket } from "socket.io";
|
| 2 |
+
import { prisma } from "@repo/db";
|
| 3 |
+
|
| 4 |
+
interface ActiveRoom {
|
| 5 |
+
roomConfig: {
|
| 6 |
+
gameDurationSec: number;
|
| 7 |
+
maxGroups: number;
|
| 8 |
+
turnDurationDasar?: number;
|
| 9 |
+
turnDurationTantangan?: number;
|
| 10 |
+
turnDurationAksi?: number;
|
| 11 |
+
};
|
| 12 |
+
groups: (any & { isOffline?: boolean })[];
|
| 13 |
+
activeGroupIndex: number;
|
| 14 |
+
timer: number;
|
| 15 |
+
globalTimer: number;
|
| 16 |
+
isTimerRunning: boolean;
|
| 17 |
+
isGlobalTimerRunning: boolean;
|
| 18 |
+
gameStatus: 'LOBBY' | 'PLAYING' | 'FINISHED';
|
| 19 |
+
currentTurn: number;
|
| 20 |
+
winner: any | null;
|
| 21 |
+
currentCard: any | null;
|
| 22 |
+
pendingReviews: any[];
|
| 23 |
+
logs: string[];
|
| 24 |
+
countdown: number | null;
|
| 25 |
+
questions?: any[];
|
| 26 |
+
intervalId?: NodeJS.Timeout;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
const activeRooms = new Map<string, ActiveRoom>();
|
| 30 |
+
const socketToUser = new Map<string, { roomCode: string, groupName: string, role: string }>();
|
| 31 |
+
|
| 32 |
+
export function handleSocketEvents(io: Server, socket: Socket) {
|
| 33 |
+
|
| 34 |
+
socket.on("room:leave", async (data: { roomCode: string, groupName: string }) => {
|
| 35 |
+
const room = activeRooms.get(data.roomCode);
|
| 36 |
+
if (room) {
|
| 37 |
+
if (room.gameStatus === 'LOBBY') {
|
| 38 |
+
const normalizedName = data.groupName.trim().toLowerCase();
|
| 39 |
+
room.groups = room.groups.filter((g: any) => g.name.trim().toLowerCase() !== normalizedName);
|
| 40 |
+
await prisma.group.deleteMany({
|
| 41 |
+
where: {
|
| 42 |
+
room: { code: data.roomCode },
|
| 43 |
+
name: { equals: data.groupName, mode: 'insensitive' }
|
| 44 |
+
}
|
| 45 |
+
});
|
| 46 |
+
} else {
|
| 47 |
+
// PLAYING: Mark as SURRENDERED instead of removing
|
| 48 |
+
const group = room.groups.find(g => g.name === data.groupName);
|
| 49 |
+
if (group) {
|
| 50 |
+
group.status = 'SURRENDERED';
|
| 51 |
+
await prisma.group.update({
|
| 52 |
+
where: { id: group.id },
|
| 53 |
+
data: { status: 'SURRENDERED' as any }
|
| 54 |
+
}).catch(err => console.warn(`[DEBUG] [SERVER] Could not update group ${group.id} status in DB: ${err.message}`));
|
| 55 |
+
room.logs = [`${data.groupName} menyerah dari permainan.`, ...room.logs];
|
| 56 |
+
|
| 57 |
+
// Check if any non-surrendered players are left
|
| 58 |
+
const remainingPlayers = room.groups.filter(g => g.status !== 'SURRENDERED');
|
| 59 |
+
if (remainingPlayers.length === 0) {
|
| 60 |
+
await finishGame(data.roomCode);
|
| 61 |
+
} else {
|
| 62 |
+
// Jika pemain yang menyerah adalah yang sedang giliran, otomatis lanjut ke pemain berikutnya
|
| 63 |
+
const activeGroup = room.groups[room.activeGroupIndex];
|
| 64 |
+
if (activeGroup && activeGroup.name === data.groupName) {
|
| 65 |
+
let nextIndex = (room.activeGroupIndex + 1) % room.groups.length;
|
| 66 |
+
let searchCount = 0;
|
| 67 |
+
|
| 68 |
+
while (room.groups[nextIndex].status === 'SURRENDERED' && searchCount < room.groups.length) {
|
| 69 |
+
nextIndex = (nextIndex + 1) % room.groups.length;
|
| 70 |
+
searchCount++;
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
room.activeGroupIndex = nextIndex;
|
| 74 |
+
room.currentTurn += 1;
|
| 75 |
+
room.currentCard = null;
|
| 76 |
+
room.timer = 0;
|
| 77 |
+
room.isTimerRunning = false;
|
| 78 |
+
room.logs = [`Giliran dialihkan ke ${room.groups[nextIndex].name} karena ${data.groupName} menyerah.`, ...room.logs];
|
| 79 |
+
|
| 80 |
+
try {
|
| 81 |
+
await prisma.room.update({
|
| 82 |
+
where: { code: data.roomCode },
|
| 83 |
+
data: {
|
| 84 |
+
activeGroupIndex: nextIndex,
|
| 85 |
+
currentTurn: room.currentTurn
|
| 86 |
+
}
|
| 87 |
+
});
|
| 88 |
+
} catch (err) {
|
| 89 |
+
console.error("Gagal update turn saat surrender:", err);
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
}
|
| 95 |
+
|
| 96 |
+
const { intervalId, ...roomData } = room;
|
| 97 |
+
io.to(data.roomCode).emit("game:state", roomData);
|
| 98 |
+
socket.leave(data.roomCode);
|
| 99 |
+
socketToUser.delete(socket.id);
|
| 100 |
+
console.log(`Group ${data.groupName} left room ${data.roomCode}`);
|
| 101 |
+
}
|
| 102 |
+
});
|
| 103 |
+
|
| 104 |
+
socket.on("disconnect", async () => {
|
| 105 |
+
const userData = socketToUser.get(socket.id);
|
| 106 |
+
if (!userData) return;
|
| 107 |
+
|
| 108 |
+
const { roomCode, groupName, role } = userData;
|
| 109 |
+
|
| 110 |
+
// Check if there are other active sockets for this same student/group or guru
|
| 111 |
+
const otherSockets = Array.from(socketToUser.entries()).filter(([id, data]) =>
|
| 112 |
+
id !== socket.id && data.roomCode === roomCode && (groupName ? data.groupName === groupName : data.role === 'guru')
|
| 113 |
+
);
|
| 114 |
+
|
| 115 |
+
const room = activeRooms.get(roomCode);
|
| 116 |
+
|
| 117 |
+
if (room && otherSockets.length === 0) {
|
| 118 |
+
if (role === 'siswa' && groupName) {
|
| 119 |
+
const group = room.groups.find(g => g.name === groupName);
|
| 120 |
+
if (group) {
|
| 121 |
+
// In LOBBY, we don't mark as offline to avoid refresh issues
|
| 122 |
+
// Offline only matters when the game is ACTIVE
|
| 123 |
+
if (room.gameStatus !== 'LOBBY') {
|
| 124 |
+
group.isOffline = true;
|
| 125 |
+
room.logs = [`${groupName} terputus (Offline).`, ...room.logs];
|
| 126 |
+
}
|
| 127 |
+
}
|
| 128 |
+
io.to(roomCode).emit("game:state", { roomCode, groups: room.groups, logs: room.logs });
|
| 129 |
+
}
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
socketToUser.delete(socket.id);
|
| 133 |
+
console.log(`Socket ${socket.id} disconnected (${groupName || role} from ${roomCode}). Remaining: ${otherSockets.length}`);
|
| 134 |
+
});
|
| 135 |
+
|
| 136 |
+
socket.on("room:cancel", async (roomCode: string) => {
|
| 137 |
+
const room = activeRooms.get(roomCode);
|
| 138 |
+
if (room) {
|
| 139 |
+
try {
|
| 140 |
+
await prisma.room.update({
|
| 141 |
+
where: { code: roomCode },
|
| 142 |
+
data: { status: 'CANCELLED' }
|
| 143 |
+
});
|
| 144 |
+
io.to(roomCode).emit("room:cancelled", { roomCode });
|
| 145 |
+
activeRooms.delete(roomCode);
|
| 146 |
+
console.log(`Room ${roomCode} cancelled by Guru`);
|
| 147 |
+
} catch (err) {
|
| 148 |
+
console.error("Gagal batalkan room:", err);
|
| 149 |
+
}
|
| 150 |
+
}
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
socket.on("room:join", async (data: { roomCode: string, groupName: string, role?: string, roomConfig?: any, avatar?: string, color?: string, token?: string }) => {
|
| 154 |
+
|
| 155 |
+
// 1. Verify Guru Identity if role is 'guru'
|
| 156 |
+
if (data.role === 'guru') {
|
| 157 |
+
if (!data.token) {
|
| 158 |
+
socket.emit("error", { message: "Akses ditolak: Token autentikasi tidak ditemukan." });
|
| 159 |
+
return;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
try {
|
| 163 |
+
const { supabase } = await import('../supabaseAuth');
|
| 164 |
+
const { data: authData, error } = await supabase.auth.getUser(data.token);
|
| 165 |
+
|
| 166 |
+
if (error || !authData.user) {
|
| 167 |
+
socket.emit("error", { message: "Akses ditolak: Token autentikasi tidak valid." });
|
| 168 |
+
return;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
const dbRoomCheck = await prisma.room.findUnique({
|
| 172 |
+
where: { code: data.roomCode },
|
| 173 |
+
select: { guruId: true }
|
| 174 |
+
});
|
| 175 |
+
|
| 176 |
+
if (dbRoomCheck && dbRoomCheck.guruId !== authData.user.id) {
|
| 177 |
+
socket.emit("error", { message: "Akses ditolak: Anda bukan pemilik ruang ini." });
|
| 178 |
+
return;
|
| 179 |
+
}
|
| 180 |
+
} catch (err) {
|
| 181 |
+
console.error("Gagal verifikasi token socket guru:", err);
|
| 182 |
+
socket.emit("error", { message: "Gagal memverifikasi identitas Guru." });
|
| 183 |
+
return;
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
socket.join(data.roomCode);
|
| 188 |
+
console.log(`[DEBUG] [SERVER] Socket ${socket.id} joined room ${data.roomCode}. Identity:`, { groupName: data.groupName, role: data.role });
|
| 189 |
+
|
| 190 |
+
// Register socket mapping
|
| 191 |
+
socketToUser.set(socket.id, {
|
| 192 |
+
roomCode: data.roomCode,
|
| 193 |
+
groupName: data.groupName,
|
| 194 |
+
role: data.role || 'siswa'
|
| 195 |
+
});
|
| 196 |
+
|
| 197 |
+
if (!activeRooms.has(data.roomCode)) {
|
| 198 |
+
try {
|
| 199 |
+
const dbRoom = await prisma.room.findUnique({
|
| 200 |
+
where: { code: data.roomCode },
|
| 201 |
+
include: { groups: true, session: true }
|
| 202 |
+
}) as any;
|
| 203 |
+
|
| 204 |
+
if (dbRoom) {
|
| 205 |
+
if (dbRoom.status === 'ENDED') {
|
| 206 |
+
socket.emit("error", { message: "Ruang permainan ini sudah berakhir." });
|
| 207 |
+
return;
|
| 208 |
+
}
|
| 209 |
+
activeRooms.set(data.roomCode, {
|
| 210 |
+
roomConfig: data.roomConfig || {
|
| 211 |
+
gameDurationSec: dbRoom.durationMinutes * 60,
|
| 212 |
+
maxGroups: dbRoom.maxGroups
|
| 213 |
+
},
|
| 214 |
+
groups: dbRoom.groups.map((g: any) => ({
|
| 215 |
+
id: g.id,
|
| 216 |
+
name: g.name,
|
| 217 |
+
score: g.score,
|
| 218 |
+
position: g.position,
|
| 219 |
+
status: g.status,
|
| 220 |
+
avatar: g.avatar,
|
| 221 |
+
color: g.color,
|
| 222 |
+
isOffline: false,
|
| 223 |
+
})).sort((a: any, b: any) => a.id.localeCompare(b.id)),
|
| 224 |
+
gameStatus: dbRoom.status as any,
|
| 225 |
+
currentTurn: dbRoom.currentTurn,
|
| 226 |
+
activeGroupIndex: dbRoom.activeGroupIndex,
|
| 227 |
+
timer: 0,
|
| 228 |
+
globalTimer: dbRoom.durationMinutes * 60,
|
| 229 |
+
isTimerRunning: false,
|
| 230 |
+
isGlobalTimerRunning: dbRoom.status === 'ACTIVE',
|
| 231 |
+
winner: null,
|
| 232 |
+
currentCard: null,
|
| 233 |
+
pendingReviews: dbRoom.session ? (await prisma.answer.findMany({
|
| 234 |
+
where: { sessionId: dbRoom.session.id, scoreGiven: null },
|
| 235 |
+
include: { group: true, question: true }
|
| 236 |
+
})).map(a => ({
|
| 237 |
+
id: `rev-${a.id}`,
|
| 238 |
+
dbAnswerId: a.id,
|
| 239 |
+
groupId: a.groupId,
|
| 240 |
+
groupName: a.group.name,
|
| 241 |
+
question: a.question.text,
|
| 242 |
+
answer: a.answerText || "",
|
| 243 |
+
points: a.question.points
|
| 244 |
+
})) : [],
|
| 245 |
+
logs: ["Sesi dipulihkan dari database."],
|
| 246 |
+
countdown: null
|
| 247 |
+
});
|
| 248 |
+
} else {
|
| 249 |
+
activeRooms.set(data.roomCode, {
|
| 250 |
+
roomConfig: data.roomConfig || { gameDurationSec: 600, maxGroups: 4 },
|
| 251 |
+
groups: [],
|
| 252 |
+
activeGroupIndex: 0,
|
| 253 |
+
timer: 0,
|
| 254 |
+
globalTimer: 600,
|
| 255 |
+
isTimerRunning: false,
|
| 256 |
+
isGlobalTimerRunning: false,
|
| 257 |
+
gameStatus: 'LOBBY',
|
| 258 |
+
currentTurn: 1,
|
| 259 |
+
winner: null,
|
| 260 |
+
currentCard: null,
|
| 261 |
+
pendingReviews: [],
|
| 262 |
+
logs: ["Room dibuat."],
|
| 263 |
+
countdown: null
|
| 264 |
+
});
|
| 265 |
+
}
|
| 266 |
+
} catch (err) {
|
| 267 |
+
console.error("Gagal memulihkan room:", err);
|
| 268 |
+
}
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
const room = activeRooms.get(data.roomCode);
|
| 272 |
+
if (!room) return;
|
| 273 |
+
|
| 274 |
+
if (data.role !== 'guru' && data.groupName) {
|
| 275 |
+
const normalizedName = data.groupName.trim().toLowerCase();
|
| 276 |
+
console.log(`[DEBUG] [SERVER] Checking for existing group: "${normalizedName}" among:`, room.groups.map(g => g.name.toLowerCase()));
|
| 277 |
+
const existingGroup = room.groups.find((g: any) => g.name.trim().toLowerCase() === normalizedName);
|
| 278 |
+
|
| 279 |
+
if (existingGroup) {
|
| 280 |
+
// ─── SESI MULTI-TAB GUARD: Cegah dua tab aktif secara bersamaan ───────
|
| 281 |
+
// Cari apakah sudah ada socket lain yang terdaftar untuk tim ini di room ini
|
| 282 |
+
const oldSocketEntry = Array.from(socketToUser.entries()).find(([sid, u]) =>
|
| 283 |
+
u.roomCode === data.roomCode &&
|
| 284 |
+
u.role !== 'guru' &&
|
| 285 |
+
u.groupName &&
|
| 286 |
+
u.groupName.trim().toLowerCase() === normalizedName &&
|
| 287 |
+
sid !== socket.id
|
| 288 |
+
);
|
| 289 |
+
|
| 290 |
+
if (oldSocketEntry) {
|
| 291 |
+
const [oldSocketId] = oldSocketEntry;
|
| 292 |
+
console.log(`[DEBUG] [SERVER] Superseding old socket session ${oldSocketId} for group: "${existingGroup.name}"`);
|
| 293 |
+
|
| 294 |
+
// Dapatkan instance socket lama dan kirimkan event supersede
|
| 295 |
+
const oldSocket = io.sockets.sockets.get(oldSocketId);
|
| 296 |
+
if (oldSocket) {
|
| 297 |
+
oldSocket.emit("room:superseded", {
|
| 298 |
+
message: "Sesi Anda telah dibuka di tab atau perangkat lain."
|
| 299 |
+
});
|
| 300 |
+
oldSocket.leave(data.roomCode);
|
| 301 |
+
}
|
| 302 |
+
socketToUser.delete(oldSocketId);
|
| 303 |
+
}
|
| 304 |
+
// ─────────────────────────────────────────────────────────────────────
|
| 305 |
+
|
| 306 |
+
if (existingGroup.status === 'SURRENDERED') {
|
| 307 |
+
socket.emit("error", { message: "Anda sudah menyerah dari permainan ini." });
|
| 308 |
+
socket.leave(data.roomCode);
|
| 309 |
+
socketToUser.delete(socket.id);
|
| 310 |
+
return;
|
| 311 |
+
}
|
| 312 |
+
existingGroup.isOffline = false;
|
| 313 |
+
|
| 314 |
+
// JANGAN menimpa avatar dan warna yang sudah terdaftar di server jika sudah ada.
|
| 315 |
+
// Hanya isi jika data tersebut masih kosong (sebagai fallback).
|
| 316 |
+
if (!existingGroup.avatar && data.avatar) {
|
| 317 |
+
existingGroup.avatar = data.avatar;
|
| 318 |
+
}
|
| 319 |
+
if (!existingGroup.color && data.color) {
|
| 320 |
+
existingGroup.color = data.color;
|
| 321 |
+
}
|
| 322 |
+
|
| 323 |
+
room.logs = [`${existingGroup.name} kembali masuk.`, ...room.logs];
|
| 324 |
+
|
| 325 |
+
// Update DB jika ada data kosong yang baru terisi
|
| 326 |
+
if (existingGroup.avatar === data.avatar || existingGroup.color === data.color) {
|
| 327 |
+
prisma.group.update({
|
| 328 |
+
where: { id: existingGroup.id },
|
| 329 |
+
data: {
|
| 330 |
+
avatar: existingGroup.avatar,
|
| 331 |
+
color: existingGroup.color
|
| 332 |
+
}
|
| 333 |
+
}).catch(err => {
|
| 334 |
+
// If update fails because record is missing, it's okay, we'll rely on memory
|
| 335 |
+
});
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
} else {
|
| 339 |
+
// ─── GUARD: Tolak bergabung jika permainan sudah berlangsung ──────────
|
| 340 |
+
// Hanya grup yang sudah terdaftar sejak LOBBY yang boleh reconnect.
|
| 341 |
+
// Ini mencegah "penumpang gelap" ikut di tengah permainan.
|
| 342 |
+
if (room.gameStatus === 'PLAYING') {
|
| 343 |
+
socket.emit("error", {
|
| 344 |
+
message: "Permainan sudah berlangsung. Hanya peserta yang terdaftar dari awal yang dapat masuk kembali."
|
| 345 |
+
});
|
| 346 |
+
socket.leave(data.roomCode);
|
| 347 |
+
socketToUser.delete(socket.id);
|
| 348 |
+
return;
|
| 349 |
+
}
|
| 350 |
+
// ─────────────────────────────────────────────────────────────────────
|
| 351 |
+
|
| 352 |
+
const maxG = room.roomConfig?.maxGroups || 4;
|
| 353 |
+
if (room.groups.length >= maxG) {
|
| 354 |
+
socket.emit("room:full", { message: `Maaf, ruangan ini sudah penuh (maks. ${maxG} kelompok).` });
|
| 355 |
+
socket.leave(data.roomCode);
|
| 356 |
+
socketToUser.delete(socket.id);
|
| 357 |
+
return;
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
try {
|
| 361 |
+
// 1. Immediately add a placeholder to memory to prevent race conditions
|
| 362 |
+
// Use a temporary unique name to block other concurrent requests
|
| 363 |
+
const tempId = `temp-${Date.now()}-${Math.random()}`;
|
| 364 |
+
const newGroupEntry = {
|
| 365 |
+
id: tempId,
|
| 366 |
+
name: data.groupName,
|
| 367 |
+
score: 0,
|
| 368 |
+
position: 0,
|
| 369 |
+
status: 'WAITING',
|
| 370 |
+
avatar: data.avatar,
|
| 371 |
+
color: data.color,
|
| 372 |
+
isOffline: false
|
| 373 |
+
};
|
| 374 |
+
room.groups.push(newGroupEntry);
|
| 375 |
+
room.groups.sort((a: any, b: any) => a.id.localeCompare(b.id));
|
| 376 |
+
|
| 377 |
+
// 2. Now perform the slow DB operations
|
| 378 |
+
const dbRoom = await prisma.room.findUnique({ where: { code: data.roomCode } });
|
| 379 |
+
if (dbRoom) {
|
| 380 |
+
const dbGroup = await prisma.group.create({
|
| 381 |
+
data: {
|
| 382 |
+
roomId: dbRoom.id,
|
| 383 |
+
name: data.groupName,
|
| 384 |
+
score: 0,
|
| 385 |
+
position: 0,
|
| 386 |
+
avatar: data.avatar,
|
| 387 |
+
color: data.color
|
| 388 |
+
}
|
| 389 |
+
});
|
| 390 |
+
|
| 391 |
+
// 3. Update the memory entry with the real DB ID
|
| 392 |
+
newGroupEntry.id = dbGroup.id;
|
| 393 |
+
room.groups.sort((a: any, b: any) => a.id.localeCompare(b.id));
|
| 394 |
+
room.logs = [`${data.groupName} bergabung.`, ...room.logs];
|
| 395 |
+
} else {
|
| 396 |
+
// Rollback memory if room not found
|
| 397 |
+
room.groups = room.groups.filter(g => g.id !== tempId);
|
| 398 |
+
}
|
| 399 |
+
} catch (err) {
|
| 400 |
+
console.error("Gagal menyimpan group ke DB:", err);
|
| 401 |
+
// Rollback if needed
|
| 402 |
+
room.groups = room.groups.filter(g => g.id.toString().startsWith('temp-') === false);
|
| 403 |
+
}
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
const { intervalId, ...roomData } = room;
|
| 409 |
+
io.to(data.roomCode).emit("game:state", { ...roomData, roomCode: data.roomCode });
|
| 410 |
+
});
|
| 411 |
+
|
| 412 |
+
// Handle intentional leave — removes group from memory and DB
|
| 413 |
+
socket.on("room:leave", async (data: { roomCode: string; groupName: string }) => {
|
| 414 |
+
console.log(`[DEBUG] [SERVER] Received room:leave for room ${data.roomCode}, group ${data.groupName}`);
|
| 415 |
+
if (!data.roomCode || !data.groupName) {
|
| 416 |
+
console.warn('[DEBUG] [SERVER] room:leave ignored: missing roomCode or groupName');
|
| 417 |
+
return;
|
| 418 |
+
}
|
| 419 |
+
const room = activeRooms.get(data.roomCode);
|
| 420 |
+
if (!room) {
|
| 421 |
+
console.warn(`[DEBUG] [SERVER] room:leave ignored: room ${data.roomCode} not found in memory`);
|
| 422 |
+
return;
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
const normalizedName = data.groupName.trim().toLowerCase();
|
| 426 |
+
const groupIndex = room.groups.findIndex((g: any) => g.name.trim().toLowerCase() === normalizedName);
|
| 427 |
+
|
| 428 |
+
if (groupIndex !== -1) {
|
| 429 |
+
const [removed] = room.groups.splice(groupIndex, 1);
|
| 430 |
+
console.log(`[DEBUG] [SERVER] Group "${removed.name}" removed from memory for room ${data.roomCode}`);
|
| 431 |
+
|
| 432 |
+
// Delete from DB so it doesn't reappear on guru refresh
|
| 433 |
+
if (removed.id) {
|
| 434 |
+
prisma.group.delete({ where: { id: removed.id } })
|
| 435 |
+
.then(() => console.log(`[DEBUG] [SERVER] Group ${removed.name} deleted from DB`))
|
| 436 |
+
.catch(err => console.error(`[DEBUG] [SERVER] Failed to delete group ${removed.id}:`, err.message));
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
room.logs = [`${removed.name} keluar dari ruang.`, ...room.logs];
|
| 440 |
+
|
| 441 |
+
// Broadcast updated state to remaining members
|
| 442 |
+
const { intervalId, ...roomData } = room;
|
| 443 |
+
io.to(data.roomCode).emit("game:state", { ...roomData, roomCode: data.roomCode });
|
| 444 |
+
}
|
| 445 |
+
});
|
| 446 |
+
|
| 447 |
+
socket.on("game:sync_state", async (data: { roomCode: string, state: any }) => {
|
| 448 |
+
const room = activeRooms.get(data.roomCode);
|
| 449 |
+
if (!room) return;
|
| 450 |
+
|
| 451 |
+
// 1. If the client is signaling the game is FINISHED, use the dedicated finish logic
|
| 452 |
+
if (data.state.gameStatus === 'FINISHED' && room.gameStatus !== 'FINISHED') {
|
| 453 |
+
return await finishGame(data.roomCode);
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
// 2. Merge state into memory, but PROTECT server-side managed fields
|
| 457 |
+
// 'groups' is server-authoritative — only modified via room:join/leave events.
|
| 458 |
+
// Avatar/color sync for groups is handled separately below via DB.
|
| 459 |
+
const protectedFields = ['intervalId', 'pendingReviews', 'logs', 'groups'];
|
| 460 |
+
Object.keys(data.state).forEach(key => {
|
| 461 |
+
if (!protectedFields.includes(key)) {
|
| 462 |
+
(room as any)[key] = data.state[key];
|
| 463 |
+
}
|
| 464 |
+
});
|
| 465 |
+
|
| 466 |
+
// 3. Persist to DB if groups are updated (profile/score sync) (Solusi B: Non-blocking DB updates)
|
| 467 |
+
if (data.state.groups) {
|
| 468 |
+
// Trigger database updates in the background (asynchronously) without blocking the WebSocket emit loop
|
| 469 |
+
Promise.all(data.state.groups.map((g: any) =>
|
| 470 |
+
prisma.group.update({
|
| 471 |
+
where: { id: g.id },
|
| 472 |
+
data: {
|
| 473 |
+
avatar: g.avatar,
|
| 474 |
+
color: g.color,
|
| 475 |
+
score: g.score,
|
| 476 |
+
position: g.position,
|
| 477 |
+
status: g.status === 'WAITING' ? 'ACTIVE' : g.status
|
| 478 |
+
}
|
| 479 |
+
}).catch(err => {
|
| 480 |
+
console.error(`[DB_SYNC] Gagal update group ${g.id}:`, err.message);
|
| 481 |
+
})
|
| 482 |
+
)).catch(err => {
|
| 483 |
+
console.error(`[DB_SYNC] Promise.all failed:`, err);
|
| 484 |
+
});
|
| 485 |
+
|
| 486 |
+
// Synchronously update in-memory room groups (immediate update for room state)
|
| 487 |
+
data.state.groups.forEach((g: any) => {
|
| 488 |
+
const memGroup = room.groups.find((mg: any) => mg.id === g.id);
|
| 489 |
+
if (memGroup) {
|
| 490 |
+
if (g.avatar !== undefined) memGroup.avatar = g.avatar;
|
| 491 |
+
if (g.color !== undefined) memGroup.color = g.color;
|
| 492 |
+
if (g.score !== undefined) memGroup.score = g.score;
|
| 493 |
+
if (g.position !== undefined) memGroup.position = g.position;
|
| 494 |
+
if (g.status !== undefined) memGroup.status = g.status;
|
| 495 |
+
}
|
| 496 |
+
});
|
| 497 |
+
room.groups.sort((a: any, b: any) => a.id.localeCompare(b.id));
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
// Persist room-level game state (turn, current index)
|
| 501 |
+
if (data.state.activeGroupIndex !== undefined || data.state.currentTurn !== undefined) {
|
| 502 |
+
// Clear submission locks for the new turn/group
|
| 503 |
+
if ((room as any).submissionLocks) {
|
| 504 |
+
(room as any).submissionLocks.clear();
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
prisma.room.update({
|
| 508 |
+
where: { code: data.roomCode },
|
| 509 |
+
data: {
|
| 510 |
+
activeGroupIndex: data.state.activeGroupIndex,
|
| 511 |
+
currentTurn: data.state.currentTurn
|
| 512 |
+
} as any
|
| 513 |
+
}).catch(err => console.error("[DB_SYNC] Gagal update room state:", err.message));
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// 4. Broadcast the updated full room state (including groups) to all in room
|
| 517 |
+
const { intervalId, ...roomData } = room;
|
| 518 |
+
io.to(data.roomCode).emit("game:state", { ...roomData, roomCode: data.roomCode });
|
| 519 |
+
});
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
socket.on("game:start", async (roomCode: string) => {
|
| 523 |
+
const room = activeRooms.get(roomCode);
|
| 524 |
+
if (!room) return;
|
| 525 |
+
|
| 526 |
+
// Persist session start to DB
|
| 527 |
+
try {
|
| 528 |
+
const dbRoom = await prisma.room.update({
|
| 529 |
+
where: { code: roomCode },
|
| 530 |
+
data: { status: 'ACTIVE' }
|
| 531 |
+
});
|
| 532 |
+
|
| 533 |
+
// Upsert GameSession
|
| 534 |
+
await prisma.gameSession.upsert({
|
| 535 |
+
where: { roomId: dbRoom.id },
|
| 536 |
+
update: { startedAt: new Date(), endedAt: null },
|
| 537 |
+
create: { roomId: dbRoom.id }
|
| 538 |
+
});
|
| 539 |
+
} catch (err) {
|
| 540 |
+
console.error("Gagal mencatat sesi di DB:", err);
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
room.gameStatus = 'LOBBY';
|
| 544 |
+
room.countdown = 3;
|
| 545 |
+
|
| 546 |
+
if (room.intervalId) clearInterval(room.intervalId);
|
| 547 |
+
room.intervalId = setInterval(() => {
|
| 548 |
+
const liveRoom = activeRooms.get(roomCode);
|
| 549 |
+
if (!liveRoom) return;
|
| 550 |
+
|
| 551 |
+
let updated = false;
|
| 552 |
+
|
| 553 |
+
if (liveRoom.countdown !== null && liveRoom.countdown > 0) {
|
| 554 |
+
liveRoom.countdown--;
|
| 555 |
+
updated = true;
|
| 556 |
+
} else if (liveRoom.countdown === 0) {
|
| 557 |
+
liveRoom.countdown = null;
|
| 558 |
+
liveRoom.gameStatus = 'PLAYING';
|
| 559 |
+
liveRoom.isGlobalTimerRunning = true;
|
| 560 |
+
liveRoom.globalTimer = liveRoom.roomConfig?.gameDurationSec || 600;
|
| 561 |
+
updated = true;
|
| 562 |
+
}
|
| 563 |
+
|
| 564 |
+
if (liveRoom.isGlobalTimerRunning && liveRoom.globalTimer > 0) {
|
| 565 |
+
liveRoom.globalTimer--;
|
| 566 |
+
updated = true;
|
| 567 |
+
}
|
| 568 |
+
|
| 569 |
+
if (liveRoom.isTimerRunning && liveRoom.timer > 0) {
|
| 570 |
+
liveRoom.timer--;
|
| 571 |
+
updated = true;
|
| 572 |
+
}
|
| 573 |
+
|
| 574 |
+
if (updated) {
|
| 575 |
+
io.to(roomCode).emit("game:timer_sync", {
|
| 576 |
+
timer: liveRoom.timer,
|
| 577 |
+
globalTimer: liveRoom.globalTimer,
|
| 578 |
+
countdown: liveRoom.countdown
|
| 579 |
+
});
|
| 580 |
+
|
| 581 |
+
if (liveRoom.gameStatus === 'PLAYING' && liveRoom.countdown === null) {
|
| 582 |
+
const { intervalId, ...roomData } = liveRoom;
|
| 583 |
+
io.to(roomCode).emit("game:state", roomData);
|
| 584 |
+
}
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
if (liveRoom.globalTimer <= 0 && liveRoom.gameStatus === 'PLAYING') {
|
| 588 |
+
finishGame(roomCode);
|
| 589 |
+
}
|
| 590 |
+
}, 1000);
|
| 591 |
+
|
| 592 |
+
const { intervalId: ignored, ...roomData } = room;
|
| 593 |
+
io.to(roomCode).emit("game:state", roomData);
|
| 594 |
+
});
|
| 595 |
+
|
| 596 |
+
async function finishGame(roomCode: string) {
|
| 597 |
+
const room = activeRooms.get(roomCode);
|
| 598 |
+
if (!room) return;
|
| 599 |
+
|
| 600 |
+
room.gameStatus = 'FINISHED';
|
| 601 |
+
room.isGlobalTimerRunning = false;
|
| 602 |
+
room.isTimerRunning = false;
|
| 603 |
+
if (room.intervalId) clearInterval(room.intervalId);
|
| 604 |
+
|
| 605 |
+
// Filter out surrendered players for winner calculation
|
| 606 |
+
const eligibleGroups = room.groups.filter(g => g.status !== 'SURRENDERED');
|
| 607 |
+
const winner = eligibleGroups.length > 0
|
| 608 |
+
? [...eligibleGroups].sort((a, b) => b.score - a.score)[0]
|
| 609 |
+
: null;
|
| 610 |
+
|
| 611 |
+
room.winner = winner;
|
| 612 |
+
|
| 613 |
+
// Persist results to DB
|
| 614 |
+
try {
|
| 615 |
+
const dbRoom = await prisma.room.update({
|
| 616 |
+
where: { code: roomCode },
|
| 617 |
+
data: { status: 'ENDED' },
|
| 618 |
+
include: { session: true }
|
| 619 |
+
});
|
| 620 |
+
|
| 621 |
+
// Update groups scores and positions in DB
|
| 622 |
+
for (const g of room.groups) {
|
| 623 |
+
await prisma.group.update({
|
| 624 |
+
where: { id: g.id },
|
| 625 |
+
data: {
|
| 626 |
+
score: g.score,
|
| 627 |
+
position: g.position
|
| 628 |
+
}
|
| 629 |
+
});
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
if (dbRoom.session) {
|
| 633 |
+
await prisma.gameSession.update({
|
| 634 |
+
where: { id: dbRoom.session.id },
|
| 635 |
+
data: {
|
| 636 |
+
endedAt: new Date(),
|
| 637 |
+
winnerGroupId: winner?.id || null
|
| 638 |
+
}
|
| 639 |
+
});
|
| 640 |
+
}
|
| 641 |
+
} catch (err) {
|
| 642 |
+
console.error("Gagal menutup sesi di DB:", err);
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
const { intervalId, ...roomData } = room;
|
| 646 |
+
io.to(roomCode).emit("game:state", roomData);
|
| 647 |
+
}
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
socket.on("student:submit_objektif", async (data: { roomCode: string, groupId: string, questionId: string, answer: string, isCorrect: boolean, score: number, turnNumber?: number }) => {
|
| 652 |
+
const room = activeRooms.get(data.roomCode);
|
| 653 |
+
if (!room) return;
|
| 654 |
+
|
| 655 |
+
const group = room.groups.find(g => g.id === data.groupId);
|
| 656 |
+
if (group) {
|
| 657 |
+
group.score += data.score;
|
| 658 |
+
room.logs = [`${group.name} menjawab ${data.isCorrect ? "benar" : "salah"}`, ...room.logs];
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
// Broadcast immediately to ensure game continues
|
| 662 |
+
io.to(data.roomCode).emit("game:state", {
|
| 663 |
+
roomCode: data.roomCode,
|
| 664 |
+
groups: room.groups,
|
| 665 |
+
logs: room.logs
|
| 666 |
+
});
|
| 667 |
+
|
| 668 |
+
// Background DB Persistence (non-blocking)
|
| 669 |
+
try {
|
| 670 |
+
let dbRoom = await prisma.room.findUnique({
|
| 671 |
+
where: { code: data.roomCode },
|
| 672 |
+
include: { session: true }
|
| 673 |
+
});
|
| 674 |
+
|
| 675 |
+
if (dbRoom) {
|
| 676 |
+
// Auto-create session if missing
|
| 677 |
+
if (!dbRoom.session) {
|
| 678 |
+
const newSession = await prisma.gameSession.create({
|
| 679 |
+
data: { roomId: dbRoom.id }
|
| 680 |
+
});
|
| 681 |
+
(dbRoom as any).session = newSession;
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
if (dbRoom.session) {
|
| 685 |
+
await prisma.answer.create({
|
| 686 |
+
data: {
|
| 687 |
+
sessionId: dbRoom.session.id,
|
| 688 |
+
groupId: data.groupId,
|
| 689 |
+
questionId: data.questionId,
|
| 690 |
+
answerText: data.answer,
|
| 691 |
+
isCorrect: data.isCorrect,
|
| 692 |
+
scoreGiven: data.score
|
| 693 |
+
}
|
| 694 |
+
});
|
| 695 |
+
|
| 696 |
+
await prisma.turnLog.create({
|
| 697 |
+
data: {
|
| 698 |
+
sessionId: dbRoom.session.id,
|
| 699 |
+
groupId: data.groupId,
|
| 700 |
+
questionId: data.questionId,
|
| 701 |
+
turnNumber: data.turnNumber || room.currentTurn || 1
|
| 702 |
+
}
|
| 703 |
+
});
|
| 704 |
+
|
| 705 |
+
await prisma.group.update({
|
| 706 |
+
where: { id: data.groupId },
|
| 707 |
+
data: { score: group?.score || 0 }
|
| 708 |
+
});
|
| 709 |
+
}
|
| 710 |
+
}
|
| 711 |
+
} catch (err) {
|
| 712 |
+
console.error("Gagal simpan jawaban objektif ke DB (non-blocking):", err);
|
| 713 |
+
}
|
| 714 |
+
});
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
socket.on("student:submit_answer", async (data: { roomCode: string, groupId: string, questionId: string, answerText: string, points?: number, turnNumber?: number }) => {
|
| 718 |
+
const room = activeRooms.get(data.roomCode);
|
| 719 |
+
if (!room) return;
|
| 720 |
+
|
| 721 |
+
// 1. SYNC GUARD: Prevent double submission for the same group in this turn
|
| 722 |
+
// We use a temporary dynamic property on the room object for immediate locking
|
| 723 |
+
if (!(room as any).submissionLocks) (room as any).submissionLocks = new Set<string>();
|
| 724 |
+
const submissionKey = `${data.groupId}-${data.turnNumber || room.currentTurn}`;
|
| 725 |
+
|
| 726 |
+
if ((room as any).submissionLocks.has(submissionKey)) {
|
| 727 |
+
console.log(`[SUBMIT_ANSWER] [GUARD] Ignored duplicate submission for group ${data.groupId} in room ${data.roomCode}`);
|
| 728 |
+
return;
|
| 729 |
+
}
|
| 730 |
+
|
| 731 |
+
// Check pendingReviews as a fallback
|
| 732 |
+
const alreadyInReviews = room.pendingReviews.some(r => r.groupId === data.groupId);
|
| 733 |
+
if (alreadyInReviews) {
|
| 734 |
+
console.log(`[SUBMIT_ANSWER] [GUARD] Submission already exists in pendingReviews for group ${data.groupId}`);
|
| 735 |
+
return;
|
| 736 |
+
}
|
| 737 |
+
|
| 738 |
+
// Set the lock IMMEDIATELY (synchronously) before any await calls
|
| 739 |
+
(room as any).submissionLocks.add(submissionKey);
|
| 740 |
+
|
| 741 |
+
console.log(`[SUBMIT_ANSWER] Processing submission for Room: ${data.roomCode}, Group: ${data.groupId}, Q: ${data.questionId}`);
|
| 742 |
+
|
| 743 |
+
try {
|
| 744 |
+
let dbRoom = await prisma.room.findUnique({
|
| 745 |
+
where: { code: data.roomCode },
|
| 746 |
+
include: { session: true }
|
| 747 |
+
});
|
| 748 |
+
|
| 749 |
+
if (dbRoom) {
|
| 750 |
+
// Auto-create session if missing
|
| 751 |
+
if (!dbRoom.session) {
|
| 752 |
+
const newSession = await prisma.gameSession.create({
|
| 753 |
+
data: { roomId: dbRoom.id }
|
| 754 |
+
});
|
| 755 |
+
(dbRoom as any).session = newSession;
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
if (dbRoom.session) {
|
| 759 |
+
const dbAnswer = await prisma.answer.create({
|
| 760 |
+
data: {
|
| 761 |
+
sessionId: dbRoom.session.id,
|
| 762 |
+
groupId: data.groupId,
|
| 763 |
+
questionId: data.questionId,
|
| 764 |
+
answerText: data.answerText
|
| 765 |
+
},
|
| 766 |
+
include: { group: true, question: true }
|
| 767 |
+
});
|
| 768 |
+
|
| 769 |
+
await prisma.turnLog.create({
|
| 770 |
+
data: {
|
| 771 |
+
sessionId: dbRoom.session.id,
|
| 772 |
+
groupId: data.groupId,
|
| 773 |
+
questionId: data.questionId,
|
| 774 |
+
turnNumber: data.turnNumber || room.currentTurn || 1
|
| 775 |
+
}
|
| 776 |
+
});
|
| 777 |
+
|
| 778 |
+
const review = {
|
| 779 |
+
id: `rev-${dbAnswer.id}`,
|
| 780 |
+
dbAnswerId: dbAnswer.id,
|
| 781 |
+
groupId: dbAnswer.groupId,
|
| 782 |
+
groupName: dbAnswer.group.name,
|
| 783 |
+
question: dbAnswer.question.text,
|
| 784 |
+
answer: dbAnswer.answerText || "",
|
| 785 |
+
points: data.points || dbAnswer.question.points || 10
|
| 786 |
+
};
|
| 787 |
+
|
| 788 |
+
room.pendingReviews = [review, ...room.pendingReviews];
|
| 789 |
+
room.logs = [`Jawaban tantangan masuk dari ${review.groupName}`, ...room.logs];
|
| 790 |
+
|
| 791 |
+
console.log(`[SUBMIT_DB] Success. Review created for ${review.groupName}`);
|
| 792 |
+
|
| 793 |
+
io.to(data.roomCode).emit("game:state", {
|
| 794 |
+
roomCode: data.roomCode,
|
| 795 |
+
pendingReviews: room.pendingReviews,
|
| 796 |
+
logs: room.logs
|
| 797 |
+
});
|
| 798 |
+
}
|
| 799 |
+
}
|
| 800 |
+
} catch (err) {
|
| 801 |
+
console.error("[SUBMIT_ERROR] Gagal simpan jawaban siswa:", err);
|
| 802 |
+
// Fallback: create an in-memory review so the teacher can still grade
|
| 803 |
+
const group = room.groups.find(g => g.id === data.groupId);
|
| 804 |
+
const fallbackReview = {
|
| 805 |
+
id: `rev-fallback-${Date.now()}`,
|
| 806 |
+
dbAnswerId: `fallback-${Date.now()}`,
|
| 807 |
+
groupId: data.groupId,
|
| 808 |
+
groupName: group?.name || "Siswa",
|
| 809 |
+
question: "(Gagal memuat pertanyaan)",
|
| 810 |
+
answer: data.answerText,
|
| 811 |
+
points: data.points || 10
|
| 812 |
+
};
|
| 813 |
+
room.pendingReviews = [fallbackReview, ...room.pendingReviews];
|
| 814 |
+
room.logs = ["Sistem: Jawaban diterima (mode offline), menunggu penilaian guru.", ...room.logs];
|
| 815 |
+
io.to(data.roomCode).emit("game:state", {
|
| 816 |
+
roomCode: data.roomCode,
|
| 817 |
+
pendingReviews: room.pendingReviews,
|
| 818 |
+
logs: room.logs
|
| 819 |
+
});
|
| 820 |
+
}
|
| 821 |
+
});
|
| 822 |
+
|
| 823 |
+
socket.on("teacher:grade_answer", async (data: { roomCode: string, dbAnswerId: string, groupId: string, score: number, isCorrect: boolean }) => {
|
| 824 |
+
const room = activeRooms.get(data.roomCode);
|
| 825 |
+
if (!room) return;
|
| 826 |
+
|
| 827 |
+
// Always update in-memory state first (so game never hangs)
|
| 828 |
+
const group = room.groups.find(g => g.id === data.groupId);
|
| 829 |
+
if (group) {
|
| 830 |
+
group.score += data.score;
|
| 831 |
+
}
|
| 832 |
+
room.pendingReviews = room.pendingReviews.filter(r => r.dbAnswerId !== data.dbAnswerId);
|
| 833 |
+
room.logs = [`Guru memberikan ${data.score} poin untuk ${group?.name || 'tim'}`, ...room.logs];
|
| 834 |
+
|
| 835 |
+
// Broadcast immediately — game continues regardless of DB
|
| 836 |
+
io.to(data.roomCode).emit("game:state", {
|
| 837 |
+
roomCode: data.roomCode,
|
| 838 |
+
groups: room.groups,
|
| 839 |
+
pendingReviews: room.pendingReviews,
|
| 840 |
+
logs: room.logs,
|
| 841 |
+
lastResult: {
|
| 842 |
+
type: data.score > 0 ? 'SUCCESS' : 'FAILURE',
|
| 843 |
+
title: data.score > 0 ? 'DINILAI!' : 'TIDAK TEPAT!',
|
| 844 |
+
message: data.score > 0
|
| 845 |
+
? `Guru memberikan ${data.score} poin untuk jawabanmu!`
|
| 846 |
+
: `Guru menyatakan jawaban kurang tepat (0 poin).`,
|
| 847 |
+
points: data.score,
|
| 848 |
+
groupName: group?.name || 'Siswa'
|
| 849 |
+
}
|
| 850 |
+
});
|
| 851 |
+
|
| 852 |
+
// Background DB persistence — skip fallback in-memory answers that have no DB record
|
| 853 |
+
if (!data.dbAnswerId.startsWith('fallback-')) {
|
| 854 |
+
try {
|
| 855 |
+
await prisma.answer.update({
|
| 856 |
+
where: { id: data.dbAnswerId },
|
| 857 |
+
data: {
|
| 858 |
+
scoreGiven: data.score,
|
| 859 |
+
isCorrect: data.isCorrect
|
| 860 |
+
}
|
| 861 |
+
});
|
| 862 |
+
if (group) {
|
| 863 |
+
await prisma.group.update({
|
| 864 |
+
where: { id: group.id },
|
| 865 |
+
data: { score: group.score }
|
| 866 |
+
});
|
| 867 |
+
}
|
| 868 |
+
} catch (err) {
|
| 869 |
+
console.error("Gagal simpan penilaian guru ke DB (Log Only):", err);
|
| 870 |
+
}
|
| 871 |
+
}
|
| 872 |
+
});
|
| 873 |
+
}
|
apps/api/src/supabaseAuth.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createClient } from "@supabase/supabase-js";
|
| 2 |
+
import { FastifyRequest, FastifyReply } from "fastify";
|
| 3 |
+
import { prisma } from "@repo/db";
|
| 4 |
+
import * as dotenv from "dotenv";
|
| 5 |
+
import * as path from "path";
|
| 6 |
+
|
| 7 |
+
// Load API's own .env first (production), then root .env as fallback (local dev)
|
| 8 |
+
dotenv.config({ path: path.resolve(__dirname, "../.env") });
|
| 9 |
+
dotenv.config({ path: path.resolve(__dirname, "../../../.env") });
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
|
| 13 |
+
const supabaseKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "";
|
| 14 |
+
|
| 15 |
+
if (!supabaseUrl || !supabaseKey) {
|
| 16 |
+
console.warn("Missing Supabase credentials in backend!");
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
export const supabase = createClient(supabaseUrl, supabaseKey);
|
| 20 |
+
|
| 21 |
+
export async function verifySupabaseAuth(request: FastifyRequest, reply: FastifyReply) {
|
| 22 |
+
const authHeader = request.headers.authorization;
|
| 23 |
+
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
| 24 |
+
return reply.code(401).send({ error: "Missing or invalid authorization header" });
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
const token = authHeader.substring(7);
|
| 28 |
+
|
| 29 |
+
try {
|
| 30 |
+
const { data, error } = await supabase.auth.getUser(token);
|
| 31 |
+
|
| 32 |
+
if (error || !data.user) {
|
| 33 |
+
return reply.code(401).send({ error: "Invalid token" });
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const sbUser = data.user;
|
| 37 |
+
|
| 38 |
+
// Check if user exists in Prisma
|
| 39 |
+
let dbUser = await prisma.user.findUnique({
|
| 40 |
+
where: { id: sbUser.id }
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
// Just-in-Time Provisioning: If user doesn't exist in Prisma DB, create them
|
| 44 |
+
if (!dbUser) {
|
| 45 |
+
const email = sbUser.email || "";
|
| 46 |
+
const name = sbUser.user_metadata?.full_name || email.split("@")[0] || "User";
|
| 47 |
+
|
| 48 |
+
// Upsert to handle edge cases where email might already exist with a different ID
|
| 49 |
+
// But ideally ID should be consistent
|
| 50 |
+
dbUser = await prisma.user.upsert({
|
| 51 |
+
where: { id: sbUser.id },
|
| 52 |
+
update: { name, email },
|
| 53 |
+
create: {
|
| 54 |
+
id: sbUser.id,
|
| 55 |
+
email,
|
| 56 |
+
name,
|
| 57 |
+
passwordHash: "supabase-auth", // placeholder for Supabase users
|
| 58 |
+
}
|
| 59 |
+
});
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
// Attach user to request
|
| 63 |
+
(request as any).user = { id: dbUser.id, email: dbUser.email, name: dbUser.name };
|
| 64 |
+
} catch (err) {
|
| 65 |
+
console.error("Auth verification error:", err);
|
| 66 |
+
return reply.code(401).send({ error: "Unauthorized" });
|
| 67 |
+
}
|
| 68 |
+
}
|
apps/api/tsconfig.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"target": "es2022",
|
| 4 |
+
"module": "commonjs",
|
| 5 |
+
"esModuleInterop": true,
|
| 6 |
+
"forceConsistentCasingInFileNames": true,
|
| 7 |
+
"strict": true,
|
| 8 |
+
"skipLibCheck": true,
|
| 9 |
+
"outDir": "./dist"
|
| 10 |
+
},
|
| 11 |
+
"include": ["src/**/*"]
|
| 12 |
+
}
|
package.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "eduboard-pai",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"scripts": {
|
| 6 |
+
"dev": "turbo run dev",
|
| 7 |
+
"build": "turbo run build",
|
| 8 |
+
"lint": "turbo run lint"
|
| 9 |
+
},
|
| 10 |
+
"devDependencies": {
|
| 11 |
+
"turbo": "^2.1.2"
|
| 12 |
+
},
|
| 13 |
+
"packageManager": "pnpm@9.5.0"
|
| 14 |
+
}
|
packages/db/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { PrismaClient } from "@prisma/client";
|
| 2 |
+
|
| 3 |
+
const globalForPrisma = global as unknown as { prisma: PrismaClient };
|
| 4 |
+
|
| 5 |
+
export const prisma =
|
| 6 |
+
globalForPrisma.prisma ||
|
| 7 |
+
new PrismaClient({
|
| 8 |
+
log: ["query"],
|
| 9 |
+
});
|
| 10 |
+
|
| 11 |
+
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
|
| 12 |
+
|
| 13 |
+
export * from "@prisma/client";
|
packages/db/package.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@repo/db",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"main": "./index.ts",
|
| 6 |
+
"scripts": {
|
| 7 |
+
"db:generate": "prisma generate",
|
| 8 |
+
"db:push": "prisma db push",
|
| 9 |
+
"db:seed": "prisma db seed"
|
| 10 |
+
},
|
| 11 |
+
"dependencies": {
|
| 12 |
+
"@prisma/client": "^5.12.1"
|
| 13 |
+
},
|
| 14 |
+
"devDependencies": {
|
| 15 |
+
"@types/node": "^25.6.0",
|
| 16 |
+
"prisma": "^5.12.1",
|
| 17 |
+
"tsx": "^4.7.2",
|
| 18 |
+
"typescript": "^5.4.5"
|
| 19 |
+
},
|
| 20 |
+
"prisma": {
|
| 21 |
+
"seed": "pnpm exec tsx prisma/seed.ts"
|
| 22 |
+
}
|
| 23 |
+
}
|
packages/db/prisma/presets/pai-kelas-10-genap.json
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "PAI dan BP Kelas 10 Semester Genap",
|
| 3 |
+
"description": "Pendidikan Agama Islam dan Budi Pekerti Kelas 10 Semester Genap",
|
| 4 |
+
"questions": [
|
| 5 |
+
{
|
| 6 |
+
"type": "DASAR",
|
| 7 |
+
"text": "Perbuatan zina termasuk dosa besar yang dilarang dalam Al-Qur'an, tepatnya dalam surah …",
|
| 8 |
+
"points": 10,
|
| 9 |
+
"options": [
|
| 10 |
+
"Al-Fatihah",
|
| 11 |
+
"Al-Isra'",
|
| 12 |
+
"Al-Kahfi",
|
| 13 |
+
"Al-Ma'un"
|
| 14 |
+
],
|
| 15 |
+
"answerKey": "Al-Isra'"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"type": "DASAR",
|
| 19 |
+
"text": "Berdasarkan Q.S. an-Nur/24: 2, jumlah hukuman dera (cambuk) yang wajib diterima oleh setiap pelaku zina adalah …",
|
| 20 |
+
"points": 10,
|
| 21 |
+
"options": [
|
| 22 |
+
"40 kali",
|
| 23 |
+
"60 kali",
|
| 24 |
+
"80 kali",
|
| 25 |
+
"100 kali"
|
| 26 |
+
],
|
| 27 |
+
"answerKey": "100 kali"
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"type": "DASAR",
|
| 31 |
+
"text": "Dalam Islam, mendekati zina saja sudah dilarang. Larangan tersebut terdapat dalam Q.S. Al-Isra ayat …",
|
| 32 |
+
"points": 10,
|
| 33 |
+
"options": [
|
| 34 |
+
"17",
|
| 35 |
+
"23",
|
| 36 |
+
"32",
|
| 37 |
+
"40"
|
| 38 |
+
],
|
| 39 |
+
"answerKey": "32"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"type": "DASAR",
|
| 43 |
+
"text": "Perbuatan zina yang dilakukan oleh laki-laki dan perempuan yang sudah pernah menikah disebut …",
|
| 44 |
+
"points": 10,
|
| 45 |
+
"options": [
|
| 46 |
+
"Zina ghairu muhsan",
|
| 47 |
+
"Zina qadf",
|
| 48 |
+
"Zina muhsan",
|
| 49 |
+
"Zina li'an"
|
| 50 |
+
],
|
| 51 |
+
"answerKey": "Zina muhsan"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"type": "DASAR",
|
| 55 |
+
"text": "Jumlah minimal saksi yang dibutuhkan untuk membuktikan tindak pidana zina dalam hukum Islam adalah …",
|
| 56 |
+
"points": 10,
|
| 57 |
+
"options": [
|
| 58 |
+
"1 orang",
|
| 59 |
+
"2 orang",
|
| 60 |
+
"3 orang",
|
| 61 |
+
"4 orang"
|
| 62 |
+
],
|
| 63 |
+
"answerKey": "4 orang"
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"type": "DASAR",
|
| 67 |
+
"text": "Sikap menyerahkan segala hasil usaha kepada Allah Swt. disebut …",
|
| 68 |
+
"points": 10,
|
| 69 |
+
"options": [
|
| 70 |
+
"Ikhtiar",
|
| 71 |
+
"Tawakal",
|
| 72 |
+
"Sabar",
|
| 73 |
+
"Syukur"
|
| 74 |
+
],
|
| 75 |
+
"answerKey": "Tawakal"
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"type": "DASAR",
|
| 79 |
+
"text": "Raja' berarti … kepada Allah Swt.",
|
| 80 |
+
"points": 10,
|
| 81 |
+
"options": [
|
| 82 |
+
"Takut",
|
| 83 |
+
"Marah",
|
| 84 |
+
"Berharap",
|
| 85 |
+
"Lalai"
|
| 86 |
+
],
|
| 87 |
+
"answerKey": "Berharap"
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"type": "DASAR",
|
| 91 |
+
"text": "Sikap khauf artinya …",
|
| 92 |
+
"points": 10,
|
| 93 |
+
"options": [
|
| 94 |
+
"Cinta",
|
| 95 |
+
"Takut",
|
| 96 |
+
"Senang",
|
| 97 |
+
"Ikhlas"
|
| 98 |
+
],
|
| 99 |
+
"answerKey": "Takut"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"type": "DASAR",
|
| 103 |
+
"text": "Cinta kepada Allah Swt. yang berarti menempatkan Allah di dalam hati sanubari disebut …",
|
| 104 |
+
"points": 10,
|
| 105 |
+
"options": [
|
| 106 |
+
"Khaufullah",
|
| 107 |
+
"Raja'ullah",
|
| 108 |
+
"Mahabbatullah",
|
| 109 |
+
"Tawakalullah"
|
| 110 |
+
],
|
| 111 |
+
"answerKey": "Mahabbatullah"
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"type": "DASAR",
|
| 115 |
+
"text": "Tawakal secara istilah artinya menyerahkan segala permasalahan kepada Allah Swt. setelah …",
|
| 116 |
+
"points": 10,
|
| 117 |
+
"options": [
|
| 118 |
+
"Berdoa saja tanpa usaha",
|
| 119 |
+
"Melakukan usaha sekuat tenaga (ikhtiar)",
|
| 120 |
+
"Meminta pendapat orang banyak",
|
| 121 |
+
"Merenungkan kebesaran Allah"
|
| 122 |
+
],
|
| 123 |
+
"answerKey": "Melakukan usaha sekuat tenaga (ikhtiar)"
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"type": "DASAR",
|
| 127 |
+
"text": "Contoh akhlak mahmudah adalah …",
|
| 128 |
+
"points": 10,
|
| 129 |
+
"options": [
|
| 130 |
+
"Suudzon",
|
| 131 |
+
"Ghadhab",
|
| 132 |
+
"Tawadhu",
|
| 133 |
+
"Khianat"
|
| 134 |
+
],
|
| 135 |
+
"answerKey": "Tawadhu"
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"type": "DASAR",
|
| 139 |
+
"text": "Sikap berprasangka buruk kepada orang lain tanpa bukti disebut …",
|
| 140 |
+
"points": 10,
|
| 141 |
+
"options": [
|
| 142 |
+
"Amanah",
|
| 143 |
+
"Suudzon",
|
| 144 |
+
"Tawadhu",
|
| 145 |
+
"Ikhlas"
|
| 146 |
+
],
|
| 147 |
+
"answerKey": "Suudzon"
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"type": "DASAR",
|
| 151 |
+
"text": "Contoh perilaku ghadab adalah …",
|
| 152 |
+
"points": 10,
|
| 153 |
+
"options": [
|
| 154 |
+
"Menolong teman yang kesusahan",
|
| 155 |
+
"Menahan emosi saat diejek",
|
| 156 |
+
"Marah berlebihan hingga menyakiti orang lain",
|
| 157 |
+
"Menghormati orang tua"
|
| 158 |
+
],
|
| 159 |
+
"answerKey": "Marah berlebihan hingga menyakiti orang lain"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"type": "DASAR",
|
| 163 |
+
"text": "Surah Al-Qur'an yang memuat perintah untuk menahan amarah dan berbuat kebaikan adalah …",
|
| 164 |
+
"points": 10,
|
| 165 |
+
"options": [
|
| 166 |
+
"Q.S. al-Baqarah/2: 133-134",
|
| 167 |
+
"Q.S. Ali Imran/3: 133-134",
|
| 168 |
+
"Q.S. an-Nisa/4: 133-134",
|
| 169 |
+
"Q.S. al-Maidah/5: 133-134"
|
| 170 |
+
],
|
| 171 |
+
"answerKey": "Q.S. Ali Imran/3: 133-134"
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"type": "DASAR",
|
| 175 |
+
"text": "Orang yang tidak menjaga titipan atau janji termasuk perilaku …",
|
| 176 |
+
"points": 10,
|
| 177 |
+
"options": [
|
| 178 |
+
"Khianat",
|
| 179 |
+
"Syukur",
|
| 180 |
+
"Qanaah",
|
| 181 |
+
"Sabar"
|
| 182 |
+
],
|
| 183 |
+
"answerKey": "Khianat"
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"type": "DASAR",
|
| 187 |
+
"text": "Al-Kulliyatul Khamsah berarti …",
|
| 188 |
+
"points": 10,
|
| 189 |
+
"options": [
|
| 190 |
+
"Lima rukun Islam",
|
| 191 |
+
"Lima prinsip dasar perlindungan dalam Islam",
|
| 192 |
+
"Lima waktu salat",
|
| 193 |
+
"Lima kitab Allah"
|
| 194 |
+
],
|
| 195 |
+
"answerKey": "Lima prinsip dasar perlindungan dalam Islam"
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"type": "DASAR",
|
| 199 |
+
"text": "Menjaga agama dalam Al-Kulliyatul Khamsah disebut …",
|
| 200 |
+
"points": 10,
|
| 201 |
+
"options": [
|
| 202 |
+
"Hifzun nafs",
|
| 203 |
+
"Hifzul maal",
|
| 204 |
+
"Hifzud diin",
|
| 205 |
+
"Hifzul aql"
|
| 206 |
+
],
|
| 207 |
+
"answerKey": "Hifzud diin"
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"type": "DASAR",
|
| 211 |
+
"text": "Larangan minuman keras bertujuan menjaga …",
|
| 212 |
+
"points": 10,
|
| 213 |
+
"options": [
|
| 214 |
+
"Harta",
|
| 215 |
+
"Jiwa",
|
| 216 |
+
"Akal",
|
| 217 |
+
"Keturunan"
|
| 218 |
+
],
|
| 219 |
+
"answerKey": "Akal"
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"type": "DASAR",
|
| 223 |
+
"text": "Tujuan utama disyariatkannya hukum Islam (maqashid al-syari'ah) adalah …",
|
| 224 |
+
"points": 10,
|
| 225 |
+
"options": [
|
| 226 |
+
"Menegakkan kekuasaan para ulama",
|
| 227 |
+
"Membatasi kebebasan individu",
|
| 228 |
+
"Mewujudkan kemaslahatan kehidupan manusia",
|
| 229 |
+
"Menyebarkan ajaran Islam ke seluruh dunia"
|
| 230 |
+
],
|
| 231 |
+
"answerKey": "Mewujudkan kemaslahatan kehidupan manusia"
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"type": "DASAR",
|
| 235 |
+
"text": "Menjaga keturunan dalam Islam disebut …",
|
| 236 |
+
"points": 10,
|
| 237 |
+
"options": [
|
| 238 |
+
"Hifzun nafs",
|
| 239 |
+
"Hifzul aql",
|
| 240 |
+
"Hifzun nasl",
|
| 241 |
+
"Hifzul maal"
|
| 242 |
+
],
|
| 243 |
+
"answerKey": "Hifzun nasl"
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"type": "DASAR",
|
| 247 |
+
"text": "Tokoh penyebar Islam di Pulau Jawa dikenal dengan sebutan …",
|
| 248 |
+
"points": 10,
|
| 249 |
+
"options": [
|
| 250 |
+
"Khulafaur Rasyidin",
|
| 251 |
+
"Ulul Azmi",
|
| 252 |
+
"Wali Songo",
|
| 253 |
+
"Muhajirin"
|
| 254 |
+
],
|
| 255 |
+
"answerKey": "Wali Songo"
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"type": "DASAR",
|
| 259 |
+
"text": "Salah satu metode dakwah Wali Songo adalah melalui …",
|
| 260 |
+
"points": 10,
|
| 261 |
+
"options": [
|
| 262 |
+
"Kekerasan",
|
| 263 |
+
"Peperangan",
|
| 264 |
+
"Kesenian dan budaya",
|
| 265 |
+
"Ancaman"
|
| 266 |
+
],
|
| 267 |
+
"answerKey": "Kesenian dan budaya"
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"type": "DASAR",
|
| 271 |
+
"text": "Sunan Kalijaga terkenal berdakwah menggunakan media …",
|
| 272 |
+
"points": 10,
|
| 273 |
+
"options": [
|
| 274 |
+
"Wayang",
|
| 275 |
+
"Perdagangan",
|
| 276 |
+
"Pertanian",
|
| 277 |
+
"Kedokteran"
|
| 278 |
+
],
|
| 279 |
+
"answerKey": "Wayang"
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"type": "DASAR",
|
| 283 |
+
"text": "Wali Songo menyebarkan Islam di wilayah …",
|
| 284 |
+
"points": 10,
|
| 285 |
+
"options": [
|
| 286 |
+
"Sumatra",
|
| 287 |
+
"Kalimantan",
|
| 288 |
+
"Jawa",
|
| 289 |
+
"Papua"
|
| 290 |
+
],
|
| 291 |
+
"answerKey": "Jawa"
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"type": "DASAR",
|
| 295 |
+
"text": "Strategi dakwah Wali Songo yang berarti 'bertahap' dan tidak memberlakukan ajaran Islam secara mendadak disebut …",
|
| 296 |
+
"points": 10,
|
| 297 |
+
"options": [
|
| 298 |
+
"'Adamul Haraj",
|
| 299 |
+
"Mujadalah",
|
| 300 |
+
"Bi al-hikmah",
|
| 301 |
+
"Tadrij"
|
| 302 |
+
],
|
| 303 |
+
"answerKey": "Tadrij"
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"type": "DASAR",
|
| 307 |
+
"text": "Hukuman untuk pelaku zina ghairu muhsan (yang belum pernah menikah) adalah rajam hingga meninggal dunia.",
|
| 308 |
+
"points": 5,
|
| 309 |
+
"options": [
|
| 310 |
+
"Benar",
|
| 311 |
+
"Salah"
|
| 312 |
+
],
|
| 313 |
+
"answerKey": "Salah"
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"type": "DASAR",
|
| 317 |
+
"text": "Menjaga pergaulan termasuk cara melindungi harkat dan martabat manusia.",
|
| 318 |
+
"points": 5,
|
| 319 |
+
"options": [
|
| 320 |
+
"Benar",
|
| 321 |
+
"Salah"
|
| 322 |
+
],
|
| 323 |
+
"answerKey": "Benar"
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"type": "DASAR",
|
| 327 |
+
"text": "Mahabbatullah merupakan tingkatan cinta tertinggi dan hakiki, dan cinta ini merupakan unsur terpenting dalam ibadah di samping khauf dan raja'.",
|
| 328 |
+
"points": 5,
|
| 329 |
+
"options": [
|
| 330 |
+
"Benar",
|
| 331 |
+
"Salah"
|
| 332 |
+
],
|
| 333 |
+
"answerKey": "Benar"
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"type": "DASAR",
|
| 337 |
+
"text": "Tawakal berarti menyerahkan semua urusan sepenuhnya kepada Allah Swt. tanpa perlu melakukan ikhtiar atau usaha apapun terlebih dahulu.",
|
| 338 |
+
"points": 5,
|
| 339 |
+
"options": [
|
| 340 |
+
"Benar",
|
| 341 |
+
"Salah"
|
| 342 |
+
],
|
| 343 |
+
"answerKey": "Salah"
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"type": "DASAR",
|
| 347 |
+
"text": "Sifat ghadhab termasuk dalam akhlak mahmudah yang dianjurkan dan dicontohkan oleh Rasulullah Saw.",
|
| 348 |
+
"points": 5,
|
| 349 |
+
"options": [
|
| 350 |
+
"Benar",
|
| 351 |
+
"Salah"
|
| 352 |
+
],
|
| 353 |
+
"answerKey": "Salah"
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"type": "DASAR",
|
| 357 |
+
"text": "Akhlak mahmudah adalah akhlak terpuji yang harus dibiasakan dalam kehidupan sehari-hari, sedangkan akhlak madzmumah adalah akhlak tercela yang harus dihindari.",
|
| 358 |
+
"points": 5,
|
| 359 |
+
"options": [
|
| 360 |
+
"Benar",
|
| 361 |
+
"Salah"
|
| 362 |
+
],
|
| 363 |
+
"answerKey": "Benar"
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"type": "DASAR",
|
| 367 |
+
"text": "Dalam ushul fiqih, al-kulliyatul al-khamsah juga disebut maqashid al-khamsah atau al-dharuriyyat al-khamsah.",
|
| 368 |
+
"points": 5,
|
| 369 |
+
"options": [
|
| 370 |
+
"Benar",
|
| 371 |
+
"Salah"
|
| 372 |
+
],
|
| 373 |
+
"answerKey": "Benar"
|
| 374 |
+
},
|
| 375 |
+
{
|
| 376 |
+
"type": "DASAR",
|
| 377 |
+
"text": "Al-Kulliyatul Khamsah tidak berkaitan dengan kehidupan sehari-hari.",
|
| 378 |
+
"points": 5,
|
| 379 |
+
"options": [
|
| 380 |
+
"Benar",
|
| 381 |
+
"Salah"
|
| 382 |
+
],
|
| 383 |
+
"answerKey": "Salah"
|
| 384 |
+
},
|
| 385 |
+
{
|
| 386 |
+
"type": "DASAR",
|
| 387 |
+
"text": "Wali Songo menyebarkan Islam di Nusantara dengan cara-cara kekerasan dan paksaan agar masyarakat mau memeluk Islam secara cepat.",
|
| 388 |
+
"points": 5,
|
| 389 |
+
"options": [
|
| 390 |
+
"Benar",
|
| 391 |
+
"Salah"
|
| 392 |
+
],
|
| 393 |
+
"answerKey": "Salah"
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"type": "DASAR",
|
| 397 |
+
"text": "Strategi dakwah 'Adamul Haraj yang diterapkan Wali Songo berarti tidak mengusik atau menyakiti tradisi asli masyarakat Nusantara dalam penyebaran Islam.",
|
| 398 |
+
"points": 5,
|
| 399 |
+
"options": [
|
| 400 |
+
"Benar",
|
| 401 |
+
"Salah"
|
| 402 |
+
],
|
| 403 |
+
"answerKey": "Benar"
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
"type": "PEMAHAMAN",
|
| 407 |
+
"text": "Zina yang dilakukan oleh laki-laki atau perempuan yang belum pernah menikah disebut zina ...",
|
| 408 |
+
"points": 20,
|
| 409 |
+
"answerKey": "Ghairu Muhsan"
|
| 410 |
+
},
|
| 411 |
+
{
|
| 412 |
+
"type": "PEMAHAMAN",
|
| 413 |
+
"text": "Dalam Q.S. al-Isra'/17:32, zina disebut sebagai perbuatan yang ... dan jalan yang buruk (sa'a sabilan).",
|
| 414 |
+
"points": 20,
|
| 415 |
+
"answerKey": "Keji (Fahisyah)"
|
| 416 |
+
},
|
| 417 |
+
{
|
| 418 |
+
"type": "PEMAHAMAN",
|
| 419 |
+
"text": "Menurut Q.S. an-Nur/24:2, hukuman dera bagi setiap pelaku zina (laki-laki maupun perempuan) adalah sebanyak ... kali.",
|
| 420 |
+
"points": 20,
|
| 421 |
+
"answerKey": "100 kali"
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"type": "PEMAHAMAN",
|
| 425 |
+
"text": "Hukuman bagi pelaku zina muhsan yang sudah terbukti adalah hukuman ..., yaitu dilempari batu sampai meninggal dunia.",
|
| 426 |
+
"points": 20,
|
| 427 |
+
"answerKey": "Rajam"
|
| 428 |
+
},
|
| 429 |
+
{
|
| 430 |
+
"type": "PEMAHAMAN",
|
| 431 |
+
"text": "Menurut Imam Sayuti, salah satu dampak buruk perbuatan zina di dunia selain kehilangan kewibawaan dan kefakiran adalah ...",
|
| 432 |
+
"points": 20,
|
| 433 |
+
"answerKey": "Memperpendek umur"
|
| 434 |
+
},
|
| 435 |
+
{
|
| 436 |
+
"type": "PEMAHAMAN",
|
| 437 |
+
"text": "Dalam fikih, perbuatan menuduh orang lain berzina tanpa menghadirkan empat saksi disebut ...",
|
| 438 |
+
"points": 20,
|
| 439 |
+
"answerKey": "Qadf (Qadzf)"
|
| 440 |
+
},
|
| 441 |
+
{
|
| 442 |
+
"type": "PEMAHAMAN",
|
| 443 |
+
"text": "Rasa takut seorang hamba kepada Allah Swt. atas dosa yang diperbuat dan azab-Nya, dalam istilah akidah Islam disebut ...",
|
| 444 |
+
"points": 20,
|
| 445 |
+
"answerKey": "Khauf"
|
| 446 |
+
},
|
| 447 |
+
{
|
| 448 |
+
"type": "PEMAHAMAN",
|
| 449 |
+
"text": "Sikap penuh harap dan optimis terhadap rahmat serta ampunan Allah Swt. dalam terminologi akidah Islam disebut ...",
|
| 450 |
+
"points": 20,
|
| 451 |
+
"answerKey": "Raja'"
|
| 452 |
+
},
|
| 453 |
+
{
|
| 454 |
+
"type": "PEMAHAMAN",
|
| 455 |
+
"text": "Menyerahkan segala hasil usaha kepada Allah Swt. setelah berikhtiar dengan sungguh-sungguh disebut ...",
|
| 456 |
+
"points": 20,
|
| 457 |
+
"answerKey": "Tawakal"
|
| 458 |
+
},
|
| 459 |
+
{
|
| 460 |
+
"type": "PEMAHAMAN",
|
| 461 |
+
"text": "Menurut Q.S. Ali Imran/3:31, tanda seseorang mencintai Allah Swt. adalah dengan mengikuti dan meneladani ...",
|
| 462 |
+
"points": 20,
|
| 463 |
+
"answerKey": "Rasulullah SAW"
|
| 464 |
+
},
|
| 465 |
+
{
|
| 466 |
+
"type": "PEMAHAMAN",
|
| 467 |
+
"text": "Khauf dan raja' harus seimbang. Jika raja' berlebihan tanpa khauf, seseorang bisa terjatuh dalam sikap ...",
|
| 468 |
+
"points": 20,
|
| 469 |
+
"answerKey": "Merasa aman dari azab Allah (lalai)"
|
| 470 |
+
},
|
| 471 |
+
{
|
| 472 |
+
"type": "PEMAHAMAN",
|
| 473 |
+
"text": "Tawakal yang benar dalam Islam bukan berarti berdiam diri, melainkan harus disertai dengan ...",
|
| 474 |
+
"points": 20,
|
| 475 |
+
"answerKey": "Ikhtiar (usaha/bekerja keras)"
|
| 476 |
+
},
|
| 477 |
+
{
|
| 478 |
+
"type": "PEMAHAMAN",
|
| 479 |
+
"text": "Akhlak yang buruk, tercela, dan harus dihindari oleh seorang Muslim disebut akhlak ...",
|
| 480 |
+
"points": 20,
|
| 481 |
+
"answerKey": "Madzmumah"
|
| 482 |
+
},
|
| 483 |
+
{
|
| 484 |
+
"type": "PEMAHAMAN",
|
| 485 |
+
"text": "Akhlak yang baik, terpuji, dan harus dibiasakan dalam kehidupan sehari-hari disebut akhlak ...",
|
| 486 |
+
"points": 20,
|
| 487 |
+
"answerKey": "Mahmudah"
|
| 488 |
+
},
|
| 489 |
+
{
|
| 490 |
+
"type": "PEMAHAMAN",
|
| 491 |
+
"text": "Prasangka buruk kepada orang lain disebut ...",
|
| 492 |
+
"points": 20,
|
| 493 |
+
"answerKey": "Suudzon"
|
| 494 |
+
},
|
| 495 |
+
{
|
| 496 |
+
"type": "PEMAHAMAN",
|
| 497 |
+
"text": "Sikap tidak dapat dipercaya dan mengingkari amanah disebut ...",
|
| 498 |
+
"points": 20,
|
| 499 |
+
"answerKey": "Khianat"
|
| 500 |
+
},
|
| 501 |
+
{
|
| 502 |
+
"type": "PEMAHAMAN",
|
| 503 |
+
"text": "Mengambil hak orang lain termasuk perilaku ...",
|
| 504 |
+
"points": 20,
|
| 505 |
+
"answerKey": "Zalim"
|
| 506 |
+
},
|
| 507 |
+
{
|
| 508 |
+
"type": "PEMAHAMAN",
|
| 509 |
+
"text": "Menahan amarah merupakan salah satu bentuk akhlak …",
|
| 510 |
+
"points": 20,
|
| 511 |
+
"answerKey": "Mahmudah"
|
| 512 |
+
},
|
| 513 |
+
{
|
| 514 |
+
"type": "PEMAHAMAN",
|
| 515 |
+
"text": "Al-Kulliyatul Khamsah adalah lima pokok kemaslahatan dalam Islam. Hifzun nafs berarti kewajiban menjaga ...",
|
| 516 |
+
"points": 20,
|
| 517 |
+
"answerKey": "Jiwa (nyawa)"
|
| 518 |
+
},
|
| 519 |
+
{
|
| 520 |
+
"type": "PEMAHAMAN",
|
| 521 |
+
"text": "Salah satu dari al-Kulliyatul Khamsah adalah hifzul 'aql, yaitu kewajiban menjaga ... yang membedakan manusia dari makhluk lain.",
|
| 522 |
+
"points": 20,
|
| 523 |
+
"answerKey": "Akal"
|
| 524 |
+
},
|
| 525 |
+
{
|
| 526 |
+
"type": "PEMAHAMAN",
|
| 527 |
+
"text": "Kewajiban menjaga keturunan (hifzun nasl) menjadi dasar diharamkannya perbuatan ...",
|
| 528 |
+
"points": 20,
|
| 529 |
+
"answerKey": "Zina"
|
| 530 |
+
},
|
| 531 |
+
{
|
| 532 |
+
"type": "PEMAHAMAN",
|
| 533 |
+
"text": "Menjaga harta (hifzul mal) diwujudkan antara lain dengan diharamkannya mencuri, merampok, dan ...",
|
| 534 |
+
"points": 20,
|
| 535 |
+
"answerKey": "Riba"
|
| 536 |
+
},
|
| 537 |
+
{
|
| 538 |
+
"type": "PEMAHAMAN",
|
| 539 |
+
"text": "Salah satu pokok dari al-Kulliyatul Khamsah merupakan Hifzud din, yaitu menjaga ...",
|
| 540 |
+
"points": 20,
|
| 541 |
+
"answerKey": "Agama"
|
| 542 |
+
},
|
| 543 |
+
{
|
| 544 |
+
"type": "PEMAHAMAN",
|
| 545 |
+
"text": "Al-Kulliyatul Khamsah dikenal juga sebagai Al-Maqashid al-khamsah (Maqashid al-syari'ah) yang berarti ...",
|
| 546 |
+
"points": 20,
|
| 547 |
+
"answerKey": "Tujuan-tujuan pokok syariat Islam"
|
| 548 |
+
},
|
| 549 |
+
{
|
| 550 |
+
"type": "PEMAHAMAN",
|
| 551 |
+
"text": "Wali Songo yang dikenal sebagai tokoh penyebar Islam pertama di tanah Jawa dan berkedudukan di Gresik adalah ...",
|
| 552 |
+
"points": 20,
|
| 553 |
+
"answerKey": "Maulana Malik Ibrahim (Sunan Gresik)"
|
| 554 |
+
},
|
| 555 |
+
{
|
| 556 |
+
"type": "PEMAHAMAN",
|
| 557 |
+
"text": "Sunan Kalijaga berdakwah menggunakan pertunjukan dengan memasukkan nilai-nilai Islam di dalamnya. Pertunjukan kesenian yang digunakan Sunan Kalijaga tersebut yaitu …",
|
| 558 |
+
"points": 20,
|
| 559 |
+
"answerKey": "Wayang"
|
| 560 |
+
},
|
| 561 |
+
{
|
| 562 |
+
"type": "PEMAHAMAN",
|
| 563 |
+
"text": "Sunan Ampel (Raden Rahmat) mendirikan pesantren yang menjadi pusat pendidikan Islam awal di Jawa Timur. Pesantren tersebut berada di daerah ...",
|
| 564 |
+
"points": 20,
|
| 565 |
+
"answerKey": "Ampel Denta (Surabaya)"
|
| 566 |
+
},
|
| 567 |
+
{
|
| 568 |
+
"type": "PEMAHAMAN",
|
| 569 |
+
"text": "Metode dakwah Wali Songo yang menggunakan pendekatan kebudayaan lokal secara bijaksana disebut dakwah ...",
|
| 570 |
+
"points": 20,
|
| 571 |
+
"answerKey": "Bil hikmah (kultural/akulturasi)"
|
| 572 |
+
},
|
| 573 |
+
{
|
| 574 |
+
"type": "PEMAHAMAN",
|
| 575 |
+
"text": "Sunan Muria dikenal berdakwah di kalangan rakyat jelata menggunakan seni yang disesuaikan dengan pesan-pesan keislaman. Kesenian yang digunakan oleh Sunan Muria adalah ...",
|
| 576 |
+
"points": 20,
|
| 577 |
+
"answerKey": "Tembang (macapat), gamelan, wayang"
|
| 578 |
+
},
|
| 579 |
+
{
|
| 580 |
+
"type": "PEMAHAMAN",
|
| 581 |
+
"text": "Sunan Kudus menunjukkan toleransi budaya dengan membangun masjid yang menaranya menyerupai ... sebagai bentuk akulturasi Islam dengan budaya Hindu.",
|
| 582 |
+
"points": 20,
|
| 583 |
+
"answerKey": "Candi (arsitektur Hindu-Jawa)"
|
| 584 |
+
},
|
| 585 |
+
{
|
| 586 |
+
"type": "TANTANGAN",
|
| 587 |
+
"text": "Sebutkan ayat Al-Qur'an yang menjadi dalil larangan mendekati perbuatan zina beserta nama suratnya!",
|
| 588 |
+
"points": 30,
|
| 589 |
+
"answerKey": "Q.S. al-Isra'/17: 32 — larangan mendekati zina dan menyebutnya sebagai perbuatan keji dan jalan yang buruk. Q.S. an-Nur/24: 2 — ayat tentang hukuman bagi pezina (100 kali cambukan)."
|
| 590 |
+
},
|
| 591 |
+
{
|
| 592 |
+
"type": "TANTANGAN",
|
| 593 |
+
"text": "Jelaskan mengapa Islam menggunakan kata 'jangan mendekati zina' bukan langsung 'jangan berzina' dalam Q.S. al-Isra': 32!",
|
| 594 |
+
"points": 30,
|
| 595 |
+
"answerKey": "Untuk mencegah dari akar masalahnya. Zina diawali oleh pandangan, kemudian pikiran, lalu perbuatan. Menjauhi yang mendekatinya berarti memutus rantai tersebut sebelum sampai pada perbuatan zina."
|
| 596 |
+
},
|
| 597 |
+
{
|
| 598 |
+
"type": "TANTANGAN",
|
| 599 |
+
"text": "Sebutkan minimal lima dampak buruk (bahaya) dari perbuatan zina bagi individu dan masyarakat!",
|
| 600 |
+
"points": 30,
|
| 601 |
+
"answerKey": "Merusak harkat dan martabat manusia, menghancurkan institusi keluarga, menimbulkan penyakit menular seksual (HIV/AIDS, dsb.), lahirnya anak tanpa kejelasan nasab/silsilah keturunan, merusak moral dan tatanan sosial masyarakat, mendapat dosa besar dan azab dari Allah Swt, dikucilkan dari lingkungan sosial / aib keluarga."
|
| 602 |
+
},
|
| 603 |
+
{
|
| 604 |
+
"type": "TANTANGAN",
|
| 605 |
+
"text": "Jelaskan cara yang dapat dilakukan oleh seorang remaja muslim untuk menghindari pergaulan bebas di era digital!",
|
| 606 |
+
"points": 30,
|
| 607 |
+
"answerKey": "Menjaga pandangan (tidak mengakses konten negatif di media sosial/internet), memilih teman bergaul yang baik dan berakhlak mulia, mengisi waktu dengan kegiatan positif (mengaji, olahraga, organisasi), memperkuat iman dengan shalat, puasa, dan ibadah lainnya, terbuka kepada orang tua tentang pergaulan, menghindari tempat-tempat yang berpotensi menimbulkan kemaksiatan."
|
| 608 |
+
},
|
| 609 |
+
{
|
| 610 |
+
"type": "TANTANGAN",
|
| 611 |
+
"text": "Bacakan dengan lantang ayat Al-Qur'an yang melarang mendekati zina!",
|
| 612 |
+
"points": 30,
|
| 613 |
+
"answerKey": "Siswa membacakan QS. Al-Isra': 32"
|
| 614 |
+
},
|
| 615 |
+
{
|
| 616 |
+
"type": "TANTANGAN",
|
| 617 |
+
"text": "Jelaskan apa yang dimaksud dengan khauf dan raja' dalam ajaran Islam serta hubungan antara keduanya!",
|
| 618 |
+
"points": 30,
|
| 619 |
+
"answerKey": "Khauf adalah rasa takut kepada Allah SWT, dan Raja' adalah rasa harap kepada Allah SWT. Keduanya harus seimbang. Khauf tanpa raja' menimbulkan putus asa, sedangkan raja' tanpa khauf menimbulkan keberanian berbuat dosa."
|
| 620 |
+
},
|
| 621 |
+
{
|
| 622 |
+
"type": "TANTANGAN",
|
| 623 |
+
"text": "Bagaimana cara menerapkan Tawakal dalam kehidupan sehari-hari!",
|
| 624 |
+
"points": 30,
|
| 625 |
+
"answerKey": "Belajar sungguh-sungguh sebelum ujian, lalu berdoa dan menyerahkan hasilnya kepada Allah. Berikhtiar mencari rezeki dengan cara halal, lalu bertawakal atas hasilnya. Tidak panik berlebihan saat menghadapi masalah, karena yakin Allah Maha Mengetahui yang terbaik."
|
| 626 |
+
},
|
| 627 |
+
{
|
| 628 |
+
"type": "TANTANGAN",
|
| 629 |
+
"text": "Sebutkan tanda-tanda atau ciri-ciri seseorang yang benar-benar mencintai Allah Swt.!",
|
| 630 |
+
"points": 30,
|
| 631 |
+
"answerKey": "Mengikuti dan meneladani Rasulullah Saw. dalam segala aspek kehidupan, lebih mencintai Allah daripada segala sesuatu selain-Nya, rajin beribadah dan merasa rindu saat jauh dari ibadah, merasa tenang dan bahagia saat berdzikir dan mengingat Allah, rela berkorban di jalan Allah, bersabar dalam ujian dan bersyukur atas nikmat, mencintai apa yang dicintai Allah dan membenci apa yang dibenci Allah."
|
| 632 |
+
},
|
| 633 |
+
{
|
| 634 |
+
"type": "TANTANGAN",
|
| 635 |
+
"text": "Apa perbedaan antara mencintai Allah dan takut kepada Allah?",
|
| 636 |
+
"points": 30,
|
| 637 |
+
"answerKey": "Mencintai Allah (mahabbah): dorongan positif beribadah karena cinta, rindu, dan rasa syukur kepada Allah; ibadah terasa menyenangkan dan mengalir dengan ikhlas. Takut kepada Allah (khauf): dorongan dari kesadaran akan keagungan Allah dan rasa takut akan azab-Nya; mendorong seseorang untuk menjauhi maksiat."
|
| 638 |
+
},
|
| 639 |
+
{
|
| 640 |
+
"type": "TANTANGAN",
|
| 641 |
+
"text": "Berikan contoh nyata dalam kehidupan sehari-hari seorang pelajar yang menerapkan sikap raja' (berharap kepada Allah)!",
|
| 642 |
+
"points": 30,
|
| 643 |
+
"answerKey": "Seorang pelajar yang nilainya jelek tidak putus asa, tetapi tetap berdoa dan belajar lebih keras karena yakin Allah dapat mengubah keadaannya. Seorang pelajar yang pernah berbuat salah tidak merasa sudah 'terlalu kotor' untuk bertobat — ia segera istighfar dan memperbaiki diri karena berharap rahmat Allah. Tetap bersemangat meraih cita-cita meski menghadapi banyak rintangan, karena yakin Allah memiliki rencana terbaik."
|
| 644 |
+
},
|
| 645 |
+
{
|
| 646 |
+
"type": "TANTANGAN",
|
| 647 |
+
"text": "Apa dampak buruk ghadhab (marah yang berlebihan) bagi diri sendiri maupun orang lain!",
|
| 648 |
+
"points": 30,
|
| 649 |
+
"answerKey": "Dampak bagi diri sendiri: merusak kesehatan (tekanan darah tinggi, stres), menyesal setelah mengeluarkan kata-kata kasar, hilangnya ketenangan batin. Dampak bagi orang lain: menyakiti perasaan orang di sekitarnya, merusak hubungan pertemanan/keluarga, menimbulkan permusuhan dan konflik berkepanjangan."
|
| 650 |
+
},
|
| 651 |
+
{
|
| 652 |
+
"type": "TANTANGAN",
|
| 653 |
+
"text": "Sebutkan dampak buruk sifat suudzon terhadap hubungan pertemanan di sekolah!",
|
| 654 |
+
"points": 30,
|
| 655 |
+
"answerKey": "Menimbulkan permusuhan, hilangnya kepercayaan, suasana tidak nyaman, dan memicu konflik."
|
| 656 |
+
},
|
| 657 |
+
{
|
| 658 |
+
"type": "TANTANGAN",
|
| 659 |
+
"text": "Bacakan potongan ayat atau hadis yang mengajarkan untuk menjauhi prasangka buruk!",
|
| 660 |
+
"points": 30,
|
| 661 |
+
"answerKey": "Q.S. Al-Hujurat/49: 12 — perintah menjauhi kebanyakan prasangka buruk karena sebagian dari prasangka itu dosa. HR. Al-Bukhari & Muslim — peringatan bahwa prasangka buruk adalah sedusta-dusta ucapan."
|
| 662 |
+
},
|
| 663 |
+
{
|
| 664 |
+
"type": "TANTANGAN",
|
| 665 |
+
"text": "Sebutkan contoh perilaku khianat yang sering terjadi di lingkungan sekolah, lalu jelaskan cara menghindarinya!",
|
| 666 |
+
"points": 30,
|
| 667 |
+
"answerKey": "Contoh: berbohong, tidak menjaga amanah, membocorkan rahasia teman, mencontek. Cara menghindarinya: dengan jujur dan bertanggung jawab."
|
| 668 |
+
},
|
| 669 |
+
{
|
| 670 |
+
"type": "TANTANGAN",
|
| 671 |
+
"text": "Jelaskan perbedaan antara suudzon dan husnudzon!",
|
| 672 |
+
"points": 30,
|
| 673 |
+
"answerKey": "Husnudzon adalah berbaik sangka (positif), sedangkan suudzon adalah berburuk sangka (negatif)."
|
| 674 |
+
},
|
| 675 |
+
{
|
| 676 |
+
"type": "TANTANGAN",
|
| 677 |
+
"text": "Sebutkan lima prinsip dasar hukum Islam (al-kulliyatu al-khamsah) beserta artinya!",
|
| 678 |
+
"points": 30,
|
| 679 |
+
"answerKey": "Hifzhu al-din (Menjaga/memelihara agama), Hifzhu al-nafs (Menjaga/memelihara jiwa/nyawa), Hifzhu al-'aql (Menjaga/memelihara akal pikiran), Hifzhu al-nasl (Menjaga/memelihara keturunan/kehormatan), Hifzhu al-mal (Menjaga/memelihara harta benda)."
|
| 680 |
+
},
|
| 681 |
+
{
|
| 682 |
+
"type": "TANTANGAN",
|
| 683 |
+
"text": "Jelaskan kenapa meminum minuman keras dilarang dalam Islam, dan kaitannya dengan salah satu prinsip al-kulliyatu al-khamsah!",
|
| 684 |
+
"points": 30,
|
| 685 |
+
"answerKey": "Larangan minuman keras berkaitan dengan hifzhu al-'aql (menjaga akal). Alkohol/minuman keras merusak fungsi otak dan akal pikiran manusia. Islam melarang segala sesuatu yang dapat menghilangkan akal pikiran."
|
| 686 |
+
},
|
| 687 |
+
{
|
| 688 |
+
"type": "TANTANGAN",
|
| 689 |
+
"text": "Hubungkan larangan zina dengan salah satu prinsip al-kulliyatu al-khamsah dan jelaskan kaitannya!",
|
| 690 |
+
"points": 30,
|
| 691 |
+
"answerKey": "Hifzhu al-nasl (menjaga keturunan): Zina mengacaukan nasab/silsilah keturunan. Anak yang lahir di luar nikah kehilangan kejelasan identitas ayahnya, sehingga hak-hak hukumnya tidak terlindungi. Hifzhu al-'ird (kehormatan) yang juga masuk dalam hifzhu al-nasl: Zina merusak martabat dan kehormatan diri, keluarga, dan masyarakat."
|
| 692 |
+
},
|
| 693 |
+
{
|
| 694 |
+
"type": "TANTANGAN",
|
| 695 |
+
"text": "Berikan dua contoh penerapan prinsip hifzhu al-nafs (menjaga jiwa) dalam kehidupan sehari-hari!",
|
| 696 |
+
"points": 30,
|
| 697 |
+
"answerKey": "Menjaga kesehatan dengan pola makan teratur, olahraga, dan istirahat cukup. Menghindari tawuran, kekerasan, dan perbuatan berbahaya lainnya yang dapat mengancam nyawa sendiri atau orang lain."
|
| 698 |
+
},
|
| 699 |
+
{
|
| 700 |
+
"type": "TANTANGAN",
|
| 701 |
+
"text": "Sebutkan 3 nama Wali Songo dan jelaskan metode dakwah yang digunakan masing-masing!",
|
| 702 |
+
"points": 30,
|
| 703 |
+
"answerKey": "Sunan Gresik (Maulana Malik Ibrahim): berdagang, membantu masyarakat, mengajarkan pertanian, dan pendekatan sosial. Sunan Ampel: mendirikan pesantren dan mendidik para santri serta calon pemimpin Islam. Sunan Kalijaga: memakai budaya lokal seperti wayang, seni, pakaian adat, dan tradisi masyarakat Jawa. (Jawaban dapat menyebut 3 wali mana saja dari Wali Songo)"
|
| 704 |
+
},
|
| 705 |
+
{
|
| 706 |
+
"type": "TANTANGAN",
|
| 707 |
+
"text": "Sebutkan sembilan nama Wali Songo yang berperan dalam penyebaran Islam di tanah Jawa!",
|
| 708 |
+
"points": 30,
|
| 709 |
+
"answerKey": "Sunan Gresik (Maulana Malik Ibrahim), Sunan Ampel (Raden Rahmat), Sunan Bonang (Raden Makhdum Ibrahim), Sunan Drajat (Raden Qasim/Syarifuddin), Sunan Kudus (Ja'far Shadiq), Sunan Giri (Raden Paku/Muhammad Ainul Yaqin), Sunan Kalijaga (Raden Mas Said), Sunan Muria (Raden Umar Said), Sunan Gunung Jati (Syarif Hidayatullah)."
|
| 710 |
+
},
|
| 711 |
+
{
|
| 712 |
+
"type": "TANTANGAN",
|
| 713 |
+
"text": "Dari beberapa metode yang digunakan oleh Sunan Kalijaga dalam menyebarkan Islam di Jawa, jelaskan salah satu metode dakwah yang digunakan selain dengan menggunakan wayang kulit!",
|
| 714 |
+
"points": 30,
|
| 715 |
+
"answerKey": "Gamelan: menggunakan musik gamelan sebagai media menarik perhatian masyarakat sebelum menyampaikan ajaran Islam. Tembang/lagu Jawa: menciptakan lagu-lagu berisi pesan Islam dalam bahasa Jawa yang mudah dipahami. Baju Takwa/Blangkon: memadukan budaya Jawa dengan nilai Islam dalam pakaian dan tradisi."
|
| 716 |
+
},
|
| 717 |
+
{
|
| 718 |
+
"type": "TANTANGAN",
|
| 719 |
+
"text": "Jelaskan mengapa para Wali Songo memilih metode dakwah yang damai dan tidak memaksakan agama kepada masyarakat Jawa!",
|
| 720 |
+
"points": 30,
|
| 721 |
+
"answerKey": "Metode dakwah Wali Songo mengikuti petunjuk Allah dalam Q.S. an-Nahl/16: 125 — dakwah harus dilakukan dengan hikmah, nasihat yang baik, dan dialog yang santun. Masyarakat Jawa saat itu memiliki budaya dan kepercayaan yang sudah kuat (Hindu-Buddha); pemaksaan hanya akan menimbulkan penolakan dan konflik. Islam rahmatan lil 'alamin harus disampaikan dengan cara yang penuh kasih sayang dan menghormati budaya setempat. Metode damai terbukti efektif: Islam menyebar luas dan mengakar kuat di Nusantara tanpa peperangan besar."
|
| 722 |
+
},
|
| 723 |
+
{
|
| 724 |
+
"type": "TANTANGAN",
|
| 725 |
+
"text": "Jelaskan mengapa dakwah dengan sikap ramah dan menghargai budaya lebih mudah diterima masyarakat!",
|
| 726 |
+
"points": 30,
|
| 727 |
+
"answerKey": "Karena masyarakat merasa dihargai, tidak dipaksa, dakwah menjadi lebih damai, dan mudah dipahami."
|
| 728 |
+
},
|
| 729 |
+
{
|
| 730 |
+
"type": "TANTANGAN",
|
| 731 |
+
"text": "Jelaskan peran Sunan Ampel dalam penyebaran Islam di Nusantara dan jelaskan satu kontribusi terbesarnya!",
|
| 732 |
+
"points": 30,
|
| 733 |
+
"answerKey": "Mendirikan pesantren di Ampel Denta yang menjadi pusat pendidikan Islam pertama di Jawa. Dari pesantren inilah lahir banyak ulama dan wali lainnya, termasuk Sunan Bonang dan Sunan Drajat. Mengajarkan Islam melalui pendekatan budaya yang halus dan tidak konfrontatif. Berperan dalam pembentukan Kerajaan Demak sebagai kerajaan Islam pertama di Jawa."
|
| 734 |
+
}
|
| 735 |
+
]
|
| 736 |
+
}
|
packages/db/prisma/schema.prisma
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
generator client {
|
| 2 |
+
provider = "prisma-client-js"
|
| 3 |
+
}
|
| 4 |
+
|
| 5 |
+
datasource db {
|
| 6 |
+
provider = "postgresql"
|
| 7 |
+
url = env("DATABASE_URL")
|
| 8 |
+
directUrl = env("DIRECT_URL")
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
model User {
|
| 12 |
+
id String @id @default(cuid())
|
| 13 |
+
email String @unique
|
| 14 |
+
passwordHash String
|
| 15 |
+
name String
|
| 16 |
+
createdAt DateTime @default(now())
|
| 17 |
+
rooms Room[]
|
| 18 |
+
questionSets QuestionSet[]
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
model Room {
|
| 22 |
+
id String @id @default(cuid())
|
| 23 |
+
code String @unique @db.Char(6)
|
| 24 |
+
guruId String
|
| 25 |
+
guru User @relation(fields: [guruId], references: [id])
|
| 26 |
+
status RoomStatus @default(LOBBY)
|
| 27 |
+
durationMinutes Int
|
| 28 |
+
turnDurationDasar Int @default(30)
|
| 29 |
+
turnDurationTantangan Int @default(60)
|
| 30 |
+
turnDurationPemahaman Int @default(90)
|
| 31 |
+
activeGroupIndex Int @default(0)
|
| 32 |
+
currentTurn Int @default(1)
|
| 33 |
+
maxGroups Int @default(6)
|
| 34 |
+
createdAt DateTime @default(now())
|
| 35 |
+
groups Group[]
|
| 36 |
+
session GameSession?
|
| 37 |
+
|
| 38 |
+
// Relation to QuestionSet
|
| 39 |
+
questionSetId String?
|
| 40 |
+
questionSet QuestionSet? @relation(fields: [questionSetId], references: [id], onDelete: SetNull)
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
enum RoomStatus {
|
| 44 |
+
LOBBY
|
| 45 |
+
ACTIVE
|
| 46 |
+
ENDED
|
| 47 |
+
CANCELLED
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
model Group {
|
| 51 |
+
id String @id @default(cuid())
|
| 52 |
+
roomId String
|
| 53 |
+
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
| 54 |
+
name String
|
| 55 |
+
score Int @default(0)
|
| 56 |
+
position Int @default(0)
|
| 57 |
+
status GroupStatus @default(ACTIVE)
|
| 58 |
+
avatar String?
|
| 59 |
+
color String?
|
| 60 |
+
answers Answer[]
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
enum GroupStatus {
|
| 64 |
+
ACTIVE
|
| 65 |
+
SKIP_NEXT
|
| 66 |
+
SURRENDERED
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
model QuestionSet {
|
| 70 |
+
id String @id @default(cuid())
|
| 71 |
+
title String
|
| 72 |
+
description String?
|
| 73 |
+
isPreset Boolean @default(false)
|
| 74 |
+
guruId String?
|
| 75 |
+
guru User? @relation(fields: [guruId], references: [id])
|
| 76 |
+
questions Question[]
|
| 77 |
+
rooms Room[]
|
| 78 |
+
createdAt DateTime @default(now())
|
| 79 |
+
updatedAt DateTime @updatedAt
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
model Question {
|
| 83 |
+
id String @id @default(cuid())
|
| 84 |
+
setId String
|
| 85 |
+
set QuestionSet @relation(fields: [setId], references: [id], onDelete: Cascade)
|
| 86 |
+
type QuestionType
|
| 87 |
+
text String
|
| 88 |
+
options Json?
|
| 89 |
+
answerKey String?
|
| 90 |
+
points Int @default(10)
|
| 91 |
+
createdAt DateTime @default(now())
|
| 92 |
+
answers Answer[]
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
enum QuestionType {
|
| 96 |
+
DASAR
|
| 97 |
+
TANTANGAN
|
| 98 |
+
PEMAHAMAN
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
model GameSession {
|
| 102 |
+
id String @id @default(cuid())
|
| 103 |
+
roomId String @unique
|
| 104 |
+
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
| 105 |
+
startedAt DateTime @default(now())
|
| 106 |
+
endedAt DateTime?
|
| 107 |
+
winnerGroupId String?
|
| 108 |
+
answers Answer[]
|
| 109 |
+
turnLogs TurnLog[]
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
model Answer {
|
| 113 |
+
id String @id @default(cuid())
|
| 114 |
+
sessionId String
|
| 115 |
+
session GameSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
| 116 |
+
groupId String
|
| 117 |
+
group Group @relation(fields: [groupId], references: [id], onDelete: Cascade)
|
| 118 |
+
questionId String
|
| 119 |
+
question Question @relation(fields: [questionId], references: [id], onDelete: Cascade)
|
| 120 |
+
answerText String?
|
| 121 |
+
isCorrect Boolean?
|
| 122 |
+
scoreGiven Int?
|
| 123 |
+
answeredAt DateTime @default(now())
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
model TurnLog {
|
| 127 |
+
id String @id @default(cuid())
|
| 128 |
+
sessionId String
|
| 129 |
+
session GameSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
| 130 |
+
groupId String
|
| 131 |
+
questionId String?
|
| 132 |
+
turnNumber Int
|
| 133 |
+
timestamp DateTime @default(now())
|
| 134 |
+
}
|
packages/db/prisma/seed.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { PrismaClient } from '@prisma/client';
|
| 2 |
+
import * as fs from 'fs';
|
| 3 |
+
import * as path from 'path';
|
| 4 |
+
import { fileURLToPath } from 'url';
|
| 5 |
+
|
| 6 |
+
const prisma = new PrismaClient();
|
| 7 |
+
|
| 8 |
+
// Helper to handle __dirname in ESM
|
| 9 |
+
const __filename = fileURLToPath(import.meta.url);
|
| 10 |
+
const __dirname = path.dirname(__filename);
|
| 11 |
+
|
| 12 |
+
async function main() {
|
| 13 |
+
console.log('--- RESETTING & SEEDING PRESETS START ---');
|
| 14 |
+
|
| 15 |
+
// 1. Read all JSON files from the presets directory
|
| 16 |
+
const presetsDir = path.join(__dirname, 'presets');
|
| 17 |
+
const presetFiles = fs.readdirSync(presetsDir).filter((file: string) => file.endsWith('.json'));
|
| 18 |
+
|
| 19 |
+
const presets = presetFiles.map((file: string) => {
|
| 20 |
+
const filePath = path.join(presetsDir, file);
|
| 21 |
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
| 22 |
+
});
|
| 23 |
+
|
| 24 |
+
// 2. Clear existing presets to ensure fresh start
|
| 25 |
+
console.log('Cleaning old preset data...');
|
| 26 |
+
await prisma.question.deleteMany({
|
| 27 |
+
where: { set: { isPreset: true } }
|
| 28 |
+
});
|
| 29 |
+
await prisma.questionSet.deleteMany({
|
| 30 |
+
where: { isPreset: true }
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
// 3. Seed new data
|
| 34 |
+
for (const preset of presets) {
|
| 35 |
+
console.log(`Creating set: ${preset.name}`);
|
| 36 |
+
|
| 37 |
+
const questionSet = await prisma.questionSet.create({
|
| 38 |
+
data: {
|
| 39 |
+
id: `preset-${preset.name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')}`,
|
| 40 |
+
title: preset.name,
|
| 41 |
+
description: preset.description,
|
| 42 |
+
isPreset: true,
|
| 43 |
+
questions: {
|
| 44 |
+
create: preset.questions.map((q: any) => ({
|
| 45 |
+
type: q.type,
|
| 46 |
+
text: q.text,
|
| 47 |
+
points: q.points,
|
| 48 |
+
options: q.options || undefined,
|
| 49 |
+
answerKey: q.answerKey || undefined,
|
| 50 |
+
}))
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
});
|
| 54 |
+
|
| 55 |
+
console.log(`✅ Set "${preset.name}" created with ${preset.questions.length} questions.`);
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
console.log('--- SEEDING COMPLETED SUCCESSFULLY ---');
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
main()
|
| 62 |
+
.catch((e) => {
|
| 63 |
+
console.error(e);
|
| 64 |
+
process.exit(1);
|
| 65 |
+
})
|
| 66 |
+
.finally(async () => {
|
| 67 |
+
await prisma.$disconnect();
|
| 68 |
+
});
|
packages/db/tsconfig.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"compilerOptions": {
|
| 3 |
+
"target": "ESNext",
|
| 4 |
+
"module": "ESNext",
|
| 5 |
+
"lib": ["ESNext"],
|
| 6 |
+
"moduleResolution": "Node",
|
| 7 |
+
"strict": true,
|
| 8 |
+
"esModuleInterop": true,
|
| 9 |
+
"skipLibCheck": true,
|
| 10 |
+
"forceConsistentCasingInFileNames": true,
|
| 11 |
+
"types": [
|
| 12 |
+
"node"
|
| 13 |
+
]
|
| 14 |
+
},
|
| 15 |
+
"include": [
|
| 16 |
+
"prisma/seed.ts",
|
| 17 |
+
"index.ts"
|
| 18 |
+
]
|
| 19 |
+
}
|
packages/types/package.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@repo/types",
|
| 3 |
+
"version": "1.0.0",
|
| 4 |
+
"private": true,
|
| 5 |
+
"main": "./src/index.ts",
|
| 6 |
+
"types": "./src/index.ts",
|
| 7 |
+
"dependencies": {
|
| 8 |
+
"zod": "^3.23.4"
|
| 9 |
+
},
|
| 10 |
+
"devDependencies": {
|
| 11 |
+
"typescript": "^5.4.5"
|
| 12 |
+
}
|
| 13 |
+
}
|
packages/types/src/index.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { z } from "zod";
|
| 2 |
+
|
| 3 |
+
export const LoginSchema = z.object({
|
| 4 |
+
email: z.string().email(),
|
| 5 |
+
password: z.string().min(6),
|
| 6 |
+
});
|
| 7 |
+
export type LoginInput = z.infer<typeof LoginSchema>;
|
| 8 |
+
|
| 9 |
+
export const CreateRoomSchema = z.object({
|
| 10 |
+
durationMinutes: z.number().min(1),
|
| 11 |
+
turnDurationDasar: z.number().min(10).max(120),
|
| 12 |
+
turnDurationTantangan: z.number().min(10).max(300),
|
| 13 |
+
turnDurationPemahaman: z.number().min(10).max(300),
|
| 14 |
+
maxGroups: z.number().min(2).max(8),
|
| 15 |
+
});
|
| 16 |
+
export type CreateRoomInput = z.infer<typeof CreateRoomSchema>;
|
| 17 |
+
|
| 18 |
+
export const QuestionSchema = z.object({
|
| 19 |
+
type: z.enum(["DASAR", "TANTANGAN", "PEMAHAMAN"]),
|
| 20 |
+
text: z.string().min(5),
|
| 21 |
+
options: z.array(z.string()).optional(),
|
| 22 |
+
answerKey: z.string().optional(),
|
| 23 |
+
points: z.number().default(10),
|
| 24 |
+
});
|
| 25 |
+
export type QuestionInput = z.infer<typeof QuestionSchema>;
|
| 26 |
+
|
| 27 |
+
// Socket Payload Types
|
| 28 |
+
export interface ClientJoinRoomPayload {
|
| 29 |
+
roomCode: string;
|
| 30 |
+
groupName: string;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
export interface TeacherStartGamePayload {
|
| 34 |
+
roomId: string;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
export interface ClientAnswerPayload {
|
| 38 |
+
questionId: string;
|
| 39 |
+
answerText: string;
|
| 40 |
+
isObjektif: boolean;
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
export interface TeacherGradePayload {
|
| 44 |
+
answerId: string;
|
| 45 |
+
score: number;
|
| 46 |
+
}
|
pnpm-lock.yaml
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pnpm-workspace.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
packages:
|
| 2 |
+
- "apps/*"
|
| 3 |
+
- "packages/*"
|
| 4 |
+
ignoredBuiltDependencies:
|
| 5 |
+
- sharp
|
| 6 |
+
- unrs-resolver
|
turbo.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"$schema": "https://turbo.build/schema.json",
|
| 3 |
+
"tasks": {
|
| 4 |
+
"build": {
|
| 5 |
+
"dependsOn": ["^build"],
|
| 6 |
+
"outputs": [".next/**", "dist/**"]
|
| 7 |
+
},
|
| 8 |
+
"dev": {
|
| 9 |
+
"cache": false,
|
| 10 |
+
"persistent": true
|
| 11 |
+
},
|
| 12 |
+
"lint": {
|
| 13 |
+
"dependsOn": ["^lint"]
|
| 14 |
+
}
|
| 15 |
+
}
|
| 16 |
+
}
|